branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>juliascript/tic-tac-toe-ttp<file_sep>/TicTacToe/Board.swift
//
// Board.swift
// TicTacToe
//
// Created by Julia on 11/2/16.
// Copyright © 2016 Make school. All rights reserved.
//
import UIKit
class Board: NSObject {
var board: [[State]] =
[
[.empty,.empty,.empty],
[.empty,.empty,.empty],
[.empty,.empty,.empty]
]
override init() {
super.init()
resetBoard()
}
func resetBoard() {
board =
[
[.empty,.empty,.empty],
[.empty,.empty,.empty],
[.empty,.empty,.empty]
]
}
func setValueAt(_ row: Int, _ column: Int, _ state: State){
board[row][column] = state
}
func isFull() -> Bool {
for row in board{
for j in 0..<(row.count){
if row[j] == .empty {
return false
}
}
}
return true
}
}
<file_sep>/README.md
# Tic Tac Toe -- TTP
## To run, git clone this repo and open the .xcodeproj file. Hit CMD+R to run in a simulator.
(For some reason, the last row only reacts to touches on the top portion of the field. You'll have to click close to the border to choose a field from the bottom row.
| 1ae73fd39a8eab89f2ef8b17fd3dd2f88100ca59 | [
"Swift",
"Markdown"
] | 2 | Swift | juliascript/tic-tac-toe-ttp | a8927f0a5637683dbf9b0f22e35addf21c9f9394 | c904f9bfe3379973442560eeaa9c0e097844ccd0 |
refs/heads/master | <repo_name>liyc7711/weighted-nmt<file_sep>/train.py
import numpy
import os
import time
from nmt import train
def main(job_id, params):
print ('timestamp {} {}'.format('running',time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
print (params)
validerr = train(saveto=params['model'][0],
reload_=params['reload'][0],
dim_word=params['dim_word'][0],
dim=params['dim'][0],
n_words=params['n-words'][0],
n_words_src=params['n-words'][0],
decay_c=params['decay-c'][0],
clip_c=params['clip-c'][0],
lrate=params['learning-rate'][0],
optimizer=params['optimizer'][0],
patience=10000,
maxlen=60,
batch_size=80,
validFreq_fine=2000,
validFreq=10000,
val_burn_in=20000,
val_burn_in_fine=400000,
dispFreq=20,
saveFreq=2000,
sampleFreq=200,
datasets=['/data/ycli/resource/wmt2017/deen/corpus.tc.en.bpe',
'/data/ycli/resource/wmt2017/deen/corpus.tc.de.bpe'],
valid_datasets=['/data/ycli/resource/wmt2017/deen/valid/valid_en_bpe',
'/data/ycli/resource/wmt2017/deen/valid/valid_de_bpe',
'./data/valid_out'],
dictionaries=['/data/ycli/resource/wmt2017/deen/vocab/v30-bpe/vocab_en.pkl',
'/data/ycli/resource/wmt2017/deen/vocab/v30-bpe/vocab_de.pkl'],
use_dropout=params['use-dropout'][0],
overwrite=False,
valid_mode=params['valid_mode'][1],
bleu_script=params['bleu_script'][0])
return validerr
if __name__ == '__main__':
main(0, {
'model': ['/data/ycli/exp/deen/wbpe/train_model.npz'],
'dim_word': [620],
'dim': [1000],
'n-words': [30000],
'optimizer': ['adam'],
'decay-c': [1e-6],
'clip-c': [1.],
'use-dropout': [True],
'learning-rate': [0.0002],
'reload': [False],
'valid_mode': ['bleu', 'ce'],
'bleu_script': ['./data/mteval-v11b.pl', './data/multi-bleu.perl']})
<file_sep>/README.md
# weighted-nmt
Source code for "Adaptive Weighting for Neural Machine Translation"
The source code is developed upon [dl4mt](https://github.com/nyu-dl/dl4mt-tutorial).
## Train
```
THEANO_FLAGS=device=gpu,floatX=float32 python train.py
```
## Test
```
THEANO_FLAGS=device=gpu,floatX=float32 python translate.py
```
## Reference
```
<NAME>, <NAME> and <NAME>. Adaptive Weighting for Neural Machine Translation. Proceedings of the 27th International Conference on Computational Linguistics (COLING 2018), 2018.
```
<file_sep>/train.sh
#!/bin/bash
#PBS -l nodes=1:ppn=20
#PBS -l walltime=168:00:00
#PBS -N session2_default
#PBS -A course
#PBS -q GpuQ
export THEANO_FLAGS=device=gpu2,lib.cnmem=0.8,floatX=float32
#cd $PBS_O_WORKDIR
python train.py
<file_sep>/test.sh
#!/bin/bash
#PBS -l nodes=1:ppn=24
#PBS -l walltime=24:00:00
#PBS -N session2_default
#PBS -A course
#PBS -q ShortQ
export THEANO_FLAGS=device=gpu1,lib.cnmem=0.1,floatX=float32
#cd $PBS_O_WORKDIR
python translate.py
<file_sep>/translate.py
'''
Translates a source file using a translation model.
'''
import argparse
import subprocess
import numpy
import time
import sys
import cPickle as pkl
import os
from nmt import (build_sampler, load_params, init_params, init_tparams)
from nmt import _idxs2words, gen_trans
from stream import get_sentences
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano import shared
import pdb
def sample(model, dictionary, dictionary_target, \
source_file, ref_file, saveto, \
k=10, normalize=False, \
bleu_script='./data/multi-bleu.perl', res_to_sgm='./data/plain2sgm'):
# load model model_options
with open(model+'.pkl', 'rb') as f:
options = pkl.load(f)
# load target dictionary and invert
with open(dictionary_target, 'rb') as f:
word_dict_trg = pkl.load(f)
word_idict_trg = dict()
for kk, vv in word_dict_trg.iteritems():
word_idict_trg[vv] = kk
val_start_time = time.time()
trng = RandomStreams(1234)
use_noise = shared(numpy.float32(0.))
# allocate model parameters
params = init_params(options)
# load model parameters and set theano shared variables
params = load_params(model, params)
tparams = init_tparams(params)
# word index
f_init, f_next = build_sampler(tparams, options, trng, use_noise)
bleu_score = gen_trans(test_src=source_file, test_ref=ref_file, out_file=saveto, \
dict_src=dictionary, idict_trg=word_idict_trg, \
tparams=tparams, f_init=f_init, f_next=f_next, model_options=options, \
trng=trng, k=10, stochastic=False, bleu_script=bleu_script, res_to_sgm=res_to_sgm)
print(model+' / '+source_file+' / '+'test bleu %.4f' %bleu_score)
print ('timestamp {} {}'.format('done',time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
sys.stdout.flush()
if __name__ == "__main__":
'''
'''
print ('timestamp {} {}'.format('running',time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
dict_src = '/data/ycli/resource/wmt2017/deen/vocab/v50/vocab_en.pkl'
dict_trg = '/data/ycli/resource/wmt2017/deen/vocab/v50/vocab_de.pkl'
test_model = ['/data/ycli/exp/deen/w/train_model.iter500000.npz']
test_file = [['/data/ycli/resource/wmt2017/deen/dev/newstest2014.tc.en',
'/data/ycli/resource/wmt2017/deen/dev/newstest2014.tc.de',
'./data/news2014.out'],
['/data/ycli/resource/wmt2017/deen/dev/newstest2015.tc.en.t',
'/data/ycli/resource/wmt2017/deen/dev/newstest2015.tc.de',
'./data/news2015.out'],
['/data/ycli/resource/wmt2017/deen/dev/newstest2016.tc.en.t',
'/data/ycli/resource/wmt2017/deen/dev/newstest2016.tc.de',
'./data/news2016.out']]
for model in test_model:
if os.path.isfile(model) == False:
continue
for i in range(len(test_file)):
if os.path.isfile(test_file[i][0]) == False:
continue
sample(model, dict_src, dict_trg, \
test_file[i][0], test_file[i][1], test_file[i][2])
| 3d7df352340711d244ee081a23dca1e687938c05 | [
"Markdown",
"Python",
"Shell"
] | 5 | Python | liyc7711/weighted-nmt | 60c2470ea1da63704f85930ea6e640e611177e13 | 5d69d4ec82d41661c8e336463639673d20999552 |
refs/heads/master | <repo_name>lzcleo/MovieTube<file_sep>/src/store/modules/movie.js
import {
getMovieListAPI,
getByMovieIdAPI
} from '@/api/movie'
const movie = {
state: {
movieList: {
},
movieListParams: {
pageNo: 1,
pageSize: 20
},
currentMovieId: ''
},
mutations: {
set_movieList: function(state, data) {
state.movieList = data
},
set_movieListParams: function(state, data) {
state.movieListParams = {
...state.movieListParams,
...data
}
},
},
actions: {
getMovieList: async({commit, state}) => {
const res = await getMovieListAPI(state.movieListParams)
if(res){
commit('set_movieList', res)
console.log(res.content)
}
},
getByMovieId: async({commit, state}) => {
const res = await getByMovieIdAPI(state.currentMovieId)
if(res){
}
}
}
}
export default movie<file_sep>/src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/user/login.vue'
import List from '../views/movie/movieList'
import movie from '../views/movie/movieDetail'
Vue.use(VueRouter)
const routes = [
{
path: '/MovieTube/list',
name: 'list',
component: List
},
{
path: '/MovieTube/user/login',
name: 'login',
component: Login
},
{
path: '/MovieTube/movie',
name: 'movie',
component: movie
}
]
const router = new VueRouter({
routes
})
export default router
<file_sep>/src/store/modules/user.js
import notification from 'ant-design-vue'
import Vue from 'vue'
import router from '@/router'
import {
loginAPI,
registerAPI
} from '@/api/user'
const user = {
state: {
token:'',
name:'',
welcome:'',
info: {}
},
mutations: {
set_token: function(state, token){
state.token = token
}
},
actions: {
login: async ({ commit }, userData) => {
const res = await loginAPI(userData)
if(res){
Vue.ls.set('ACCESS_TOKEN', res, 7 * 24 * 60 * 60 * 1000)
commit('set_token', res)
router.push('/MovieTube/list')
}
}
}
}
export default user | 50b807176286fc9cee86ead11a7cf6a6a37b2c36 | [
"JavaScript"
] | 3 | JavaScript | lzcleo/MovieTube | a6dc9f15c3fb7f7af68b349c877d4adb7eeff254 | fff5c67e5e608e75ed5d74a742549bd59f1f4ba0 |
refs/heads/master | <file_sep>import unittest
import data_import as datimp
from datetime import datetime
import os
def create_test_csvs():
with open('static_test.csv', 'w') as f:
f.write('Id,time,value\n')
for i in range(100):
f.write(str(i)+','+str(datetime.now())+','+str(10)+'\n')
with open('bad_date_test.csv', 'w') as f:
f.write('Id,time,value\n')
f.write(str(0)+','+str(1)+','+str(10)+'\n')
with open('bad_value_test.csv', 'w') as f:
f.write('Id,time,value\n')
f.write(str(0)+','+str(datetime.now())+','+'blah'+'\n')
with open('high_low_test.csv', 'w') as f:
f.write('Id,time,value\n')
f.write(str(0)+','+str(datetime.now())+','+'low'+'\n')
f.write(str(1)+','+str(datetime.now())+','+'high'+'\n')
with open('skip_empty_value_test.csv', 'w') as f:
f.write('Id,time,value\n')
f.write(str(0)+','+str(datetime.now())+','+''+'\n')
f.write(str(1)+','+str(datetime.now())+','+'10'+'\n')
class TestImportData(unittest.TestCase):
create_test_csvs()
#File Input Tests
def test_file_not_found(self):
self.assertRaises(TypeError,datimp.ImportData,None)
def test_bad_input_type(self):
self.assertRaises(TypeError,datimp.ImportData,1)
self.assertRaises(TypeError,datimp.ImportData,[1,12,3,4])
self.assertRaises(TypeError,datimp.ImportData,1.0000)
def test_file_doesnotexist(self):
self.assertRaises(FileNotFoundError,datimp.ImportData,'no_file.csv')
#File Value Tests
def test_file_values(self):
data=datimp.ImportData('static_test.csv')
self.assertEqual(sum(data._value),1000)
'''
def test_bad_values(self):
self.assertRaises(ValueError,datimp.ImportData,'bad_value_test.csv')
def test_bad_date(self):
self.assertRaises(ValueError,datimp.ImportData,'bad_date_test.csv')
'''
def test_high_low(self):
data=datimp.ImportData('high_low_test.csv',replace_high_low=True)
self.assertEqual(data._value[0],40)
self.assertEqual(data._value[1],300)
def test_no_key(self):
data=datimp.ImportData('high_low_test.csv',replace_high_low=True)
self.assertRaises(TypeError,data.linear_search_value,None)
def test_bad_key_type(self):
data=datimp.ImportData('high_low_test.csv',replace_high_low=True)
self.assertRaises(TypeError,data.linear_search_value,[1,1,1])
self.assertRaises(TypeError,data.linear_search_value,1)
self.assertRaises(TypeError,data.linear_search_value,'text')
def test_search_miss(self):
data=datimp.ImportData('smallData/cgm_small.csv')
self.assertEqual(data.linear_search_value(datetime.now()),-1)
def test_search_hit(self):
data=datimp.ImportData('smallData/cgm_small.csv')
self.assertEqual(data.linear_search_value(data._time[0]),data._value[0])
def test_skip_empty_value(self):
data=datimp.ImportData('skip_empty_value_test.csv')
self.assertEqual(data._value[0],10)
self.remove_test_csvs()
def remove_test_csvs(self):
os.remove('skip_empty_value_test.csv')
os.remove('high_low_test.csv')
os.remove('bad_value_test.csv')
os.remove('bad_date_test.csv')
os.remove('static_test.csv')
class TestRoundTimeArray(unittest.TestCase):
def test_no_object(self):
self.assertRaises(TypeError,datimp.roundTimeArray,None,5)
def test_no_res(self):
data=datimp.ImportData('smallData/cgm_small.csv')
self.assertRaises(TypeError,datimp.roundTimeArray,data,None)
def test_obj_type(self):
self.assertRaises(TypeError,datimp.roundTimeArray,'text',5)
self.assertRaises(TypeError,datimp.roundTimeArray,[1,1,1],5)
self.assertRaises(TypeError,datimp.roundTimeArray,1,5)
def test_res_type(self):
data=datimp.ImportData('smallData/cgm_small.csv')
self.assertRaises(TypeError,datimp.roundTimeArray,data,'text')
self.assertRaises(TypeError,datimp.roundTimeArray,data,[1,1,1])
self.assertRaises(TypeError,datimp.roundTimeArray,data,{})
def test_round_output_type(self):
data=datimp.ImportData('smallData/cgm_small.csv')
output = datimp.roundTimeArray(data,5)
self.assertEqual(type(output),zip)
class TestPrintArray(unittest.TestCase):
def test_bad_data_list(self):
self.assertRaises(TypeError,datimp.printArray,None,['a','b','c','d'],'txt.fn','txt.str')
self.assertRaises(TypeError,datimp.printArray,1,['a','b','c','d'],'txt.fn','txt.str')
self.assertRaises(TypeError,datimp.printArray,'txt',['a','b','c','d'],'txt.fn','txt.str')
def test_bad_annotation_list(self):
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],1,'txt.fn','txt.str')
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],'str','txt.fn','txt.str')
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],None,'txt.fn','txt.str')
def test_bad_base_name(self):
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],None,'txt.str')
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],[1,1,1],'txt.str')
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],1,'txt.str')
def test_bad_key_file(self):
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],'txt.str',None)
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],'txt.str',[1,1,1])
self.assertRaises(TypeError,datimp.printArray,['a','b','c','d'],['a','b','c','d'],'txt.str',0)<file_sep>import csv
import dateutil.parser
from os import listdir
from os.path import isfile, join
import argparse
import datetime
import numpy as np
class ImportData:
def __init__(self, data_csv,replace_high_low=False):
if data_csv is None:
raise TypeError("ImportData: No input filepath provided")
if not isinstance(data_csv,str):
raise TypeError('ImportData: Filename must be string')
self._time = []
self._value = []
with open(data_csv, "r") as fhandle:
try:
reader = csv.DictReader(fhandle)
except FileNotFoundError:
print('ImportData: File does not exist')
for row in reader:
try:
if row['time'] == '':
print('ImportData: Removing blank time value')
continue
self._time.append(dateutil.parser.parse(row['time']))
except ValueError:
raise ValueError('ImportData: Bad time value')
if replace_high_low is True:
if row['value'] == '':
print('ImportData: Removing blank value')
continue
if row['value'] == 'low':
self._value.append(float(40))
print('ImportData: Replacing "low" value with 40')
elif row['value'] == 'high':
self._value.append(float(300))
print('ImportData: Replacing "high" value with 300')
else:
try:
self._value.append(float(row['value']))
except ValueError:
continue
else:
if row['value'] == '':
print('ImportData: Removing blank value')
continue
try:
self._value.append(float(row['value']))
except ValueError:
continue
fhandle.close()
# open file, create a reader from csv.DictReader, and read input times and values
def linear_search_value(self, key_time):
if key_time is None:
raise TypeError('ImportData.linear_search_value: No key value supplied')
if not isinstance(key_time,datetime.datetime):
raise TypeError('ImportData.linear_search_value: Key must be datetime.datetime data type')
for i in range(len(self._time)):
curr = self._time[i]
if key_time == curr:
return self._value[i]
print('invalid time')
return -1
# return list of value(s) associated with key_time
# if none, return -1 and error message
pass
def binary_search_value(self,key_time):
# optional extra credit
# return list of value(s) associated with key_time
# if none, return -1 and error message
pass
def roundTimeArray(obj, res, repeat_operation='average'):
if obj is None:
raise TypeError('roundTimeArray: requires an ImportData object')
if res is None:
raise TypeError('roundTimeArray: requires a rounding resolution')
if not isinstance(obj,ImportData):
raise TypeError('roundTimeArray: obj must be an ImportData object')
if not isinstance(res,(int,float)):
raise TypeError('roundTimeArray: res must be a float or int')
#round times to resolution and return to object array
rounded_times = []
for time in obj._time:
minminus = datetime.timedelta(minutes = (time.minute % res))
minplus = datetime.timedelta(minutes=res) - minminus
if (time.minute % res) <= res/2:
newtime = time - minminus
else:
newtime=time + minplus
rounded_times.append(newtime)
obj._time = rounded_times
#remove duplicate times from the array
unique_times = []
unique_values = []
for time in obj._time:
if time not in unique_times:
if repeat_operation == 'average':
combined_value = np.average(obj.linear_search_value(time))
if repeat_operation == 'sum':
combined_value = np.sum(obj.linear_search_value(time))
unique_times.append(time)
unique_values.append(combined_value)
else:
continue
obj._time = unique_times
obj._value = unique_values
output = zip(obj._time,obj._value)
return output
def printArray(data_list, annotation_list, base_name, key_file):
if data_list is None:
raise TypeError('printArray: requires data_list')
if annotation_list is None:
raise TypeError('printArray: requires annotation_list')
if base_name is None:
raise TypeError('printArray: requires base_name')
if key_file is None:
raise TypeError('printArray: requires key_file')
if not isinstance(data_list,list):
raise TypeError('printArray: data_list must be list')
if not isinstance(annotation_list,list):
raise TypeError('printArray: annotation_list must be list')
if not isinstance(base_name,str):
raise TypeError('printArray: base_name must be str')
if not isinstance(key_file,str):
raise TypeError('printArray: key_file must be str')
for i in range(len(annotation_list)):
if key_file == 'smallData/'+annotation_list[i]:
align_data = data_list[i]
key_index = i
break
if '.csv' not in base_name:
raise TypeError('printArray: base_name must end with .csv')
with open(base_name, 'w') as f:
f.write('time'+annotation_list[key_index].split('/')[-1].split('_')[0]+',')
other_files = list(range(len(annotation_list)))
other_files.remove(key_index)
for i in other_files:
f.write(annotation_list[i].split('/')[-1].split('_')[0]+',')
f.write('\n')
for time, value in align_data:
print('NO')
f.write(str(time)+','+str(value)+',')
for i in other_files:
time_list = [data[0] for data in data_list[i]]
if time in time_list:
f.write(str(data_list[i][time_list.index(time)][1])+',')
else: f.write('0,')
f.write('\n')
if __name__ == '__main__':
#adding arguments
parser = argparse.ArgumentParser(description= 'A class to import, combine, and print data from a folder.',
prog= 'dataImport')
parser.add_argument('--folder_name', type = str, help = 'Name of the folder')
parser.add_argument('--output_file', type=str, help = 'Name of Output file')
parser.add_argument('--sort_key', type = str, help = 'File to sort on')
parser.add_argument('--number_of_files', type = int,
help = "Number of Files", required = False)
args = parser.parse_args()
#pull all the folders in the file
files_lst = [file for file in listdir(args.folder_name)] # list the folders
#import all the files into a list of ImportData objects (in a loop!)
data_lst = []
for file in files_lst:
data_lst.append([file,ImportData(args.folder_name+'/'+file)])
#create two new lists of zip objects
# do this in a loop, where you loop through the data_lst
data_5 = [] # a list with time rounded to 5min
data_15 = [] # a list with time rounded to 15min
for data in data_lst:
if data[0] == 'activity_small.csv':
repeat_operation='sum'
elif data[0] == 'bolus_small.csv':
repeat_operation='sum'
elif data[0] == 'meal_small.csv':
repeat_operation='sum'
else:
repeat_operation = 'average'
data_5.append(roundTimeArray(data[1],5,repeat_operation))
data_15.append(roundTimeArray(data[1],15,repeat_operation))
#print to a csv file
printArray(data_5,files_lst,'5'+args.output_file,args.sort_key)
printArray(data_15, files_lst,'15'+args.output_file,args.sort_key)<file_sep>import numpy as np
import pandas as pd
import datetime as dt
import os
def import_data(filepath):
if not isinstance(filepath, str):
raise TypeError('import_data: filepath must be a string')
if filepath.endswith('.csv'):
data_frame = pd.read_csv(filepath)
return data_frame
else:
raise ImportError('import_data: filepath string must be csv')
def format_data(filename):
data_frame = import_data(filename)
data_frame['time'] = pd.to_datetime(data_frame['time'])
data_frame = data_frame.set_index('time')
data_frame = data_frame[data_frame['value'].apply(type) != str]
data_frame['value'].astype(float)
new_title = get_title(filename)
data_frame = data_frame.rename(columns={'value': new_title})
return data_frame
def get_title(filename):
sep1 = '/'
sep2 = '_'
text = filename.split(sep1, 2)[1]
text = text.split(sep2, 1)[0]
return text
def main():
data_frames = []
for filename in os.listdir('smallData'):
filepath = 'smallData/' + filename
data_frames.append(format_data(filepath))
df_key = data_frames[3]
del data_frames[3]
df = df_key.join(data_frames, how='outer')
df = df.fillna(0)
df['time5'] = df.index.round('5min')
df['time15'] = df.index.round('15min')
df = df[['cgm', 'activity', 'basal', 'bolus',
'hr', 'meal', 'smbg', 'time5', 'time15']]
df_5_sums = df[['activity', 'bolus', 'meal', 'time5']].groupby([
'time5']).sum()
df_5_means = df[['cgm', 'basal', 'hr', 'smbg', 'time5']].groupby([
'time5']).mean()
df_5 = df_5_means.join(df_5_sums, how='outer')
df_15_sums = df[['activity', 'bolus', 'meal', 'time15']].groupby([
'time15']).sum()
df_15_means = df[['cgm', 'basal', 'hr', 'smbg', 'time15']].groupby([
'time15']).mean()
df_15 = df_15_means.join(df_15_sums, how='outer')
df_5.to_csv('5min_data_pandas.csv')
df_15.to_csv('15min_data_pandas.csv')
if __name__ == '__main__':
main()
<file_sep>import unittest
import pandas_import
class TestImportData(unittest.TestCase):
def test_file_import(self):
self.assertRaises(TypeError, pandas_import.import_data,None)
self.assertRaises(ImportError, pandas_import.import_data,'data.txt')
self.assertRaises(FileNotFoundError, pandas_import.import_data,'fake_data.csv')<file_sep># time-series-basics
This code takes some data from the folder `smallData`, in the form of csvs, cleans it, and produces output csvs based on rounded times.
Usage: `python data_import.py --folder_name smallData/ --output_file 5out.csv --sort_key smallData/cgm_small.csv`
## Pandas
This is an improved version of the previous problem that uses `pandas` to solve the problem.
Usage: `python pandas_import.py`
This file takes all the csv files that are in the `smallData` folder, puts them all into pandas dataframes, then strips non-numerical values. These dataframes are then joined based on the time index for `cgm_small`. Then, the times are rounded and `groupby` is used to add or average each value accordingly. It then outputs these to csv files.
## Benchmarking
The benchmarks and results are as follows:
### Original
```
/usr/bin/time -f '%e\t%M' python data_import.py --folder_name smallData/ --output_file 5out.csv --sort_key
11.21 50468
```
### Pandas
```
/usr/bin/time -f '%e\t%M' python pandas_import.py
2.47 103060
```
This new version with pandas performs much better!
| f3d264ed29f8e8ab2f1fd8e5cea6d27771371713 | [
"Markdown",
"Python"
] | 5 | Python | cu-swe4s-fall-2019/time-series-basics-ocmadin | eeb6145a11c6f0eac1dbdf948932e4bf7a30a432 | 02ca4c1176f26ca51cfe7a1bdca9080c6fe25e3d |
refs/heads/master | <repo_name>clutterjoe/musical_markup<file_sep>/instrument.test.php
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>Musical Markup</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Viewport Scale -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS -->
<link rel="stylesheet" href="css/screen.css" />
</head>
<body>
<div id="display_char">
</div>
<span class="play_control">Pause</span>
<input type="range" id="set_bpm" min="60" max="150" />
<span id="cur_bpm"></span>bpm
<span class="markup_importer">
<textarea placeholder="Paste the markup here..." id="markup_content"><?php echo htmlspecialchars($str); ?></textarea><input type="button" value="SUBMIT" />
</span>
<!-- jquery -->
<script src="js/libs/jquery/jquery.js"></script>
<!-- modernizr -->
<script src="js/libs/modernizr/modernizr.js"></script>
<!-- underscore -->
<script src="js/libs/underscore/underscore.js"></script>
<!-- backbone -->
<script src="js/libs/backbone/backbone.js"></script>
<!-- app -->
<script src="js/models/drum.js"></script>
<script src="js/collections/drums.js"></script>
<script>
</script>
</body>
</html>
<file_sep>/js/collections/conductor.js
var Conductor = Backbone.Collection.extend({
// Begin object-scope variables.
// Backbone-required model setting.
model: Instrument, // Custom instrument, part of the package
// AudioContext object.
ac: null, // AudioContext
// Computer time values.
playTimer: 0, // the actual amount of time that has elapsed from the beginning of play
previousSampleTime: 0, // the amount of time between each loop around onaudioprocess. Gets set on play
// Both these values must be true in order to play the song.
currentlyPlaying: false, // Is the song currently playing?
readyToPlay: false, // Are all the instruments ready to play? (may need to load samples)
// Song time values
tempo: 120, // Default tempo
timeSignature: { // Default time signature is 4/4
top: 4,
bottom: 4
},
// AudioContext required values
masterVolume: 100, // The master volume
bufferSize: 1024, // The audio buffer, in samples
numOutputs: 2, // The number of audio outputs (stereo)
numInputs: 1, // The number of inputs, mandatory to avoid horrible noises
// This value may need to be changed so that all instruments have their own node. Currently all instruments share the same.
node: null, // AudioContext.createJavaScriptNode
// Play buffers hold all the notes that have been or are remaining to be played.
playBuffer: {}, // Items remaining to be played playBuffer[model.id] = [{... play buffer values ...}]
playBufferDone: {}, // Once played, items move from the playBuffer to here, restore to playBuffer on rewind
// Duration of notes as defined by the length of a meaure.
// This may need to be re-thought for alternate time signatures.
notes: {
w: 1,
hd: 0.75, // dotted half
h: 0.5, // half note
qd: 0.375, //dotted quarter
ht: 0.33333334, // triplet half
q: 0.25, // quarter note
ed: 0.1875, // dotted eighth
qt: 0.166666667, // quarter triplet
e: 0.125, // eighth
sd: 0.09375, // dotted sixteenth
et: 0.083333333, // eighth note triplet
s: 0.0625, // sixteenth note
st: 0.041666667, // triplet sixteenth
th: 0.03125 // thirty-second note
},
// End object-scope variables.
// Constructor
initialize: function() {
this.ac = this.audioContext || (new (window.AudioContext || window.webkitAudioContext));
this.node = this.ac.createJavaScriptNode(this.bufferSize, this.numInputs, this.numOutputs);
this.node.connect(this.ac.destination);
// Overcome scope.
var $this = this;
// Specify the audio generation function
this.node.onaudioprocess = function() {
$this.generateAudio();
};
},
// This is the function that plays audio
generateAudio: function() {
// check the play buffer for notes to be played
if (this.currentlyPlaying && this.isReadyToPlay) {
this.playTimer = this.playTimer + this.ac.currentTime - this.previousSampleTime;
for(i = 0; i < this.models.length; i++) {
}
}
this.previousSampleTime = this.ac.currentTime;
},
pause: function() {
this.currentlyPlaying = false;
},
play: function() {
this.currentlyPlaying = true;
},
setTempo: function() {
// When changing the tempo, you must shorten or
// lengthen the notes currently playing.
},
// Loads notes into a buffer to be played at the appropriate time.
loadBuffer: function(model_id, pitches, note_duration, velocity, automation) {
// Load the model specified in the arguments
var model = null;
for(i = 0; i < this.models.length; i++) {
if (this.models[i].id == model_id) {
model = this.models[i];
}
}
// If this is not a valid model, just return, we aren't playing anything.
if (model == null) {
return this;
}
// If there is currently no buffer set for this instrument, make one.
if (typeof(this.playBuffer[model.id]) != 'object') {
this.playBuffer[model.id] = [];
stTime = 0;
}
else {
lastItem = this.playBuffer[model.id][this.playBuffer[model.id].length-1];
stTime = lastItem.endTime;
}
endTime = stTime + this.notes[note_duration];
this.playBuffer[model.id][this.playBuffer[model.id].length] = {
stTime: stTime,
endPlayTime: endTime - model.getArticulationGap(),
endTime: endTime,
pitch: pitches,
velocity: velocity
};
console.log(this.playBuffer[model.id]);
return this;
},
// poll all the instruments to check if the band is ready
isReadyToPlay: function() {
this.readyToPlay = true;
return this.readyToPlay;
},
setTimeSignature: function(top, bottom) {
this.timeSignature.top = top;
this.timeSignature.bottom = bottom;
}
});
<file_sep>/js/collections/drums.js
var DrumSet = Backbone.Collection.extend(
{
model: DrumModel,
isReady: function() {
var ready = true;
for(i=0;i<this.models.length;i++) {
if (!this.models[i].isReady()) {
ready = false;
}
}
return ready;
},
play: function(cur_beat, measure, cur_char, cur_tag) {
var play_sounds = {};
var tom_tags = {} ;
var ride_tags = {} ;
ride_tags['meta'] = true;
tom_tags['script'] = true;
tom_tags['link'] = true;
tom_tags['img'] = true;
tom_tags['style'] = true;
if (cur_beat == 1) {
play_sounds['kik'] = true;
if (measure == 1) {
play_sounds['crash'] = true;
}
}
if (cur_beat == 5 || cur_beat == 13) {
play_sounds['snr'] = true;
}
if (cur_beat == 9) {
play_sounds['kik'] = true;
}
rexp = /[\.,-\/#$%\^&\*;:=\-_`~]/;
if (rexp.test(cur_char)) {
play_sounds['snr'] = true;
}
if (cur_char == '!') {
play_sounds['crash'] = true;
}
rexp = /[\(\)\{\}]/;
if (rexp.test(cur_char)) {
play_sounds['crash'] = true;
}
// if (cur_char == '=' || cur_char == '"' || cur_char == ':') {
// }
if (cur_char == '<' || cur_char == '>' || cur_char == '"') {
play_sounds['kik'] = true;
}
rexp = /^[0-9a-zA-Z]+$/
if(rexp.test(cur_char)){
if (tom_tags[cur_tag]) {
if (Math.floor(cur_beat / 2) != cur_beat / 2) {
rexp = /^[a-z]+$/
if(rexp.test(cur_char)){
play_sounds['tom_floor'] = true;
}
else {
play_sounds['tom1'] = true;
}
}
}
else {
if (ride_tags[cur_tag]) {
play_sounds['ride'] = true;
}
else {
play_sounds['hh'] = true;
}
}
}
rexp = /\s/;
if(rexp.test(cur_char)){
play_sounds = {};
}
if (play_sounds['snr']) {
play_sounds['kik'] = false;
}
for(drum in play_sounds) {
if (play_sounds[drum]) {
this.getModel(drum).playSound();
}
}
},
getModel: function(drum) {
for(i=0;i<this.models.length;i++) {
if (this.models[i].drum == drum) {
return this.models[i];
}
}
}
});
<file_sep>/js/views/scene.js
var SceneView = Backbone.View.extend({
events: {
'resize': 'sceneResize'
},
initialize: function() {
this.window = window;
this.scene = new THREE.Scene();
$this = this;
$(window).bind('resize', function() {
$this.sceneResize();
});
},
// Resize the view
sceneResize: function() {
}
});
<file_sep>/js/app.js
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audio_context = new AudioContext();
var kik = new DrumModel('kik', audio_context, ['audio/kik1.mp3']);
var snr = new DrumModel('snr', audio_context, ['audio/snr1.mp3','audio/snr2.mp3']);
var hh = new DrumModel('hh', audio_context, ['audio/hh1.mp3','audio/hh2.mp3','audio/hh3.mp3']);
var tom1 = new DrumModel('tom1', audio_context, ['audio/tom1.mp3', 'audio/tom2.mp3']);
var tom_floor = new DrumModel('tom_floor', audio_context, ['audio/tom_floor1.mp3', 'audio/tom_floor2.mp3']);
var crash = new DrumModel('crash', audio_context, ['audio/crash1.mp3', 'audio/crash2.mp3']);
var ride = new DrumModel('ride', audio_context, ['audio/ride1.mp3', 'audio/ride2.mp3']);
var drumSet = new DrumSet();
drumSet.add(kik);
drumSet.add(snr);
drumSet.add(hh);
drumSet.add(tom1);
drumSet.add(tom_floor);
drumSet.add(crash);
drumSet.add(ride);
var currentPlayTime = 0;
var totalPlayTime = 0;
var bpm = 110;
var cur_beat = 1;
var char_count = 0;
var char_tot = 0;
var markup = '';
var interval = Math.floor((1000 / 16) * (60 / bpm) * 4);
var measure = 1;
var play_state = true;
var cur_char = '';
var cur_tag = '';
function play() {
markup = $('#markup_content').val();
char_tot = markup.length;
if (markup == '') {
play_state = false;
return;
}
setTimeout(function() {
interval = Math.floor((1000 / 16) * (60 / bpm) * 4);
if (play_state == true) {
char_count += 1;
if (char_count >= char_tot) {
play_state = false;
return;
}
cur_char = '';
cur_char = markup.substring(char_count, char_count+1);
if (cur_char == '<') {
a = markup.substring(char_count + 1, markup.length).split(/[^A-Za-z]/);
cur_tag = a[0];
console.log(cur_tag);
}
$('#display_char').html(cur_char);
currentPlayTime += interval;
drumSet.play(cur_beat, measure, cur_char, cur_tag);
cur_beat++;
if (cur_beat > 16) {
cur_beat = 1;
measure++;
if (measure > 4) {
measure = 1;
}
}
play();
}
/*
if (cur_beat == 1 && measure == 1) {
crash.playSound();
}
else {
hh.playSound();
}
if (cur_beat == 1 || cur_beat == 9) {
kik.playSound();
}
if (cur_beat == 5 || cur_beat == 13 || cur_beat == 14) {
snr.playSound();
}
if (measure == 4){
if (cur_beat >= 10) {
rndm = Math.random();
if (rndm < 0.25) {
tom1.playSound();
}
else {
if (rndm < 0.5) {
tom_floor.playSound();
}
else {
if (rndm < 0.75) {
crash.playSound();
}
}
}
}
}
}
*/
}, interval);
}
function init() {
setTimeout(function() {
if (drumSet.isReady()) {
play();
} else {
console.log('drums not ready');
init();
}
}, 20);
}
init();
$(document).ready(function() {
$('.play_control').click(function () {
if ($(this).html() == 'Pause') {
$(this).html('Play');
play_state = false;
}
else {
$(this).html('Pause');
play_state = true;
}
});
$('#cur_bpm').html(bpm);
$('#set_bpm').val(bpm);
$('#set_bpm').change(function() {
bpm = $(this).val();
$('#cur_bpm').html($(this).val());
});
});
/*
hh = new DrumModel(audio_context, ['audio/kik1.mp3']);
snr = new DrumModel(audio_context, ['audio/kik1.mp3']);
tom1 = new DrumModel(audio_context, ['audio/kik1.mp3']);
tom_floor = new DrumModel(audio_context, ['audio/kik1.mp3']);
*/
<file_sep>/markup_interpreter.php
<?php
$str = '';
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>Musical Markup</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Viewport Scale -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS -->
<link rel="stylesheet" href="css/screen.css" />
</head>
<body>
<div id="display_char">
</div>
<span class="play_control">Pause</span>
<textarea placeholder="Paste the markup here..." id="markup_content"><?php echo htmlspecialchars($str); ?></textarea><input type="button" value="SUBMIT" />
<!-- jquery -->
<script src="js/libs/jquery/jquery.js"></script>
<script src="js/markup_interpreter.js"></script>
</body>
</html>
<file_sep>/js/collections/planets.js
var PlanetCollection = Backbone.Collection.extend(
{
model: PlanetModel,
animate: function(seconds_per_year, rotation_ratio, fps) {
for(i=0; i< this.models.length;i++) {
m = this.models[i];
m.animate(seconds_per_year, rotation_ratio, fps);
// rot_inc = fps * ;
// orbit_inc = fps * ;
}
},
getPlanet: function(planet_id) {
for(var planet_key in this.models) {
if (this.models[planet_key].planet_id == planet_id) {
return this.models[planet_key];
}
}
return null;
},
addPlanetsToScene: function(scene) {
for(var planet_key in this.models) {
//console.log(this.models[planet_key].planet_id + ' = ' + this.models[planet_key].parent_planet);
if (this.models[planet_key].parent_planet == null) {
scene.add(this.models[planet_key].vector);
}
else {
this.models[planet_key].parent_planet.vector.add(this.models[planet_key].vector);
console.log('goo');
console.log(this.models[planet_key].parent_planet);
}
}
}
});
<file_sep>/js/views/camera.js
var CameraView = Backbone.View.extend({
model: CameraModel,
initialize: function() {
this.perspective = this.model.perspective;
},
trackMouseMovement: function(domElement) {
/*
$this = this;
radius = this.model.distance;
$(domElement).mousedown(function(e) {
$this.model.onMouseDownPosition.x = e.clientX;
$this.model.onMouseDownPosition.y = e.clientY;
$this.model.onMouseDownTheta = $this.model.theta;
$this.model.onMouseDownPhi = $this.model.phi;
$(this).mousemove(function(e) {
xAmt = e.clientX - $this.model.onMouseDownPosition.x;
yAmt = e.clientY - $this.model.onMouseDownPosition.y;
radius = $this.model.distance;
theta = - ( ( xAmt ) * 0.5 ) + $this.model.onMouseDownTheta;
phi = ( ( yAmt ) * 0.5 ) + $this.model.onMouseDownPhi;
$this.model.perspective.position.x = $this.model.perspective.position.x + radius * Math.sin( theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );
$this.model.perspective.position.y = $this.model.perspective.position.y + radius * Math.sin( phi * Math.PI / 360 );
$this.model.perspective.position.z = $this.model.perspective.position.z + radius * Math.cos( theta * Math.PI / 360 ) * Math.cos( phi * Math.PI / 360 );
$this.model.perspective.updateMatrix();
});
});
$(domElement).mouseup(function(e) {
$(this).unbind('mousemove');
});
*/
},
animate: function(event) {
this.model.updateLookAt();
},
updateLookAt: function(lookAtObject) {
this.model.setLookAt(lookAtObject);
// console.log(lookAtObject);
}
});
<file_sep>/js/markup_interpreter.js
var ObjectifyMarkup = function(markup) {
// set up object attributes
$jqObj = $(markup);
this.return_obj = {
tag: $jqObj[0].localName,
tag_attributes: [],
source: markup,
inner_content: $jqObj.html(),
children: []
};
// get attributes
var attrMap = $jqObj[0].attributes;
$.each(attrMap, function(i, e) {
console.log(this.return_obj.tag_attributes);
console.log(e);
this.return_obj.tag_attributes[this.return_obj.tag_attributes.length] = e;
});
console.log(this.tag_attributes);
// get children
for(child in $jqObj[0].children) {
if (typeof($jqObj[0].children[child]) == 'object') {
this.return_obj.children[this.return_obj.children.length] = new ObjectifyMarkup($jqObj[0].children[child]);
}
}
return this.return_obj;
};
(function($) {
console.log('start app');
var markup = $('#markup_content').val();
var markup = '<div><div id="tmp_wrapper" class="classy super_classy"><h1>Above paragraph</h1><p>This is the content <span>within</span> a div</p></div><div>Other div</div></div>';
var obj = new ObjectifyMarkup(markup);
console.log(obj);
})(jQuery);
<file_sep>/js/models/drum.js
var DrumModel = Backbone.Model.extend({
defaults: {
audio_context: null,
sound_files: [],
audio: [],
ready: []
},
constructor: function(drum, audio_context, sound_files) {
this.drum = drum;
this.audio_context = audio_context;
this.sound_files = sound_files;
this.audio = [];
this.ready = false;
this.gainNode = audio_context.createGain();
var callback = [];
var $this = this;
for (i=0;i<this.sound_files.length;i++) {
this.loadSound(this.sound_files[i], i);
}
},
isReady: function() {
return this.ready;
},
loadSound: function(sound_file, index) {
var request = new XMLHttpRequest();
var $this = this;
request.open('GET', sound_file, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
audio_context.decodeAudioData(request.response, function(buffer) {
$this.audio[index] = buffer;
if ($this.audio.length == $this.sound_files.length) {
$this.ready = true;
}
});
}
request.send();
},
playSound: function (velocity) {
// humanize the beat
min_delay = 0;
max_delay = 17;
delay = Math.floor(Math.random() * max_delay);
max_gain = 1;
min_gain = 0.0;
gain = Math.random() * (max_gain - min_gain ) + min_gain;
gainNode = audio_context.createGain();
gainNode.gain.value = gain;
audio_key = 0; // Math.floor(velocity / Math.floor(127 / this.audio.length));
audio_key = Math.floor(Math.random() * this.audio.length);
var source = audio_context.createBufferSource(); // creates a sound source
source.buffer = this.audio[audio_key]; // tell the source which sound to play
source.connect(audio_context.destination); // connect the source to the context's destination (the speakers)
source.connect(gainNode);
setTimeout(function() {
source.start(0); // play the source now
}, delay);
}
});
| a2b612e6395678f24cfb42a3511990f877a9c978 | [
"JavaScript",
"PHP"
] | 10 | PHP | clutterjoe/musical_markup | 23c86aeca0f879a7264a88bf2debb67d18947d7a | 794d0e0e83e2f167761b2edbd4498e995c00fcac |
refs/heads/master | <repo_name>shihaosun2013/WorkdayMeal<file_sep>/src/main/java/com/workdaymeals/model/FoodItem.java
package com.workdaymeals.model;
public class FoodItem {
}
<file_sep>/src/main/java/com/workdaymeals/persistence/GuestDao.java
package com.workdaymeals.persistence;
import com.workdaymeals.model.Guest;
import org.jdbi.v3.sqlobject.config.RegisterConstructorMapper;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import java.util.List;
public interface GuestDao {
@SqlUpdate("INSERT INTO guest values (:uuid, :deliverAddressId)")
void insert(@BindBean Guest guest);
@SqlUpdate("INSERT INTO guest(uuid) values (:uuid)")
void insertId(@BindBean Guest guest);
@SqlQuery("SELECT * FROM guest")
@RegisterConstructorMapper(Guest.class)
List<Guest> listGuests();
}<file_sep>/src/main/java/com/workdaymeals/persistence/UserDao.java
package com.workdaymeals.persistence;
import com.workdaymeals.model.User;
import org.jdbi.v3.sqlobject.config.RegisterConstructorMapper;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.customizer.BindFields;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import java.util.List;
public interface UserDao {
@SqlUpdate("INSERT INTO user(username, first_name, last_name, password, email, email_bind, mobile, mobile_bind)" +
" VALUES (:username, :firstName, :lastName, :password, :email, :emailBind, :mobile, :mobileBind)")
void insert(@BindBean User user);
@SqlQuery("SELECT * FROM user")
@RegisterConstructorMapper(User.class)
List<User> listUsers();
@SqlQuery("SELECT * FROM user WHERE username = :username")
@RegisterConstructorMapper(User.class)
User getUserByUserName(String username);
@SqlUpdate("UPDATE user set email = :email where username = :username")
void update(@BindBean User user);
}<file_sep>/Readme.txt
a profile description, a phone number, 3 event pictures or more, a complete address (street number, street)
Authentication:
http://javaeeeee.blogspot.com/2015/02/getting-started-with-dropwizard.html
sudo /usr/local/mysql/support-files/mysql.server stop
mvn liquibase:updateSQL
mvn liquibase:generateChangeLog
mvn liquibase:update
mvn liquibase:clearCheckSums
mvn liquibase:dropAll liquibase:update
Write code
Find you need a database change
Append new changeSet to db.changelog.xml
liquibase.bat update
Test code and database
Repeat 1-4 as necessary
Update local codebase from version control
liquibase.bat update to apply changes from other developers
Repeat 1-8 as necessary
Commit your code and db.changelog.xml to version control
When ready, update QA database with db.changelog.xml built up during development
When ready, update production database with db.changelog.xml built up during development
https://github.com/benjamin-bader/droptools/tree/master/dropwizard-jooq
List<UserJDBI> userNames = jdbi.withExtension(UserJDBIDao.class, dao -> {
System.out.println(1123);
dao.dropTable();
dao.createTable();
dao.insertPositional(0, "Alice");
dao.insertPositional(1, "Bob");
List<String> names = jdbi.withHandle(handle -> handle.createQuery("select name from user")
.mapTo(String.class)
.list());
System.out.println(names);
Handle handle = jdbi.open();
Optional<String> name = handle.createQuery("select name from user where id = :id")
.bind("id", 1)
.mapTo(String.class)
.findFirst();
System.out.println(name.get());
dao.insertNamed(2, "Clarice");
handle.registerRowMapper(ConstructorMapper.factory(UserJDBI.class));
Set<UserJDBI> userSet = handle.createQuery("SELECT * FROM user ORDER BY id ASC")
.mapTo(UserJDBI.class)
.collect(Collectors.toSet());
System.out.println(userSet);
// handle.registerRowMapper(BeanMapper.factory(UserJDBI.class));
// List<UserJDBI> users = handle
// .createQuery("select id, name from user")
// .mapToBean(UserJDBI.class)
// .list();
//
// System.out.println(users.size());
System.out.println(dao.findName(1).get());
UserJDBI user = dao.getUser(1);
System.out.println(dao.listUsers());
return dao.listUsers();
});
public List<User> getAll() {
return ImmutableList.of(User.builder().userName("happyshihao").build());
}
public User getById(int id) {
return User.builder().userName("happyshihao").build();
}
public String getCount() {
return "7";
}
public void remove() {
}
public String save(User person) {
return "Done";
}
https://xvik.github.io/dropwizard-guicey/4.1.0/getting-started/
@SqlUpdate("INSERT INTO user(id, name) VALUES (?, ?)")
void insertPositional(int id, String name);
@SqlUpdate("INSERT INTO user(id, name) VALUES (:id, :name)")
void insertNamed(@Bind("id") int id, @Bind("name") String name);
@SqlUpdate("INSERT INTO `user` (username, first_name, last_name, password, email, email_bind, mobile, mobile_bind, create_time, update_time, last_login_time, status, is_delete)\n" +
"VALUES ('happycora','shihao', 'shihao', '<PASSWORD>', '<EMAIL>', 1, '2133998198', 0, now(), now(), now(), 1, 0)")
void insert(@BindBean User user);<file_sep>/src/main/java/com/workdaymeals/model/Test.java
package com.workdaymeals.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@Builder(builderClassName = "Builder", toBuilder = true)
@AllArgsConstructor
public class Test {
private int id;
private String name;
}
<file_sep>/src/main/java/com/workdaymeals/module/WorkdayMealsModule.java
package com.workdaymeals.module;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.workdaymeals.config.WorkdayMealsConfig;
import com.workdaymeals.persistence.UserDao;
import com.workdaymeals.resources.rest.GuestResource;
import com.workdaymeals.resources.rest.UserResource;
import io.dropwizard.jdbi3.JdbiFactory;
import io.dropwizard.setup.Environment;
import lombok.extern.slf4j.Slf4j;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
@Slf4j
public class WorkdayMealsModule extends AbstractModule {
private final WorkdayMealsConfig config;
private final Environment environment;
public WorkdayMealsModule(WorkdayMealsConfig config, Environment environment) {
this.config = config;
this.environment = environment;
}
@Override
protected void configure() {
bind(UserResource.class).in(Singleton.class);
bind(GuestResource.class).in(Singleton.class);
}
@Provides
@Singleton
@Named("jdbi")
public Jdbi getJdbi() {
final JdbiFactory factory = new JdbiFactory();
final Jdbi jdbi = factory.build(environment, config.getDataSourceFactory(), "mysql");
jdbi.installPlugin(new SqlObjectPlugin());
return jdbi;
}
@Provides
@Singleton
public UserDao getUserDao(@Named("jdbi") Jdbi jdbi) {
return jdbi.onDemand(UserDao.class);
}
}
<file_sep>/liquibase.properties
url=jdbc:mysql://localhost:3306/workday_meals
username=root
password=<PASSWORD>
driver=com.mysql.jdbc.Driver
outputChangeLogFile=src/main/resources/outputChangeLog.xml
changeLogFile=src/main/resources/changeLog.xml
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.workdaymeals</groupId>
<artifactId>workdaymeals</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<dropwizard.version>1.3.1</dropwizard.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jdbi3</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-auth</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views-freemarker</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-assets</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.dropwizard/dropwizard-jdbi -->
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jdbi</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>org.jdbi</groupId>
<artifactId>jdbi3-sqlobject</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.jdbi</groupId>
<artifactId>jdbi3-guava</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>3.10.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jooq/jooq -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.10.6</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.workdaymeals.app.WorkdayMealsApp</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>3.4.1</version>
<configuration>
<propertyFile>liquibase.properties</propertyFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project> | 10f1fd2a6747f7ae86df95fb1d01f168af637720 | [
"Java",
"Text",
"Maven POM",
"INI"
] | 8 | Java | shihaosun2013/WorkdayMeal | 93f6f5ddfbaf06fe09039cfce0cfef0771dbadd7 | 88d5efe26230934fc1abe0d89874dcdcb322c026 |
refs/heads/main | <repo_name>Bashrc-007/Hex2Str<file_sep>/hex2Str.sh
#!/bin/sh
read -p "Paste the IsErIk Hex value here:" text
if ! [[ $text =~ ^[0-9A-Fa-f]+$ ]] ; then
echo "Unable to decode, string is not hex"
else
text1=$(echo $text | xxd -r -p | awk '{print $1}')
echo "string contains hex => $text1"
fi
<file_sep>/README.md
# Hex2Str
IsErIk Adware decoder | Hex to String
Run:
```
\> chmod +x Hex2Str.sh
\>. Hex2Str.sh
```
Requirement:
```
xxd
```
| b4c918158b889e4e43143100c8a6d8aa73f84f2c | [
"Markdown",
"Shell"
] | 2 | Shell | Bashrc-007/Hex2Str | f97756ec1fbfca0b8972deba120077d293f0e010 | c7384fe83d17efc2ba6208bf517bb95953d929ba |
refs/heads/master | <repo_name>yangruofeng/fri_community<file_sep>/framework/api_test/apis/microbank/member.login_account.is.exist.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/27
* Time: 14:12
*/
class memberLogin_accountIsExistApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Account Is Exist";
$this->description = "会员登陆账号是否存在";
$this->url = C("bank_api_url") . "/member.login_account.is.exist.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("login_code", "登陆账号", 'test', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'is_exist' => '0 不存在 1 已经存在'
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.resident.book.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div-1">
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Resident Book</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info" style="display: none">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<input type="hidden" name="resident_book_front" value="">
<input type="hidden" name="resident_book_back" value="">
</form>
<div class="snapshot_div" id="resident_book_front" onclick="callWin_snapshot_master('resident_book_front');">
<img src="resource/img/member/photo.png">
<div>Frontal resident book image</div>
</div>
<div class="snapshot_div" id="resident_book_back" onclick="callWin_snapshot_master('resident_book_back');">
<img src="resource/img/member/photo.png">
<div>Back resident book image</div>
</div>
<div class="snapshot_msg error_msg">
<div class="resident_book_front"></div>
<div class="resident_book_back"></div>
</div>
</div>
</div>
<div class="operation">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
function callWin_snapshot_master(type){
if(window.external){
try{
var _img_path= window.external.getSnapshot("0");
if(_img_path!="" && _img_path!=null){
_img_path = getUPyunImgUrl(_img_path);
$("#" + type + " img").attr("src", _img_path);
$('input[name="' + type + '"]').val(_img_path);
}
}catch (ex){
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveResidentBookAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
var name = $(element).attr('name');
if (name == 'resident_book_front' || name == 'resident_book_back') {
error.appendTo($('.snapshot_msg .' + name));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
resident_book_front : {
required : true
},
resident_book_back : {
required : true
}
},
messages : {
resident_book_front : {
required : 'Frontal resident book image must be uploaded!'
},
resident_book_back : {
required : 'Back resident book image must be uploaded!'
}
}
});
</script><file_sep>/framework/weixin_baike/api/control/help.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 10:44
*/
class helpControl extends bank_apiControl
{
public function getHelpCategoryOp()
{
$category = (new helpCategoryEnum())->Dictionary();
return new result(true, '', $category);
}
public function getHelpListOp()
{
$params = array_merge(array(), $_GET, $_POST);
$m_common_cms = M('common_cms');
$re = $m_common_cms->getHelpList($params);
return $re;
}
public function helpDetailOp()
{
$params = array_merge(array(), $_GET, $_POST);
$m_common_cms = M('common_cms');
$uid = intval($params['uid']);
$re = $m_common_cms->getHelpDetail($uid);
return $re;
}
}
<file_sep>/framework/test/inc.app.php
<?php
/**
* Created by PhpStorm.
* User: tim
* Date: 5/1/2015
* Time: 8:26 PM
*/
//初始化yo
require_once(BASE_CORE_PATH . "/ormYo.php");
require_once(BASE_CORE_PATH . "/Yo.php");
$dsn = $GLOBALS['config']['db_conf'];//getConf('db_conf');
ormYo::setup($dsn);
ormYo::$default_db_key = "db_point";
ormYo::$lang_current = "en";
ormYo::$freez = !$GLOBALS['config']['debug'];//==true;//是否冻结
ormYo::$log_path = _LOG_;//日志路径
//ormYo::$IDField="uid";//表的自增列
ormYo::$schema_path = _DATA_SCHEMA_ . "/";//datasource保存路径
ormYo::$lang_a = getLangTypeList();
require_once(_APP_COMMON_ . "/define_enum.php");
global $config;
define('GLOBAL_RESOURCE_SITE_URL', $config['global_resource_site_url']);
define('PROJECT_RESOURCE_SITE_URL', $config['project_resource_site_url']);
define('CURRENT_RESOURCE_SITE_URL', "resource"); // 直接使用resource目录
define('UPLOAD_SITE_URL', $config['upload_site_url']);
define('ATTACH_AVATAR', 'shop/avatar');
define('ATTACH_COMMON', 'shop/common');
define('DESKTOP_SITE_URL', $config['desktop_site_url']);
define('API_SITE_URL', $config['api_site_url']);<file_sep>/framework/weixin_baike/mobile/control/index.php
<?php
/**
* Created by PhpStorm.
* User: hh
* Date: 2018/3/18
* Time: 下午 2:36
*/
class indexControl extends baseControl
{
public function indexOp()
{
echo 'Hello';
}
}<file_sep>/framework/api_test/apis/microbank/credit.loan.index.page.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/12
* Time: 14:12
*/
// credit.loan.index.page
class creditLoanIndexPageApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Credit Loan Index";
$this->description = "信用贷主页";
$this->url = C("bank_api_url") . "/credit.loan.index.page.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'product_id' => '信用贷产品id',
'credit_info' => array(
'is_active' => '是否激活(可用) 0 未激活 1 激活',
'credit' => '信用值',
'balance' => '信用余额',
'evaluate_time' => '最后授信时间,没有为null',
'credit_process' => array(
'@description' => '激活详情',
'fingerprint' => array(
'@description' => '指纹',
'is_check' => '是否需要录入指纹 1 是 0否',
'is_complete' => '是否完成 1 完成 0 未完成',
),
'authorized_contract' => array(
'@description' => '授权合同',
'is_check' => '是否需要签订授权合同 1 是 0否',
'is_complete' => '是否完成 1 完成 0 未完成',
)
)
),
'monthly_min_rate' => '最低月利率',
'next_repayment_schema' => array(
'@description' => '下期应还款计划,没有为null',
'uid' => '计划ID',
'contract_id' => '合同ID',
'next_repayment_amount' => '应还款金额',
'currency' => '币种',
)
// 'rate_list' => array(
//
// 'total_num' => '总条数',
// 'total_pages' => '总页数',
// 'current_page' => '当前页',
// 'page_size' => '每页条数',
// 'list' => array(
// array(
// 'uid' => '利率ID',
// 'product_id' => '产品id',
// 'currency' => '币种',
// 'loan_size_min' => '最低贷款金额',
// 'loan_size_max' => '最高贷款金额',
// 'repayment_type' => '还款方式',
// 'repayment_period' => '还款周期,只有分期付款才有',
// 'loan_term_time' => '可贷款时间周期',
// 'interest_rate_des_value' => '利息利率值',
// 'interest_rate_unit' => '利息利率周期',
// 'operation_fee_des_value' => '运营费利率值',
// 'operation_fee_unit' => '运营费利率周期',
// )
// )
// )
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.family.book.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div-1">
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Family Book</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info" style="display: none">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<input type="hidden" name="family_book_front" value="">
<input type="hidden" name="family_book_back" value="">
<input type="hidden" name="family_book_household" value="">
</form>
<div class="snapshot_div" id="family_book_front" onclick="callWin_snapshot_master('family_book_front');">
<img src="resource/img/member/photo.png">
<div>Frontal family book image</div>
</div>
<div class="snapshot_div" id="family_book_back" onclick="callWin_snapshot_master('family_book_back');">
<img src="resource/img/member/photo.png">
<div>Frontal family book image</div>
</div>
<div class="snapshot_div" id="family_book_household" onclick="callWin_snapshot_master('family_book_household');">
<img src="resource/img/member/photo.png">
<div>Back family book image</div>
</div>
<div class="snapshot_msg error_msg">
<div class="family_book_front"></div>
<div class="family_book_back"></div>
<div class="family_book_household"></div>
</div>
</div>
</div>
<div class="operation">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
function callWin_snapshot_master(type){
if(window.external){
try{
var _img_path = window.external.getSnapshot("0");
if (_img_path != "" && _img_path != null) {
_img_path = getUPyunImgUrl(_img_path);
$("#" + type + " img").attr("src", _img_path);
$('input[name="' + type + '"]').val(_img_path);
}
} catch (ex) {
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveFamilyBookAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
var name = $(element).attr('name');
if (name == 'family_book_front' || name == 'family_book_back' || name == 'family_book_household') {
error.appendTo($('.snapshot_msg .' + name));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
family_book_front : {
required : true
},
family_book_back : {
required : true
},
family_book_household : {
required : true
}
},
messages : {
family_book_front : {
required : 'Frontal family book image must be uploaded!'
},
family_book_back : {
required : 'Back family book image must be uploaded!'
},
family_book_household : {
required : 'Household family book image image must be uploaded!'
}
}
});
</script><file_sep>/framework/weixin_baike/backoffice/language/en/tools.php
<?php
$lang['task_state_0'] = 'Create';
$lang['task_state_10'] = 'Sending';
$lang['task_state_11'] = 'Send Failed';
$lang['task_state_20'] = 'Send Success';
$lang['task_state_30'] = 'Cancel';
<file_sep>/framework/api_test/apis/officer_app/officer.get.member.cert.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 16:43
*/
// officer.get.member.cert.detail
class officerGetMemberCertDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Cert result";
$this->description = "会员各项认证结果";
$this->url = C("bank_api_url") . "/officer.get.member.cert.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("type", "类型 1 身份证 2 户口本 3 护照 4 房产 5 汽车资产 6 工作证明 7 公务员(合在工作)8 家庭关系证明 9 土地", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => 'cert_result 基础信息(家庭关系没有返回) extend_info 扩展信息(家庭关系-》多条,工作证明有)',
'cert_result' => array(
'uid' => '基础认证id',
'cert_type' => '类型',
'cert_name' => '证件上名字',
'cert_sn' => '证件号码',
'cert_addr' => '证件地址',
'cert_expire_time' => '过期时间',
'source_type' => '资料来源',
'verify_remark' => '审核备注',
'verify_state' => '审核结果 -1 审核中 0未审核,10审核通过,100审核未通过',
),
'extend_info' => array(
array(
'@description' => '家庭关系格式,可能是多条的',
'uid' => '扩展认证id',
'cert_id' => '基础认证id',
'relation_type' => '关系类型',
'relation_name' => '关系人名字',
'relation_cert_type' => '关系人证件类型',
'relation_cert_photo' => '关系人证件照片',
'relation_cert_sn' => '关系人证件号码',
'relation_phone' => '关系人电话',
'relation_state' => '审核状态,0=>创建,10=>无效,11=>解除,100=>核准',
),
array(
'@description' => '工作证明',
'uid' => '扩展认证id',
'cert_id' => '基础认证id',
'company_name' => '公司名称',
'company_addr' => '公司地址',
'position' => '职位',
'month_salary' => '月薪',
'is_government' => '是否政府员工',
'state' => '认证状态 0 新建 10 审核中 20 当前active 30 历史',
)
),
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.set.trading.password.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/19
* Time: 14:57
*/
// member.set.trading.password
class memberSetTradingPasswordApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Set trading password";
$this->description = "会员设置交易密码";
$this->url = C("bank_api_url") . "/member.set.trading.password.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("login_password", "<PASSWORD>", '', true);
$this->parameters[]= new apiParameter("id_no", "身份证最后4位", 'xxxx', true);
$this->parameters[]= new apiParameter("trading_password", "<PASSWORD>", '', true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.prepayment.add.payment.info.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/22
* Time: 16:10
*/
// loan.contract.prepayment.add.payment.info
class loanContractPrepaymentAddPaymentInfoApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Prepayment add payment info";
$this->description = "提前还款申请补充还款信息";
$this->url = C("bank_api_url") . "/loan.contract.prepayment.add.payment.info.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("request_id", "申请id", 1, true);
$this->parameters[]= new apiParameter("amount", "还款金额", 500, true);
$this->parameters[]= new apiParameter("currency", "还款货币", 'USD', true);
$this->parameters[]= new apiParameter("repayment_way", "还款的方式,0 线下银行转账 1 绑定的账户自动扣款", 0, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->parameters[]= new apiParameter("name", "线下银行转账方式参数,个人账户名字", 'test');
$this->parameters[]= new apiParameter("account", "线下银行转账方式参数,个人账户账号", '3658745512');
$this->parameters[]= new apiParameter("country_code", "线下银行转账方式参数,国家码", '855');
$this->parameters[]= new apiParameter("phone", "线下银行转账方式参数,电话号码", '85625415');
$this->parameters[]= new apiParameter("company_account_id", "线下银行转账方式参数,公司账户id", 1);
$this->parameters[]= new apiParameter("handler_id", "绑定账户自动扣款方式参数,绑定的账户id", 1);
$this->parameters[]= new apiParameter("receipt_image", "转账回执,文件流", '');
$this->parameters[]= new apiParameter("remark", "备注", '');
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => ''
);
}
}<file_sep>/framework/api_test/apis/officer_app/co.sign.in.footprint.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/28
* Time: 14:02
*/
class coSignInFootprintApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "CO sign in footprint";
$this->description = "签到记录";
$this->url = C("bank_api_url") . "/co.sign.in.footprint.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1, true);
$this->parameters[]= new apiParameter("date", "日期,yyyy-mm-dd格式", '2018-02-28', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '记录列表,没有为null',
array(
'coord_x' => '经度',
'coord_y' => '纬度',
'location' => '地理位置',
'sign_time' => '签到时间',
'remark' => '备注'
)
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.land.property.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/magnifier/magnifier.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div-1">
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Land Property</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info" style="display: none;">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<input type="hidden" name="land_property_card" value="">
<input type="hidden" name="land_trading_record" value="">
</form>
<div class="snapshot_div" id="land_property_card" onclick="callWin_snapshot_master('land_property_card');">
<img src="resource/img/member/photo.png">
<div>Land Property</div>
</div>
<div class="snapshot_div" id="land_trading_record" onclick="callWin_snapshot_master('land_trading_record');">
<img src="resource/img/member/photo.png">
<div>Land Transaction Table</div>
</div>
<div class="snapshot_msg error_msg">
<div class="land_property_card"></div>
<div class="land_trading_record"></div>
</div>
</div>
</div>
<div class="operation" style="margin-bottom: 40px">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
<div class="certification-history">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Certification History</h5>
</div>
<div class="content">
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/magnifier/magnifier.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
$(document).ready(function () {
btn_search_onclick();
});
function callWin_snapshot_master(type){
if(window.external){
try{
var _img_path= window.external.getSnapshot("0");
if(_img_path!="" && _img_path!=null){
_img_path = getUPyunImgUrl(_img_path);
$("#" + type + " img").attr("src", _img_path);
$('input[name="' + type + '"]').val(_img_path);
}
}catch (ex){
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 10;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var uid = $('input[name="client_id"]').val();
var cert_type = '<?php echo certificationTypeEnum::LAND;?>';
yo.dynamicTpl({
tpl: "member/history.list",
control: "counter_base",
dynamic: {
api: "member",
method: "getCertificationList",
param: {pageNumber: _pageNumber, pageSize: _pageSize, uid: uid, cert_type: cert_type}
},
callback: function (_tpl) {
$(".certification-history .content").html(_tpl);
}
});
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveLandPropertyAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
var name = $(element).attr('name');
if (name == 'land_property_card' || name == 'land_trading_record') {
error.appendTo($('.snapshot_msg .' + name));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
land_property_card : {
required : true
},
land_trading_record : {
required : true
}
},
messages : {
land_property_card : {
required : 'Land property image must be uploaded!'
},
land_trading_record : {
required : 'Land transaction table image must be uploaded!'
}
}
});
</script><file_sep>/framework/api_test/apis/microbank/system.company.receive.account.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/12
* Time: 11:19
*/
// system.company.receive.account
class systemCompanyReceiveAccountApiDocument extends apiDocument
{
function __construct()
{
$this->name = "Company Global Receive Bank Account";
$this->description = "公司对外收钱银行账户";
$this->url = C("bank_api_url") . "/system.company.receive.account.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("currency", "币种", null, false);
// currency
$str = '{"STS":true,"MSG":"success","DATA":[{"uid":"1","bank_code":"wing","currency":"USD","bank_name":"wing","bank_account_no":"23658745","bank_account_name":"test","bank_address":"","bank_account_phone":"+8558654874"},{"uid":"2","bank_code":"wing","currency":"KHR","bank_name":"wing","bank_account_no":"3698574511","bank_account_name":"test2","bank_address":"","bank_account_phone":"+8551254874"}],"CODE":200,"logger":[]}';
$re = @json_decode($str,true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
array(
'uid' => '',
'bank_code' => '银行编码',
'currency' => '账户币种',
'bank_name' => '银行名称',
'bank_account_no' => '账户账号',
'bank_account_name' => '账户名字',
'bank_address' => '账户银行所在地址',
'bank_account_phone' => '账户联系电话',
)
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/register.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="register-div">
<div class="basic-info">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Basic Information</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info">
<input type="hidden" name="member_image" value="">
<input type="hidden" name="verify_id" value="">
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Mobile Phone</label>
<div class="col-sm-8">
<div class="input-group">
<span class="input-group-addon" style="padding: 0;border: 0;">
<select class="form-control" name="country_code" style="min-width: 80px;height: 30px">
<option value="855">+855</option>
<option value="66">+66</option>
<option value="86">+86</option>
</select>
</span>
<input type="text" class="form-control" name="phone" value="">
<span class="input-group-addon" style="padding: 0;border: 0;" >
<a class="btn btn-default" id="btnSendCode" style="width: 60px;height: 30px;padding:5px 12px;border-radius: 0" onclick="send_verify_code()">Send</a>
</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-5 control-label"><span class="required-options-xing">*</span>Login Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" name="login_password" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Verify Code</label>
<div class="col-sm-8">
<input type="number" class="form-control" name="verify_code" value="" maxlength="6">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-5 control-label"><span class="required-options-xing">*</span>Confirm Login Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" name="confirm_login_password" confirm_name="login_password" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Login Account</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="login_account" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-5 control-label"><span class="required-options-xing">*</span>Trading Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" name="trading_password" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Marital Status</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" name="civil_status" value="1" checked>Married
</label>
<label class="radio-inline">
<input type="radio" name="civil_status" value="0">Single
</label>
<label class="radio-inline">
<input type="radio" name="civil_status" value="2">Divorce
</label>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-5 control-label"><span class="required-options-xing">*</span>Confirm Trading Password</label>
<div class="col-sm-7">
<input type="password" class="form-control" name="confirm_trading_password" confirm_name="trading_password" value="">
<div class="error_msg"></div>
</div>
</div>
</form>
</div>
</div>
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Scene Photo</h5>
</div>
<div class="content">
<div class="snapshot_div" onclick="callWin_snapshot_slave();">
<img id="img_slave" src="resource/img/member/photo.png">
</div>
<div class="snapshot_msg error_msg" style="margin-left: 15px;float: left;background-color: #FFF"></div>
</div>
</div>
<div class="operation">
<button class="btn btn-default" onclick="reset_form()">Reset</button>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
var InterValObj; //timer变量,控制时间
var count = 30; //间隔函数,1秒执行
var curCount;//当前剩余秒数
function callWin_snapshot_slave() {
if (window.external) {
try {
var _img_path = window.external.getSnapshot("1");
if (_img_path != "" && _img_path != null) {
_img_path = getUPyunImgUrl(_img_path);
$("#img_slave").attr("src", _img_path);
$('input[name="member_image"]').val(_img_path);
}
} catch (ex) {
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
function send_verify_code() {
var country_code = $('select[name="country_code"]').val();
var phone = $('input[name="phone"]').val();
phone = $.trim(phone);
if (!phone) {
return;
}
curCount = count;
$("#btnSendCode").attr("disabled", "true");
$("#btnSendCode").html(curCount + "S");
InterValObj = window.setInterval(SetRemainTime, 1000);
yo.loadData({
_c: "member",
_m: "sendVerifyCodeForRegister",
param: {country_code: country_code, phone: phone},
callback: function (_o) {
if (_o.STS) {
$('input[name="verify_id"]').val(_o.DATA.verify_id);
} else {
alert(_o.MSG);
window.clearInterval(InterValObj);//停止计时器
$("#btnSendCode").attr("disabled", false);//启用按钮
$("#btnSendCode").html("Send");
}
}
});
}
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btnSendCode").attr("disabled", false);//启用按钮
$("#btnSendCode").html("Send");
} else {
curCount--;
$("#btnSendCode").html(curCount + "s");
}
}
function reset_form() {
$('#basic-info input[type!="radio"]').val('');
$('#basic-info input[name="civil_status"][value="1"]').prop('checked', true);
$('#basic-info select[name="country_code"]').val(855);
$("#img_slave").attr("src", "resource/img/member/photo_default.png");
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'registerClient',
param: values,
callback: function (_o) {
if (_o.STS) {
reset_form();
alert(_o.MSG);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
if ($(element).attr('name') == 'member_image') {
error.appendTo($('.snapshot_msg'));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
phone : {
required : true
},
verify_code : {
required : true
},
login_account : {
required : true,
chkAccount : true
},
member_image : {
required : true
},
login_password : {
required : true,
checkPwd : true
},
confirm_login_password : {
required : true,
verifyPwd : true
},
trading_password : {
required : true,
checkPwd : true
},
confirm_trading_password : {
required : true,
verifyPwd : true
}
},
messages : {
phone : {
required : 'Required'
},
verify_code : {
required : 'Required'
},
login_account : {
required : 'Required',
chkAccount : 'Account number one must be the letter, and the length is between 5 and 12.'
},
member_image : {
required : 'Required'
},
login_password : {
required : 'Required',
checkPwd : '<PASSWORD> <PASSWORD>.'
},
confirm_login_password : {
required : 'Required',
verifyPwd : '<PASSWORD>.'
},
trading_password : {
required : 'Required',
checkPwd : '<PASSWORD> <PASSWORD>.'
},
confirm_trading_password : {
required : 'Required',
verifyPwd : '<PASSWORD>.'
}
}
});
jQuery.validator.addMethod("chkAccount", function (value, element) {
value = $.trim(value);
if (!/^[a-zA-z][A-Za-z0-9]{4,11}$/.test(value)) {
return false;
} else {
return true;
}
});
jQuery.validator.addMethod("checkPwd", function (value, element) {
value = $.trim(value);
if (!/^[A-Za-z0-9]{6,18}$/.test(value)) {
return false;
} else {
return true;
}
});
jQuery.validator.addMethod("verifyPwd", function (value, element) {
var confirm_name = $(element).attr('confirm_name');
var new_password = $.trim($('input[name="' + confirm_name + '"]').val());
value = $.trim(value);
if (new_password == value) {
return true;
} else {
return false;
}
});
</script><file_sep>/framework/api_test/apis/microbank/member.credit.process.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/5
* Time: 18:25
*/
// member.credit.process
class memberCreditProcessApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Credit process";
$this->description = "会员信用认证过程";
$this->url = C("bank_api_url") . "/member.credit.process.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'phone' => array(
'@description' => '电话',
'is_must' => '是否必须 1 必须 0 不',
'is_complete' => '是否完成 1 完成 0 没完成'
),
'personal_info' => array(
'@description' => '个人信息',
'is_must' => '是否必须 1 必须 0 不',
'is_complete' => '是否完成 1 完成 0 没完成'
),
'assets_cert' => array(
'@description' => '资产',
'is_must' => '是否必须 1 必须 0 不',
'is_complete' => '是否完成 1 完成 0 没完成'
),
'fingerprint' => array(
'@description' => '指纹录入',
'is_must' => '是否必须 1 必须 0 不',
'is_complete' => '是否完成 1 完成 0 没完成'
),
'authorized_contract' => array(
'@description' => '授权合同',
'is_must' => '是否必须 1 必须 0 不',
'is_complete' => '是否完成 1 完成 0 没完成'
),
'credit_info' => array(
'@description' => '信用信息',
'credit' => '信用值',
'balance' => '信用余额'
),
'is_active' => array(
'@description' => '信用是否可用 1 可用 0 不可用',
),
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.motorcycle.property.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/magnifier/magnifier.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div-1">
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Motorcycle Asset Certificate</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info" style="display: none;">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<input type="hidden" name="motorbike_cert_front" value="">
<input type="hidden" name="motorbike_cert_back" value="">
<input type="hidden" name="motorbike_photo" value="">
</form>
<div class="snapshot_div" id="motorbike_cert_front" onclick="callWin_snapshot_master('motorbike_cert_front');">
<img src="resource/img/member/photo.png">
<div>Frontal resident book image</div>
</div>
<div class="snapshot_div" id="motorbike_cert_back" onclick="callWin_snapshot_master('motorbike_cert_back');">
<img src="resource/img/member/photo.png">
<div>Back resident book image</div>
</div>
<div class="snapshot_div" id="motorbike_photo" onclick="callWin_snapshot_slave('motorbike_photo');">
<img src="resource/img/member/photo.png">
<div>Motorcycle panorama image</div>
</div>
<div class="snapshot_msg error_msg">
<div class="motorbike_cert_front"></div>
<div class="motorbike_cert_back"></div>
<div class="motorbike_photo"></div>
</div>
</div>
</div>
<div class="operation" style="margin-bottom: 40px">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
<div class="certification-history">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Certification History</h5>
</div>
<div class="content">
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/magnifier/magnifier.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
$(document).ready(function () {
btn_search_onclick();
});
function callWin_snapshot_slave(type) {
if (window.external) {
try {
var _img_path = window.external.getSnapshot("1");
if (_img_path != "" && _img_path != null) {
_img_path = getUPyunImgUrl(_img_path);
$("#" + type + " img").attr("src", _img_path);
$('input[name="' + type + '"]').val(_img_path);
}
} catch (ex) {
alert(ex.Message);
}
}
}
function callWin_snapshot_master(type){
if(window.external){
try{
var _img_path= window.external.getSnapshot("0");
if(_img_path!="" && _img_path!=null){
_img_path = getUPyunImgUrl(_img_path);
$("#" + type + " img").attr("src", _img_path);
$('input[name="' + type + '"]').val(_img_path);
}
}catch (ex){
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 10;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var uid = $('input[name="client_id"]').val();
var cert_type = '<?php echo certificationTypeEnum::MOTORBIKE;?>';
yo.dynamicTpl({
tpl: "member/history.list",
control: "counter_base",
dynamic: {
api: "member",
method: "getCertificationList",
param: {pageNumber: _pageNumber, pageSize: _pageSize, uid: uid, cert_type: cert_type}
},
callback: function (_tpl) {
$(".certification-history .content").html(_tpl);
}
});
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveMotorcyclePropertyAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
var name = $(element).attr('name');
if (name == 'motorbike_cert_front' || name == 'motorbike_cert_back' || name == 'motorbike_photo' || name == 'car_back') {
error.appendTo($('.snapshot_msg .' + name));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
motorbike_cert_front : {
required : true
},
motorbike_cert_back : {
required : true
},
motorbike_photo : {
required : true
}
},
messages : {
motorbike_cert_front : {
required : 'Frontal resident book image required!'
},
motorbike_cert_back : {
required : 'Back resident book image required!'
},
motorbike_photo : {
required : 'Motorcycle panorama image required!'
}
}
});
</script><file_sep>/framework/weixin_baike/data/model/loan_credit_release.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/10
* Time: 10:04
*/
class loan_credit_releaseModel extends tableModelBase
{
function __construct()
{
parent::__construct('loan_credit_release');
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/credit.edit.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<style>
#auth-list .list-group-item {
border-radius: 0px;
font-size: 14px;
padding: 7px 15px;
}
#auth-list .auth_group {
margin-bottom: 10px;
}
.form-filter {
width: 49%;
float: left;
}
.client-info {
width: 49%;
float: right;
}
.client-info .ibox-content {
padding: 0;
}
.client-info .verification-info .ibox-content .item {
padding: 15px 15px;
width: 50%;
float: left;
}
.client-info .verification-info .item span {
font-size: 12px;
margin-left: 5px;
float: right;
}
.client-info .verification-info .item span.checked {
color: #32BC61;
}
.client-info .verification-info .item span.checking {
color: red;
}
.client-info .base-info {
margin-top: 20px;
}
.activity-list .item {
margin-top: 0;
border-right: 1px solid #e7eaec;
}
.activity-list .item:nth-child(2n){
border-right: 0;
}
.row-active-list .item{
padding: 10px;
border-bottom: 1px solid #e7eaec;
}
</style>
<?php
$approval_info = $output['approval_info'];
$reference_value = $output['credit_reference_value'];
$credit_info = $output['credit_info'];
$info = $output['info'];
?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Credit</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('loan', 'credit', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a></li>
<li><a class="current"><span>Edit</span></a></li>
</ul>
</div>
</div>
<div class="container clearfix">
<div class="form-filter">
<div class="form-wrap">
<form class="form-horizontal" method="post" action="<?php echo getUrl('loan', 'editCredit', array(), false, BACK_OFFICE_SITE_URL) ?>">
<input type="hidden" name="form_submit" value="ok">
<input type="hidden" name="obj_guid" value="<?php echo $output['loan_info']['obj_guid']?>">
<div class="form-group">
<label class="col-sm-2 control-label">CID</label>
<div class="col-sm-8" style="line-height: 30px;">
<?php echo $info['obj_guid'];?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-8" style="line-height: 30px;">
<?php echo $info['display_name'];?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span class="required-options-xing">*</span><?php echo 'Credit Limit'?></label>
<div class="col-sm-8">
<input type="number" class="form-control" name="credit" placeholder="" value="<?php if($approval_info['uid']){echo $approval_info['current_credit'];}else{echo $credit_info['credit'];}?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span class="required-options-xing">*</span><?php echo 'Valid Time';?></label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="valid_time" placeholder="" value="">
<span class="input-group-addon">Year</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span class="required-options-xing">*</span><?php echo 'Monthly Repayment Ability'?></label>
<div class="col-sm-8">
<input type="number" class="form-control" name="repayment_ability" placeholder="" value="<?php if($approval_info['uid']){echo $approval_info['repayment_ability'];}else{echo $output['loan_info']['repayment_ability'];}?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span class="required-options-xing">*</span><?php echo 'Remark'?></label>
<div class="col-sm-8">
<textarea class="form-control" name="remark" rows="8" cols="80"><?php if($approval_info['uid']){ echo $approval_info['remark']; }?></textarea>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-col-sm-8" style="padding-left: 15px">
<button type="button" class="btn btn-danger <?php if($approval_info['uid']){echo 'disabled';} ?>"><?php echo 'Save' ?></button>
<!--<button type="button" class="btn btn-default" onclick="javascript:history.go(-1);"><?php echo 'Back'?></button>-->
<?php if($approval_info['uid']){ ?><span style="color: red;">Auditing...</span><?php }?>
</div>
</div>
</form>
</div>
<!--建议授信金额-->
<div class="credit-reference-value" style="margin-top: 20px;">
<div>
<div class="ibox-title">
<h4>Credit Reference Value</h4>
</div>
<div class="ibox-content">
<div class="row-active-list clearfix">
<div class="item row">
<div class="col-sm-4">
Credit Amount
</div>
<div class="col-sm-8">
Certification List
</div>
</div>
<?php if( !empty($reference_value) ){ foreach( $reference_value as $reference ){ ?>
<div class="item row">
<div class="col-sm-4">
<?php echo $reference['min_amount'].' - '.$reference['max_amount']; ?>
</div>
<div class="col-sm-8">
<?php
echo join(',',$reference['cert_list']);
?>
</div>
</div>
<?php } } ?>
</div>
</div>
</div>
</div>
</div>
<div class="client-info">
<div class="verification-info">
<div class="ibox-title">
<h5>Verification Result</h5>
</div>
<div class="ibox-content">
<div class="activity-list clearfix">
<?php $verify_field = $output['verify_field']; $verifys = $output['verifys'];?>
<?php foreach ($verify_field as $key => $value) { ?>
<div class="item">
<div>
<?php echo $value; ?>
<span>
<?php if( $verifys[$key] == 1 ){ ?>
<i class="fa fa-check" aria-hidden="true" style="font-size: 18px;color:green;"></i>
<?php }else{ ?>
<i class="fa fa-question" aria-hidden="true" style="font-size: 18px;color:red;"></i>
<?php } ?>
<i></i>
</span>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="base-info">
<div class="ibox-title">
<h5>Client Info</h5>
<a class="pull-right" href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$info['uid'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>">More Detail</a>
</div>
<div class="ibox-content">
<div class="activity-list clearfix">
<table class="table">
<tbody class="table-body">
<tr>
<td><label class="control-label">CID</label></td><td><?php echo $info['obj_guid'];?></td>
</tr>
<tr>
<td><label class="control-label">Name</label></td><td><?php echo $info['display_name'];?></td>
</tr>
<tr>
<td><label class="control-label">Credit</label></td><td><?php echo $info['credit'];?></td>
</tr>
<tr>
<td><label class="control-label">Account Type</label></td><td><?php echo 'Member';?></td>
</tr>
<tr>
<td><label class="control-label">Phone</label></td><td><?php echo $info['phone_id'];?></td>
</tr>
<tr>
<td><label class="control-label">Email</label></td><td><?php echo $info['email'];?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
});
$('.btn-danger').click(function () {
if (!$(".form-horizontal").valid()) {
return;
}
$('.form-horizontal').submit();
});
$('.form-horizontal').validate({
errorPlacement: function(error, element){
var ele =$(element).closest('.form-group').find('.error_msg');
error.appendTo(ele);
},
rules : {
credit : {
required : true
},
valid_time:{
required: true
},
repayment_ability : {
required : true
},
remark : {
required : true
}
},
messages : {
credit : {
required : '<?php echo 'Required';?>'
},
valid_time:{
required: '<?php echo 'Required';?>'
},
repayment_ability : {
required : '<?php echo 'Required';?>'
},
remark : {
required : '<?php echo 'Required';?>'
}
}
});
</script>
<file_sep>/framework/weixin_baike/counter/control/cash.php
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2018/3/12
* Time: 13:58
*/
class cashControl extends counter_baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setDir("cash");
Language::read('cash');
Tpl::setLayout('home_layout');
$this->outputSubMenu('cash_on_hand');
}
public function cashOnHandOp(){
Tpl::showPage("coming.soon");
}
public function cashInVaultOp(){
$this->outputSubMenu('cash_in_vault');
Tpl::showPage("coming.soon");
}
}
<file_sep>/framework/api_test/apis/officer_app/co.bound.loan.request.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/9
* Time: 13:15
*/
// co.bound.loan.request.list
class coBoundLoanRequestListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "CO bound loan request";
$this->description = "绑定到CO的贷款申请";
$this->url = C("bank_api_url") . "/co.bound.loan.request.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "CO id", 1, true);
$this->parameters[] = new apiParameter('state','类型 0 全部 1 待处理 2 拒绝的 3 审核通过的',0,true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'uid' => 'id',
'member_id' => '会员id',
'applicant_name' => '申请人名字',
'apply_amount' => '申请金额',
'currency' => '货币',
'contact_phone' => '联系电话',
'apply_time' => '申请时间',
'state' => '状态 0-100'
)
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.set.trading.verify.amount.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/24
* Time: 17:45
*/
// member.set.trading.verify.amount
class memberSetTradingVerifyAmountApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member set trading verify amount ";
$this->description = "设置交易密码启用金额";
$this->url = C("bank_api_url") . "/member.set.trading.verify.amount.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("amount", "金额", 100, true);
$this->parameters[]= new apiParameter("currency", "货币", 'USD', true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/weixin_baike/data/model/client_black.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/6
* Time: 17:53
*/
class client_blackModel extends tableModelBase{
public function __construct(){
parent::__construct('client_black');
}
/**
* 获取role信息
* @param $uid
* @return result
*/
public function getBlackInfo($obj_guid){
$info = $this->find(array('obj_guid' => $obj_guid));
if (empty($info)) {
return new result(false, 'Invalid Member');
}
return new result(true, '', $info);
}
public function insertBlack($param){
$obj_guid = $param['obj_guid'];
$auditor_id = $param['auditor_id'];
$auditor_name = $param['auditor_name'];
unset($param['obj_guid']);
unset($param['auditor_id']);
unset($param['auditor_name']);
$insert = $this->newRow();
$insert->obj_guid = $obj_guid;
$insert->type = json_encode($param);
$insert->auditor_id = $auditor_id;
$insert->auditor_name = $auditor_name;
$insert->update_time = Now();
$rt = $insert->insert();
if ($rt->STS) {
return new result(true, 'Add successful!');
} else {
return new result(false, 'Add failed--' . $rt->MSG);
}
}
public function updateBlack($param){
$type = $param['type'];
$list = $param['list'];
$auditor_id = $param['auditor_id'];
$auditor_name = $param['auditor_name'];
$row = $this->getRow(array('type' => $type));
$row->list = $list;
$row->auditor_id = $auditor_id;
$row->auditor_name = $auditor_name;
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
return new result(true, 'Update successful!');
} else {
return new result(false, 'Update failed--' . $rt->MSG);
}
}
public function updateBlackOld($param){
$obj_guid = $param['obj_guid'];
$auditor_id = $param['auditor_id'];
$auditor_name = $param['auditor_name'];
unset($param['obj_guid']);
unset($param['auditor_id']);
unset($param['auditor_name']);
$row = $this->getRow(array('obj_guid' => $obj_guid));
$row->type = json_encode($param);
$row->auditor_id = $auditor_id;
$row->auditor_name = $auditor_name;
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
return new result(true, 'Update successful!');
} else {
return new result(false, 'Update failed--' . $rt->MSG);
}
}
}
<file_sep>/framework/weixin_baike/counter/control/user.php
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2018/3/7
* Time: 15:48
*/
class userControl extends counter_baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setDir("user");
Language::read('user');
Tpl::setLayout('home_layout');
}
/**
* 用户修改密码
*/
public function changePasswordOp()
{
Tpl::showPage("user.change_pwd");
}
/**
* 修改密码
* @param $p
* @return result
*/
public function apiChangePasswordOp($p)
{
$p['user_id'] = $this->user_id;
if (trim($p['new_password'] != trim($p['verify_password']))) {
return new result(false, 'Verify password error!');
}
$class_user = new userClass();
$rt = $class_user->changePassword($p);
return $rt;
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.create.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/30
* Time: 14:20
*/
class loanContractCreateApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Create";
$this->description = "通用产品贷款合同创建(暂时不使用此api)";
$this->url = C("bank_api_url") . "/credit_loan.contract.create.php";
$this->parameters = array();
/* $this->parameters[]= new apiParameter("member_id", '会员id', 1, true);
$this->parameters[]= new apiParameter("product_id", "贷款产品id", 1, true);
$this->parameters[]= new apiParameter("amount", "贷款金额", 500, true);
$this->parameters[]= new apiParameter("loan_period", "贷款周期,单位月", 6, true);
$this->parameters[]= new apiParameter("repayment_type", "还款方式,等额本息 annuity_scheme,等额本金 fixed_principal,一次偿还(每月计算一次利息) single_repayment,固定利息 flat_interest,先利息后本金 balloon_interest", 'annuity_scheme', true);
$this->parameters[]= new apiParameter("repayment_period", "还款周期,一年一次 yearly,半年一次 semi_yearly,一季度一次 quarter,一月一次 monthly,一周一次 weekly,一天一次 daily", 'monthly', true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>牌", '', true);
$this->parameters[] = new apiParameter('insurance_item_id','绑定的保险项目id',0);
$this->parameters[] = new apiParameter('insurance_amount','保险购买金额,非固定价格产品需要',0);*/
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'contract_id' => '合同id',
'loan_amount' => '贷款金额',
'loan_period' => '贷款周期',
'repayment_type' => '还款方式',
'repayment_period' => '还款周期',
'lending_time' => '出借时间',
'product_info' => '产品信息',
'product_size_interest' => '产品贷款利率信息',
'contract_detail' => '合同详细信息',
'loan_disbursement_scheme' => '放款计划',
'loan_installment_scheme' => '还款计划'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.propose.get.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/9
* Time: 11:10
*/
class loanProposeGetApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Propose Lists";
$this->description = "贷款目的列表";
$this->url = C("bank_api_url") . "/loan.propose.get.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '目的列表'
);
}
}<file_sep>/framework/weixin_baike/mobile/templates/default/home/assets.evaluate.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/home.css?v=2">
<?php include_once(template('widget/inc_header'));?>
<?php $data = $output['data'];$list = $data['list'];?>
<div class="wrap assets-evalute-wrap">
<div class="evalute-amount">
<p class="amount"><?php echo $data['total_amount'];?> <em>USD</em></p>
<p class="title">Total Amount</p>
</div>
<div class="assets-list">
<ul class="aui-list assets-ul aui-margin-b-10">
<li class="aui-list-item assets-title">
<div class="i">Index</div>
<div>Type</div>
<div>Remark</div>
<div>Evalution</div>
</li>
<?php if(count($list) > 0){ ?>
<?php foreach($list as $k => $v){ ?>
<li class="aui-list-item assets-item">
<div class="i"><?php echo $k+1;?></div>
<div>
<?php
$str = '';
switch ($v['asset_type']) {
case certificationTypeEnum::CAR :
$str = 'Car';
break;
case certificationTypeEnum::HOUSE :
$str = 'House';
break;
case certificationTypeEnum::LAND :
$str = 'Land';
break;
case certificationTypeEnum::MOTORBIKE :
$str = 'Motorbike';
break;
default:
$str = 'Car';
break;
}
echo $str;
?>
</div>
<div><?php echo $v['remark'];?></div>
<div>
<?php if($v['valuation'] <= 0){ ?>
<a class="evalute-edit" href="<?php echo getUrl('home', 'editAssetsEvaluate', array('cid'=>$_GET['cid'],'uid'=>$v['uid'],'mid'=>$_GET['id']), false, WAP_OPERATOR_SITE_URL)?>">Edit ></a>
<?php }else{ ?>
<?php echo $v['valuation'];?>
<a class="evalute-edit" href="<?php echo getUrl('home', 'editAssetsEvaluate', array('cid'=>$_GET['cid'],'uid'=>$v['uid'],'mid'=>$_GET['id']), false, WAP_OPERATOR_SITE_URL)?>"><i class="aui-iconfont aui-icon-edit"></i></a>
<?php } ?>
</div>
</li>
<?php } ?>
<?php }else{ ?>
<div class="no-record"><?php echo $lang['label_no_data'];?></div>
<?php } ?>
</ul>
</div>
</div>
<script type="text/javascript">
var back = '<?php echo $_GET['back']?>';
</script>
<file_sep>/framework/weixin_baike/common/define_enum.php
<?php
class errorCodesEnum extends Enum
{
const UNKNOWN_ERROR = 0; // 没有定义的错误
const NO_ERROR = 200; // 无任何错误
const SIGN_ERROR = 1001; // 签名错误
const DATA_LACK = 1002; // 参数缺乏
const INVALID_PARAM = 1003; // 非法参数
const INVALID_TOKEN = 1004; // 非法token
const USER_EXIST = 1005; // 用户已存在
const PHONE_USED = 1006; // 电话已使用
const PHONE_VERIFIED = 1007; // 电话已验证
const DATA_EXPIRED = 1008; // 数据过期
const MEMBER_NOT_EXIST = 1009; // member不存在
const NO_LOGIN = 1010; //没有登录
const SESSION_EXPIRED = 10001; // session 过期
const DB_ERROR = 10002; // 数据库操作失败
const UNEXPECTED_DATA = 10003; // 错误数据
const NOT_SUPPORTED = 10004;
const UNIMPLEMENTED = 10005;
const API_FAILED = 10006; // api错误
const NOT_PERMITTED = 10007;
const LOGIN_NULLIFIED = 10008;
const DATA_INCONSISTENCY = 10009; // 数据不一致
const DATA_DUPLICATED = 10010; // 数据已经存在
const REQUEST_FLOOD = 10011; // 请求过于频繁
const CONFIG_ERROR = 10012; // 配置错误
// 业务相关的CODE
const SMS_CODE_ERROR = 11013; // 短信验证码错误
const NO_LOAN_PRODUCT = 11014; // 没有贷款产品
const LOAN_PRODUCT_UNSHELVE = 11015; // 产品已下架(历史版本)
const LOAN_PRODUCT_NX = 11016; // 非产品的执行版本
const NO_LOAN_INTEREST = 11017; // 没有设置利率信息
const NO_INSURANCE_ITEM = 11018; // 没有保险产品投保项
const NO_INSURANCE_PRODUCT = 11019; // 没有保险产品
const INSURANCE_PRODUCT_NX = 11020; // 非执行版本
const CREATE_INSURANCE_CONTRACT_FAIL = 11021; // 创建保险合同失败
const WITHDRAW_AMOUNT_INVALID = 11022; // 取现金额非法
const OUT_OF_PER_WITHDRAW = 11023; // 单次取现超额
const OUT_OF_DAY_WITHDRAW = 11024; // 当日取现超额
const NO_LOAN_ACCOUNT = 11025; // 不存在贷款账户
const NO_BIND_ACE_ACCOUNT = 11026; // 没有绑定ACE账号
const OUT_OF_ACCOUNT_CREDIT = 11027; // 超出信用额度
const NO_CONTRACT = 11028; // 没有合同信息
const TWO_PWD_DIFFER = 11029; // 两次密码不一致
const PASSWORD_ERROR = 11030; // 密码错误
const NO_MESSAGE = 11031; // 消息不存在
const REPAYMENT_UN_MATCH_LOAN_TIME = 11032; // 贷款时间周期和还款方式不匹配
const ACE_ACCOUNT_NOT_EXIST = 11033; // ACE账户不存在
const NO_PASSPORT = 11034; // 没有登陆通行令牌
const PASSPORT_EXPIRED = 11035; // 登陆通行令牌失效
const NO_ACCOUNT_HANDLER = 11036; // 没有操作账户
const UNDER_COOL_TIME = 11037; // 冷却时间内,稍后再试
const ACCOUNT_NOT_VALID = 11038; // 账号格式不符合
const PASSWORD_NOT_STRONG = 11039; // 密码格式错误或强度不够
const EMAIL_BEEN_REGISTERED = 11040; // 邮箱已被注册
const FUNCTION_CLOSED = 11041; // 后台功能关闭了
const OUT_OF_CREDIT_BALANCE = 11042; // 超出信用余额
const INVALID_PHONE_NUMBER = 11043; // 非法电话号码
const INVALID_EMAIL = 11044; // 非法邮箱
const CAN_NOT_CANCEL_CONTRACT = 11045; // 合同进行中,不能取消
const LOAN_CONTRACT_CAN_NOT_REPAYMENT = 11046; // 贷款合同未执行,不能还款
const INSUFFICIENT_REPAYMENT_CAPACITY = 11047; // 还款能力不足
const APPROVING_CAN_NOT_DELETE = 11048; // 审核中,不能删除
const AMOUNT_TOO_LITTLE = 11049; // 金额太小
const INVALID_PERIOD_NUM = 11050; // 不合理的期数数量
const NO_CURRENCY_EXCHANGE_RATE = 11051; // 没有设置汇率
const NOT_SUPPORT_PREPAYMENT = 11052; // 该合同不支持提前还款
const NOT_CERTIFICATE_ID = 11053; // 没有认证身份证
const ID_SN_ERROR = 11054; // 身份证号错误
const ID_SN_HAS_CERTIFICATED = 11055; // 身份证号已经被认证
const SAME_PASSWORD = <PASSWORD>; // 新、旧密码一样
const NOT_SET_TRADING_PASSWORD = <PASSWORD>; // 没有设置交易密码
const MEMBER_UN_GRANT_CREDIT = 11058; // 还未授信
const INVALID_AMOUNT = 11059; // 不合理的数量
const NOT_ACE_MEMBER = 11060; // 不是ACE的member
const SMS_CODE_SEND_FAIL = 11061; // 验证码发送失败
const USER_NOT_EXISTS = 11062; // 用户不存在
const USER_LOCKED = 11063; // 用户被锁定
const HAVE_HANDLED = 11064; // 已经处理了
const HAVE_CANCELED = 11065; // 已经取消
const UN_MATCH_OPERATION = 11066; // 不匹配操作
const BANK_ALREADY_BOUND = 11067; // 银行卡已经绑定了
const NO_LOGIN_ACCESS = 11068; // 账号没有登录权限
const HANDLING_LOCKED = 11069; // 处理锁定中,不能执行其他操作
const CONTRACT_BEEN_PAID_OFF = 11070; // 合同已还清
const CONTRACT_BEEN_WRITTEN_OFF = 11071; // 合同已核销
const BALANCE_NOT_ENOUGH = 11100; // 余额不足
const BILL_NOT_EXIST = 11101; // 账单不存在
// API相关错误代码
const API_ERROR_ACE_BASE = 20000; // ACE API错误CODE的基础编号
}
class globalOrderStateEnum extends Enum
{
const ORDER_STATE_CANCEL = "0"; // 取消
const ORDER_STATE_CREATED = '1'; // 创建
const ORDER_STATE_PENDING_PAY = "10"; // 待支付
const ORDER_STATE_PAYING = '11'; // 正在支付
const ORDER_STATE_PAID = "20"; // 已支付
const ORDER_STATE_SUCCESS = "40"; // 完成
}
class treeKeyTypeEnum extends Enum
{
const ADDRESS = 'region'; // 地址key
}
class addressCategoryEnum extends Enum
{
const MEMBER_RESIDENCE_PLACE = 'residence_place';
}
class partnerEnum extends Enum
{
// 合作伙伴code
const ACE = 'ace';
}
class memberSourceEnum extends Enum
{
const ONLINE = 0; // 网络
const CLIENT = 1; // 柜台
const THIRD = 10; // 第三方
}
class memberStateEnum extends Enum
{
const CANCEL = 0; // 注销
const CREATE = 1; // 创建
const CHECKED = 10; // 已检查
const LOCKING = 20; //锁定
const VERIFIED = 100; // 已验证
}
class newMemberCheckStateEnum extends Enum
{
const CREATE = 0; // 新创建
const LOCKED = 10; // 锁定
const CLOSE = 11; //关闭
const ALLOT = 20; //分配给co
const PASS = 100; // 通过验证
}
class operateTypeEnum extends Enum
{
const NEW_CLIENT = 'new_client';
const REQUEST_LOAN = 'request_loan';
const CERTIFICATION_FILE = 'certification_file';
}
class creditProcessEnum extends Enum
{
// 信用激活过程
const FINGERPRINT = 'fingerprint'; // 指纹录入
const AUTHORIZED_CONTRACT = 'authorized_contract'; // 授权合同
}
class creditEventTypeEnum extends Enum
{
const GRANT = 'grant';
const CREDIT_LOAN = 'credit_loan';
}
class smsTaskType extends Enum
{
const VERIFICATION_CODE = "VerificationCode";
const PIN_CODE = "PinCode";
const WALLET_CHANGED = "WalletChanged";
const LUCKY_NOTICE = 'LuckyNotice';
const TOPUP_NOTICE = 'TopupNotice';
}
class smsTaskState extends Enum
{
const NONE = 0;
const CREATE = 1;
const SENDING = 10;
const SEND_FAILED = 11;
const SEND_SUCCESS = 20;
const CANCEL = 30;
}
class phoneCodeCDEnum extends Enum
{
const CD = 60; // 发送短信验证码的冷却时间(s)
}
class emailCoolTimeEnum extends Enum
{
const CD = 60;
}
class memberLoginTypeEnum extends Enum
{
const LOGIN_CODE = 1;
const PHONE = 2;
const EMAIL = 3;
}
class insuranceProductStateEnum extends Enum
{
const TEMP = 10;
const ACTIVE = 20;
const INACTIVE = 30;
const HISTORY = 40;
}
class objGuidTypeEnum extends Enum
{
const CLIENT_MEMBER = 1;
const UM_USER = 2;
const SITE_BRANCH = 3;
const PARTNER = 4;
const BANK_ACCOUNT = 5;
const SHORT_LOAN = 6;
const LONG_LOAN = 7;
const SHORT_DEPOSIT = 8;
const LONG_DEPOSIT = 9;
const GL_ACCOUNT = 10;
}
class appTypeEnum extends Enum
{
const MEMBER_APP = 'smarithiesak-member';
const OPERATOR_APP = 'credit_officer';
}
class loanAccountTypeEnum extends Enum
{
const MEMBER = 0;
const PARTNER = 10;
const DEALER = 20;
const LEGAL = 30;
}
class insuranceAccountTypeEnum extends Enum
{
const MEMBER = 0;
const PARTNER = 10;
const DEALER = 20;
const LEGAL = 30;
}
class schemaStateTypeEnum extends Enum
{
const CANCEL = -1; // 取消
const CREATE = 0;
const GOING = 10; // 开始执行
const FAILURE = 11;
const COMPLETE = 100;
}
class loanContractStateEnum extends Enum
{
const CANCEL = -1;
const CREATE = 0; // 新建,待审核
const PENDING_APPROVAL = 10;
const REFUSED = 11; // 审核拒绝
const PENDING_DISBURSE = 20; // 待放款,进入执行状态
const PROCESSING = 30;
const PAUSE = 90; // 执行异常,人工介入
const COMPLETE = 100;
const WRITE_OFF = 101; // 注销
}
class dueDateTypeEnum extends Enum
{
// 还款日类型 0 固定日期 1 每周 2 每月 3 每年
const FIXED_DATE = 0;
const PER_WEEK = 1;
const PER_MONTH = 2;
const PER_YEAR = 3;
const PER_DAY = 4; // 每天
}
class insuranceContractStateEnum extends Enum
{
const CANCEL = -1;
const CREATE = 0; // 待审核
const PENDING_APPROVAL = 10;
const REFUSED = 11; // 审核拒绝
const PENDING_RECEIPT = 20; // 待收款
const PROCESSING = 30; // 进行中
const PAUSE = 90; // 执行异常,人工介入
const COMPLETE = 100;
const WRITE_OFF = 101; // 注销
}
class contractPrefixSNEnum extends Enum
{
const LOAN = 1;
const INSURANCE = 2;
}
class memberAccountHandlerTypeEnum extends Enum
{
const CASH = 0;
const BANK = 10;
const PARTNER_ASIAWEILUY = 21;
const PARTNER_LOAN = 22;
const PASSBOOK = 30;
}
class accountHandlerStateEnum extends Enum
{
const ACTIVE = 10;
const HISTORY = 20;
}
class certSourceTypeEnum extends Enum
{
const MEMBER = 0; // 会员自提交
const CLIENT = 1; // 柜台提交
const OPERATOR = 2; // operator app(业务员提交)
}
class certificationTypeEnum extends Enum
{
const ID = 1; //身份证
const FAIMILYBOOK = 2; //户口本
const PASSPORT = 3; //护照
const HOUSE = 4; //房屋资产证明
const CAR = 5; //汽车资产证明
const WORK_CERTIFICATION = 6; // 工作证明
//const CIVIL_SERVANT = 7; // 公务员证明
const GUARANTEE_RELATIONSHIP = 8; // 担保人信息
const LAND = 9; // 土地
const RESIDENT_BOOK = 10; // 居住证
const MOTORBIKE = 11; // 摩托车
}
class certImageKeyEnum extends Enum
{
const ID_HANDHELD = 'id_handheld'; // 手持身份证照片
const ID_FRONT = 'id_front'; // 身份证正面
const ID_BACK = 'id_back'; // 身份证背面
const FAMILY_BOOK_FRONT = 'family_book_front'; // 户口本正面
const FAMILY_BOOK_BACK = 'family_book_back'; // 户口本背面
const FAMILY_BOOK_HOUSEHOLD = 'family_book_household'; // 户主页
const RESIDENT_BOOK_FRONT = 'resident_book_front'; // 居住证正面
const RESIDENT_BOOK_BACK = 'resident_book_back'; // 居住证背面
const WORK_CARD = 'work_card'; // 工作卡或证明
const WORK_EMPLOYMENT_CERTIFICATION = 'work_employment_certification'; // 雇佣证明
const FAMILY_RELATION_CERT_PHOTO = 'family_relation_cert_photo'; // 家庭关系人证件照
const MOTORBIKE_PHOTO = 'motorbike_photo'; // 摩托车照片
const MOTORBIKE_CERT_FRONT = 'motorbike_cert_front'; // 摩托车证件正面
const MOTORBIKE_CERT_BACK = 'motorbike_cert_back'; // 摩托车证件背面
const CAR_FRONT = 'car_front'; // 汽车前面照片
const CAR_BACK = 'car_back'; // 汽车后面照片
const CAR_CERT_FRONT = 'car_cert_front'; // 汽车证件正面
const CAR_CERT_BACK = 'car_cert_back'; // 汽车证件背面
const HOUSE_PROPERTY_CARD = 'house_property_card'; // 房屋产权证
const HOUSE_RELATIONSHIPS_CERTIFY = 'house_relationships_certify'; // 房屋关系证明
const HOUSE_FRONT = 'house_front'; // 房屋正面图
const HOUSE_SIDE_FACE = 'house_side_face'; // 房屋侧面图
const HOUSE_FRONT_ROAD = 'house_front_road'; // 房屋门前马路图
const HOUSE_INSIDE = 'house_inside'; // 房内图
const LAND_PROPERTY_CARD = 'land_property_card'; // 土地产权证
const LAND_TRADING_RECORD = 'land_trading_record'; // 土地交易记录表
}
class certTypeCalculateValueEnum extends Enum
{
const ID = 1;
const FAMILY_BOOK = 2;
const GUARANTEE_RELATIONSHIP = 4;
const WORK_CERT = 8;
const CIVIL_SERVANT = 16;
const CAR_CERT = 32;
const HOUSE_CERT = 64;
const LAND_CERT = 128;
const PASSPORT = 256;
const RESIDENT_BOOK = 512;
const MOTORBIKE = 1024;
const FAMILY_RELATION = 4;
}
class certStateEnum extends Enum
{
const LOCK = -1; // 审核中,锁定
const CREATE = 0;
const PASS = 10;
const EXPIRED = 11; // 过期
const NOT_PASS = 100;
}
class creditLevelTypeEnum extends Enum
{
const MEMBER = 0;
const MERCHANT = 1;
}
class blackTypeEnum extends Enum
{
const LOGIN = 1; //登录
const DEPOSIT = 2; //存款
const INSURANCE = 3; //保险
const CREDIT_LOAN = 4; //信用贷
const MORTGAGE_LOAN = 5; //抵押贷
}
class fileDirsEnum extends Enum
{
// 文件夹名常量
const CLIENT = 'client';
const ID = 'id';
const PASSPORT = 'passport';
const FAMILY_BOOK = 'familybook';
const FAMILY_RELATION = 'family_relation';
const WORK_CERT = 'work_cert';
const MOTORBIKE = 'motorbike';
const HOUSE = 'house';
const CAR = 'car';
const LAND = 'land';
const RESIDENT_BOOK = 'resident_book';
}
class disbursementStateEnum extends Enum
{
const GOING = 10;
const FAILED = 11;
const DONE = 100;
}
class repaymentStateEnum extends Enum
{
const GOING = 10;
const FAILED = 11;
const DONE = 100;
}
class loanProductStateEnum extends Enum
{
const TEMP = 10;
const ACTIVE = 20;
const INACTIVE = 30;
const HISTORY = 40;
}
class loanApplyStateEnum extends Enum
{
// 贷款申请状态
const LOCKED = -1;
const CREATE = 0; // 客人提交
const OPERATOR_REJECT = 1; // Operator拒绝
const ALLOT_CO = 2; // 指派给CO
const CO_HANDING = 10; // CO正在这处理
const CO_CANCEL = 11; // CO直接cancel了
const CO_APPROVED = 20; // CO check通过
const BM_APPROVED = 30; // BM 审核通过 权限内 -> ALL_APPROVED
const BM_CANCEL = 31; // BM 否决
const HQ_APPROVED = 40; // HQ 审核通过 -> ALL_APPROVED
const HQ_CANCEL = 41; // HQ否决
const ALL_APPROVED = 50; // 可转为contract的状态
const ALL_APPROVED_CANCEL = 51; // approve后被取消
const DONE = 100; // 已经转为合同
}
class loanApplySourceEnum extends Enum
{
const MEMBER_APP = 'member_app';
const OPERATOR_APP = 'operator_app';
const PHONE = 'phone';
const FACEBOOK = 'facebook';
const CLIENT = 'client'; // 柜台
}
class loanRepaymentStateEnum extends Enum
{
const START = 10;
const FAILURE = 11;
const SUCCESS = 100;
}
class requestRepaymentTypeEnum extends Enum
{
const SCHEME = 'schema';
const BALANCE = 'balance';
}
class repaymentWayEnum extends Enum
{
const CASH = 0;
const AUTO_DEDUCTION = 1; // partner-> api
const BANK_TRANSFER = 2; // bank
}
class requestRepaymentStateEnum extends Enum
{
const CREATE = 0;//新建
const PROCESSING = 20;//查账中
const FAILED = 21;//未到账
const RECEIVED = 30; // 只是钱到账,没更改合同
const SUCCESS = 100;// 到账,合同已更改
}
class prepaymentApplyStateEnum extends Enum
{
// 提前还款申请的状态
const CREATE = 0; // 申请
const AUDITING = 10; //提前还款审核中
const DISAPPROVE = 11; //审核不通过
const APPROVED = 20; // 审核通过
const PAID = 30; // 已付款
const PROCESSING = 31; // 查账中
const RECEIVED = 40; // 钱已到账,未处理合同
const SUCCESS = 100; // 合同处理完成
const FAIL = 101; // 合同处理失败
}
class prepaymentRequestTypeEnum extends Enum
{
const PARTLY = 0; // 部分偿还
const FULL_AMOUNT = 1; // 全部偿还
const LEFT_PERIOD = 2; // 偿还期数方式
}
class penaltyOnEnum extends Enum
{
const OVERDUE_PRINCIPAL = 'overdue_principal';
const PRINCIPAL_INTEREST = 'principal_interest';
const TOTAL = 'total';
}
class singleRepaymentEnum extends Enum
{
const DAYS_7 = '7_days';
const DAYS_15 = '15_days';
const MONTH_1 = '1_month';
const MONTHS_3 = '3_months';
const MONTHS_6 = '6_months';
const YEAR_1 = '1_year';
}
class interestRatePeriodEnum extends Enum
{
const YEARLY = 'yearly';
const SEMI_YEARLY = 'semi_yearly';
const QUARTER = 'quarter';
const MONTHLY = 'monthly';
const WEEKLY = 'weekly';
const DAILY = 'daily';
}
class loanPeriodUnitEnum extends Enum
{
const YEAR = 'year';
const MONTH = 'month';
const DAY = 'day';
}
class interestPaymentEnum extends Enum
{
const SINGLE_REPAYMENT = 'single_repayment';
const FIXED_PRINCIPAL = 'fixed_principal';
const ANNUITY_SCHEME = 'annuity_scheme';
const FLAT_INTEREST = 'flat_interest';
const BALLOON_INTEREST = 'balloon_interest';
}
class memberFamilyStateEnum extends Enum
{
const CREATE = 0;
const INVALID = 10; // 无效
const REMOVE = 11; // 解除
const APPROVAL = 100; // 核准
}
class memberGuaranteeStateEnum extends Enum
{
const CANCEL = -1; // 取消
const CREATE = 0;
const REJECT = 11;
const ACCEPT = 100;
}
class workStateStateEnum extends Enum
{
const CREATE = 0;
const APPROVING = 10;
const INVALID = 11; // 审核未通过
const VALID = 20; // 核实
const HISTORY = 30; // 历史
}
class assetStateEnum extends Enum
{
const CANCEL = -1; // 删除
const CREATE = 0; // 新加
const INVALID = 11; //无效
const CERTIFIED = 100; // 已认证
}
class clientTypeRateEnum extends Enum
{
const STAFF = 'staff'; // 公司内部员工
const GOVERNMENT = 'government'; // 政府员工
const RIVAL_CLIENT = 'rival_client'; // 对手客户
}
class contractWriteOffTypeEnum extends Enum
{
const SYSTEM = 10;
const ABNORMAL = 20;
}
class writeOffStateEnum extends Enum
{
const CREATE = 0;
const APPROVING = 10;
const INVALID = 11; // 审核未通过
const COMPLETE = 100; // 审核通过,已核销
}
class loanDeductingPenaltiesState extends Enum
{
const CREATE = 0;
const PROCESSING = 10;
const DISAPPROVE = 20;
const APPROVE = 30;
const USED = 40;
}
class helpCategoryEnum extends Enum
{
const CREDIT_LOAN = 'credit_loan';
const MORTGAGE_LOAN = 'mortgage_loan';
const SAVINGS = 'savings';
const INSURANCE = 'insurance';
}
class helpStateEnum extends Enum
{
const CREATE = 0;
const NOT_SHOW = 10;
const SHOW = 100;
}
class pointEventEnum extends Enum
{
const ADD = 'add';
const AUDIT = 'audit';
const VERIFY = 'verify';
}
class currencyEnum extends Enum
{
const USD = "USD";
const KHR = "KHR";
const CNY = "CNY";
const VND = 'VND';
const THB = 'THB';
}
//用户定义enum start
class userDefineEnum extends Enum
{
const MORTGAGE_TYPE = 'mortgage_type';
const GUARANTEE_TYPE = 'guarantee_type';
const LOAN_USE = 'loan_use';
const GENDER = 'gender';
const OCCUPATION = 'occupation';
const FAMILY_RELATIONSHIP = 'family_relationship';
const GUARANTEE_RELATIONSHIP = 'guarantee_relationship'; // Guarantee Relationship
const MARITAL_STATUS = 'marital_status';
// const BANK_CODE = 'bank_code';
}
//用户定义enum end
class trxTypeEnum extends Enum
{
const DEC = -1; // 减
const INVALID = 0; // 无效
const INC = 1; // 加
}
class apiStateEnum extends Enum
{
const CANCELLED = 0;
const CREATED = 10;
const STARTED = 20;
const PENDING_CHECK = 30;
const FINISHED = 40;
}
class nationalityEnum extends Enum
{
const CAMBODIA = 'cambodia';
const CHINESE = 'chinese';
}
class refBizTypeEnum extends Enum
{
// API 外部业务类型
const LOAN = 'loan';
const INSURANCE = 'insurance';
const SAVINGS = 'savings';
}
class limitKeyEnum extends Enum
{
const LIMIT_LOAN = 'limit_loan';
const LIMIT_DEPOSIT = 'limit_deposit';
const LIMIT_EXCHANGE = 'limit_exchange';
const LIMIT_WITHDRAW = 'limit_withdraw';
const LIMIT_TRANSFER = 'limit_transfer';
}
class passbookTypeEnum extends Enum
{
const ASSET = "asset"; // 资产类
const DEBT = "debt"; // 负债类
const EQUITY = "equity"; // 所有着权益类
const PROFIT = "profit"; // 损益类 - 收入
const COST = "cost"; // 成本类
const COMMON = "common"; // 共同类
}
class passbookObjTypeEnum extends Enum
{
// 储蓄账户对象类型
const CLIENT_MEMBER = 'client_member';
const UM_USER = 'um_user';
const BRANCH = 'branch';
const GL_ACCOUNT = 'gl_account';
const BANK = 'bank';
const PARTNER = 'partner';
}
class passbookStateEnum extends Enum
{
const CANCEL = -1;
const ACTIVE = 100;
const FREEZE = 10;
}
class passbookTradingStateEnum extends Enum
{
const CREATE = 0;
const DONE = 100;
}
class passbookTradingTypeEnum extends Enum
{
const BANK_TO_BRANCH = 'bank_to_branch';
const BANK_TO_HEADQUARTER = 'bank_to_headquarter';
const INIT_BRANCH = 'init_branch';
const BRANCH_TO_BANK = 'branch_to_bank';
const BRANCH_TO_CASHIER = 'branch_to_cashier';
const BRANCH_TO_HEADQUARTER = 'branch_to_headquarter';
const RECEIVE_CAPITAL = 'receive_capital';
const CASHIER_TO_BRANCH = 'cashier_to_branch';
const DEPOSIT_BY_BANK = 'deposit_by_bank';
const DEPOSIT_BY_CASH = 'deposit_by_cash';
const DEPOSIT_BY_PARTNER = 'deposit_by_partner';
const TRANSFER = 'transfer';
const WITHDRAW_BY_BANK = 'withdraw_by_bank';
const WITHDRAW_BY_CASH = 'withdraw_by_cash';
const WITHDRAW_BY_PARTNER = 'withdraw_by_partner';
const HEADQUARTER_TO_BANK = 'headquarter_to_bank';
const HEADQUARTER_TO_BRANCH = 'headquarter_to_branch';
const DISBURSE_LOAN = 'disburse_loan';
const LOAN_PREPAYMENT = 'loan_prepayment';
const LOAN_REPAYMENT = 'loan_repayment';
}
class passbookAccountFlowStateEnum extends Enum
{
const CREATE = 0;
const OUTSTANDING = 90;
const DONE = 100;
}
class userPositionEnum extends Enum
{
const CREDIT_OFFICER = 'credit_officer';
const TELLER = 'teller';
const CHIEF_TELLER = 'chief_teller';
const BRANCH_MANAGER = 'branch_manager';
const OPERATOR = 'operator';
}
class authTypeEnum extends Enum
{
const BACK_OFFICE = 'back_office';
const COUNTER = 'counter';
}
/**
* Class incomingTypeEnum
* 收入类型
*/
class incomingTypeEnum extends Enum
{
/**
* 年费
*/
const ANNUAL_FEE = "annual_fee_incoming";
/**
* 利息
*/
const INTEREST = "interest_incoming";
/**
* 管理费
*/
const ADMIN_FEE = "admin_fee_incoming";
/**
* 手续费
*/
const LOAN_FEE = "loan_fee_incoming";
/**
* 运营费
*/
const OPERATION_FEE = "operation_fee_incoming";
/**
* 保险费
*/
const INSURANCE_FEE = "insurance_fee_incoming";
/**
* 逾期罚金
*/
const OVERDUE_PENALTY = "overdue_penalty_incoming";
/**
* 提前还款违约金
*/
const PREPAYMENT_PENALTY = "prepayment_penalty_incoming";
}
/**
* Class businessTypeEnum
* 业务类型
*/
class businessTypeEnum extends Enum
{
/**
* 信用贷
*/
const CREDIT_LOAN = "credit_loan";
}
/**
* Class systemAccountCodeEnum
* 系统账户代码枚举
*/
class systemAccountCodeEnum extends Enum
{
const HQ_CIV = "hq_civ";
const HQ_CAPITAL = "hq_capital";
const HQ_INIT = "hq_init";
const RECEIVABLE_LOAN_INTEREST = "receivable_loan_interest";
const EXCHANGE_SETTLEMENT = "exchange_settlement"; // 换汇结算户
const FEE_INCOMING = "fee_incoming"; // 手续费收入
const FINANCIAL_EXPENSES = "financial_expenses"; // 财务费用
}
/**
* Class accountingDirectionEnum
* 会计记账方向
*/
class accountingDirectionEnum extends Enum
{
/**
* 借方
* 对于资产类、费用类账户,借加
* 对于负债、所有者权益、收入类账户,借减
*/
const DEBIT = 0;
/**
* 贷方
* 对于负债、所有者权益、收入类账户,贷加
* 对于资产类、费用类账户,贷减
*/
const CREDIT = 1;
}
class withdrawStateEnum extends Enum
{
const CREATE = 0;
const DONE = 100;
const FAIL = 101;
}
class depositStateEnum extends Enum
{
const CREATE = 0;
const DONE = 100;
const FAIL = 101;
}
class bizSceneEnum extends Enum
{
const APP_MEMBER = "app_member";
const APP_CO = "app_co";
const COUNTER = "counter";
const BACK_OFFICE = "back_office";
}
class bizCheckTypeEnum extends Enum
{
const TRADING_PASSWORD = '<PASSWORD>';
}
class bizCodeEnum extends Enum
{
const MEMBER_WITHDRAW_TO_PARTNER = 'member_withdraw_to_partner';
const MEMBER_TRANSFER_TO_MEMBER = 'member_transfer_to_member';
const MEMBER_DEPOSIT_BY_PARTNER = 'member_deposit_by_partner';
}
class complaintAdviceEnum extends Enum
{
const CREATE = 1;
const HANDLE = 2;
const CHECKED = 3;
}<file_sep>/framework/api_test/apis/microbank/client.member.get.fingerprint.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/24
* Time: 10:32
*/
// client.member.get.fingerprint
class clientMemberGetFingerprintApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Get client member fingerprint";
$this->description = "获取会员指纹库";
$this->url = C("bank_api_url") . "/client.member.get.fingerprint.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员GUID", 10000001, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'member_id' => '',
'finger_index' => '',
'feature_img' => '',
'feature_data' => ''
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/report/loan.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Loan Name';?></td>
<td><?php echo 'loan Code';?></td>
<td><?php echo 'Version Number';?></td>
<td><?php echo 'Contract Number';?></td>
<td><?php echo 'Loan Client';?></td>
<td><?php echo 'Principal Amount';?></td>
<td><?php echo 'Interest Amount';?></td>
<td><?php echo 'Admin Fee';?></td>
<td><?php echo 'Unreceived';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<?php echo $row['product_name'] ?>
</td>
<td>
<?php echo $row['product_code']; ?>
</td>
<td>
<?php echo $row['count']; ?>
</td>
<td>
<?php echo $row['loan_contract']; ?>
</td>
<td>
<?php echo $row['loan_client']; ?>
</td>
<td>
<?php echo ncAmountFormat($row['loan_ceiling']); ?>
</td>
<td>
<?php echo ncAmountFormat($row['loan_interest']); ?>
</td>
<td>
<?php echo ncAmountFormat($row['admin_fee']); ?>
</td>
<td>
<?php echo ncAmountFormat($row['loan_balance']);?>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/weixin_baike/backoffice/control/loan.php
<?php
class loanControl extends baseControl
{
public function __construct()
{
parent::__construct();
Language::read('enum,loan,certification');
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "User List");
$verify_field = enum_langClass::getCertificationTypeEnumLang();
Tpl::output("verify_field", $verify_field);
// 客户类型语言包
$client_type_lang = enum_langClass::getClientTypeLang();
Tpl::output('client_type_lang', $client_type_lang);
Tpl::setDir("loan");
}
public function creditOp()
{
Tpl::showPage("credit");
}
public function getCreditListOp($p)
{
$r = new ormReader();
$sql = "SELECT client.*,loan.uid as load_uid,loan.allow_multi_contract,c.credit,c.credit_balance FROM client_member as client left join loan_account as loan on loan.obj_guid = client.obj_guid left join member_credit c on c.member_id=client.uid where 1 = 1 ";
if ($p['item']) {
$sql .= " and loan.obj_guid = " . $p['item'];
}
if ($p['name']) {
$sql .= ' and client.display_name like "%' . $p['name'] . '%"';
}
$sql .= " ORDER BY client.create_time desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
/*$sql1 = "select uid from (select * from loan_approval order by uid desc) loan_approval group by obj_guid";
$ids = $r->getRows($sql1);
$ids = array_column($ids, 'uid');
$ids = implode(',', $ids);
$sql2 = "select * from loan_approval where uid in (".$ids.")";
$applys = $r->getRows($sql2);
$new_applys = array();
foreach ($applys as $key => $value) {
$new_applys[$value['obj_guid']] = $applys[$key];
}*/
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("credit.list");
}
public function editCreditOp()
{
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
$m_member = new memberModel();
$m_core_dictionary = M('core_dictionary');
$member = $m_member->getRow(array(
'obj_guid' => intval($p['obj_guid'])
));
if (!$member) {
showMessage('No member');
}
$setting = $m_core_dictionary->getDictionary('global_settings');
$setting = my_json_decode($setting['dict_value']);
if ($p['credit'] > $setting['operator_credit_maximum']) {
showMessage('Credit limit.');
}
$m_loan_account = new loan_accountModel();
$rt = $m_loan_account->getCreditInfo(intval($p['obj_guid']));
$data = $rt->DATA;
$m_credit = new member_creditModel();
$member_credit = $m_credit->getRow(array(
'member_id' => $member['uid']
));
$credit_reference = credit_loanClass::getCreditLevelList();
$cert_lang = enum_langClass::getCertificationTypeEnumLang();
foreach ($credit_reference as $k => $v) {
$item = $v;
$cert_list = $item['cert_list'];
foreach ($cert_list as $key => $value) {
$cert_list[$key] = $cert_lang[$value];
}
$item['cert_list'] = $cert_list;
$credit_reference[$k] = $item;
}
Tpl::output('credit_reference_value', $credit_reference);
if ($p['form_submit'] == 'ok') {
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$p['before_credit'] = $member_credit['credit'];
$rt = $m_loan_account->editCredit($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('loan', 'credit', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('user', 'editCredit', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
$m_loan_approval = M('loan_approval');
$approvaling = $m_loan_approval->getRow(array('obj_guid' => intval($p['obj_guid']), 'state' => 0));//申请中
if ($approvaling) {
Tpl::output('approval_info', $approvaling);
}
$sql = "SELECT loan.*,client.uid as member_id,client.display_name,client.alias_name,client.phone_id,client.email FROM loan_account as loan left join client_member as client on loan.obj_guid = client.obj_guid where loan.obj_guid = '" . intval($p['obj_guid']) . "'";
$info = $r->getRow($sql);
Tpl::output('info', $info);
/*$sql1 = "SELECT * FROM member_verify_cert where member_id = " . $info['member_id'];
$rows = $r->getRows($sql1);*/
$member_id = $member['uid'];
$re = memberClass::getMemberSimpleCertResult($member_id);
if (!$re->STS) {
showMessage('Error: ' . $re->MSG);
}
$verifys = $re->DATA;
Tpl::output("verifys", $verifys);
Tpl::output('credit_info', $member_credit);
Tpl::output('loan_info', $data);
Tpl::showPage("credit.edit");
}
}
public function contractOp()
{
Tpl::showPage("contract");
}
public function getInsurancePrice($uid = 0)
{
$r = new ormReader();
$sql1 = "select loan_contract_id,sum(price) as price from insurance_contract GROUP BY loan_contract_id";
if ($uid) {
$sql1 = "select loan_contract_id,sum(price) as price from insurance_contract where loan_contract_id = " . $uid . " GROUP BY loan_contract_id";
}
$insurance = $r->getRows($sql1);
$insurance_arr = array();
foreach ($insurance as $key => $value) {
$insurance_arr[$value['loan_contract_id']] = $value;
}
return $insurance_arr;
}
public function getContractListOp($p)
{
$r = new ormReader();
$sql = "SELECT contract.*,account.obj_guid,member.uid as member_id,member.display_name,member.alias_name,member.phone_id,member.email FROM loan_contract as contract"
. " inner join loan_account as account on contract.account_id = account.uid"
. " left join client_member as member on account.obj_guid = member.obj_guid where contract.state != -1 ";
if ($p['item']) {
$sql .= " and contract.contract_sn = '" . $p['item'] . "'";
}
if ($p['name']) {
$sql .= ' and member.display_name like "%' . $p['name'] . '%"';
}
if ($p['date']) {
$sql .= ' and contract.start_date > "' . $p['date'] . '"';
}
if ($p['state'] > -1) {
$sql .= " and contract.state = " . $p['state'];
}
$sql .= " ORDER BY contract.create_time desc";
$insurance_arr = $this->getInsurancePrice();
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$insurance = $insurance_arr;
$total = $data->count;
$pageTotal = $data->pageCount;
$sql1 = "select count(uid) as count from loan_contract where state = " . loanContractStateEnum::WRITE_OFF;
$count_write_off = $r->getRow($sql1);
$sql2 = "select count(uid) as count from loan_contract where state != " . loanContractStateEnum::WRITE_OFF . " and state != " . loanContractStateEnum::COMPLETE;
$count_in = $r->getRow($sql2);
return array(
"sts" => true,
"data" => $rows,
"insurance" => $insurance_arr,
"total" => $total,
"count_write_off" => $count_write_off['count'],
"count_in" => $count_in['count'],
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("contract.list");
}
public function contractDetailOp()
{
$p = array_merge(array(), $_GET, $_POST);
$r = new ormReader();
$uid = intval($p['uid']);
$sql = "SELECT contract.*,account.obj_guid,product.uid product_id,product.product_code,product.product_name,product.product_description,product.product_feature,member.uid as member_id,member.display_name,member.alias_name,member.phone_id,member.email FROM loan_contract as contract"
. " inner join loan_account as account on contract.account_id = account.uid"
. " left join client_member as member on account.obj_guid = member.obj_guid"
. " left join loan_product as product on contract.product_id = product.uid where contract.uid = " . $uid;
$data = $r->getRow($sql);
if( !$data ){
showMessage('No contract!');
}
$contract_id = $data['uid'];
// 待还金额
$re = loan_contractClass::getContractLeftPayableInfo($contract_id);
$payable_info = $re->DATA;
$data['left_principal'] = $payable_info['total_payable_amount'];
Tpl::output("detail", $data);
$sql1 = "select * from loan_disbursement_scheme where contract_id = " . $uid;
$disbursement = $r->getRows($sql1);
Tpl::output("disbursement", $disbursement);
// $sql3 = "SELECT * FROM loan_deducting_penalties WHERE contract_id = $uid AND state <= " . loanDeductingPenaltiesState::PROCESSING;
// $deducting_penalties = $r->getRow($sql3);
// if ($deducting_penalties) {
// Tpl::output("is_deducting_penalties", false);
// } else {
// Tpl::output("is_deducting_penalties", true);
// }
$sql2 = "select * from loan_installment_scheme where state!='".schemaStateTypeEnum::CANCEL."' and contract_id = " . $data['uid'];
$installment = $r->getRows($sql2);
$penalties_total = 0;
$time = date('Y-m-d 23:59:59', time());
$repayment_arr = array();
foreach ($installment as $key => $val) {
if ($val['penalty_start_date'] <= $time && $val['state'] != schemaStateTypeEnum::COMPLETE) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($val['uid']);
$val['penalties'] = $penalties;
// $val['amount'] += $penalties;
$penalties_total += $penalties;
$installment[$key] = $val;
}
if ($val['receivable_date'] <= $time && $val['state'] != schemaStateTypeEnum::COMPLETE) {
$repayment_arr[] = $val;
}
}
Tpl::output("penalties_total", $penalties_total);
Tpl::output("installment", $installment);
$insurance_arr = $this->getInsurancePrice($p['uid']);
Tpl::output("insurance", $insurance_arr);
Tpl::output("repayment_arr", $repayment_arr);
Tpl::showPage("contract.detail");
}
public function approvalOp()
{
Tpl::showPage("approval");
}
public function getApprovalListOp($p)
{
$r = new ormReader();
$sql1 = "select max(uid) as uid,obj_guid from loan_approval group by obj_guid";
$ids = $r->getRows($sql1);
$ids = array_column($ids, 'uid');
$ids = implode(',', $ids) ?: 0;
$sql = "SELECT loan.*,client.uid member_id,client.display_name,client.alias_name,client.phone_id,"
. " approval.uid as a_uid,approval.before_credit,approval.current_credit,approval.repayment_ability as approval_repayment_ability,approval.operator_id,approval.operate_time,approval.create_time,approval.remark,approval.type,approval.state"
. " FROM loan_account as loan "
. " left join client_member as client on loan.obj_guid = client.obj_guid"
. " inner join loan_approval as approval on client.obj_guid = approval.obj_guid where approval.uid in (" . $ids . ") ";
if ($p['member_item']) {
$sql .= " and loan.obj_guid = " . $p['member_item'];
}
if ($p['member_name']) {
$sql .= ' and client.display_name like "%' . $p['member_name'] . '%"';
}
if ($p['type'] > -1) {
$sql .= " and approval.type = " . $p['type'];
}
if ($p['state'] != 2) {
$sql .= " and approval.state = " . $p['state'];
}
$sql .= " ORDER BY approval.create_time desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("approval.list");
}
public function approvalEditOp()
{
$p = array_merge(array(), $_GET, $_POST);
$r = new ormReader();
$sql = "select approval.*,member.uid as member_id,member.display_name,member.phone_id,member.email FROM loan_approval as approval LEFT JOIN client_member as member ON approval.obj_guid = member.obj_guid where approval.uid = " . $p['uid'];
$data = $r->getRow($sql);
if (!$data) {
showMessage('Error', getUrl('loan', 'approval', array(), false, BACK_OFFICE_SITE_URL));
}
Tpl::output('info', $data);
$sql = "select * FROM loan_approval where obj_guid = " . $data['obj_guid'];
$list = $r->getRows($sql);
Tpl::output('list', $list);
Tpl::showPage("approval.edit");
}
public function approvalConfirmOp()
{
$p = array_merge(array(), $_GET, $_POST);
$m_loan_approval = new loan_approvalModel();
$data = $m_loan_approval->find(array('uid' => $p['uid']));
if (!$data) {
showMessage('No Data', getUrl('loan', 'approval', array(), false, BACK_OFFICE_SITE_URL));
}
$data['operator_id'] = $this->user_id;
$data['operator_name'] = $this->user_name;
// 审核状态
$data['state'] = $p['state'];
$rt = $m_loan_approval->creditGrantConfirm($data);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('loan', 'approval', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('user', 'approvalEdit', $p, false, BACK_OFFICE_SITE_URL));
}
}
/**
* 产品页
*/
public function productOp()
{
$r = new ormReader();
$m_loan_product = M('loan_product');
$sql = "SELECT MAX(uid) uid FROM loan_product WHERE state < 40 GROUP BY product_key";
$product_ids = $r->getRows($sql);
if ($product_ids) {
$product_ids = array_column($product_ids, 'uid');
$sql = "SELECT * FROM loan_product WHERE uid IN (" . implode(',', $product_ids) . ") ORDER BY uid DESC";
$product_list = $r->getRows($sql);
foreach ($product_list as $key => $product) {
$product_key = $product['product_key'];
$product_count = $m_loan_product->field('count(*) count')->find(array('product_key' => $product_key));
$product_list[$key]['count'] = $product_count;
if ($product['state'] == 10 && $product_count > 1) {
$product_valid = $m_loan_product->find(array('product_key' => $product_key, 'state' => 20));
if ($product_valid) {
$product_list[$key]['valid_id'] = $product_valid['uid'];
}
}
$product_contract = $this->getProductContractById($product['uid']);
$product_list[$key]['loan_contract'] = $product_contract['loan_count'] ?: 0;
$product_list[$key]['loan_client'] = $product_contract['loan_client'] ?: 0;
$product_list[$key]['loan_ceiling'] = $product_contract['loan_ceiling'] ?: 0;
$product_list[$key]['loan_balance'] = $product_contract['loan_balance'] ?: 0;
}
} else {
$product_list = array();
};
Tpl::output("product_list", $product_list);
Tpl::showPage("product.list");
}
/**
* 系列历史版本
*/
public function showProductHistoryOp()
{
$uid = intval($_REQUEST['uid']);
$m_loan_product = M('loan_product');
$row = $m_loan_product->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
$product_history = $m_loan_product->orderBy('uid DESC')->select(array('product_key' => $row['product_key']));
foreach ($product_history as $key => $product) {
$product_contract = $this->getProductContractById($product['uid']);
$product_history[$key]['loan_contract'] = $product_contract['loan_count'] ?: 0;
$product_history[$key]['loan_client'] = $product_contract['loan_client'] ?: 0;
$product_history[$key]['loan_ceiling'] = $product_contract['loan_ceiling'] ?: 0;
$product_history[$key]['loan_balance'] = $product_contract['loan_balance'] ?: 0;
}
Tpl::output("product_history", $product_history);
Tpl::showPage("product.history");
}
/**
* 获取产品合同信息
* @param $product_id
* @return ormDataRow
*/
private function getProductContractById($product_id)
{
$r = new ormReader();
$sql = "SELECT COUNT(*) loan_count,SUM(apply_amount) loan_ceiling,sum(receivable_principal+receivable_interest+receivable_operation_fee+receivable_annual_fee+receivable_penalty-loss_principal-loss_interest-loss_operation_fee-loss_annual_fee-loss_penalty) receivable FROM loan_contract WHERE product_id = " . $product_id;
$product_contract = $r->getRow($sql);
$sql = "SELECT SUM(lr.amount) repayment FROM loan_repayment AS lr INNER JOIN loan_contract AS lc ON lr.contract_id = lc.uid WHERE lr.state = 100 AND lc.product_id = " . $product_id;
$repayment = $r->getOne($sql);
$loan_balance = $product_contract['receivable'] - $repayment;
$sql = "SELECT COUNT(member.uid) loan_client FROM loan_contract AS contract"
. " INNER JOIN loan_account AS account ON contract.account_id = account.uid"
. " INNER JOIN client_member AS member ON account.obj_guid = member.obj_guid WHERE contract.product_id = " . $product_id . " GROUP BY member.uid";
$loan_client = $r->getOne($sql);
$product_contract['loan_balance'] = $loan_balance;
$product_contract['loan_client'] = $loan_client;
return $product_contract;
}
/**
* 展示产品信息
*/
public function showProductOp()
{
$uid = intval($_REQUEST['uid']);
$class_product = new product();
$rt = $class_product->getProductInfoById($uid);
if (!$rt->STS) {
showMessage($rt->MSG);
}
Tpl::output('product_info', $rt->DATA);
$currency_list = C('currency');
Tpl::output("currency_list", $currency_list);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type', 'guarantee_type'));
Tpl::output("mortgage_type", $define_arr['mortgage_type']);
Tpl::output("guarantee_type", $define_arr['guarantee_type']);
Tpl::output("is_edit", isset($_GET['is_edit']) ? $_GET['is_edit'] : true);
Tpl::showPage('product.info');
}
/**
* 添加页
*/
public function addProductOp()
{
$currency_list = C('currency');
Tpl::output("currency_list", $currency_list);
$penalty_on = (new penaltyOnEnum())->Dictionary();
$interest_payment = (new interestPaymentEnum())->Dictionary();
$interest_rate_period = (new interestRatePeriodEnum())->Dictionary();
Tpl::output("interest_payment", $interest_payment);
Tpl::output("penalty_on", $penalty_on);
Tpl::output("interest_rate_period", $interest_rate_period);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type', 'guarantee_type'));
Tpl::output("mortgage_type", $define_arr['mortgage_type']);
Tpl::output("guarantee_type", $define_arr['guarantee_type']);
Tpl::showPage('product.add');
}
/**
* 编辑产品
*/
public function editProductOp()
{
$uid = intval($_REQUEST['uid']);
$class_product = new product();
$rt = $class_product->getProductInfoById($uid);
if (!$rt->STS) {
showMessage($rt->MSG);
}
Tpl::output('product_info', $rt->DATA);
$currency_list = C('currency');
Tpl::output("currency_list", $currency_list);
$penalty_on = (new penaltyOnEnum())->Dictionary();
$interest_payment = (new interestPaymentEnum())->Dictionary();
$interest_rate_period = (new interestRatePeriodEnum())->Dictionary();
Tpl::output("interest_payment", $interest_payment);
Tpl::output("penalty_on", $penalty_on);
Tpl::output("interest_rate_period", $interest_rate_period);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type', 'guarantee_type'));
Tpl::output("mortgage_type", $define_arr['mortgage_type']);
Tpl::output("guarantee_type", $define_arr['guarantee_type']);
Tpl::showPage('product.add');
}
/**
* 保存产品主要信息
* @param $p
* @return result
*/
public function insertProductMainOp($p)
{
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$class_product = new product();
$rt = $class_product->insertProductMain($p);
return $rt;
}
/**
* 更新产品主要信息
* @param $p
* @return result
*/
public function updateProductMainOp($p)
{
$class_product = new product();
$rt = $class_product->updateProductMain($p);
return $rt;
}
/**
* 保存罚金信息
* @param $p
* @return result
*/
public function updateProductPenaltyOp($p)
{
$class_product = new product();
$rt = $class_product->updateProductPenalty($p);
return $rt;
}
/**
* 利率列表
* @param $p
* @return array
*/
public function getSizeRateListOp($p)
{
$class_product = new product();
$rt = $class_product->getSizeRateList($p);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type', 'guarantee_type'));
$rt['mortgage_type'] = $define_arr['mortgage_type'];
$rt['guarantee_type'] = $define_arr['guarantee_type'];
$rt['type'] = $p['type'];
return $rt;
}
/**
* 保存size利率
* @param $p
* @return result
*/
public function insertSizeRateOp($p)
{
$class_product = new product();
$rt = $class_product->insertSizeRate($p);
return $rt;
}
/**
* 更新size利率
* @param $p
* @return result
*/
public function updateSizeRateOp($p)
{
$class_product = new product();
$rt = $class_product->updateSizeRate($p);
return $rt;
}
/**
* 保存size利率
* @param $p
* @return result
*/
public function removeSizeRateOp($p)
{
$class_product = new product();
$rt = $class_product->removeSizeRate($p);
return $rt;
}
/**
* 更新贷款条件
* @param $p
* @return result
*/
public function updateProductConditionOp($p)
{
$class_product = new product();
$rt = $class_product->updateProductCondition($p);
return $rt;
}
/**
* 更新详情
* @param $p
* @return result
*/
public function updateDescriptionOp($p)
{
$class_product = new product();
$rt = $class_product->updateDescription($p);
return $rt;
}
/**
* 发布产品
* @param $p
* @return result
*/
public function releaseProductOp($p)
{
$uid = intval($p['uid']);
$class_product = new product();
$rt = $class_product->changeProductState($uid, 20);
if ($rt->STS) {
return new result(true, 'Release Successful!');
} else {
return new result(false, 'Release Failure!');
}
}
/**
* 产品下架
* @param $p
* @return result
*/
public function unShelveProductOp($p)
{
$uid = intval($p['uid']);
$class_product = new product();
$rt = $class_product->changeProductState($uid, 30);
if ($rt->STS) {
return new result(true, 'Inactive Successful!');
} else {
return new result(false, 'Inactive Failure!');
}
}
/**
* 逾期合同
*/
public function overdueOp()
{
Tpl::showPage('contract.overdue');
}
/**
* @param $p
* @return array
*/
public function getOverdueListOp($p)
{
$r = new ormReader();
$sql = "SELECT lis.contract_id,SUM(lis.amount) amount,COUNT(lis.uid) num ,MIN(lis.receivable_date) receivable_date" .
" FROM loan_installment_scheme lis WHERE lis.state = 0 AND lis.receivable_date < '" . Now() . "' GROUP BY lis.contract_id ORDER BY lis.receivable_date DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$contract_ids = array_column($rows, 'contract_id');
$contract_id_str = '(' . implode(',', $contract_ids) . ')';
$sql = "SELECT lc.uid,lc.contract_sn,cm.display_name,cm.phone_id" .
" FROM loan_contract lc LEFT JOIN loan_account la ON lc.account_id = la.uid" .
" LEFT JOIN client_member cm ON la.obj_guid = cm.obj_guid" .
" WHERE lc.uid IN $contract_id_str";
$arr = $r->getRows($sql);
$arr = resetArrayKey($arr, 'uid');
foreach ($rows as $key => $row) {
$contract_id = $row['contract_id'];
$row = array_merge($row, $arr[$contract_id]);
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 特殊利率
*/
public function specialRateOp()
{
$product_id = intval($_GET['product_id']);
$size_rate_id = intval($_GET['size_rate_id']);
$class_product = new product();
$special_rate_list = $class_product->getSpecialRateList($size_rate_id);
Tpl::output('special_rate_list', $special_rate_list);
Tpl::output('product_id', $product_id);
Tpl::output('size_rate_id', $size_rate_id);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('client_grade'));
Tpl::output('client_grade', $define_arr['client_grade']);
//Tpl::output('client_type', $define_arr['client_type']);
Tpl::showpage('special.rate');
}
/**
* 增加特殊利率
* @param $p
* @return result
*/
public function insertSpecialSizeRateOp($p)
{
$class_product = new product();
if (!trim($p['client_type']) && !trim($p['client_grade'])) {
return new result(false, 'Please set member grade or member type first!');
}
$rt = $class_product->insertSpecialSizeRate($p);
if ($rt->STS) {
$data = $rt->DATA;
$url = getUrl('loan', 'specialRate', array('size_rate_id' => $data['size_rate_id'], 'product_id' => $data['product_id']), false, BACK_OFFICE_SITE_URL);
$rt->DATA = array('url' => $url);
return $rt;
} else {
return $rt;
}
}
/**
* 编辑特殊利率
* @param $p
* @return result
*/
public function updateSpecialSizeRateOp($p)
{
$class_product = new product();
if (!trim($p['client_type']) && !trim($p['client_grade'])) {
return new result(false, 'Please set member grade or member type first!');
}
$rt = $class_product->updateSpecialSizeRate($p);
if ($rt->STS) {
$data = $rt->DATA;
$url = getUrl('loan', 'specialRate', array('size_rate_id' => $data['size_rate_id'], 'product_id' => $data['product_id']), false, BACK_OFFICE_SITE_URL);
$rt->DATA = array('url' => $url);
return $rt;
} else {
return $rt;
}
}
/**
* 移除特殊利率
* @param $p
* @return result
*/
public function removeSpecialSizeRateOp($p)
{
$class_product = new product();
$rt = $class_product->removeSpecialSizeRate($p);
if ($rt->STS) {
$data = $rt->DATA;
$url = getUrl('loan', 'specialRate', array('size_rate_id' => $data['size_rate_id'], 'product_id' => $data['product_id']), false, BACK_OFFICE_SITE_URL);
$rt->DATA = array('url' => $url);
return $rt;
} else {
return $rt;
}
}
/**
* 申请列表
*/
public function applyOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
$type = $_GET['type'] ?: 'unprocessed';
Tpl::output('type', $type);
Tpl::showpage('apply');
}
/**
* 获取申请列表
* @param $p
* @return array
*/
public function getApplyListOp($p)
{
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
// todo 暂时只有operator权限的列表
$sql = "SELECT la.*,uu.user_name,uu.user_code FROM loan_apply la LEFT JOIN um_user uu ON la.credit_officer_id = uu.uid WHERE (la.apply_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['type']) == 'unprocessed') {
$sql .= " AND la.state in ('" . loanApplyStateEnum::LOCKED . "','" . loanApplyStateEnum::CREATE . "') ";
} else {
$sql .= " AND la.state > " . loanApplyStateEnum::CREATE;
}
if (trim($p['search_text'])) {
$sql .= " AND al.applicant_name like '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY la.apply_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
$apply_source = (new loanApplySourceEnum)->Dictionary();
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"cur_uid" => $this->user_id,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"type" => trim($p['type']),
"apply_source" => $apply_source,
);
}
/**
* 审核通过
*/
public function operatorAuditApplyOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$m_loan_apply = M('loan_apply');
$row = $m_loan_apply->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
$m_um_user = M('um_user');
// 绑定的credit officer
$bound_credit_officer = $m_um_user->find(array(
'uid' => $row->credit_officer_id
));
Tpl::output('bound_credit_officer', $bound_credit_officer);
if ($p['form_submit'] == 'ok') {
$row->operator_id = $this->user_id;
$row->operator_name = $this->user_name;
$row->operator_remark = $p['remark'];
$row->update_time = Now();
$state = intval($p['approve_state']);
if ($state == 1) {
// 通过,分配CO
$co_id = intval($p['credit_officer_id']);
if (!$co_id) {
showMessage('Please allot credit officer!');
}
$co = $m_um_user->getRow($co_id);
if (!$co) {
showMessage('Credit officer not exist!');
}
$row->state = loanApplyStateEnum::ALLOT_CO;
$row->credit_officer_id = $co_id;
} else {
// 拒绝
$row->state = loanApplyStateEnum::OPERATOR_REJECT;
}
$rt = $row->update();
if ($rt->STS) {
showMessage('Handle Successful!', getUrl('loan', 'apply', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL));
} else {
showMessage('Handle fail!');
}
} else {
//审核中
if ($row->state == loanApplyStateEnum::LOCKED) {
// 超时放开,让别人可审 1小时
if ((strtotime($row['update_time']) + 3600) < time()) {
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->update_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG, getUrl('loan', 'apply', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL));
}
}
} elseif ($row->state == loanApplyStateEnum::CREATE) {
$row->state = loanApplyStateEnum::LOCKED;
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->update_time = Now();
$rt = $row->update();
if (!$rt->STS) {
showMessage($rt->MSG);
}
}
$lock = false;
if ($row['state'] == loanApplyStateEnum::LOCKED && $this->user_id != $row['handler_id']) {
//审核中
$lock = true;
}
Tpl::output('lock', $lock);
Tpl::output('apply_info', $row);
$apply_source = (new loanApplySourceEnum)->Dictionary();
Tpl::output('apply_source', $apply_source);
$sql = "select * from um_user where user_status='1' and user_position like '%".userPositionEnum::CREDIT_OFFICER."%' ";
$credit_officer_list = $m_um_user->reader->getRows($sql);
Tpl::output('credit_officer_list', $credit_officer_list);
Tpl::showpage('apply.audit');
}
}
/**
* 解锁申请锁定
* @param $p
* @return result
*/
public function unlockedApplyOp($p)
{
$uid = intval($p['uid']);
$m_loan_apply = M('loan_apply');
$row = $m_loan_apply->getRow($uid);
if (!$row) {
return new result(false, 'Invalid Id!');
}
if ($row->state == loanApplyStateEnum::LOCKED) {
return new result(true);
}
$row->state = loanApplyStateEnum::CREATE;
$row->handler_id = 0;
$row->handler_name = '';
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
return new result(true);
} else {
return new result(false, $rt->MSG);
}
}
/**
* 添加贷款申请
*/
public function addApplyOp()
{
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$m_loan_apply = M('loan_apply');
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$rt = $m_loan_apply->addApply($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('loan', 'apply', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('loan', 'addApply', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type'));
Tpl::output('mortgage_type', $define_arr['mortgage_type']);
$apply_source = (new loanApplySourceEnum)->Dictionary();
Tpl::output('request_source', $apply_source);
Tpl::showpage('apply.add');
}
}
/**
* 提前还款
*/
public function requestToPrepaymentOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
$request_state = (new prepaymentApplyStateEnum())->Dictionary();
Tpl::output('request_state', $request_state);
Tpl::showPage('request.prepayment');
}
/**
* 获取提前还款申请
* @param $p
* @return array
*/
public function getRequestPrepaymentListOp($p)
{
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn FROM loan_prepayment_apply lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " WHERE (lrr.apply_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if ($p['state'] >= 0) {
$sql .= " AND lrr.state = " . intval($p['state']);
}
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn like '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY lrr.apply_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"cur_uid" => $this->user_id,
"type" => trim($p['type']),
);
}
/**
* 提前还款审核页面
*/
public function auditRequestPrepaymentOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$m_loan_request_repayment = M('loan_prepayment_apply');
$row = $m_loan_request_repayment->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
//审核中
if ($row->state == prepaymentApplyStateEnum::AUDITING) {
// 超时放开,让别人可审 1小时
if ((strtotime($row['update_time']) + 3600) < time()) {
$row->state = prepaymentApplyStateEnum::AUDITING;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->update_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG);
}
}
} elseif ($row->state == prepaymentApplyStateEnum::CREATE) {
$row->state = prepaymentApplyStateEnum::AUDITING;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->update_time = Now();
$rt = $row->update();
if (!$rt->STS) {
showMessage($rt->MSG);
}
}
$lock = false;
if ($this->user_id != $row['auditor_id']) {
//审核中
$lock = true;
}
Tpl::output('lock', $lock);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn,lc.currency contract_currency"
. " FROM loan_prepayment_apply lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " WHERE lrr.uid =" . $uid;
$detail = $r->getRow($sql);
Tpl::output('detail', $detail);
$re = loan_contractClass::getPrepaymentDetail($detail['contract_id']);
$prepayment_detail = $re->DATA;
Tpl::output('prepayment_detail', $prepayment_detail);
Tpl::showpage('request.prepayment.audit');
}
/**
* 审核提前还款 批准?不批准
* @param $p
* @return result
*/
public function auditPrepaymentOp($p)
{
$uid = intval($p['uid']);
$type = trim($p['type']);
$remark = trim($p['remark']);
$m_loan_request_prepayment = M('loan_prepayment_apply');
$row = $m_loan_request_prepayment->getRow($uid);
if ($row->auditor_id != $this->user_id) {
return new result(false, 'Auditor Error!');
}
if ($type == 'approve') {
$row->state = prepaymentApplyStateEnum::APPROVED;
} else {
$row->state = prepaymentApplyStateEnum::DISAPPROVE;
}
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->audit_remark = $remark;
$row->audit_time = Now();
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
return new result(true, 'Audit Successful!');
} else {
return new result(false, 'Audit Failed!');
}
}
/**
* 查看提前还款申请情况
*/
public function viewRequestPrepaymentOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn"
. " FROM loan_prepayment_apply lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " WHERE lrr.uid =" . $uid;
$detail = $r->getRow($sql);
if (!$detail) {
showMessage('Invalid Id!');
}
Tpl::output('detail', $detail);
Tpl::showpage('request.prepayment.view');
}
/**
* 还款请求
*/
public function requestToRepaymentOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
$request_state = (new requestRepaymentStateEnum())->Dictionary();
Tpl::output('request_state', $request_state);
Tpl::showPage('request.repayment');
}
/**
* 获取还款申请列表
* @param $p
* @return array
*/
public function getRequestRepaymentListOp($p)
{
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$type = trim($p['type']);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn,lis.scheme_name FROM loan_request_repayment lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " LEFT JOIN loan_installment_scheme lis ON lrr.scheme_id = lis.uid"
. " WHERE (lrr.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if ($p['state'] >= 0) {
$sql .= " AND lrr.state = " . intval($p['state']);
}
if ($type) {
$sql .= " AND lrr.type = '" . $type . "'";
}
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn like '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY lrr.create_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"cur_uid" => $this->user_id,
);
}
/**
* 审核还款申请
*/
public function auditRequestRepaymentOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$m_loan_request_repayment = M('loan_request_repayment');
$row = $m_loan_request_repayment->getRow(array('uid' => $uid));
if (!$row) {
showMessage('Invalid Id!');
}
//审核中
if ($row->state == requestRepaymentStateEnum::PROCESSING) {
// 超时放开,让别人可审 1小时
if ((strtotime($row['update_time']) + 3600) < time()) {
$row->state = requestRepaymentStateEnum::PROCESSING;
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->update_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG);
}
}
} elseif ($row->state == requestRepaymentStateEnum::CREATE) {
$row->state = requestRepaymentStateEnum::PROCESSING;
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->update_time = Now();
$rt = $row->update();
if (!$rt->STS) {
showMessage($rt->MSG);
}
}
$lock = false;
if ($this->user_id != $row['handler_id']) {
//审核中
$lock = true;
}
Tpl::output('lock', $lock);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn"
. " FROM loan_request_repayment lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " WHERE lrr.uid =" . $uid;
$detail = $r->getRow($sql);
Tpl::output('detail', $detail);
$repayment_type_lang = enum_langClass::getPaymentTypeLang();
Tpl::output('repayment_type_lang',$repayment_type_lang);
if ($row['type'] == 'schema') {
$rt = loan_contractClass::getRepaymentSchemaByAmount($detail['contract_id'], $detail['amount'],$row['currency']);
if (!$rt->STS) {
showMessage($rt->MSG);
}
$repayment_schema = $rt->DATA;
$expired_schema = array();
$unexpired_schema = array();
$today_start = strtotime(date('Y-m-d 00:00:00', time()));
foreach ($repayment_schema['repayment_schema'] as $schema) {
$receivable_date = strtotime(date('Y-m-d 00:00:00', strtotime($schema['receivable_date'])));
if ($receivable_date <= $today_start) {
$expired_schema[] = $schema;
} else {
$unexpired_schema[] = $schema;
}
}
Tpl::output('expired_schema', $expired_schema);
Tpl::output('unexpired_schema', $unexpired_schema);
Tpl::showpage('request.repayment.audit');
} else {
$prepayment_apply_id = $row['prepayment_apply_id'];
$m_loan_prepayment_apply = M('loan_prepayment_apply');
$prepayment_apply = $m_loan_prepayment_apply->find(array('uid' => $prepayment_apply_id));
Tpl::output('prepayment_apply', $prepayment_apply);
Tpl::showpage('request.prepayment.handle');
}
}
/**
* 确定还款到账
* @param $p
* @return result
*/
public function auditRepaymentOp($p)
{
$uid = intval($p['uid']);
$type = $p['type'];
$remark = trim($p['remark']);
$payer_name = trim($p['payer_name']);
$payer_type = trim($p['payer_type']);
$payer_account = trim($p['payer_account']);
$payer_phone = trim($p['payer_phone']);
$bank_name = trim($p['bank_name']);
$bank_account_name = trim($p['bank_account_name']);
$bank_account_no = trim($p['bank_account_no']);
$m_loan_request_repayment = M('loan_request_repayment');
$row = $m_loan_request_repayment->getRow($uid);
if ($payer_name) $row->payer_name = $payer_name;
if ($payer_type) $row->payer_type = $payer_type;
if ($payer_account) $row->payer_account = $payer_account;
if ($payer_phone) $row->payer_phone = $payer_phone;
if ($bank_name) $row->bank_name = $bank_name;
if ($bank_account_name) $row->bank_account_name = $bank_account_name;
if ($bank_account_no) $row->bank_account_no = $bank_account_no;
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->handle_remark = $remark;
$row->handle_time = Now();
if ($type == 'offline_failure') {
$row->state = requestRepaymentStateEnum::FAILED;
$rt_1 = $row->update();
if ( !$rt_1->STS ) {
return new result(false, 'Handle failure!');
}
return new result(true, 'Handle successful!');
} else {
$row->state = requestRepaymentStateEnum::PROCESSING;
$rt_1 = $row->update();
if ( !$rt_1->STS ) {
return new result(false, 'Handle failure!');
}
$request_id = $row->uid;
if ($p['received_date']) {
$received_date = date('Y-m-d H:i:s', strtotime($p['received_date']));
} else {
$received_date = date('Y-m-d H:i:s');
}
$handler_info = array(
'handler_id' => $this->user_id,
'handler_name' => $this->user_name,
'handle_remark' => $remark,
'handle_time' => Now()
);
try{
$conn = ormYo::Conn();
$conn->startTransaction();
$re = loan_contractClass::requestRepaymentConfirmReceived($request_id, $received_date, $handler_info);
if (!$re->STS) {
$conn->rollback();
return new result(false, $re->MSG);
}
$conn->submitTransaction();
return new result(true, 'Handle success!');
}catch(Exception $e ){
return new result(false,$e->getMessage());
}
}
}
/**
* 查看提前还款申请情况
*/
public function viewRequestRepaymentOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$r = new ormReader();
$sql = "SELECT lrr.*,lc.contract_sn"
. " FROM loan_prepayment_apply lrr"
. " INNER JOIN loan_contract lc ON lrr.contract_id = lc.uid"
. " WHERE lrr.uid =" . $uid;
$detail = $r->getRow($sql);
if (!$detail) {
showMessage('Invalid Id!');
}
Tpl::output('detail', $detail);
Tpl::showpage('request.prepayment.view');
}
/**
* 查看还款明细
*/
public function viewRequestRepaymentDetailOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$r = new ormReader();
$sql = "select r.*,c.contract_sn from loan_request_repayment r left join loan_contract c on r.contract_id=c.uid where r.uid='$uid' ";
$detail = $r->getRow($sql);
$payment_type_lang = enum_langClass::getPaymentTypeLang();
Tpl::output('detail', $detail);
Tpl::output('payment_type_lang', $payment_type_lang);
Tpl::showpage('request.repayment.view');
}
/**
* @param $p
* @return result
*/
public function modifyPenaltiesOp($p)
{
$uid = intval($p['uid']);
$r = new ormReader();
$sql = "SELECT * FROM loan_contract WHERE uid = $uid AND state > " . loanContractStateEnum::PENDING_APPROVAL;
$loan_contract = $r->getRow($sql);
if (!$loan_contract) {
return array("sts" => false);
}
$sql3 = "SELECT * FROM loan_deducting_penalties WHERE contract_id = $uid AND state <= " . loanDeductingPenaltiesState::PROCESSING;
$deducting_penalties = $r->getRow($sql3);
$sql = "SELECT * FROM loan_installment_scheme WHERE contract_id = $uid AND state < " . schemaStateTypeEnum::COMPLETE . " AND penalty_start_date < '" . Now() . "'";
$scheme_list = $r->getRows($sql);
$penalties_total = 0;
$deduction_total = 0;
foreach ($scheme_list as $key => $scheme) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($scheme['uid']);
$scheme['penalties'] = $penalties;
$penalties_total += $penalties;
$deduction_total += $scheme['deduction_penalty'];
$scheme_list[$key] = $scheme;
}
return array(
"sts" => true,
"loan_contract" => $loan_contract,
"deducting_penalties" => $deducting_penalties,
"penalties_total" => $penalties_total,
"deduction_total" => $deduction_total,
"data" => $scheme_list
);
}
/**
* 保存减免罚息申请
* @param $p
* @return result
*/
public function savePenaltiesApplyOp($p)
{
$contract_id = intval($p['uid']);
$deducting_penalties = round($p['deducting_penalties'], 2);
$remark = $p['remark'];
$r = new ormReader();
$sql = "SELECT * FROM loan_contract WHERE uid = $contract_id AND state > " . loanContractStateEnum::PENDING_APPROVAL;
$loan_contract = $r->getRow($sql);
if (!$loan_contract) {
return new result(false, 'Invalid Id!');
}
$sql3 = "SELECT * FROM loan_deducting_penalties WHERE contract_id = $contract_id AND state <= " . loanDeductingPenaltiesState::PROCESSING;
$deducting_penalties_apply = $r->getRow($sql3);
if ($deducting_penalties_apply) {
return new result(false, 'There has been an unaudited application!');
}
$sql = "SELECT * FROM loan_installment_scheme WHERE contract_id = $contract_id AND state < " . schemaStateTypeEnum::COMPLETE . " AND penalty_start_date < '" . Now() . "'";
$scheme_list = $r->getRows($sql);
$penalties_total = 0;
foreach ($scheme_list as $key => $scheme) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($scheme['uid']);
$penalties_total += $penalties;
}
if ($deducting_penalties > $penalties_total) {
return new result(false, 'It can\'t be greater than penalties total!');
}
$m_loan_deducting_penalties = M('loan_deducting_penalties');
$row = $m_loan_deducting_penalties->newRow();
$row->contract_id = $contract_id;
$row->deducting_penalties = $deducting_penalties;
$row->type = 1;
$row->remark = $remark;
$row->state = loanDeductingPenaltiesState::CREATE;
$row->creator_id = $this->user_id;
$row->creator_name = $this->user_name;
$row->creator_name = $this->user_name;
$row->create_time = Now();
$rt = $row->insert();
if ($rt->STS) {
return new result(true, 'Add Successful!');
} else {
return new result(false, 'Add Failure!');
}
}
/**
* 减免罚息
*/
public function deductingPenaltiesOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showPage('deducting_penalties');
}
/**
* @param $p
* @return array
*/
public function getDeductingPenaltiesListOp($p)
{
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT ldp.*,lc.contract_sn FROM loan_deducting_penalties ldp"
. " INNER JOIN loan_contract lc ON ldp.contract_id = lc.uid"
. " WHERE (ldp.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn like '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY ldp.create_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 审核减免申请
*/
public function showAuditPenaltiesOp()
{
$uid = intval($_GET['uid']);
$m_loan_deducting_penalties = M('loan_deducting_penalties');
$deducting_penalties = $m_loan_deducting_penalties->find(array('uid' => $uid));
if (!$deducting_penalties || $deducting_penalties['state'] != loanDeductingPenaltiesState::CREATE) {
showMessage('Invalid Id!');
}
$r = new ormReader();
$contract_id = intval($deducting_penalties['contract_id']);
$sql = "SELECT lc.*,cm.display_name,cm.login_code FROM loan_contract lc LEFT JOIN loan_account la ON lc.account_id = la.uid"
. " LEFT JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " WHERE lc.uid = $contract_id AND lc.state > " . loanContractStateEnum::PENDING_APPROVAL;
$loan_contract = $r->getRow($sql);
if (!$loan_contract) {
showMessage('Invalid Id!');
}
$sql = "SELECT * FROM loan_installment_scheme WHERE contract_id = $contract_id AND state < " . schemaStateTypeEnum::COMPLETE . " AND penalty_start_date < '" . Now() . "'";
$scheme_list = $r->getRows($sql);
$penalties_total = 0;
$deduction_total = 0;
foreach ($scheme_list as $key => $scheme) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($scheme['uid']);
$scheme['penalties'] = $penalties;
$penalties_total += $penalties;
$deduction_total += $scheme['deduction_penalty'];
$scheme_list[$key] = $scheme;
}
$loan_contract['penalties_total'] = $penalties_total;
$loan_contract['deduction_total'] = $deduction_total;
Tpl::output('deducting_penalties', $deducting_penalties);
Tpl::output('loan_contract', $loan_contract);
Tpl::output('scheme_list', $scheme_list);
Tpl::showpage('audit.penalties');
}
/**
* 审核
* @param $p
* @return result
*/
public function auditPenaltiesOp($p)
{
$uid = intval($p['uid']);
$type = $p['type'];
$r = new ormReader();
$m_loan_deducting_penalties = M('loan_deducting_penalties');
$m_loan_installment_scheme = M('loan_installment_scheme');
$deducting_penalties_row = $m_loan_deducting_penalties->getRow(array('uid' => $uid));
if (!$deducting_penalties_row || $deducting_penalties_row['state'] != loanDeductingPenaltiesState::CREATE) {
return new result(false, 'Invalid Id!');
}
if ($type == 'disapprove') {
$deducting_penalties_row->state = loanDeductingPenaltiesState::DISAPPROVE;
$deducting_penalties_row->auditor_id = $this->user_id;
$deducting_penalties_row->auditor_id = $this->user_name;
$deducting_penalties_row->audit_time = Now();
$rt = $deducting_penalties_row->update();
if ($rt->STS) {
return new result(true, 'Audit Successful!');
} else {
return new result(true, 'Audit Failure!');
}
} else {
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$deducting_penalties_row->state = loanDeductingPenaltiesState::USED;
$deducting_penalties_row->auditor_id = $this->user_id;
$deducting_penalties_row->auditor_name = $this->user_name;
$deducting_penalties_row->audit_time = Now();
$rt_1 = $deducting_penalties_row->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(true, 'Audit Failure!');
}
$deducting_penalties = $deducting_penalties_row['deducting_penalties'];
$contract_id = $deducting_penalties_row['contract_id'];
$sql = "SELECT * FROM loan_installment_scheme WHERE contract_id = $contract_id AND state!=" . schemaStateTypeEnum::CANCEL . " AND state < " . schemaStateTypeEnum::COMPLETE . " AND penalty_start_date < '" . Now() . "'";
$scheme_list = $r->getRows($sql);
if (!$scheme_list) {
$conn->rollback();
return new result(true, 'Invalid Id!');
}
foreach ($scheme_list as $scheme) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($scheme['uid']);
if ($penalties <= 0) continue;
if ($penalties > $deducting_penalties) {
$deduction_penalty = $deducting_penalties + $scheme['deduction_penalty'];
$rt = $m_loan_installment_scheme->update(array('uid' => $scheme['uid'], 'deduction_penalty' => $deduction_penalty));
if (!$rt->STS) {
$conn->rollback();
return new result(true, 'Audit Failure!');
} else {
break;
}
} else {
$deducting_penalties -= $penalties;
$deduction_penalty = $penalties + $scheme['deduction_penalty'];
$update = array(
'uid' => $scheme['uid'],
'deduction_penalty' => $deduction_penalty
);
if ($scheme['actual_payment_amount'] >= $scheme['amount']) {
$update['state'] = schemaStateTypeEnum::COMPLETE;
$update['done_time'] = Now();
}
$rt = $m_loan_installment_scheme->update($update);
if (!$rt->STS) {
$conn->rollback();
return new result(true, 'Audit Failure!');
}
}
}
$is_paid_off = loan_contractClass::contractIsPaidOff($contract_id);
if ($is_paid_off) {
$rt_2 = loan_contractClass::contractComplete($contract_id);
if (!$rt_2->STS) {
$conn->rollback();
return $rt_2;
}
}
$conn->submitTransaction();
return new result(true, 'Audit Successful!');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
}
/**
* 确认还款
* @param $p
* @return result
*/
public function submitRepaymentOp($p)
{
$uid = intval($p['uid']);
$repayment_total = round($p['repayment_total'], 2);
$remark = trim($p['remark']);
$currency = $p['currency'] ? $p['currency'] : currencyEnum::USD;
$class_user = new userClass();
$user_info = $class_user->getUserInfo($this->user_id);
$payment_info = array(
'branch_id' => $user_info->DATA['branch_id'],
'teller_id' => $this->user_id,
'teller_name' => $this->user_name,
'creator_id' => $this->user_id,
'creator_name' => $this->user_name,
'remark' => $remark
);
try{
$conn = ormYo::Conn();
$conn->startTransaction();
$rt = loan_contractClass::schemaManualRepaymentByCash($uid,$repayment_total,$currency,$user_info->DATA['branch_id'],$this->user_id,$this->user_name);
if ($rt->STS) {
$conn->submitTransaction();
return new result(true, 'Repayment successful!');
} else {
$conn->rollback();
return new result(false, 'Repayment failure!');
}
}catch( Exception $e ){
return new result(false, 'Repayment failure!'.$e->getMessage());
}
}
/**
* 核销贷款
*/
public function writeOffApplyOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$rt = loan_contractClass::calculateContractWriteOffLoss($uid);
if (!$rt->STS) {
showMessage($rt->MSG);
}
$loss_amount = $rt->DATA['loss_principal'];
if ($p['form_submit'] == 'ok') {
$close_remark = trim($p['close_remark']);
if (!$close_remark) {
showMessage('Remark required!');
}
$m_loan_writtenoff = M('loan_writtenoff');
$row = $m_loan_writtenoff->newRow();
$row->contract_id = $uid;
$row->close_type = 10;
$row->close_remark = $close_remark;
$row->loss_amount = $loss_amount;
$row->creator_id = $this->user_id;
$row->creator_name = $this->user_name;
$row->create_time = Now();
$row->state = writeOffStateEnum::CREATE;
$rt = $row->insert();
if ($rt->STS) {
showMessage('Add successful!', getUrl('loan', 'contractDetail', array('uid' => $uid), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->STS);
}
} else {
$r = new ormReader();
$sql = "SELECT lc.*,cm.display_name FROM loan_contract lc"
. " INNER JOIN loan_account la ON lc.account_id = la.uid"
. " INNER JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " WHERE lc.uid = $uid";
$contact_info = $r->getRow($sql);
if (!$contact_info) {
showMessage('Invalid Id!');
}
$sql = "SELECT * FROM loan_writtenoff WHERE contract_id = $uid AND state IN (" . writeOffStateEnum::CREATE . ',' . writeOffStateEnum::APPROVING . ') ORDER BY uid DESC';
$write_off = $r->getRow($sql);
if ($write_off) {
Tpl::output('write_off', $write_off);
}
$contact_info['loss_amount'] = $loss_amount;
Tpl::output('contact_info', $contact_info);
Tpl::showpage('write.off.apply');
}
}
/**
* 核销列表
*/
public function writeOffOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
$type = $_GET['type'] ?: 'unprocessed';
Tpl::output('type', $type);
Tpl::showPage('write.off');
}
/**
* 获取核销列表
* @param $p
* @return array
*/
public function getWriteOffListOp($p)
{
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT lw.*,lc.contract_sn,cm.display_name FROM loan_writtenoff lw"
. " INNER JOIN loan_contract lc ON lw.contract_id = lc.uid"
. " INNER JOIN loan_account la ON lc.account_id = la.uid"
. " INNER JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " WHERE (lw.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['type']) == 'unprocessed') {
$sql .= " AND lw.state < " . writeOffStateEnum::INVALID;
} else {
$sql .= " AND lw.state > " . writeOffStateEnum::APPROVING;
}
if (trim($p['search_text'])) {
$sql .= " AND (lc.contract_sn like '%" . trim($p['search_text']) . "%' OR cm.display_name like '%" . trim($p['search_text']) . "%')";
}
$sql .= " ORDER BY lw.create_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"cur_uid" => $this->user_id,
"type" => trim($p['type']),
);
}
/**
* 审核还款申请
*/
public function auditWriteOffOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($p['uid']);
$m_loan_writtenoff = M('loan_writtenoff');
$row = $m_loan_writtenoff->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
if ($p['form_submit'] == 'ok') {
$conn = ormYo::Conn();
$conn->startTransaction();
if ($row->auditor_id == $this->user_id && $row->state == writeOffStateEnum::APPROVING) {
$state = $p['state'] == 'approve' ? writeOffStateEnum::COMPLETE : writeOffStateEnum::INVALID;
$row->state = $state;
$row->update_time = Now();
if ($state == writeOffStateEnum::COMPLETE) {
$row->close_date = Now();
$rt = loan_contractClass::contractWriteOff($uid, array('auditor_id' => $this->user_id, 'auditor_name' => $this->user_name));
if (!$rt->STS) {
$conn->rollback();
showMessage($rt->MSG);
}
}
$rt_1 = $row->update();
if ($rt_1->STS) {
$conn->submitTransaction();
showMessage('Audit successful!', getUrl('loan', 'writeOff', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL));
} else {
$conn->rollback();
showMessage('Audit failed!' . $rt->MSG);
}
} else {
showMessage('Param error!');
}
}
//审核中
if ($row->state == writeOffStateEnum::APPROVING) {
// 超时放开,让别人可审 1小时
if ((strtotime($row['update_time']) + 3600) < time()) {
$row->state = writeOffStateEnum::APPROVING;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->update_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG);
}
}
} elseif ($row->state == writeOffStateEnum::CREATE) {
$row->state = writeOffStateEnum::APPROVING;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->update_time = Now();
$rt = $row->update();
if (!$rt->STS) {
showMessage($rt->MSG);
}
}
$lock = false;
if ($this->user_id != $row['auditor_id']) {
//审核中
$lock = true;
}
Tpl::output('lock', $lock);
$r = new ormReader();
$sql = "SELECT lw.*,lc.contract_sn,cm.display_name FROM loan_writtenoff lw"
. " INNER JOIN loan_contract lc ON lw.contract_id = lc.uid"
. " INNER JOIN loan_account la ON lc.account_id = la.uid"
. " INNER JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " WHERE lw.uid = $uid";
$detail = $r->getRow($sql);
Tpl::output('detail', $detail);
Tpl::showpage('write.off.audit');
}
}
<file_sep>/framework/api_test/apis/microbank/credit.loan.withdraw.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/30
* Time: 14:20
*/
class creditLoanWithdrawApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Credit Loan Withdraw";
$this->description = "信用贷款体现";
$this->url = C("bank_api_url") . "/credit_loan.withdraw.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", '会员id', 1, true);
$this->parameters[]= new apiParameter("amount", "贷款金额", 500, true);
$this->parameters[]= new apiParameter("loan_period", "贷款时间", 6, true);
//$this->parameters[]= new apiParameter("loan_period_unit", "贷款时间单位,年 year 月 month 日 day", 'month', true);
//$this->parameters[]= new apiParameter("repayment_type", "还款方式,只支持三个,等额本息 annuity_scheme,一次偿还 single_repayment,先利息后本金 balloon_interest", 'annuity_scheme', true);
//$this->parameters[]= new apiParameter("repayment_period", "还款周期,一年一次 yearly,半年一次 semi_yearly,一季度一次 quarter,一月一次 monthly,一周一次 weekly", 'monthly', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
//$this->parameters[]= new apiParameter("propose", "贷款目的", '', false);
$this->parameters[] = new apiParameter('insurance_item_id','绑定的保险项目id,多个用,隔开,如 1,5,9 ',0);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'contract_id' => '合同id',
'loan_amount' => '贷款金额',
'currency' => '货币类型',
'loan_period_value' => '贷款周期',
'loan_period_unit' => '贷款周期单位 year 年 month 月 day 日',
'repayment_type' => '还款方式',
'repayment_period' => '还款周期',
'interest_rate' => '利率值',
'interest_rate_type' => '利率类型',
'interest_rate_unit' => '利率周期,yearly 年 monthly 月 daily 日',
'due_date' => '还款日',
'due_date_type' => '还款日类型,once 一次还,日期 yearly 每年(周期的月-日) monthly 每月多少号 weekly 每周几(0-6)daily 每天',
'admin_fee' => '管理费',
'insurance_fee' => '保险费',
'operation_fee' => '总计运营费',
'total_interest' => '合计利息',
'actual_receive_amount' => '实发款金额',
'total_repayment' => '总计应还本金+利息',
'lending_time' => '贷款时间',
'contract_info' => '合同详细信息',
'loan_product_info' => '贷款产品信息',
'interest_info' => '贷款利率信息',
'size_rate' => '基本利率信息',
'special_rate' => '特殊利率信息',
'loan_disbursement_scheme' => '放款计划',
'loan_installment_scheme' => '还款计划',
'bind_insurance' => '绑定的保险合同',
)
);
}
}<file_sep>/framework/weixin_baike/entry_desktop/control/index.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2017/10/16
* Time: 10:44
*/
class indexControl extends baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setLayout("book_layout");
Tpl::setDir("layout");
Tpl::output("html_title", "Back Office");
Tpl::output("user_info", $this->user_info);
Tpl::output("is_operator", in_array(userPositionEnum::OPERATOR, $this->user_position));
Tpl::output("menu_items", $this->getResetMenu());
if (in_array(userPositionEnum::OPERATOR, $this->user_position)) {
Tpl::output('system_title', 'Operator');
}
}
public function indexOp()
{
if (in_array(userPositionEnum::OPERATOR, $this->user_position)) {
$rt = $this->getTaskNumOp();
Tpl::output("task_num", $rt->DATA);
}
Tpl::showPage("null_layout");
}
}<file_sep>/framework/api_test/apis/microbank/member.mortgage.goods.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/6
* Time: 18:01
*/
// member.mortgage.goods.list.php
class memberMortgageGoodsListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member mortgage goods List";
$this->description = "会员抵押的物品";
$this->url = C("bank_api_url") . "/member.mortgage.goods.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "身份令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'list' => array(
'@description' => '没有为null',
array(
'uid' => '资产ID',
'asset_type' => '资产类型',
'valuation' => '估值',
'mortgage_time' => '抵押时间',
'main_image' => '图片'
)
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.get.member.residence.place.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/17
* Time: 14:29
*/
class officerGetMemberResidencePlaceApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Get member residence place";
$this->description = "获取会员居住地址";
$this->url = C("bank_api_url") . "/officer.get.member.residence.place.php";
$this->parameters = array();
$this->parameters[] = new apiParameter("member_id", "会员id", 1, true);
$this->parameters[] = new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'address_info' => array(
'@description' => '没有为null',
'uid' => '地址ID',
'coord_x' => '经度',
'coord_y' => '纬度',
'full_text' => '全地址',
'create_time' => ''
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/member_follow_officer.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/1
* Time: 14:25
*/
class member_follow_officerModel extends tableModelBase
{
function __construct()
{
parent::__construct('member_follow_officer');
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/client.list.php
<style>
.avatar-icon {
width: 50px;
height: 50px;
}
</style>
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Icon'; ?></td>
<td><?php echo 'CID'; ?></td>
<td><?php echo 'Name'; ?></td>
<td><?php echo 'Phone'; ?></td>
<td><?php echo 'Email'; ?></td>
<td><?php echo 'Account Type'; ?></td>
<td><?php echo 'State'; ?></td>
<?php if ($data['verify_state'] != newMemberCheckStateEnum::CREATE) { ?>
<td><?php echo 'Operator'; ?></td>
<?php }?>
<?php if (!in_array($data['verify_state'], array(newMemberCheckStateEnum::CREATE, newMemberCheckStateEnum::LOCKED))) { ?>
<td><?php echo 'Operator Remark'; ?></td>
<?php } ?>
<?php if ($data['verify_state'] == newMemberCheckStateEnum::ALLOT) { ?>
<td><?php echo 'Credit Officer'; ?></td>
<?php } ?>
<td><?php echo 'Create Time'; ?></td>
<?php if (in_array($data['verify_state'], array(newMemberCheckStateEnum::CREATE, newMemberCheckStateEnum::LOCKED))) { ?>
<td><?php echo 'Function'; ?></td>
<?php } ?>
</tr>
</thead>
<tbody class="table-body">
<?php if ($data['data']) { ?>
<?php foreach ($data['data'] as $row) { ?>
<tr>
<td>
<?php if ($row['member_icon']) { ?>
<a href="<?php echo $row['member_icon'] ?>">
<img class="avatar-icon" src="<?php echo $row['member_icon'] ?>">
</a>
<?php } ?>
</td>
<td>
<?php echo $row['obj_guid'] ?>
</td>
<td>
<?php echo $row['display_name'] ?>
</td>
<td>
<?php echo $row['phone_id'] ?>
</td>
<td>
<?php echo $row['email'] ?>
</td>
<td>
<?php if ($row['account_type'] == 0) {
echo 'Member';
} ?>
</td>
<td>
<?php echo $lang['operator_task_state_' . $row['operate_state']] ?>
</td>
<?php if ($data['verify_state'] != newMemberCheckStateEnum::CREATE) { ?>
<td>
<?php echo $row['operator_name'] ?>
</td>
<?php } ?>
<?php if (!in_array($data['verify_state'], array(newMemberCheckStateEnum::CREATE, newMemberCheckStateEnum::LOCKED))) { ?>
<td>
<?php echo $row['operate_remark'] ?>
</td>
<?php } ?>
<?php if ($data['verify_state'] == newMemberCheckStateEnum::ALLOT) { ?>
<td>
<?php echo $row['co_name'] ?>
</td>
<?php } ?>
<td>
<?php echo timeFormat($row['create_time']); ?>
</td>
<?php if (in_array($data['verify_state'], array(newMemberCheckStateEnum::CREATE, newMemberCheckStateEnum::LOCKED))) { ?>
<td>
<?php if($row['operate_state'] == newMemberCheckStateEnum::CREATE || ($row['operate_state'] == newMemberCheckStateEnum::LOCKED && $row['operator_id'] == $data['current_user'])){?>
<div class="custom-btn-group">
<a class="custom-btn custom-btn-secondary"
href="<?php echo getUrl('operator', 'checkNewClient', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<span><i class="fa fa-vcard-o"></i><?php echo $row['operate_state'] == newMemberCheckStateEnum::CREATE ? 'Get' : 'Handle';?></span>
</a>
</div>
<?php }?>
</td>
<?php } ?>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="20">
Null
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<hr>
<?php include_once(template("widget/inc_content_pager")); ?>
<file_sep>/framework/api_test/apis/microbank/loan.product.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/5
* Time: 10:44
*/
//loan.product.detail
class loanProductDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Product Detail";
$this->description = "贷款产品详细";
$this->url = C("bank_api_url") . "/loan.product.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("product_id", "产品ID", 1, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'product_info' =>
array(
'uid' => '产品ID',
'product_code' => '产品Code',
'product_name' => '产品名',
'product_description' => '产品描述,富文本',
'product_qualification' => '贷款条件,富文本',
'product_feature' => '产品特色,富文本',
'product_required' => '贷款必须资料,富文本',
'product_notice' => '产品公告,富文本',
//'state' => '状态',
//'create_time' => '创建时间',
//'creator_id' => '创建者Id',
//'creator_name' => '创建者Name',
'update_time' => '更新时间',
'penalty_divisor_days' => '罚款利率除以多少天',
'penalty_on' => '罚款基数',
'penalty_rate' => '罚款利率',
'is_multi_contract' => '允许多合同标志',
'is_advance_interest' => '罚款利率',
'is_editable_penalty' => '是否允许合同修改罚款利率',
'is_editable_interest' => '是否允许修改利息',
'is_editable_grace_days' => '是否允许修改宽限天数',
'product_key' => '产品系列key',
'is_credit_loan' => '是否信用贷',
'min_rate_desc' => '最低利率',
),
'rate_list' => array(
array(
'uid' => '利率ID',
'product_id' => '产品id',
'currency' => '币种',
'loan_size_min' => '最低贷款金额',
'loan_size_max' => '最高贷款金额',
'loan_term_time' => '可贷款时间周期',
'repayment_type' => '还款方式',
'repayment_period' => '还款周期,只有分期付款才有',
'interest_rate_des' => '利息利率值',
'total_rate_des_value' => '合计利息利率值(合计interest+operation)',
'interest_rate_unit' => '利息利率周期',
'operation_fees_des' => '运营费利率值',
'operation_fee_unit' => '运营费利率周期',
)
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.get.member.assessment.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 16:24
*/
class officerGetMemberAssessmentApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member assessment";
$this->description = "会员综合评估";
$this->url = C("bank_api_url") . "/officer.get.member.assessment.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'asset_evaluation' => '资产估值',
'business_profitability' => '业务盈利能力'
)
);
}
}<file_sep>/framework/index.php
<?php
header('Location: weixin_baike/mobile/index.php');<file_sep>/framework/weixin_baike/api/control/bank_api.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 10:18
*/
abstract class bank_apiControl{
protected $appId;
protected $appKey;
public function __construct()
{
}
/**
* app使用api检查token
* @return result
*/
protected function checkToken($app='member')
{
$params = array_merge(array(),$_GET,$_POST);
if( empty($params['token']) ){
return new result(false,'Invalid token',null,errorCodesEnum::NO_LOGIN);
}
$m_member_token = new member_tokenModel();
$token = $m_member_token->orderBy('uid desc')->getRow(array(
'token' => $params['token']
));
if( !$token ){
return new result(false,'Invalid token',null,errorCodesEnum::INVALID_TOKEN);
}
// 检查过期时间,超过12小时重新登录
if( ( strtotime($token['create_time']) + 12*3600 ) < time() ){
$token->delete();
return new result(false,'Invalid token',null,errorCodesEnum::INVALID_TOKEN);
}
return new result(true);
}
protected function checkOperator()
{
$params = array_merge(array(),$_GET,$_POST);
if( empty($params['token']) ){
return new result(false,'Invalid token',null,errorCodesEnum::NO_LOGIN);
}
$m_token = new um_user_tokenModel();
$token = $m_token->orderBy('uid desc')->getRow(array(
'token' => $params['token']
));
if( !$token ){
return new result(false,'Invalid token',null,errorCodesEnum::INVALID_TOKEN);
}
return new result(true);
}
protected function checkAppSign()
{
$params = array_merge(array(),$_GET,$_POST);
$key = getConf('app_secret_key');
if ( $this->sign($params,$key) != $params['sign'] ) {
return new result(false, "Sign error", null, errorCodesEnum::SIGN_ERROR);
}
return new result(true);
}
/**
* 强验证api检查签名
* @return result
*/
protected function checkSign()
{
$api_config = getConf('api_config');
if( !$api_config ){
return new result(false,'Api config not exist!',null,errorCodesEnum::CONFIG_ERROR);
}
$this->appId = $api_config['appId'];
$this->appKey = $api_config['appKey'];
$params = array_merge(array(),$_GET,$_POST);
if ( $this->sign($params,$this->appKey) != $params['sign'] ) {
return new result(false, "Sign error", null, errorCodesEnum::SIGN_ERROR);
}
return new result(true);
}
protected function sign($parameters,$key)
{
$parameters = array_ksort($parameters);
$segments = array();
foreach ($parameters as $k=>$v) {
if ($k == "sign_type") continue;
if ($k == "sign") continue;
if ($k == "act") continue;
if ($k == "op") continue;
if ($k == "yoajax") continue;
if ($k == "_s") continue;
if ($v === null || $v === "") continue;
$segments[]="$k=$v";
}
return md5(join("&", $segments).$key);
}
}
<file_sep>/framework/api_test/apis/officer_app/officer.get.member.work.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 16:00
*/
class officerGetMemberWorkDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member work detail";
$this->description = "会员工作详情";
$this->url = C("bank_api_url") . "/officer.get.member.work.detail.php";
$this->parameters = array();
$this->parameters[] = new apiParameter("member_id", "会员id", 1, true);
$this->parameters[] = new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'work_detail' => array(
'@description' => '没有认证为null',
'company_name' => '公司名字',
'company_addr' => '公司地址',
'position' => '职位',
'is_government' => '是否公务员',
'state' => '认证状态 0 新建 10 审核中 20 当前active 30 历史'
)
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/language/en/auth.php
<?php
$lang['auth_home'] = 'Home Group';
$lang['auth_home_monitor'] = 'Monitor';
$lang['auth_user'] = 'Hr Group';
$lang['auth_user_branch'] = 'Branch';
$lang['auth_user_department'] = 'Department';
$lang['auth_user_role'] = 'Role';
$lang['auth_user_user'] = 'User';
$lang['auth_user_log'] = 'User Log';
$lang['auth_user_pointevent'] = 'Point Event';
$lang['auth_user_pointperiod'] = 'Point Period';
$lang['auth_user_departmentpoint'] = 'Department Point';
$lang['auth_client'] = 'Client Group';
$lang['auth_client_client'] = 'Client';
$lang['auth_client_cerification'] = 'Certification File';
$lang['auth_client_blacklist'] = 'Black List';
$lang['auth_client_grade'] = 'Grade';
$lang['auth_partner'] = 'Partner Group';
$lang['auth_partner_bank'] = 'Bank';
$lang['auth_partner_dealer'] = 'Dealer';
$lang['auth_loan'] = 'Loan Group';
$lang['auth_loan_product'] = 'Loan Product';
$lang['auth_loan_credit'] = 'Grant Credit';
$lang['auth_loan_approval'] = 'Approval Credit';
$lang['auth_loan_apply'] = 'Request To Loan';
$lang['auth_loan_requesttoprepayment'] = 'Request To Prepayment';
$lang['auth_loan_requesttorepayment'] = 'Repayment';
$lang['auth_loan_contract'] = 'Contract';
$lang['auth_loan_writeoff'] = 'Write Off';
//$lang['auth_loan_prepayment'] = 'Prepayment';
$lang['auth_loan_overdue'] = 'Overdue';
$lang['auth_loan_deductingpenalties'] = 'Deducting Penalties';
$lang['auth_insurance'] = 'Insurance Group';
$lang['auth_insurance_product'] = 'Insurance Product';
$lang['auth_insurance_contract'] = 'Insurance Contract';
$lang['auth_setting'] = 'Setting Group';
$lang['auth_setting_companyinfo'] = 'Company Info';
$lang['auth_setting_creditlevel'] = 'Credit Level';
$lang['auth_setting_creditprocess'] = 'Credit Process';
$lang['auth_setting_global'] = 'Global';
$lang['auth_region_list'] = 'Region';
$lang['auth_setting_systemdefine'] = 'System Define';
$lang['auth_setting_shortcode'] = 'Short Code';
$lang['auth_setting_codingrule'] = 'Coding Rule';
$lang['auth_setting_exchangerates'] = 'Exchange Rates';
$lang['auth_setting_resetsystem'] = 'Reset System';
$lang['auth_financial'] = 'Financial Group';
$lang['auth_financial_bankaccount'] = 'Bank Account';
$lang['auth_financial_exchangerate'] = 'Exchange Rate';
$lang['auth_dev'] = 'Dev Group';
$lang['auth_dev_appversion'] = 'App Version';
$lang['auth_dev_functionswitch'] = 'Function Switch';
$lang['auth_dev_resetpassword'] = 'Reset Password';
$lang['auth_report'] = 'Report Group';
$lang['auth_report_overview'] = 'Overview';
$lang['auth_report_clientlist'] = 'Client List';
$lang['auth_report_contractlist'] = 'Contract List';
$lang['auth_report_creditlist'] = 'Credit List';
$lang['auth_report_todayreport'] = 'Today Report';
$lang['auth_report_loanlist'] = 'Loan List';
$lang['auth_report_repaymentlist'] = 'Repayment List';
$lang['auth_report_assetliability'] = 'Asset Liability';
$lang['auth_report_profitreport'] = 'Profit Report';
$lang['auth_editor'] = 'Editor Group';
$lang['auth_editor_help'] = 'Cms';
$lang['auth_tools'] = 'Tools Group';
$lang['auth_tools_calculator'] = 'Calculator';
$lang['auth_tools_sms'] = 'SMS';
$lang['auth_counter_member'] = 'Member Group';
$lang['auth_counter_member_register'] = 'Register';
$lang['auth_counter_member_documentcollection'] = 'Document Collection';
$lang['auth_counter_member_fingerprintcollection'] = 'Fingerprint Collection';
$lang['auth_counter_member_loan'] = 'Loan';
$lang['auth_counter_member_deposit'] = 'deposit';
$lang['auth_counter_member_withdrawal'] = 'Withdrawal';
$lang['auth_counter_member_profile'] = 'Profile';
$lang['auth_counter_member_profile'] = 'Profile';
$lang['auth_counter_company'] = 'Company Group';
$lang['auth_counter_company_index'] = 'Index';
$lang['auth_counter_service'] = 'Service Group';
$lang['auth_counter_service_requestloan'] = 'Request Loan';
$lang['auth_counter_service_currencyexchange'] = 'Currency Exchange';
$lang['auth_counter_mortgage'] = 'Mortgage Group';
$lang['auth_counter_mortgage_index'] = 'Index';
$lang['auth_counter_cash_on_hand'] = 'Cash On Hand Group';
$lang['auth_counter_cash_cashonhand'] = 'Cash On Hand';
$lang['auth_counter_cash_in_vault'] = 'Cash In Vault Group';
$lang['auth_counter_cash_cashinvault'] = 'Cash In Vault';<file_sep>/framework/weixin_baike/backoffice/templates/default/report/credit.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Name';?></td>
<td><?php echo 'Before Credit';?></td>
<td><?php echo 'Approval Credit';?></td>
<td><?php echo 'Type';?></td>
<td><?php echo 'Remark';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Operator';?></td>
<td><?php echo 'Operate Time';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<a href="#" onclick="search_name('<?php echo $row['display_name'] ?>')"><?php echo $row['display_name'] ?></a>
</td>
<td>
<?php echo $row['before_credit']; ?>
</td>
<td>
<?php echo $row['current_credit']; ?>
</td>
<td>
<?php echo $lang['loan_credit_type_' . $row['type']]; ?>
</td>
<td>
<?php echo $row['remark']; ?>
</td>
<td>
<?php echo $lang['loan_credit_state_' . $row['state']]; ?>
</td>
<td><?php echo $row['user_name'] ;?></td>
<td><?php echo timeFormat($row['operate_time']) ;?></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/weixin_baike/backoffice/templates/default/client/client.php
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Client</h3>
<ul class="tab-base">
<li><a class="current"><span>List</span></a></li>
</ul>
</div>
</div>
<div class="container">
<div class="table-form">
<div class="business-condition">
<form class="form-inline" id="frm_search_condition">
<table class="search-table">
<tr>
<td>
<div class="form-group">
<label for="exampleInputName2">CID</label>
<input type="text" class="form-control" name="member_item" id="member_item">
</div>
</td>
<td>
<div class="form-group">
<label for="exampleInputName2">Name</label>
<input type="text" class="form-control" name="username" id="username">
</div>
</td>
<td>
<div class="form-group">
<label for="exampleInputName2">Phone</label>
<div style="display: inline-block;">
<select class="form-control" name="country_code" id="country_code" style="float:left;">
<option value="855">+855</option>
<option value="84">+84</option>
<option value="86">+86</option>
</select>
<input type="text" class="form-control" name="phone" id="phone" style="margin-left: -1px;">
</div>
</div>
</td>
<td>
<div class="form-group">
<label>
<input type="checkbox" name="ck" id="ck"> Register On Today
</label>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-default" id="btn_search_list" onclick="btn_search_onclick();">
<i class="fa fa-search"></i>
<?php echo 'Search';?>
</button>
</span>
</div><!-- /input-group -->
</td>
</tr>
</table>
</form>
</div>
<hr>
<div class="business-content">
<div class="business-list"></div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
btn_search_onclick();
});
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 10;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var member_item = $('#member_item').val(), member_name = $('#username').val(), ck = $('#ck').is(':checked'), country_code = $('#country_code').val(), phone = $('#phone').val();
mobile = phone ? '+' + country_code + phone : '';
yo.dynamicTpl({
tpl: "client/client.list",
dynamic: {
api: "client",
method: "getClientList",
param: {pageNumber: _pageNumber, pageSize: _pageSize, member_item: member_item, member_name: member_name, ck: ck, phone: mobile}
},
callback: function (_tpl) {
$(".business-list").html(_tpl);
}
});
}
</script>
<file_sep>/framework/api_test/apis/microbank/member.message.delete.php
<?php
class memberMessageDeleteApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Delete Messages";
$this->description = "会员删除收到的消息";
$this->url = C("bank_api_url") . "/member.message.delete.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("message_id_list", "消息ID列表,使用|分割多个ID", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)'
);
}
}<file_sep>/framework/api_test/apis/microbank/member.message.unread.count.php
<?php
class memberMessageUnreadCountApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Get Member Unread Messages Count";
$this->description = "获取会员未读消息条数";
$this->url = C("bank_api_url") . "/member.message.unread.count.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '未读消息条数'
);
}
}<file_sep>/framework/weixin_baike/api/control/loan_common.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/13
* Time: 10:17
*/
class loan_commonControl extends bank_apiControl
{
public function newCalculatorOp()
{
$params = array_merge(array(),$_GET,$_POST);
$loan_amount = $params['loan_amount'];
$loan_period = $params['loan_period'];
$loan_period_unit = $params['loan_period_unit'];
$repayment_type = $params['repayment_type'];
$repayment_period = $params['repayment_period'];
if( $loan_amount < 1 ){
return new result(false,'Invalid amount',null,errorCodesEnum::INVALID_PARAM);
}
if( $loan_period <= 0 ){
return new result(false,'Invalid loan period',null,errorCodesEnum::INVALID_PARAM);
}
$re = (new loan_baseClass())->calculator($loan_amount,$loan_period,$loan_period_unit,$repayment_type,$repayment_period);
return $re;
}
public function contractDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
$re = loan_contractClass::getLoanContractDetailInfo($contract_id);
return $re;
}
public function appLoanApplyOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
$amount = round($params['amount'],2);
$propose = $params['loan_propose'];
$loan_time = intval($params['loan_time']);
$loan_time_unit = $params['loan_time_unit'];
$mortgage = $params['mortgage']; // 多个用,隔开
$currency = $params['currency']?:currencyEnum::USD;
if( $amount <= 0 ){
return new result(false,'Invalid amount',null,errorCodesEnum::INVALID_PARAM);
}
// 登陆会员
if( $member_id ){
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$applicant_name = $member->display_name?:($member->login_code?:'Unknown');
$applicant_address = null; // member 地址
$contact_phone = $member->phone_id;
}else{
// 没登陆
$applicant_name = $params['name'];
$applicant_address = $params['address'];
$country_code = $params['country_code'];
$phone = $params['phone'];
$sms_id = $params['sms_id'];
$sms_code = $params['sms_code'];
if( !$applicant_name || !$applicant_address || !$country_code || !$phone || !$sms_id || !$sms_code ){
return new result(false,'Lack param',null,errorCodesEnum::DATA_LACK);
}
$phone_arr = tools::getFormatPhone($country_code,$phone);
$contact_phone = $phone_arr['contact_phone'];
if( !isPhoneNumber($contact_phone) ){
return new result(false,'Invalid phone',null,errorCodesEnum::INVALID_PHONE_NUMBER);
}
// 验证码
$m_sms = new phone_verify_codeModel();
$row = $m_sms->getRow(array(
'uid' => $sms_id,
'verify_code' => $sms_code
));
if( !$row ){
return new result(false,'Code error',null,errorCodesEnum::SMS_CODE_ERROR);
}
}
$m_apply = new loan_applyModel();
$apply = $m_apply->newRow();
$apply->member_id = $member_id;
$apply->applicant_name = $applicant_name;
$apply->applicant_address = $applicant_address;
$apply->apply_amount = $amount;
$apply->currency = $currency;
$apply->loan_time = $loan_time;
$apply->loan_time_unit = $loan_time_unit;
$apply->mortgage = $mortgage;
$apply->loan_purpose = $propose;
$apply->contact_phone = $contact_phone;
$apply->apply_time = Now();
$apply->request_source = loanApplySourceEnum::MEMBER_APP;
$insert = $apply->insert();
if( !$insert->STS ){
return new result(false,'Apply fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$apply);
}
public function contractCancelOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
$re = loan_baseClass::cancelContract($contract_id);
return $re;
}
/** 还款请求
* @return result
*/
public function repaymentApplyOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = loan_contractClass::repaymentApply($params);
return $re;
}
/** 还款请求取消
* @return result
*/
public function repaymentApplyCancelOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$m = new loan_request_repaymentModel();
$request = $m->getRow($request_id);
if( !$request ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
if( $request->state != requestRepaymentStateEnum::CREATE ){
return new result(false,'Handling...',null,errorCodesEnum::HANDLING_LOCKED);
}
$delete = $request->delete();
if( !$delete->STS ){
return new result(false,'Cancel fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function getContractPayableInfoOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
if( $contract_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$re = loan_contractClass::getContractLeftPayableInfo($contract_id);
return $re;
}
public function calculateContractPayOffDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
if( $contract_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$re = loan_contractClass::calculateContractPrepaymentOffAmount($contract_id);
return $re;
}
public function prepaymentPreviewOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = loan_contractClass::prepaymentPreview($params);
return $re;
}
public function prepaymentApplyOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = loan_contractClass::prepaymentApply($params);
return $re;
}
public function prepaymentAddPaymentInfoOp()
{
return new result(false,'Give up using',null,errorCodesEnum::FUNCTION_CLOSED);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = loan_contractClass::prepaymentAddPaymentInfo($params);
return $re;
}
public function getPrepaymentDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
$m_contract = new loan_contractModel();
$contract_info = $m_contract->getRow($contract_id);
if( !$contract_info ){
return new result(false,'No contract',null,errorCodesEnum::NO_CONTRACT);
}
// todo 计算方法不应该区分合同是否被支持的
$re = loan_contractClass::getPrepaymentDetail($contract_id);
if( !$re->STS ){
return $re;
}
$data_return = $re->DATA;
$data = array(
'contract_info' => $contract_info,
'total_overdue_amount' => $data_return['total_overdue_amount'],
'next_repayment_date' => $data_return['next_repayment_date'],
'next_repayment_amount' => $data_return['next_repayment_amount'],
'total_left_periods' => $data_return['total_left_periods'],
'total_left_principal' => $data_return['total_left_principal'],
'total_need_pay' => $data_return['total_need_pay']
);
$r = new ormReader();
// 查询最近申请
$request = loan_contractClass::getContractLastPrepaymentRequest($contract_id);
// 过滤掉处理完成的,其他的需要展示给客户
if( $request && $request['state'] == prepaymentApplyStateEnum::SUCCESS ){
$request = null;
}
if( $request ){
// 计算申请的方式应还的总额
$re = loan_contractClass::prepaymentPreview(array(
'contract_id' => $request['contract_id'],
'prepayment_type' => $request['prepayment_type'],
'amount' => $request['principal_amount'],
'repay_period' => $request['repay_period']
));
$total_amount = round($re->DATA['total_prepayment_amount'],2);
$request['amount'] = $total_amount;
$apply_id = $request['uid'];
$sql = "select * from loan_request_repayment where prepayment_apply_id='$apply_id' order by create_time desc ";
$prepayment_payment_record = $r->getRows($sql);
}else{
$prepayment_payment_record = null;
}
$data['last_prepayment_request'] = $request;
$data['prepayment_payment_record'] = $prepayment_payment_record;
return new result(true,'success',$data);
}
public function getSchemaRepaymentDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$schema_id = $params['schema_id'];
$list = loan_contractClass::getSchemaRepaymentDetail($schema_id);
return new result(true,'success',$list);
}
public function getSchemaDisbursementDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$schema_id = $params['schema_id'];
$list = loan_contractClass::getSchemaDisbursementDetail($schema_id);
return new result(true,'success',$list);
}
public function loanApplyPreviewOp()
{
$params = array_merge(array(),$_GET,$_POST);
$amount = intval($params['amount']);
$currency = currencyEnum::USD;
$loan_month = intval($params['loan_time']);
$loan_days = $loan_month*30;
if( $amount <=0 || $loan_days <=0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
// 默认取信用贷的利率
$credit_product = credit_loanClass::getProductInfo();
if( !$credit_product ){
return new result(false,'No alive product',null,errorCodesEnum::NO_LOAN_PRODUCT);
}
$product_id = $credit_product['uid'];
$r = new ormReader();
// 首先匹配选中条件的
$sql = "select * from loan_product_size_rate where product_id='$product_id' and loan_size_min<='$amount'
and loan_size_max>='$amount' and currency='$currency' and min_term_days<='$loan_days' and max_term_days>='$loan_days'
and interest_payment='".interestPaymentEnum::ANNUITY_SCHEME."' and interest_rate_period='".interestRatePeriodEnum::MONTHLY."' ";
$rate = $r->getRow($sql);
if( !$rate ){
$sql = "select * from loan_product_size_rate where product_id='$product_id' order by loan_size_max desc,loan_size_min desc ";
$rate = $r->getRow($sql);
if( !$rate ){
return new result(false,'No match rate',null,errorCodesEnum::NO_LOAN_INTEREST);
}
}
$interest_rate = $rate['interest_rate'];
$rate_re = loan_baseClass::interestRateConversion($interest_rate,$rate['interest_rate_unit'],interestRatePeriodEnum::MONTHLY);
if( $rate_re->STS ){
$interest_rate = $rate_re->DATA;
}
$operation_rate = $rate['operation_fee'];
$operate_re = loan_baseClass::interestRateConversion($operation_rate,$rate['operation_fee_unit'],interestRatePeriodEnum::MONTHLY);
if( $operate_re->STS ){
$operation_rate = $operate_re->DATA;
$rate['operation_fee'] = $operation_rate;
}
$total_rate = round($interest_rate+$operation_rate,2);
$preview_re = loan_calculatorClass::annuity_schema_getPaymentSchemaByFixInterest($amount,$interest_rate/100,$loan_month,$rate,$rate['interest_min_value']);
$preview_data = $preview_re->DATA;
$repayment_total = $preview_data['payment_total'];
return new result(true,'success',array(
'total_interest_rate' => $total_rate.'%',
'total_repayment_amount' => $repayment_total['total_payment'],
//'repayment_schema' => $preview_data['payment_schema']
));
}
}<file_sep>/framework/api_test/apis/microbank/member.account.index.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/15
* Time: 17:53
*/
class memberAccountIndexApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Account sum ";
$this->description = "账户统计";
$this->url = C("bank_api_url") . "/member.account.index.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'credit' => array(
'credit' => '信用',
'balance' => '信用余额'
),
'loan_total' => '贷款总额(本金)',
'loan_balance' => '贷款余额(本金)',
'loan_total_repayable' => '贷款合计欠款(本息+罚金)',
'insurance_total' => '保险总额',
'processing_loan_contracts' => '进行中的贷款合同数',
'processing_insurance_contracts' => '进行中的保险合同数'
)
);
}
}<file_sep>/framework/weixin_baike/wxt/control/index.php
<?php
/**
* Created by PhpStorm.
* User: hh
* Date: 2018/3/18
* Time: 下午 2:47
*/
class indexControl
{
public function indexOp()
{
echo 'OK';
}
public function testOp()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if( !$postStr ){
$postStr = file_get_contents('php://input');
}
echo $postStr;die;
}
}
<file_sep>/framework/weixin_baike/entry_desktop/templates/default/widget/app.menu.left.php
<style>
#sidebar li .icon {
transition: all .25s ease;
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
}
#sidebar li.open .icon {
transform: rotate(90deg);
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transition: all .25s ease;
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
}
#sidebar .submenu img {
width: 12px;
margin-top: -4px;
}
<?php if($output['is_operator']){?>
#sidebar > ul li.active a {
background: url(resource/img/menu-active.png) no-repeat scroll right center transparent !important;
text-decoration: none;
}
#sidebar .submenu img.tab-active {
display: none;
}
#sidebar .submenu.active img.tab-active, #sidebar .submenu:hover img.tab-active {
display: inline-block;
}
#sidebar .submenu.active img.tab-default, #sidebar .submenu:hover img.tab-default {
display: none;
}
#sidebar > ul li ul li a {
padding-left: 25px;
}
#sidebar > ul li ul li {
position: relative;
}
#sidebar > ul li ul li a .label-important {
position: absolute;
right: 25px;
top: 10px;
}
<?php } ?>
</style>
<div id="sidebar" style="OVERFLOW-Y: auto; OVERFLOW-X:hidden;">
<ul>
<?php if($output['is_operator']){?>
<?php $i = 0;foreach ($output['menu_items'] as $k_c => $s_item) {
++$i;
$args = explode(',', $s_item['args']); ?>
<li class="submenu <?php echo $k_c?>">
<a href="#" class="<?php echo $s_item['child'] ? '' : 'menu_a'?>" link="<?php echo getUrl($args[1], $args[2], array(), false, C('site_root') . DS . $args[0]); ?>">
<img class="tab-default" src="<?php echo ENTRY_DESKTOP_SITE_URL . '/resource/img/tab_' . $k_c . '.png' ?>">
<img class="tab-active" src="<?php echo ENTRY_DESKTOP_SITE_URL . '/resource/img/tab_' . $k_c . '_active.png' ?>">
<span><?php echo $s_item['title'] ?></span>
<?php if($i <= 3){?>
<span class="label label-important"><?php echo $output['task_num'][$k_c]?></span>
<?php }?>
</a>
<ul>
<?php foreach ($s_item['child'] as $key => $item) { ?>
<li class="<?php echo 'type_' . $key?>">
<a class="menu_a" link="<?php echo getUrl($args[1], $args[2], array('type' => $key), false, C('site_root'). DS . $args[0]); ?>">
<span><?php echo $item?></span>
<span class="label label-important sub-num"><?php echo $output['task_num'][$k_c . '_arr'][$key]?></span>
</a>
</li>
<?php } ?>
</ul>
</li>
<?php } ?>
<?php } else {?>
<?php foreach ($output['menu_items'] as $k_c => $s_item) { ?>
<li class="submenu">
<a href="#">
<img src="<?php echo ENTRY_DESKTOP_SITE_URL . '/resource/img/icon-' . $k_c . '.png' ?>">
<span><?php echo $s_item['title']?></span>
<i class="icon fa fa-angle-right"></i>
</a>
<ul>
<?php foreach ($s_item['child'] as $item) { $args = explode(',', $item['args']);?>
<li>
<a class="menu_a <?php echo $args[1] . '-' . $args[2] ?>" link="<?php echo getUrl($args[1], $args[2], array(), false, C('site_root'). DS . $args[0]); ?>">
<span><?php echo $item['title']?></span>
</a>
</li>
<?php } ?>
</ul>
</li>
<?php } ?>
<?php } ?>
</ul>
</div>
<!--sidebar-menu--><file_sep>/framework/weixin_baike/backoffice/templates/default/report/repayment.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Contract Sn';?></td>
<td><?php echo 'Amount';?></td>
<td><?php echo 'Payer Name';?></td>
<td><?php echo 'Type';?></td>
<td><?php echo 'Payer Phone';?></td>
<td><?php echo 'Payer Account';?></td>
<td><?php echo 'Branch';?></td>
<td><?php echo 'Teller Name';?></td>
<td><?php echo 'Time';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<?php echo $row['contract_sn'] . '(' . $row['scheme_name'] . ')' ?>
</td>
<td>
<?php echo ncAmountFormat($row['amount']); ?>
</td>
<td>
<?php echo $row['payer_name']; ?>
</td>
<td>
<?php echo $row['payer_type']; ?>
</td>
<td>
<?php echo $row['payer_phone']; ?>
</td>
<td>
<?php echo $row['payer_account']; ?>
</td>
<td>
<?php echo $row['branch_name']; ?>
</td>
<td>
<?php echo $row['teller_name']; ?>
</td>
<td>
<?php echo timeFormat($row['create_time']); ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/api_test/apis/microbank/member.cert.family.book.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/1
* Time: 18:05
*/
class memberCertFamilyBookApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Family book cert";
$this->description = "户口本认证";
$this->url = C("bank_api_url") . "/member.cert.familybook.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
//$this->parameters[]= new apiParameter("hand_photo", "手持照片,文件流", '', true);
$this->parameters[]= new apiParameter("front_photo", "正面照,文件流", '', true);
$this->parameters[]= new apiParameter("back_photo", "背面照,文件流", '', true);
$this->parameters[]= new apiParameter("householder_photo", "户主页,文件流", '', true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/co.get.all.loan.product.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/9
* Time: 13:52
*/
// co.get.all.loan.product
class coGetAllLoanProductApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan product list";
$this->description = "贷款产品列表";
$this->url = C("bank_api_url") . "/co.get.all.loan.product.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'list' => array(
array(
'product_id' => '产品ID',
'product_code' => '产品code',
'product_name' => '产品名称',
)
)
)
);
}
}<file_sep>/framework/weixin_baike/counter/control/login.php
<?php
/**
* Created by PhpStorm.
* User: Seven
* Date: 2017/10/30
* Time: 16:00 PM
*/
class loginControl
{
function __construct()
{
Tpl::setDir("login");
}
/**
* 登录页面
*/
function loginOp()
{
Tpl::output('login_sign', true);
Tpl::showPage("login", "login_layout");
}
/**
* 退出
*/
function loginOutOp()
{
session_start();
$user_id = $_SESSION['counter_info']['uid'];
unset($_SESSION['counter_info']);
unset($_SESSION['is_login']);
session_write_close();
// 退出记录日志
$m_um_user_log = M('um_user_log');
$m_um_user_log->recordLogout($user_id);
$login_url = getUrl("login", "login", array(), false, ENTRY_COUNTER_SITE_URL);
@header('Location:' . $login_url);
}
}<file_sep>/framework/weixin_baike/api/control/system_setting.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 11:46
*/
class system_settingControl extends bank_apiControl
{
public function configInitOp()
{
set_time_limit(120);
// 用户定义的
$define = (new userDefineEnum())->toArray();
foreach( $define as $k=>$v ){
$define[$k] = "'$v'";
}
$reader = new ormReader();
$sql = "select * from core_definition where category in (".join(',',$define).") ";
$rows = $reader->getRows($sql);
$user_define = array();
if( count($rows) > 0 ){
foreach( $rows as $item ){
$user_define[$item['category']][] = $item;
}
}
$system_define = array();
$system_define['phone_country_code'] = array(
'86','855','66','84'
);
foreach( (new interestPaymentEnum())->toArray() as $v ){
$system_define['repayment_type'][] = $v;
}
foreach( (new interestRatePeriodEnum())->toArray() as $v ){
$system_define['repayment_period'][] = $v;
}
foreach( (new loanPeriodUnitEnum())->toArray() as $v ){
$system_define['loan_time_unit'][] = $v;
}
$system_define['currency'] = (new currencyEnum())->toArray();
// 地址分级信息
/* $sql1 = "select * from core_tree where root_key='".treeKeyTypeEnum::ADDRESS."' and node_level='1' order by node_text asc ";
$level_1 = $reader->getRows($sql1);
$sql2 = "select * from core_tree where root_key='".treeKeyTypeEnum::ADDRESS."' and node_level='2' order by node_text asc ";
$level_2 = $reader->getRows($sql2);
$sql3 = "select * from core_tree where root_key='".treeKeyTypeEnum::ADDRESS."' and node_level='3' order by node_text asc ";
$level_3 = $reader->getRows($sql3);
$sql4 = "select * from core_tree where root_key='".treeKeyTypeEnum::ADDRESS."' and node_level='4' order by node_text asc ";
$level_4 = $reader->getRows($sql4);
$system_define['address_region'] = array(
'lv1' => $level_1,
'lv2' => $level_2,
'lv3' => $level_3,
'lv4' => $level_4
);*/
return new result(true,'success',array(
'user_define' => $user_define,
'system_define' => $system_define
));
}
/**
* 系统定义的列表
* @return result
*/
public function defineListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$type = $params['type'];
switch( $type )
{
case 1: // 性别
$category = userDefineEnum::GENDER;
break;
case 2: // 职业
$category = userDefineEnum::OCCUPATION;
break;
case 3: // 家庭关系
$category = userDefineEnum::FAMILY_RELATIONSHIP;
break;
case 4: // 贷款用途
$category = userDefineEnum::LOAN_USE;
break;
default:
$category = '';
}
$reader = new ormReader();
$sql = "select * from core_definition where category='$category' ";
$rows = $reader->getRows($sql);
return new result(true,'success',$rows);
}
/** 国家编码
* @return result
*/
public function countryCodeOp()
{
return new result(true,'success',array(
'855','86','84','66'
));
}
public function getCompanyInfoOp()
{
$re = global_settingClass::getCompanyInfo();
return new result(true,'success',$re);
}
public function getCompanyHotlineOp()
{
$re = global_settingClass::getCompanyHotline();
return new result(true,'success',$re);
}
public function getCommonHelpListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$type = $params['type'];
$page_num = $params['page_num']?:1;
$page_size = $params['page_size']?:100000;
$re = global_settingClass::getSystemHelpList($type,$page_num,$page_size);
return new result(true,'success',$re);
}
public function getCompanyGlobalReceiveBankAccountOp()
{
$params = array_merge(array(),$_GET,$_POST);
$currency = $params['currency'];
$re = global_settingClass::getCompanyGlobalReceiveBankAccount($currency);
return new result(true,'success',$re);
}
public function getAddressListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$pid = intval($params['pid']);
$list = global_settingClass::getChildrenAddressList($pid);
return new result(true,'success',$list);
}
public function currencyExchangeRateOp()
{
$list = global_settingClass::currencyExchangeRate();
return new result(true,'success',$list);
}
public function getBankListOp()
{
$r = new ormReader();
$sql = "select * from common_bank_lists order by bank_code asc ";
$list = $r->getRows($sql);
return new result(true,'success',array(
'list' => $list
));
}
}<file_sep>/framework/weixin_baike/backoffice/control/dev.php
<?php
class devControl extends baseControl
{
public $abc;
public function __construct()
{
parent::__construct();
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Dev");
Tpl::setDir("dev");
}
/**
* app版本
*/
public function appVersionOp()
{
Tpl::showPage("app_version");
}
/**
* @param $p
* @return array
*/
public function getAppVersionOp($p)
{
$search_text = trim($p['search_text']);
$r = new ormReader();
$sql = "SELECT * FROM common_app_version";
if ($search_text) {
$sql .= " WHERE app_name LIKE '%" . $search_text . "%' OR version LIKE '%" . $search_text . "%'";
}
$sql .= " ORDER BY uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 添加新版本
*/
public function addVersionOp()
{
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$m_common_app_version = M('common_app_version');
$rt = $m_common_app_version->addVersion($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('dev', 'appVersion', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('dev', 'addVersion', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
Tpl::showPage("app_version.add");
}
}
/**
* 功能开关
*/
public function functionSwitchOp()
{
$m_core_dictionary = M('core_dictionary');
if ($_POST['form_submit'] == 'ok') {
$param = $_POST;
unset($param['form_submit']);
$param['close_reset_password'] = intval($param['close_reset_password']);
$param['close_credit_withdraw'] = intval($param['close_credit_withdraw']);
$param['close_register_send_credit'] = intval($param['close_register_send_credit']);
$rt = $m_core_dictionary->updateDictionary('function_switch', my_json_encode($param));
if ($rt->STS) {
showMessage($rt->MSG, getUrl('dev', 'functionSwitch', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->MSG);
}
} else {
$data = $m_core_dictionary->getDictionary('function_switch');
if ($data) {
tpl::output('function_switch', my_json_decode($data['dict_value']));
}
Tpl::showPage("function.switch");
}
}
/**
* 重置密码
*/
public function resetPasswordOp()
{
$m_core_dictionary = M('core_dictionary');
$data = $m_core_dictionary->getDictionary('function_switch');
$data = my_json_decode($data['dict_value']);
if ($data['close_reset_password'] == 1) {
showMessage('Reset password closed!');
}
Tpl::showpage('reset.password');
}
/**
* 获取重置密码列表
* @param $p
* @return array
*/
public function getResetPasswordListOp($p)
{
$search_text = trim($p['search_text']);
$r = new ormReader();
$sql = "SELECT * FROM client_member";
if ($search_text) {
$sql .= " WHERE obj_guid = '" . $search_text . "' OR display_name like '%" . $search_text . "%' OR phone_id like '" . $search_text . "' OR login_code like '" . $search_text . "'";
}
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
public function apiResetPasswordOp($p)
{
$m_core_dictionary = M('core_dictionary');
$data = $m_core_dictionary->getDictionary('function_switch');
$data = my_json_decode($data['dict_value']);
if ($data['close_reset_password'] == 1) {
return new result(false, 'Reset password closed!');
}
$uid = intval($p['uid']);
$new_password = trim($p['<PASSWORD>']);
$verify_password = trim($p['<PASSWORD>']);
if ($new_password != $verify_password) {
return new result(false, 'Verify password error');
}
$rt = memberClass::commonUpdateMemberPassword($uid, $new_password);
if ($rt->STS) {
return new result(true, 'Reset Successful!');
} else {
return new result(false, $rt->MSG);
}
}
}
<file_sep>/framework/weixin_baike/counter/control/service.php
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2018/3/5
* Time: 10:48
*/
class serviceControl extends counter_baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setDir("service");
Language::read('service');
Tpl::setLayout('home_layout');
$this->outputSubMenu('service');
}
// requestLoan页面展示
public function requestLoanOp()
{
Tpl::showPage("request.loan");
}
// currencyExchange页面展示
public function currencyExchangeOp()
{
Tpl::showPage("coming.soon");
}
// 查询贷款申请列表,分页展示
public function getRequestLoanListOp($p)
{
$search_text = trim($p['search_text']);
$r = new ormReader();
$sql = "SELECT la.*,uu.user_name,uu.user_code FROM loan_apply la LEFT JOIN um_user uu ON la.credit_officer_id = uu.uid"
. " WHERE la.creator_id = " . $this->user_id;
if($search_text){
$sql .= " AND la.applicant_name like '%" . $search_text . "%'";
}
$sql .= " ORDER BY la.apply_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
$apply_source = (new loanApplySourceEnum)->Dictionary();
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"cur_uid" => $this->user_id,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"type" => trim($p['type']),
"apply_source" => $apply_source,
);
}
// 添加贷款申请
public function addRequestLoanOp()
{
Tpl::output('show_menu','requestLoan');
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
// $m_loan_apply = M('loan_apply');
$m_loan_apply = new loan_applyModel();
$p['request_source'] = loanApplySourceEnum::CLIENT;
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$rt = $m_loan_apply->addApply($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('service', 'requestLoan', array(), false, ENTRY_COUNTER_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('service', 'addRequestLoan', $p, false, ENTRY_COUNTER_SITE_URL));
}
} else {
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type'));
Tpl::output('mortgage_type', $define_arr['mortgage_type']);
$apply_source = (new loanApplySourceEnum)->Dictionary();
Tpl::output('request_source', $apply_source);
Tpl::showPage("add.request.loan");
}
}
// 返回区域信息
public function getAreaListOp($p)
{
$pid = intval($p['uid']);
$m_core_tree = M('core_tree');
$list = $m_core_tree->getChildByPid($pid, 'region');
return array('list' => $list);
}
// 删除新增申请
public function deleteRequestLoanOp(){
$uid = $_GET["uid"];
$m_loan_apply =M("loan_apply");
$r = $m_loan_apply->delete(array("uid"=>$uid));
if($r->STS){
showMessage("Delete Success");
}else{
showMessage("Delete failure");
}
}
}<file_sep>/framework/api_test/apis/officer_app/co.bound.member.loan.contract.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/11
* Time: 14:40
*/
// co.bound.member.loan.contract.list
class coBoundMemberLoanContractListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "CO bound member loan contract";
$this->description = "绑定到CO的会员的贷款合同";
$this->url = C("bank_api_url") . "/co.bound.member.loan.contract.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "CO id", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
'@description' => '合同列表',
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/gl_account.model.php
<?php
class gl_accountModel extends tableModelBase {
public function __construct()
{
parent::__construct('gl_account');
}
}<file_sep>/framework/weixin_baike/script/control/script_cert.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/26
* Time: 16:28
*/
class script_certControl
{
/**
* 更新过期的认证资料
*/
public function updateExpireCertListOp()
{
$m_cert = new member_verify_certModel();
$sql = "update member_verify_cert set verify_state='".certStateEnum::EXPIRED."' where cert_expire_time is not null
and verify_state='".certStateEnum::PASS."' and date_format(cert_expire_time,'%Y%m%d')<'".date('Ymd')."' ";
$up = $m_cert->conn->execute($sql);
$date = date('Y-m-d H:i:s');
if( !$up->STS ){
echo $date." -> success \n";
}
echo $date." -> success \n";
}
}<file_sep>/framework/api_test/apis/microbank/common.bank.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/6
* Time: 13:17
*/
// common.bank.list
class commonBankListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Common bank list";
$this->description = "银行类型列表";
$this->url = C("bank_api_url") . "/common.bank.list.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'list' => array(
array(
'uid' => '银行ID',
'bank_code' => '银行编码',
'currency' => '银行支持的货币类型',
'bank_name' => '银行的名称',
'bank_address' => '地址',
'enable_digit' => '',
'digit_length' => ''
)
)
)
);
}
}<file_sep>/framework/weixin_baike/mobile/templates/default/home/credit.add.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/home.css?v=2">
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/inc_header.css?v=6">
<header class="top-header" id="header" style="display: <?php echo $_GET['source'] == 'app' ? 'none' : 'block';?>">
<span class="back" onclick="javascript:history.back(-1);"><i class="aui-iconfont aui-icon-left"></i></span>
<h2 class="title"><?php echo $output['header_title'];?></h2>
</header>
<div class="wrap loan-wrap">
<?php $data = $output['data'];?>
<form id="" method="post">
<div class="cerification-input aui-margin-b-10">
<div class="loan-form request-credit-form">
<ul class="aui-list aui-form-list loan-item">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Evalution of assets
</div>
<div class="aui-list-item-input">
<input type="text" name="member_id" id="member_id" value="<?php echo $data['asset_evaluation'];?>" readonly />
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Evalution of business profitabilily
</div>
<div class="aui-list-item-input">
<input type="text" name="member_name" id="member_name" value="<?php echo $data['business_profitability'];?>" readonly />
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Monthly Repayment Ability
</div>
<div class="aui-list-item-input">
<input type="text" name="monthly_repayment_ability" id="monthly_repayment_ability" value="" placeholder="Enter" />
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Request for credit
</div>
<div class="aui-list-item-input">
<input type="text" name="suggest_credit" id="suggest_credit" value="" placeholder="Enter" />
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Remark
</div>
<div class="aui-list-item-input">
<input type="text" name="remark" id="remark" value="" placeholder="Enter" />
</div>
</div>
</li>
</ul>
</div>
</div>
<div style="padding: 0 .8rem;">
<div class="aui-btn aui-btn-danger aui-btn-block custom-btn custom-btn-purple aui-margin-t-15" id="submit">Submit</div>
</div>
</form>
</div>
<div class="upload-success">
<div class="content">
<img src="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/image/gou.png" alt="">
<p class="title"><?php echo 'Upload Successfully';?></p>
<p class="tip"><?php echo str_replace('xxx','<em id="count">3</em>','It exits automatically xxx seconds later.');?></p>
</div>
</div>
<script src="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/script/common.js"></script>
<script type="text/javascript">
if(window.operator){
window.operator.showTitle('<?php echo $output['header_title'];?>');
}
var type = '<?php echo $_GET['source']?>', l = '<?php echo $_GET['lang']?>';
if (type == 'app') {
app_show(type);
}
function app_show(type) {
if (type == 'app') {
$('#header').hide();
} else {
$('#header').show();
}
}
var formData = new FormData(document.getElementById('uploadPicture'));
$('#submit').on('click', function(){
var client_id = '<?php echo $_GET['id'];?>';
monthly_repayment_ability = $.trim($('#monthly_repayment_ability').val()),
suggest_credit = $.trim($('#suggest_credit').val()),
remark = $.trim($('#remark').val());
if(!client_id){
verifyFail('<?php echo 'Please reselect client.';?>');
return;
}
if(!monthly_repayment_ability){
verifyFail('<?php echo 'Please input monthly repayment ability.';?>');
return;
}
if(!suggest_credit){
verifyFail('<?php echo 'Please input request for credit.';?>');
return;
}
if(!remark){
verifyFail('<?php echo 'Please input remark.';?>');
return;
}
toast.loading({
title: '<?php echo $lang['label_loading'];?>'
});
$.ajax({
type: 'POST',
url: '<?php echo WAP_OPERATOR_SITE_URL;?>/index.php?act=home&op=ajaxAddCreditRequest',
data: {member_id: client_id,monthly_repayment_ability: monthly_repayment_ability,suggest_credit: suggest_credit,remark: remark},
dataType: 'json',
success: function(data){
toast.hide();
if(data.STS){
$('.upload-success').show();
var count = $('#count').text();
var times = setInterval(function(){
count--;
$('#count').text(count);
if(count <= 1){
clearInterval(times);
$('.back').click();
}
},1000);
}else{
verifyFail(data.MSG);
}
},
error: function(xhr, type){
toast.hide();
verifyFail('<?php echo $lang['tip_get_data_error'];?>');
}
});
});
</script>
<file_sep>/framework/api_test/apis/microbank/phone.is.registered.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/25
* Time: 10:15
*/
class phoneIsRegisteredApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Phone Is Registered";
$this->description = "验证手机号是否被注册";
$this->url = C("bank_api_url") . "/phone.is.registered.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("country_code", "电话国际区号", '86', true);
$this->parameters[]= new apiParameter("phone", "电话", '18902461905', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'is_registered' => '1 是 0 否',
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/product.info.php
<link href="<?php echo BACK_OFFICE_SITE_URL ?>/resource/css/product.css?v=5" rel="stylesheet" type="text/css"/>
<style>
.btn-release,.btn-unshelve{
position: absolute;
top: 0px;
right: 0px;
height: 30px;
line-height: 30px;
padding: 0px 15px;
}
.base-info .size-info .content{
overflow: auto;
padding: 5px 0 10px;
margin: 5px 15px;
}
</style>
<?php $product_info = $output['product_info'];?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Product</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('loan', 'product', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a></li>
<li><a href="<?php echo getUrl('loan', 'addProduct', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>Add</span></a></li>
<li><a class="current"><span>Info</span></a></li>
</ul>
</div>
</div>
<div class="container">
<ul class="tab-top clearfix">
<li class="active" page="page-1"><a>Base Info</a></li>
<li page="page-2"><a>Condition</a></li>
<li page="page-3"><a>Details</a></li>
</ul>
<button class="btn btn-default btn-release" style="display:<?php echo $product_info['state'] == 30 ? 'block;' : 'none;' ?>">Putaway</button>
<button class="btn btn-default btn-unshelve" style="display:<?php echo $product_info['state'] == 20 ? 'block;' : 'none;' ?>">Inactive</button>
<div class="page-1">
<div class="base-info clearfix">
<div class="product-info">
<div class="ibox-title">
<div class="col-sm-8"><h5>Loan Info</h5></div>
</div>
<div class="content clearfix">
<div class="wrap1">
<table>
<tr style="font-weight: bold">
<input type="hidden" id="uid" value="<?php echo $product_info['uid'];?>">
<td>Product Name:</td>
<td id="product_name"><?php echo $product_info['product_name']?></td>
</tr>
<tr>
<td>Is credit loan: </td>
<td id="is_credit_loan" val="<?php echo $product_info['is_credit_loan']; ?>"><?php if( isset($product_info['is_credit_loan']) ){ echo $product_info['is_credit_loan']?'YES':'NO'; } ?></td>
</tr>
<tr>
<td>Advance Interest:</td>
<td id="is_advance_interest" val="<?php echo $product_info['is_advance_interest']?>"><?php echo (isset($product_info['is_advance_interest'])?($product_info['is_advance_interest']==1?'YES':'NO'):'')?></td>
</tr>
<tr>
<td>Editable Grace Days:</td>
<td id="is_editable_grace_days" val="<?php echo $product_info['is_editable_grace_days']?>"><?php echo (isset($product_info['is_editable_grace_days'])?($product_info['is_editable_grace_days']==1?'YES':'NO'):'')?></td>
</tr>
</table>
</div>
<div class="wrap2">
<table>
<tr style="font-weight: bold">
<td>Product Code:</td>
<td id="product_code"><?php echo $product_info['product_code']?></td>
</tr>
<tr>
<td>Multi Contract:</td>
<td id="is_multi_contract" val="<?php echo $product_info['is_multi_contract']?>"><?php echo (isset($product_info['is_multi_contract'])?($product_info['is_multi_contract']==1?'YES':'NO'):'')?></td>
</tr>
<tr>
<td>Editable Interest:</td>
<td id="is_editable_interest" val="<?php echo $product_info['is_editable_interest']?>"><?php echo (isset($product_info['is_editable_interest'])?($product_info['is_editable_interest']==1?'YES':'NO'):'')?></td>
</tr>
<tr>
<td>State:</td>
<td id="state" val="<?php echo $product_info['state']?>"><?php echo $lang['enum_loan_product_state_'.$product_info['state']]?></td>
</tr>
</table>
</div>
</div>
</div>
<div class="penalty-info">
<div class="ibox-title">
<div class="col-sm-8"><h5>Penalty</h5></div>
</div>
<div class="content">
<table>
<tr>
<td>Penalty On:</td>
<td id="penalty_on" val="<?php echo $product_info['penalty_on']?>"><?php echo ucwords(strtolower($output['penalty_on'][$product_info['penalty_on']]))?></td>
</tr>
<tr>
<td>Penalty Rate:</td>
<td id="penalty_rate" val="<?php echo $product_info['penalty_rate'] > 0 ? $product_info['penalty_rate'] : ""?>"><?php echo $product_info['penalty_rate'] > 0 ? ($product_info['penalty_rate'] . '%') : ''?></td>
</tr>
<tr>
<td>Divisor Days:</td>
<td id="penalty_divisor_days" val="<?php echo $product_info['penalty_divisor_days'] > 0 ? $product_info['penalty_divisor_days'] : ""?>"><?php echo $product_info['penalty_divisor_days'] > 0 ? ($product_info['penalty_divisor_days'].'Days'):''?></td>
</tr>
<tr>
<td>Editable:</td>
<td id="is_editable_penalty" val="<?php echo $product_info['penalty_on']?$product_info['is_editable_penalty']:''?>"><?php echo $product_info['penalty_on']?($product_info['is_editable_penalty']==1?'YES':'NO'):''?></td>
</tr>
</table>
</div>
</div>
</div>
<div class="base-info clearfix">
<div class="size-info">
<div class="ibox-title">
<div class="col-sm-8"><h5>Size Rate</h5></div>
</div>
<div class="content clearfix">
</div>
</div>
</div>
</div>
<div class="base-info clearfix page-2">
<div class="condition-info">
<div class="ibox-title">
<div class="col-sm-8"><h5>Condition</h5></div>
</div>
<div class="content">
<form class="form-horizontal" id="condition_form">
<?php
$condition = $product_info['condition'];
$condition_new = array();
foreach ($condition as $val) {
$condition_new[] = $val['definition_category'] . ',' . $val['definition_id'];
}
?>
<?php foreach ($output['condition_list'] as $key => $condition) { ?>
<div class="form-group col-sm-6">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo $output['condition_arr'][$key] ?></label>
<div class="col-sm-9 checkbox-div">
<?php foreach($condition as $val){?>
<label class="col-sm-4"><input type="checkbox" <?php echo in_array($key . ',' . $val['uid'], $condition_new)?'checked':''?> name="<?php echo $key . ',' . $val['uid'] ?>"><?php echo $val['item_name']?></label>
<?php } ?>
</div>
</div>
<?php } ?>
</form>
</div>
</div>
</div>
<div class="page-3">
<div class="base-info clearfix">
<div class="description">
<div class="ibox-title">
<div class="col-sm-8"><h5>Description</h5></div>
</div>
<div class="content clearfix">
<div><?php echo $product_info['product_description']?></div>
<textarea name="description" id="description" style="display: none;"><?php echo $product_info['product_description']?></textarea>
</div>
</div>
<div class="qualification">
<div class="ibox-title">
<div class="col-sm-8"><h5>Qualification</h5></div>
</div>
<div class="content clearfix">
<div><?php echo $product_info['product_qualification']?></div>
<textarea name="qualification" id="qualification" style="display: none;"><?php echo $product_info['product_qualification']?></textarea>
</div>
</div>
</div>
<div class="base-info clearfix">
<div class="feature">
<div class="ibox-title">
<div class="col-sm-8"><h5>Feature</h5></div>
</div>
<div class="content clearfix">
<div><?php echo $product_info['product_feature']?></div>
<textarea name="feature" id="feature" style="display: none;"><?php echo $product_info['product_feature']?></textarea>
</div>
</div>
<div class="required">
<div class="ibox-title">
<div class="col-sm-8"><h5>Required</h5></div>
</div>
<div class="content clearfix">
<div><?php echo $product_info['product_required']?></div>
<textarea name="required" id="required" style="display: none;"><?php echo $product_info['product_required']?></textarea>
</div>
</div>
</div>
<div class="base-info clearfix">
<div class="notice">
<div class="ibox-title">
<div class="col-sm-8"><h5>Notice</h5></div>
</div>
<div class="content clearfix">
<div><?php echo $product_info['product_required']?></div>
<textarea name="notice" id="notice" style="display: none;"><?php echo $product_info['product_notice']?></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
var height = $('.product-info .content').height();
$('.penalty-info .content').height(height);
$('.tab-top li').click(function () {
var _page = $(this).attr('page');
$('.tab-top li').removeClass('active');
$(this).addClass('active');
$('.page-1,.page-2,.page-3').hide();
$('.' + _page).show();
})
});
var uid = '<?php echo intval($product_info['uid'])?>';
if (uid != 0) {
getSizeRateList(uid)
}
function getSizeRateList(product_id) {
if(product_id == 0) return;
yo.dynamicTpl({
tpl: "loan/size_rate.list",
dynamic: {
api: "loan",
method: "getSizeRateList",
param: {product_id: product_id, type: 'info'}
},
callback: function (_tpl) {
$(".size-info .content").html(_tpl);
}
});
}
$('.btn-release').click(function () {
if (!uid) {
return;
}
yo.loadData({
_c: "loan",
_m: "releaseProduct",
param: {uid: uid},
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
$(this).hide();
$('.btn-unshelve').show();
$('#state').html('Valid');
} else {
alert(_o.MSG);
}
}
});
})
$('.btn-unshelve').click(function () {
if (!uid) {
return;
}
yo.loadData({
_c: "loan",
_m: "unShelveProduct",
param: {uid: uid},
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
$(this).hide();
$('.btn-release').show();
$('#state').html('Invalid');
} else {
alert(_o.MSG);
}
}
});
})
</script>
<file_sep>/framework/weixin_baike/data/config/conf.demo.ali.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 9:56
*/
$config['db_conf']=array(
"db_loan"=>array(
"db_type"=>"mysql",
"db_host"=>"127.0.0.1",
"db_user"=>"demo",
"db_pwd"=>"<PASSWORD>",
"db_name"=>"weixin_baike",
"db_port"=>3306
)
);
// 暂时使用
$config['session'] = array(
'save_handler' => 'files',
'save_path' => BASE_DATA_PATH.'/session'
);
$config['weixin_url_init'] = 0;
$config['debug']=true;
$config['site_root'] = 'http://www.iruofeng.cn/fri_community/framework';
$config['global_resource_site_url'] = "http://www.iruofeng.cn/fri_community/framework/resource";
$config['project_site_url'] = "http://www.iruofeng.cn/fri_community/weixin_baike";
$config['entry_api_url'] = "http://www.iruofeng.cn/fri_community/weixin_baike/api/v1";
<file_sep>/framework/weixin_baike/backoffice/templates/default/user/depart.option.php
<option value="0" selected="selected">Select Department</option>
<?php foreach($data['data'] as $depart){?>
<option value="<?php echo $depart['uid']?>"><?php echo $depart['depart_name']?></option>
<?php }?><file_sep>/framework/weixin_baike/backoffice/control/financial.php
<?php
class financialControl extends baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "");
Tpl::setDir("financial");
Language::read('financial');
}
/**
* 收款账号
*/
public function bankAccountOp()
{
$m_bank_account = M('site_bank');
$account_list = $m_bank_account->orderBy('bank_code ASC')->select(array('uid' => array('neq', 0)));
Tpl::output('account_list', $account_list);
Tpl::showpage('receive.account.list');
}
/**
* 添加收款人账号
*/
public function addReceiveAccountOp()
{
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$m_bank_account = M('site_bank');
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$rt = $m_bank_account->addReceiveAccount($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('financial', 'bankAccount', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('financial', 'addReceiveAccount', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
$m_common_bank_lists = M('common_bank_lists');
$bank_list = $m_common_bank_lists->select(array('uid' => array('neq', 0)));
Tpl::output("bank_list", $bank_list);
$m_site_branch = M('site_branch');
$branch_list = $m_site_branch->select(array('status' => 1));
Tpl::output("branch_list", $branch_list);
$currency_list = currency::getKindList();
Tpl::output("currency_list", $currency_list);
Tpl::showPage("receive.account.add");
}
}
public function editReceiveAccountOp()
{
$p = array_merge(array(), $_GET, $_POST);
$m_bank_account = M('site_bank');
if ($p['form_submit'] == 'ok') {
$rt = $m_bank_account->editReceiveAccount($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('financial', 'bankAccount', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('financial', 'editReceiveAccount', array('uid' => intval($p['uid'])), false, BACK_OFFICE_SITE_URL));
}
} else {
$m_common_bank_lists = M('common_bank_lists');
$bank_list = $m_common_bank_lists->select(array('uid' => array('neq', 0)));
Tpl::output("bank_list", $bank_list);
$m_site_branch = M('site_branch');
$branch_list = $m_site_branch->select(array('status' => 1));
Tpl::output("branch_list", $branch_list);
$currency_list = currency::getKindList();
Tpl::output("currency_list", $currency_list);
$uid = intval($p['uid']);
$account_info = $m_bank_account->find(array('uid' => $uid));
if (!$account_info) {
showMessage('Invalid Id!');
}
Tpl::output('account_info', $account_info);
$m_site_bank_branch = M('site_bank_branch');
$branch_id = $m_site_bank_branch->select(array('bank_id' => $uid));
Tpl::output('branch_id', array_column($branch_id, 'branch_id'));
Tpl::showPage("receive.account.edit");
}
}
public function deleteReceiveAccountOp()
{
$uid = intval($_GET['uid']);
$m_bank_account = M('site_bank');
$row = $m_bank_account->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
$rt = $row->delete();
if ($rt->STS) {
showMessage('Remove successful!');
} else {
showMessage('Remove failed!');
}
}
/**
* 货币汇率表
*/
public function exchangeRateOp()
{
$m_common_exchange_rate = M('common_exchange_rate');
$exchange_rate_list = $m_common_exchange_rate->select(array('uid' => array('neq', 0)));
Tpl::output('exchange_rate_list', $exchange_rate_list);
Tpl::showpage('exchange_rate.list');
}
public function addNewExchangeRateOp($p)
{
$m_common_exchange_rate = new common_exchange_rateModel();
$row = $m_common_exchange_rate->newRow();
$first_currency = $p['first_currency'];
$second_currency = $p['second_currency'];
$buy_rate = round($p['buy_rate'], 2);
$buy_rate_unit = round($p['buy_rate_unit'], 2);
$sell_rate = round($p['sell_rate'], 2);
$sell_rate_unit = round($p['sell_rate_unit'], 2);
if (($buy_rate / $buy_rate_unit) > ($sell_rate_unit / $sell_rate)) {
showMessage('The sell price is greater than the buy price!');
}
$row->first_currency = $first_currency;
$row->second_currency = $second_currency;
$row->buy_rate = $buy_rate;
$row->buy_rate_unit = $buy_rate_unit;
$row->sell_rate = $sell_rate;
$row->sell_rate_unit = $sell_rate_unit;
$row->update_id = $this->user_id;
$row->update_name = $this->user_name;
$row->update_time = Now();
$insert = $row->insert();
return $insert;
}
/**
* 设置汇率
*/
public function setExchangeRateOp()
{
$p = array_merge(array(), $_GET, $_POST);
$m_common_exchange_rate = M('common_exchange_rate');
if ($p['form_submit'] == 'ok') {
$first_currency = $p['first_currency'];
$second_currency = $p['second_currency'];
$row = $m_common_exchange_rate->getRow(array('first_currency' => $first_currency, 'second_currency' => $second_currency));
$currency_list = (new currencyEnum)->Dictionary();
unset($currency_list[$first_currency]);
unset($currency_list[$second_currency]);
$other_currency = array_pop($currency_list);
if ($row) {
$buy_rate = round($p['buy_rate'], 2);
$buy_rate_unit = round($p['buy_rate_unit'], 2);
$sell_rate = round($p['sell_rate'], 2);
$sell_rate_unit = round($p['sell_rate_unit'], 2);
if (($buy_rate / $buy_rate_unit) > ($sell_rate_unit / $sell_rate)) {
showMessage('The sell price is greater than the buy price!');
}
$exchange_0 = $buy_rate / $buy_rate_unit;
$exchange_1 = $m_common_exchange_rate->getRateBetween($second_currency, $other_currency);
$exchange_2 = $m_common_exchange_rate->getRateBetween($other_currency, $first_currency);
$exchange = $exchange_0 * $exchange_1 * $exchange_2;
if ($exchange > 1) {
showMessage('If buying in a third currency, the principal increases!');
}
$row->buy_rate = $buy_rate;
$row->buy_rate_unit = $buy_rate_unit;
$row->sell_rate = $sell_rate;
$row->sell_rate_unit = $sell_rate_unit;
} else {
$row = $m_common_exchange_rate->getRow(array('second_currency' => $first_currency, 'first_currency' => $second_currency));
if (!$row) {
$re = $this->addNewExchangeRateOp($p);
if ($re->STS) {
showMessage('Setting successful!', getUrl('financial', 'exchangeRate', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage('Setting failed!');
}
}
$buy_rate = round($p['buy_rate'], 2);
$buy_rate_unit = round($p['buy_rate_unit'], 2);
$sell_rate = round($p['sell_rate'], 2);
$sell_rate_unit = round($p['sell_rate_unit'], 2);
if (($sell_rate / $sell_rate_unit) > ($buy_rate_unit / $buy_rate)) {
showMessage('The sell price is greater than the buy price!');
}
$exchange_0 = $sell_rate / $sell_rate_unit;
$exchange_1 = $m_common_exchange_rate->getRateBetween($first_currency, $other_currency);
$exchange_2 = $m_common_exchange_rate->getRateBetween($other_currency, $second_currency);
$exchange = $exchange_0 * $exchange_1 * $exchange_2;
if ($exchange > 1) {
showMessage('If buying in a third currency, the principal increases!');
}
$row->buy_rate = $sell_rate;
$row->buy_rate_unit = $sell_rate_unit;
$row->sell_rate = $buy_rate;
$row->sell_rate_unit = $buy_rate_unit;
}
$row->update_id = $this->user_id;
$row->update_name = $this->user_name;
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
showMessage('Setting successful!', getUrl('financial', 'exchangeRate', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage('Setting failed!');
}
} else {
$uid = intval($p['uid']);
if ($uid > 0) {
$currency = $m_common_exchange_rate->find(array('uid' => $uid));
Tpl::output('currency', $currency);
}
$currency_list = (new currencyEnum)->Dictionary();
Tpl::output('currency_list', $currency_list);
Tpl::showpage('exchange_rate.setting');
}
}
/**
* 获取汇率
* @param $p
* @return result
*/
public function getRateOp($p)
{
$first_currency = $p['first_currency'];
$second_currency = $p['second_currency'];
$m_common_exchange_rate = M('common_exchange_rate');
$currency_rate = $m_common_exchange_rate->find(array('first_currency' => $first_currency, 'second_currency' => $second_currency));
if ($currency_rate) {
$data = array(
'buy_rate' => rtrim(rtrim($currency_rate['buy_rate'], '0'), '.'),
'buy_rate_unit' => rtrim(rtrim($currency_rate['buy_rate_unit'], '0'), '.'),
'sell_rate' => rtrim(rtrim($currency_rate['sell_rate'], '0'), '.'),
'sell_rate_unit' => rtrim(rtrim($currency_rate['sell_rate_unit'], '0'), '.')
);
return new result(true, '', $data);
}
$currency_rate = $m_common_exchange_rate->find(array('first_currency' => $second_currency, 'second_currency' => $first_currency));
if ($currency_rate) {
$data = array(
'buy_rate' => rtrim(rtrim($currency_rate['sell_rate'], '0'), '.'),
'buy_rate_unit' => rtrim(rtrim($currency_rate['sell_rate_unit'], '0'), '.'),
'sell_rate' => rtrim(rtrim($currency_rate['buy_rate'], '0'), '.'),
'sell_rate_unit' => rtrim(rtrim($currency_rate['buy_rate_unit'], '0'), '.')
);
return new result(true, '', $data);
} else {
return new result(true, '', null);
}
}
}
<file_sep>/framework/api_test/apis/officer_app/officer.followed.member.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 16:52
*/
// officer.followed.member
class officerFollowedMemberApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Officer follow member";
$this->description = "业务员跟进的会员";
$this->url = C("bank_api_url") . "/officer.followed.member.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '会员列表,没有为null',
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/grand.credit.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'CID'; ?></td>
<td><?php echo 'Name'; ?></td>
<td><?php echo 'Credit'; ?></td>
<td><?php echo 'Multi Contract'; ?></td>
<td><?php echo 'Type'; ?></td>
<td><?php echo 'Certificate Time'; ?></td>
<td><?php echo 'Update Time'; ?></td>
<td><?php echo 'Function'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach ($data['data'] as $row) { ?>
<tr>
<td>
<?php echo $row['obj_guid'] ?>
<br/>
</td>
<td>
<?php echo $row['display_name'] ?>
</td>
<td>
<?php echo $row['credit'] ?: 0; ?><br/>
</td>
<td>
<?php echo ($row['allow_multi_contract'] == 1) ? 'Yes' : 'No'; ?><br/>
</td>
<td>
<?php switch ($row['account_type']) {
case 0:
echo 'member';
break;
case 10:
echo 'partner';
break;
case 20:
echo 'dealer';
break;
case 30:
echo 'Legal person';
break;
default:
echo 'member';
break;
} ?><br/>
</td>
<td>
<?php echo timeFormat($row['last_cert_time']) ?><br/>
</td>
<td>
<?php echo timeFormat($row['update_time']) ?><br/>
</td>
<td>
<div class="custom-btn-group">
<a class="custom-btn custom-btn-primary"
href="<?php echo getUrl('operator', 'editCredit', array('obj_guid' => $row['obj_guid']), false, BACK_OFFICE_SITE_URL) ?>">
<span><i class="fa fa-send-o"></i>Credit</span>
</a>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<hr>
<?php include_once(template("widget/inc_content_pager")); ?>
<file_sep>/framework/weixin_baike/wxt/control/weixin.php
<?php
/**
* Created by PhpStorm.
* User: hh
* Date: 2018/3/18
* Time: 下午 2:50
*/
class weixinControl
{
public function helloOp()
{
ob_get_clean(); // 框架原因,必须添加
ob_clean();
ob_end_clean();//清除缓冲区,Bom头,避免乱码和不能识别的文件类型
// http://www.iruofeng.cn/fri_community/framework/weixin_baike/wxt/index.php?act=weixin&op=hello
if( $_GET['echostr'] ){
$this->validOp();
}else{
$this->responseMsgOp();
}
}
public function validOp()
{
$token = getConf('weixin_token');
$params = $_GET;
$signature = $params['signature'];
$timestamp = $params['timestamp'];
$nonce = $params['nonce'];
$echostr = $params['echostr'];
$temp = array($token,$timestamp,$nonce);
sort($temp,SORT_STRING);
$tmp_str = implode('',$temp);
$sign = sha1($tmp_str);
if( $sign == $signature ){
echo $echostr;
}else{
echo 'OK';
}
}
public function responseMsgOp()
{
wechatCallbackClass::responseMsg();
}
}<file_sep>/framework/api_test/apis/officer_app/officer.edit.member.residence.place.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/17
* Time: 14:32
*/
class officerEditMemberResidencePlaceApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Edit member residence place";
$this->description = "编辑会员居住地址";
$this->url = C("bank_api_url") . "/officer.edit.member.residence.place.php";
$this->parameters = array();
$this->parameters[] = new apiParameter("member_id", "会员id", 1, true);
$this->parameters[] = new apiParameter("address_id", "地址ID,如果是新增传0", 0);
$this->parameters[] = new apiParameter("id1", "一级地址ID", 1, true);
$this->parameters[] = new apiParameter("id2", "二级地址ID", 52, true);
$this->parameters[] = new apiParameter("id3", "三级地址ID", 99, true);
$this->parameters[] = new apiParameter("id4", "四级地址ID", 125, true);
$this->parameters[] = new apiParameter("full_text", "全路径详细地址", 'test', true);
$this->parameters[] = new apiParameter("cord_x", "经度", 28.2314854, true);
$this->parameters[] = new apiParameter("cord_y", "纬度", 145.125478, true);
$this->parameters[] = new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'uid' => '地址ID',
'coord_x' => '经度',
'coord_y' => '纬度',
'full_text' => '全地址',
'create_time' => ''
)
);
}
}<file_sep>/framework/api_test/apis/test.ace.api/ace.bind.finish.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 17:31
*/
class aceBindFinishApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.member.sign.finish";
$this->description = "Member sign finish. ACE will verify the verification code, if correct, sign success";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=bind_finish";
$this->parameters = array();
$this->parameters[]= new apiParameter("sign_id", "Bind Start 获得的事务ID", null, true);
$this->parameters[]= new apiParameter("verify_code", "验证码", null, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'flag_success' => "1: 绑定成功,2:失败"
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.product.rate.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/12
* Time: 13:09
*/
// loan.product.rate.list
class loanProductRateListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Product Rate List";
$this->description = "贷款产品列表";
$this->url = C("bank_api_url") . "/loan.product.rate.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("product_id", "产品id", 1,true);
$this->parameters[]= new apiParameter("currency", "币种", 'USD');
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'uid' => '利率ID',
'product_id' => '产品id',
'currency' => '币种',
'loan_size_min' => '最低贷款金额',
'loan_size_max' => '最高贷款金额',
'repayment_type' => '还款方式',
'repayment_period' => '还款周期,只有分期付款才有',
'loan_term_time' => '可贷款时间周期',
'interest_rate_des_value' => '利息利率值',
'interest_rate_unit' => '利息利率周期',
'operation_fee_des_value' => '运营费利率值',
'operation_fee_unit' => '运营费利率周期',
)
)
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/lock.list.php
<?php
$loanApplyStateLang = enum_langClass::getMemberStateLang();
?>
<style>
.content{
margin-top:50px;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Lock </h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('operator', 'requestLock', array(0), false, BACK_OFFICE_SITE_URL)?>"><span>request</span></a></li>
<li><a class="current"><span>request list</span></a></li>
</ul>
</div>
</div>
<div class="business-condition content">
<form class="form-inline" id="frm_search_condition">
<table class="search-table">
<tbody>
<tr>
<td>
<div class="input-group">
<input type="text" class="form-control" id="search_text" style="height: 34px" name="search_text" placeholder="Search for name">
<span class="input-group-btn">
<button type="button" class="btn btn-default square" id="btn_search_list" onclick="btn_search_onclick();">
<i class="fa fa-search"></i>
Search
</button>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div style="padding: 0;border-bottom: 1px solid #D5D5D5;">
<table class="table table-bordered">
<thead>
<tr class="table-header">
<td>No.</td>
<td>ID</td>
<td>Account</td>
<td>Client Name</td>
<td>Contact Phone</td>
<td>Apply Time</td>
<td>State</td>
</tr>
</thead>
<tbody class="table-body">
<?php $i = 0; foreach ($output['data'] as $row) { $i++ ?>
<tr>
<td>
<?php echo $i ?>
</td>
<td>
<?php echo $row['obj_guid'] ?>
</td>
<td>
<?php echo $row['login_code'] ?>
</td>
<td>
<?php echo $row['display_name'] ?>
</td>
<td>
<?php echo $row['phone_id'] ?>
</td>
<td>
<?php echo $row['update_time'] ?>
</td>
<td>
<?php echo $loanApplyStateLang[$row['member_state']] ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
<script>
function btn_search_onclick() {
var _search_text = $('#search_text').val();
yo.loadData({
});
}
</script>
<file_sep>/framework/api_test/apis/microbank/ace.bind.account.start.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/31
* Time: 10:29
*/
// ace.bind.account.start
class aceBindAccountStartApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Ace bind account start";
$this->description = "开始绑定ACE账号(发送验证码)";
$this->url = C("bank_api_url") . "/ace.bind.account.start.php";
$this->parameters = array();
$this->parameters[] = new apiParameter('account','ACE账号','+86-18902461905',true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'verify_id' => '短信验证ID',
'phone_id' => '发送电话'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/system.address.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/17
* Time: 11:57
*/
// system.address.list
class systemAddressListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System Address Children List ";
$this->description = "获取地址子区域";
$this->url = C("bank_api_url") . "/system.address.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("pid", "父级区域ID", 0, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
array(
'uid' => '',
'node_text' => '',
'node_text_alias' => array(
'只有英文,柬文',
'en' => '',
'kh' => ''
),
'node_level' => '层级',
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.login.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/1
* Time: 15:20
*/
// officer.login
class officerLoginApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Officer login";
$this->description = "业务员登陆";
$this->url = C("bank_api_url") . "/officer.login.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("user_code", "登陆账号", 'admin', true);
$this->parameters[]= new apiParameter("password", "密码", '<PASSWORD>', true);
$this->parameters[]= new apiParameter("client_type", "终端类型", 'android',true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'user_info' => array(
'@description' => '用户信息',
),
'token' => '登陆令牌'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.payable.info.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/11
* Time: 16:06
*/
// loan.contract.payable.info
class loanContractPayableInfoApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Payable Info";
$this->description = "贷款合同欠款信息";
$this->url = C("bank_api_url") . "/loan.contract.payable.info.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", "合同id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_overdue_amount' => '合计逾期应还本息',
'total_overdue_penalty' => '合计逾期应还罚金',
'total_payable_amount' => '合计剩余应还金额',
'next_repayment_date' => '下一期还款日期',
'next_repayment_amount' => '下一期还款金额',
'last_request_repayment_info' => '最后一次申请还款的信息'
)
);
}
}<file_sep>/framework/weixin_baike/data/model/loan_contract.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/29
* Time: 14:51
*/
class loan_contractModel extends tableModelBase
{
function __construct()
{
parent::__construct('loan_contract');
}
}<file_sep>/framework/weixin_baike/script/shell/update.cert.expire.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/26
* Time: 16:26
*/
require_once(dirname(__FILE__).'/../include_common.php');
$url = SCRIPT_SITE_URL.'/index.php?act=script_cert&op=updateExpireCertList';
while( true ){
$re = @file_get_contents($url);
print_r($re);
sleep(12*3600);
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/request.repayment.list.php
<style>
.verify-table .locking {
color: red;
font-style: normal;
}
.verify-table .locking i {
margin-right: 3px;
}
</style>
<div>
<table class="table verify-table">
<thead>
<tr class="table-header">
<td><?php echo 'Contract Sn'; ?></td>
<td><?php echo 'Type'; ?></td>
<td><?php echo 'Currency'; ?></td>
<td><?php echo 'Amount'; ?></td>
<!-- <td>--><?php //echo 'Payer Name'; ?><!--</td>-->
<!-- <td>--><?php //echo 'Payer Account'; ?><!--</td>-->
<!-- <td>--><?php //echo 'Bank Name'; ?><!--</td>-->
<!-- <td>--><?php //echo 'Bank Account'; ?><!--</td>-->
<td><?php echo 'State'; ?></td>
<td><?php echo 'Create Time'; ?></td>
<td><?php echo 'Handler'; ?></td>
<!-- <td>--><?php //echo 'Handle Remark'; ?><!--</td>-->
<td><?php echo 'Handle Time'; ?></td>
<td><?php echo 'Function'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach ($data['data'] as $row) { ?>
<tr>
<td>
<?php echo $row['contract_sn'] . ' ' . $row['scheme_name']; ?>
</td>
<td>
<?php echo $row['type'] == 'schema' ? "Schema" : "Prepayment"; ?>
</td>
<td>
<?php echo $row['currency']; ?>
</td>
<td>
<?php echo ncAmountFormat($row['amount'], false, $row['currency']); ?>
</td>
<!-- <td>-->
<!-- --><?php //echo $row['payer_name']; ?>
<!-- </td>-->
<!-- <td>-->
<!-- --><?php //echo $row['payer_account']; ?>
<!-- </td>-->
<!-- <td>-->
<!-- --><?php //echo $row['bank_name']; ?>
<!-- </td>-->
<!-- <td>-->
<!-- --><?php //echo $row['bank_account_no']; ?>
<!-- </td>-->
<td>
<?php if ($data['state'] != requestRepaymentStateEnum::PROCESSING){
echo '<span>' . $lang['request_repayment_state_' . $row['state']] . '</span>';
} elseif ($data['cur_uid'] == $row['handler_id']) {
echo '<span class="locking"><i class="fa fa-gavel"></i>' . $lang['request_repayment_state_' . $row['state']] . '</span>';
} else {
echo '<span class="locking">' . $lang['request_repayment_state_' . $row['state']] . '</span>';
}
?>
</td>
<td>
<?php echo timeFormat($row['create_time']) ?>
</td>
<td>
<?php echo $row['handler_name'] ?>
</td>
<!-- <td>--><?php //echo $row['remark']; ?><!--</td>-->
<td><?php echo timeFormat($row['handle_time']); ?></td>
<td>
<?php if( $row['state'] == requestRepaymentStateEnum::SUCCESS ){ ?>
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="<?php echo getUrl('loan', 'viewRequestRepaymentDetail', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<span><i class="fa fa-eye"></i>View</span>
</a>
</div>
<?php }else{ ?>
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="<?php echo getUrl('loan', 'auditRequestRepayment', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<span><i class="fa fa-check-circle-o"></i>Handle</span>
</a>
</div>
<?php } ?>
<?php /*if(in_array($row['state'],array(requestRepaymentStateEnum::CREATE,requestRepaymentStateEnum::PROCESSING))){ */?><!--
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="<?php /*echo getUrl('loan', 'auditRequestRepayment', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) */?>">
<span><i class="fa fa-check-circle-o"></i>Handle</span>
</a>
</div>
<?php /*}*/?>
<?php /*if(in_array($row['state'],array(requestRepaymentStateEnum::FAILED,requestRepaymentStateEnum::SUCCESS))){ */?>
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="<?php /*echo getUrl('loan', 'viewRequestRepaymentDetail', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) */?>">
<span><i class="fa fa-eye"></i>View</span>
</a>
</div>
--><?php /*}*/?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager")); ?>
<file_sep>/framework/weixin_baike/backoffice/control/report.php
<?php
class reportControl extends baseControl
{
public function __construct()
{
parent::__construct();
Language::read('report');
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Report");
Tpl::setDir("report");
}
/**
* 会员列表
*/
public function clientListOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('client');
}
/**
* 会员列表
* @param $p
* @return array
*/
public function getClientListOp($p)
{
$search_text = trim($p['search_text']);
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT cm.*,la.uid account_id,la.credit FROM " .
"client_member cm INNER JOIN loan_account la ON la.obj_guid = cm.obj_guid " .
"WHERE (cm.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if ($search_text) {
$sql .= ' AND (cm.display_name like "%' . $search_text . '%" OR cm.obj_guid = "' . $search_text . '")';
}
$sql .= ' ORDER BY cm.uid DESC';
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$account_ids = array_column($rows, 'account_id');
$sql = "SELECT account_id,COUNT(uid) loan_number,SUM(apply_amount) loan_amount FROM loan_contract WHERE account_id IN (" . implode(',', $account_ids) . ") AND state > " . loanContractStateEnum::CREATE . " GROUP BY account_id";
$loan_statistics_1 = $r->getRows($sql);
$loan_statistics_1 = resetArrayKey($loan_statistics_1, 'account_id');
$state = '(' . implode(',', array(schemaStateTypeEnum::CREATE, schemaStateTypeEnum::GOING, schemaStateTypeEnum::FAILURE)) . ')';
$sql = "SELECT lc.account_id,SUM(lis.receivable_interest + lis.receivable_operation_fee) total_interest," .
"SUM(lis.receivable_admin_fee) total_admin_fee," .
"SUM(CASE WHEN lis.state IN $state THEN (lis.receivable_principal) ELSE 0 END) receivable_principal," .
"SUM(CASE WHEN lis.state IN $state THEN (lis.receivable_principal + lis.receivable_interest + lis.receivable_operation_fee) ELSE 0 END) unpaid_amount " .
"FROM loan_installment_scheme lis INNER JOIN " .
"loan_contract lc ON lis.contract_id = lc.uid " .
"WHERE lc.account_id IN (" . implode(',', $account_ids) . ") GROUP BY lc.account_id";
$loan_statistics_2 = $r->getRows($sql);
$loan_statistics_2 = resetArrayKey($loan_statistics_2, 'account_id');
foreach ($rows as $key => $row) {
$account_id = $row['account_id'];
$row['loan_number'] = $loan_statistics_1[$account_id]['loan_number'];
$row['loan_amount'] = $loan_statistics_1[$account_id]['loan_amount'];
$row['total_interest'] = $loan_statistics_2[$account_id]['total_interest'];
$row['total_admin_fee'] = $loan_statistics_2[$account_id]['total_admin_fee'];
$row['receivable_principal'] = $loan_statistics_2[$account_id]['receivable_principal'];
$row['unpaid_amount'] = $loan_statistics_2[$account_id]['unpaid_amount'];
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
'statistics' => $this->getClientStatistics()
);
}
/**
* 会员统计
* @return array|ormDataRow
*/
private function getClientStatistics()
{
$r = new ormReader();
$sql = "SELECT COUNT(cm.uid) client_quantity,SUM(la.credit) sum_credit FROM " .
"client_member cm LEFT JOIN loan_account la ON la.obj_guid = cm.obj_guid ";
$client_statistics = $r->getRow($sql);
if ($client_statistics['client_quantity'] == 0) return array();
$client_statistics['avg_credit'] = round($client_statistics['sum_credit'] / $client_statistics['client_quantity'], 2);
$sql = "SELECT COUNT(uid) loan_number,SUM(apply_amount) loan_amount FROM loan_contract WHERE state > " . loanContractStateEnum::CREATE;
$loan = $r->getRow($sql);
$client_statistics['avg_loan_number'] = round($loan['loan_number'] / $client_statistics['client_quantity'], 2);
$client_statistics['avg_loan_amount'] = round($loan['loan_amount'] / $client_statistics['client_quantity'], 2);
$time = date('Y-m-d', time());
$sql = "SELECT SUM(uid) new_client FROM client_member WHERE create_time >= '" . $time . "'";
$new_client = $r->getOne($sql);
$client_statistics['new_client'] = $new_client;
return $client_statistics;
}
/**
* client detail
*/
public function clientDetailOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
$uid = intval($_GET['uid']);
Tpl::output("uid", $uid);
Tpl::showpage('client.detail');
}
/**
* Client Detail
* @param $p
* @return array
*/
public function getClientDetailOp($p)
{
$uid = intval($p['uid']);
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT cm.*,la.uid account_id,la.credit FROM " .
"client_member cm INNER JOIN loan_account la ON la.obj_guid = cm.obj_guid " .
"WHERE cm.uid = " . $uid;
$client_info = $r->getRow($sql);
$sql = "SELECT COUNT(uid) loan_number,SUM(apply_amount) loan_amount FROM loan_contract WHERE account_id = " . $client_info['account_id'] . " AND state > " . loanContractStateEnum::CREATE . " AND (create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
$loan_statistics_1 = $r->getRow($sql);
$state = '(' . implode(',', array(schemaStateTypeEnum::CREATE, schemaStateTypeEnum::GOING, schemaStateTypeEnum::FAILURE)) . ')';
$sql = "SELECT SUM(lis.receivable_interest + lis.receivable_operation_fee) total_interest," .
"SUM(lis.receivable_admin_fee) total_admin_fee," .
"SUM(CASE WHEN lis.state IN $state THEN (lis.receivable_principal) ELSE 0 END) receivable_principal," .
"SUM(CASE WHEN lis.state IN $state THEN (lis.receivable_principal + lis.receivable_interest + lis.receivable_operation_fee) ELSE 0 END) unpaid_amount " .
"FROM loan_installment_scheme lis INNER JOIN " .
"loan_contract lc ON lis.contract_id = lc.uid " .
"WHERE lc.account_id = " . $client_info['account_id'] . " AND (lc.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
$loan_statistics_2 = $r->getRow($sql);
$client_info['loan_number'] = $loan_statistics_1['loan_number'];
$client_info['loan_amount'] = $loan_statistics_1['loan_amount'];
$client_info['total_interest'] = $loan_statistics_2['total_interest'];
$client_info['total_admin_fee'] = $loan_statistics_2['total_admin_fee'];
$client_info['receivable_principal'] = $loan_statistics_2['receivable_principal'];
$client_info['unpaid_amount'] = $loan_statistics_2['unpaid_amount'];
$sql = "SELECT lc.*,lp.product_name"
. " FROM loan_contract lc"
. " LEFT JOIN loan_product lp ON lc.product_id = lp.uid"
. " WHERE lc.account_id = " . $client_info['account_id'] . " AND lc.state > " . loanContractStateEnum::CANCEL . " AND (lc.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$contract_ids = array_column($rows, 'uid');
$contract_id_str = '(' . implode(',', $contract_ids) . ')';
$sql = "SELECT contract_id,SUM(amount) disbursement_amount FROM loan_disbursement_scheme WHERE state = " . schemaStateTypeEnum::COMPLETE . " AND contract_id IN $contract_id_str GROUP BY contract_id";
$disbursement_arr = $r->getRows($sql);
$disbursement_arr = resetArrayKey($disbursement_arr, 'contract_id');
$sql = "SELECT contract_id,SUM(amount) receive_amount,SUM(CASE WHEN state = " . schemaStateTypeEnum::COMPLETE . " THEN amount ELSE 0 END) received_amount,SUM(CASE WHEN state != " . schemaStateTypeEnum::COMPLETE . " THEN amount ELSE 0 END) unreceived_amount FROM loan_installment_scheme WHERE contract_id IN $contract_id_str GROUP BY contract_id";
$installment_arr = $r->getRows($sql);
$installment_arr = resetArrayKey($installment_arr, 'contract_id');
foreach ($rows as $key => $row) {
$contract_id = $row['uid'];
$row['disbursement_amount'] = $disbursement_arr[$contract_id]['disbursement_amount'];
$row['receive_amount'] = $installment_arr[$contract_id]['receive_amount'];
$row['received_amount'] = $installment_arr[$contract_id]['received_amount'];
$row['unreceived_amount'] = $installment_arr[$contract_id]['unreceived_amount'];
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"client_info" => $client_info
);
}
/**
* 合同列表
*/
public function contractListOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('contract');
}
/**
* 获取合同列表
* @param $p
* @return array
*/
public function getContractListOp($p)
{
$r = new ormReader();
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$sql = "SELECT lc.*,cm.display_name,lp.product_name FROM loan_contract lc"
. " LEFT JOIN loan_account la ON lc.account_id = la.uid"
. " LEFT JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " LEFT JOIN loan_product lp ON lc.product_id = lp.uid"
. " WHERE lc.state != " . loanContractStateEnum::CANCEL . " AND (cm.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn = '" . trim($p['search_text']) . "'";
}
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$contract_ids = array_column($rows, 'uid');
$contract_id_str = '(' . implode(',', $contract_ids) . ')';
$sql = "SELECT contract_id,SUM(amount) disbursement_amount FROM loan_disbursement_scheme WHERE state = " . schemaStateTypeEnum::COMPLETE . " AND contract_id IN $contract_id_str GROUP BY contract_id";
$disbursement_arr = $r->getRows($sql);
$disbursement_arr = resetArrayKey($disbursement_arr, 'contract_id');
$sql = "SELECT contract_id,SUM(amount) receive_amount,SUM(CASE WHEN state = " . schemaStateTypeEnum::COMPLETE . " THEN amount ELSE 0 END) received_amount,SUM(CASE WHEN state != " . schemaStateTypeEnum::COMPLETE . " THEN amount ELSE 0 END) unreceived_amount FROM loan_installment_scheme WHERE contract_id IN $contract_id_str GROUP BY contract_id";
$installment_arr = $r->getRows($sql);
$installment_arr = resetArrayKey($installment_arr, 'contract_id');
$current_amount = array(
'apply_amount' => 0,
'disbursement_amount' => 0,
'receive_amount' => 0,
'received_amount' => 0,
'unreceived_amount' => 0,
);
foreach ($rows as $key => $row) {
$contract_id = $row['uid'];
$row['disbursement_amount'] = $disbursement_arr[$contract_id]['disbursement_amount'];
$row['receive_amount'] = $installment_arr[$contract_id]['receive_amount'];
$row['received_amount'] = $installment_arr[$contract_id]['received_amount'];
$row['unreceived_amount'] = $installment_arr[$contract_id]['unreceived_amount'];
$current_amount['apply_amount'] += $row['apply_amount'];
$current_amount['disbursement_amount'] += $row['disbursement_amount'];
$current_amount['receive_amount'] += $row['receive_amount'];
$current_amount['received_amount'] += $row['received_amount'];
$current_amount['unreceived_amount'] += $row['unreceived_amount'];
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"current_amount" => $current_amount,
"amount" => $this->getContractAmount($p)
);
}
/**
* 获取合同总额
* @param $p
* @return array
*/
private function getContractAmount($p)
{
$r = new ormReader();
$sql = "SELECT SUM(apply_amount) apply_amount FROM loan_contract WHERE state != " . loanContractStateEnum::CANCEL;
if (trim($p['search_text'])) {
$sql .= " AND contract_sn = '" . trim($p['search_text']) . "'";
}
$apply_amount = $r->getOne($sql);
$sql = "SELECT SUM(lds.amount) disbursement_amount FROM loan_disbursement_scheme lds INNER JOIN loan_contract lc ON lds.contract_id = lc.uid WHERE lds.state = " . schemaStateTypeEnum::COMPLETE;
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn = '" . trim($p['search_text']) . "'";
}
$disbursement_amount = $r->getOne($sql);
$sql = "SELECT SUM(lis.amount) receive_amount,SUM(CASE WHEN lis.state = " . schemaStateTypeEnum::COMPLETE . " THEN lis.amount ELSE 0 END) received_amount,SUM(CASE WHEN lis.state != " . schemaStateTypeEnum::COMPLETE . " THEN lis.amount ELSE 0 END) unreceived_amount FROM loan_installment_scheme lis INNER JOIN loan_contract lc ON lis.contract_id = lc.uid WHERE 1=1";
if (trim($p['search_text'])) {
$sql .= " AND lc.contract_sn = '" . trim($p['search_text']) . "'";
}
$installment_arr = $r->getRow($sql);
$data = array(
'apply_amount' => $apply_amount,
'disbursement_amount' => $disbursement_amount,
'receive_amount' => $installment_arr['receive_amount'],
'received_amount' => $installment_arr['received_amount'],
'unreceived_amount' => $installment_arr['unreceived_amount'],
);
return $data;
}
/**
* 授信列表
*/
public function creditListOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('credit');
}
/**
* 获取信用贷授权列表
* @param $p
* @return array
*/
public function getCreditListOp($p)
{
$r = new ormReader();
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$sql = "SELECT la.*,cm.display_name,uu.user_name FROM loan_approval la"
. " INNER JOIN client_member cm ON la.obj_guid = cm.obj_guid"
. " LEFT JOIN um_user uu ON la.operator_id = uu.uid"
. " WHERE (la.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['search_text'])) {
$sql .= " AND cm.display_name LIKE '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY la.uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize
);
}
/**
* 贷款产品
*/
public function loanListOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('loan');
}
/**
* 贷款产品列表
* @param $p
* @return array
*/
public function getLoanListOp($p)
{
$r = new ormReader();
$m_loan_product = M('loan_product');
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$sql = "SELECT MAX(uid) uid FROM loan_product WHERE (create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "') AND state < 40";
if (trim($p['search_text'])) {
$sql .= " AND product_name LIKE '%" . trim($p['search_text']) . "%'";
}
$sql .= " GROUP BY product_key ORDER BY uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$product_ids = array_column($rows, 'uid');
$sql = "SELECT * FROM loan_product WHERE uid IN (" . implode(',', $product_ids) . ") ORDER BY uid DESC";
$product_list = $r->getRows($sql);
foreach ($product_list as $key => $product) {
$product_key = $product['product_key'];
$product_count = $m_loan_product->field('count(*) count')->find(array('product_key' => $product_key));
$product_list[$key]['count'] = $product_count;
$product_contract = $this->getProductContractByKey($product_key);
$product_list[$key]['loan_contract'] = $product_contract['loan_count'] ?: 0;
$product_list[$key]['loan_client'] = $product_contract['loan_client'] ?: 0;
$product_list[$key]['loan_ceiling'] = $product_contract['loan_ceiling'] ?: 0;
$product_list[$key]['loan_balance'] = $product_contract['loan_balance'] ?: 0;
}
} else {
$product_list = array();
};
return array(
"sts" => true,
"data" => $product_list,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize
);
}
/**
* 获取系列产品合同信息
* @param $key
* @return ormDataRow
*/
private function getProductContractByKey($key)
{
$r = new ormReader();
$sql = "select uid from loan_product WHERE product_key = '" . $key . "'";
$product_ids = $r->getRows($sql);
if (!$product_ids) {
return array();
}
$product_id_str = '(' . implode(',', array_column($product_ids, 'uid')) . ')';
$sql = "SELECT COUNT(uid) loan_count,SUM(apply_amount) loan_ceiling,SUM(receivable_admin_fee-loss_admin_fee) admin_fee,SUM(receivable_interest+receivable_operation_fee+receivable_annual_fee+receivable_penalty-loss_principal-loss_interest-loss_operation_fee-loss_annual_fee-loss_penalty) loan_interest FROM loan_contract WHERE product_id IN " . $product_id_str;
$product_contract = $r->getRow($sql);
$sql = "SELECT SUM(lr.amount) repayment FROM loan_repayment AS lr INNER JOIN loan_contract AS lc ON lr.contract_id = lc.uid WHERE lr.state = 100 AND lc.product_id IN " . $product_id_str;
$repayment = $r->getOne($sql);
$loan_balance = $product_contract['loan_ceiling'] + $product_contract['loan_interest'] - $repayment;
$sql = "SELECT COUNT(member.uid) loan_client FROM loan_contract AS contract"
. " INNER JOIN loan_account AS account ON contract.account_id = account.uid"
. " INNER JOIN client_member AS member ON account.obj_guid = member.obj_guid WHERE contract.product_id IN " . $product_id_str . " GROUP BY member.uid";
$loan_client = $r->getOne($sql);
$product_contract['loan_balance'] = $loan_balance;
$product_contract['loan_client'] = $loan_client;
return $product_contract;
}
public function repaymentListOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('repayment');
}
public function getRepaymentListOp($p)
{
$r = new ormReader();
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$sql = "SELECT lr.*,lc.contract_sn,lis.scheme_name,sb.branch_name FROM loan_repayment lr"
. " INNER JOIN loan_contract lc ON lr.contract_id = lc.uid"
. " INNER JOIN loan_installment_scheme lis ON lr.scheme_id = lis.uid"
. " LEFT JOIN site_branch sb ON lr.branch_id = sb.uid"
. " WHERE lr.state = 100 AND (lr.create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if (trim($p['search_text'])) {
$sql .= " AND (lr.payer_name LIKE '%" . trim($p['search_text']) . "%' OR lc.contract_sn LIKE '%" . trim($p['search_text']) . "%')";
}
$sql .= " ORDER BY lr.uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize
);
}
}
<file_sep>/framework/api_test/apis/microbank/member.credit.release.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/20
* Time: 17:40
*/
class memberCreditReleaseListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Credit List";
$this->description = "会员授信历史列表";
$this->url = C("bank_api_url") . "/member.credit.release.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
)
)
);
}
}<file_sep>/framework/weixin_baike/language/zh_cn/certification.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/16
* Time: 15:42
*/
$lang['certification_id'] = 'ID';
$lang['certification_family_book'] = 'Family Book';
$lang['certification_family_relationship'] = 'Family Relationship';
$lang['certification_passport'] = 'Passport';
$lang['certification_work'] = 'Work';
$lang['certification_civil_servant'] = 'Civil Servant';
$lang['certification_house_asset'] = 'Housing Assets';
$lang['certification_car_asset'] = 'Car Assets';
$lang['certification_land_asset'] = 'Land Assets';
$lang['certification_resident_book'] = 'Resident Book';
$lang['certification_motorbike'] = 'Motorbike';
$lang['cert_sample_des_id_handheld'] = 'Handheld ID Card';
$lang['cert_sample_des_id_front'] = 'ID Card Front';
$lang['cert_sample_des_id_back'] = 'ID Card Back';
$lang['cert_sample_des_family_book_front'] = 'Family Book Front';
$lang['cert_sample_des_family_book_back'] = 'Family Book Back';
$lang['cert_sample_des_family_householder'] = 'Householder Page';
$lang['cert_sample_des_resident_book_front'] = 'Resident Book Front';
$lang['cert_sample_des_resident_book_back'] = 'Resident Book Back';
$lang['cert_sample_des_motorbike_certificate_front'] = 'Motorbike Certificate Front';
$lang['cert_sample_des_motorbike_certificate_back'] = 'Motorbike Certificate Back';
$lang['cert_sample_des_motorbike_photo'] = 'Motorbike Photo';
$lang['cert_sample_des_car_certificate_front'] = 'Car Certificate Front';
$lang['cert_sample_des_car_certificate_back'] = 'Car Certificate Back';
$lang['cert_sample_des_car_front'] = 'Car Front';
$lang['cert_sample_des_car_back'] = 'Car Back';
$lang['cert_sample_des_house_front'] = 'House Front';
$lang['cert_sample_des_house_front_road'] = 'House Front Road';
$lang['cert_sample_des_house_side_face'] = 'House Side Face';
$lang['cert_sample_des_house_property_card'] = 'House Property Card';
$lang['cert_sample_des_land_property_card'] = 'Land Property Card';
$lang['cert_sample_des_land_trading_record'] = 'Land Trading Record';
<file_sep>/framework/api_test/apis/officer_app/co.get.footprint.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/28
* Time: 16:56
*/
class coGetFootprintListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "CO get footprint list";
$this->description = "获取足迹列表";
$this->url = C("bank_api_url") . "/co.get.footprint.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "CO id", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
'@description' => '记录列表,没有为null',
array(
'coord_x' => '经度',
'coord_y' => '纬度',
'location' => '地理位置',
'sign_month' => '签到年月',
'sign_day' => '签到年月日',
'sign_time' => '签到时间',
'remark' => '备注'
)
)
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/widget/app.menu.top.php
<div id="header">
<div>
<h1>SAMRITHISAK</h1>
</div>
</div>
<div id="top-tools">
<ul class="list-inline">
<li title="Full Screen" class="full_screen"><i class="fa fa-arrows-alt"></i>Screen</li>
<li title="Lock Screen" onclick="callWin_lock_screen()"><i class="fa fa-lock"></i>Lock</li>
<li><i class="fa fa-wrench"></i>Tools</li>
<li class="dropdown open" id="profile-messages">
<a title="" href="#" data-toggle="dropdown" data-target="#profile-messages" class="dropdown-toggle" style="padding-right: 15px" aria-expanded="true">
<span class="text user_name"><i class="fa fa-cog"></i>Settings</span>
<b class="caret" style="margin-left: 0"></b>
</a>
<ul class="dropdown-menu" style="left:auto;right: 0;">
<li><a href="#" id="my_profile"><i class="fa fa-user"></i> My Profile</a></li>
<li class="divider"></li>
<li><a href="#" id="change_password"><i class="fa fa-tasks"></i> Change Password</a></li>
<li class="divider"></li>
<li><a href="<?php echo getUrl('login','loginOut', array(), false, ENTRY_COUNTER_SITE_URL)?>"><i class="fa fa-key"></i> Logout</a></li>
</ul>
</li>
</ul>
</div>
<div id="top-counter">
<div class="counter-icon">
<img src="<?php echo getUserIcon($output['user_info']['user_icon'])?>">
</div>
<div class="counter-info">
<div class="name"><?php echo $output['user_info']['user_code'] ."/". $output['user_info']['user_name'] ?></div>
<div class="department"><?php echo $output['department_info']['branch_name'] . ' ' . $output['department_info']['depart_name'];?></div>
</div>
<div class="balance">
<div class="cash_in_hand">
<div class="col-sm-3">Cash On Hand:</div>
<div class="col-sm-3">USD00.00</div>
<div class="col-sm-3">KHR00.00</div>
<div class="col-sm-3">CNY00.00</div>
<!-- <div class="col-sm-3">-->
<!-- <select class="form-control" style="font-size: 12px;border-radius: 0">-->
<!-- <option>USD</option>-->
<!-- <option>KHR</option>-->
<!-- <option>CNY</option>-->
<!-- </select>-->
<!-- </div>-->
</div>
<div class="outstanding">
<div class="col-sm-3">Outstanding:</div>
<div class="col-sm-3">USD00.00</div>
<div class="col-sm-3">KHR00.00</div>
<div class="col-sm-3">CNY00.00</div>
<!-- <div class="col-sm-3">-->
<!-- <select class="form-control" style="font-size: 12px;border-radius: 0">-->
<!-- <option>USD</option>-->
<!-- <option>KHR</option>-->
<!-- <option>CNY</option>-->
<!-- </select>-->
<!-- </div>-->
</div>
</div>
</div>
<script>
$(function () {
$('#top-tools').on('click', ' .full_screen', function () {
callWin_set_fullscreen();
$(this).removeClass('full_screen').addClass('un_full_screen').attr('title', 'Exit full screen');
})
$('#top-tools').on('click', ' .un_full_screen', function () {
callWin_unset_fullscreen();
$(this).removeClass('un_full_screen').addClass('full_screen').attr('title', 'Full screen');
})
$('#top-tools .full_screen').click();
})
function callWin_set_fullscreen(){
if(window.external){
try{
window.external.setFullScreen();
}catch (ex){
alert(ex.Message);
}
}
}
function callWin_unset_fullscreen(){
if(window.external){
try{
window.external.unsetFullScreen();
}catch (ex){
alert(ex.Message);
}
}
}
function callWin_lock_screen(){
if(window.external){
try{
window.external.lockScreen();
}catch (ex){
alert(ex.Message);
}
}
}
</script>
<file_sep>/framework/api_test/apis/microbank/member.guarantee.confirm.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/19
* Time: 14:39
*/
//member.guarantee.confirm
class memberGuaranteeConfirmApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member guarantee confirm ";
$this->description = "担保关系确认";
$this->url = C("bank_api_url") . "/member.guarantee.confirm.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("uid", "关系ID", 1, true);
$this->parameters[]= new apiParameter("state", "确认结果, 0 拒绝 1 接受", 0, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/system.currency.exchange.rate.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/22
* Time: 17:19
*/
// system.currency.exchange.rate
class systemCurrencyExchangeRateApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Currency exchange rate";
$this->description = "汇率列表";
$this->url = C("bank_api_url") . "/system.currency.exchange.rate.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/control/operator.php
<?php
class operatorControl extends baseControl
{
public function __construct()
{
parent::__construct();
Language::read('operator,certification');
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Operator");
Tpl::setDir("operator");
$this->getProcessingTask();
}
/**
* 新创建client
*/
public function newClientOp()
{
Tpl::showPage('new_client');
}
/**
* 获取新创建client列表
* @param $p
* @return array
*/
public function getClientListOp($p)
{
$verify_state = intval($p['verify_state']);
$r = new ormReader();
$sql = "SELECT cm.*,uu.user_name operator_name FROM client_member cm LEFT JOIN um_user uu ON cm.operator_id = uu.uid WHERE cm.operate_state = " . $verify_state;
if (trim($p['search_text'])) {
$sql .= " AND cm.display_name LIKE '%" . trim($p['search_text']) . "%' OR cm.login_code LIKE '%" . trim($p['search_text']) . "%' OR cm.phone_id LIKE '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY cm.uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"current_user" => $this->user_id,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"verify_state" => $verify_state
);
}
/**
* 检查新注册Client
*/
public function checkNewClientOp()
{
$uid = intval($_GET['uid']);
$m_client_member = M('client_member');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$is_handle_task = $m_um_user_operator_task->isHandleTask($uid, operateTypeEnum::NEW_CLIENT);
if (!$is_handle_task) {
showMessage('You can\'t deal with new task before finish the suspended task.');
}
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
showMessage('Invalid Id!');
}
if (in_array($client_info->operate_state, array(newMemberCheckStateEnum::CLOSE, newMemberCheckStateEnum::ALLOT, newMemberCheckStateEnum::PASS))) {
showMessage('The new user has been checked!');
}
if ($client_info->operate_state == newMemberCheckStateEnum::LOCKED && $client_info->operator_id != $this->user_id) {
showMessage('Other operator have been reprocessed!');
}
if ($client_info->operate_state == newMemberCheckStateEnum::CREATE) {
$conn = ormYo::Conn();
$conn->startTransaction();
$client_info->operate_state = newMemberCheckStateEnum::LOCKED;
$client_info->operator_id = $this->user_id;
$client_info->update_time = Now();
$rt_1 = $client_info->update();
if (!$rt_1->STS) {
$conn->rollback();
showMessage($rt_1->MSG);
}
$rt_2 = $m_um_user_operator_task->insertTask($uid, operateTypeEnum::NEW_CLIENT);
if (!$rt_2->STS) {
$conn->rollback();
showMessage($rt_2->MSG);
}
$conn->submitTransaction();
$this->getProcessingTask();
}
if ($client_info['member_grade']) {
$m_member_grade = M('member_grade');
$member_grade = $m_member_grade->find(array('uid' => $client_info['member_grade']));
$client_info['grade_code'] = $member_grade['grade_code'];
}
Tpl::output('client_info', $client_info);
$m_site_branch = M('site_branch');
$branch_list = $m_site_branch->orderBy('uid DESC')->select(array('status' => 1));
Tpl::output('branch_list', $branch_list);
Tpl::showPage('new_client.check');
}
/**
* 获取co列表
* @param $p
* @return array
*/
public function getCoListOp($p)
{
$search_text = trim($p['search_text']);
$branch_id = intval($p['branch_id']);
$r = new ormReader();
$sql = "SELECT uu.uid,uu.user_name,sb.branch_name,sd.depart_name FROM um_user uu INNER JOIN um_user_position up ON uu.uid = up.user_id INNER JOIN site_depart sd ON uu.depart_id = sd.uid INNER JOIN site_branch sb ON sb.uid = sd.branch_id WHERE uu.user_status = 1 AND sb.status = 1 AND up.user_position = '" . userPositionEnum::CREDIT_OFFICER . "'";
if ($search_text) {
$sql .= " AND uu.user_name like '%" . $search_text . "'";
}
if ($branch_id) {
$sql .= " AND sb.uid = " . $branch_id;
}
$sql .= " ORDER BY sb.uid asc, sd.uid ASC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$co_ids = array_column($rows, 'uid');
$co_id_str = "(" . implode(',', $co_ids) . ")";
$sql = "SELECT co_id,count(*) member_num FROM client_member WHERE co_id IN $co_id_str GROUP BY co_id";
$member_num = $r->getRows($sql);
$member_num = resetArrayKey($member_num, 'co_id');
$sql = "SELECT co_id,count(*) apply_num FROM loan_apply WHERE co_id IN $co_id_str AND (state = " . loanApplyStateEnum::ALLOT_CO . " OR state = " . loanApplyStateEnum::ALLOT_CO . ") GROUP BY co_id";
$apply_num = $r->getRows($sql);
$apply_num = resetArrayKey($apply_num, 'co_id');
foreach ($rows as $key => $row) {
$row['member_num'] = intval($member_num[$row['uid']]['member_num']);
$row['apply_num'] = intval($apply_num[$row['uid']]['apply_num']);
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 处理结果
* @param $p
* @return result
*/
public function submitCheckClientOp($p)
{
$member_id = intval($p['uid']);
$verify_state = trim($p['verify_state']);
$credit_officer_id = intval($p['credit_officer_id']);
$remark = trim($p['remark']);
$m_client_member = M('client_member');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$client_info = $m_client_member->getRow(array('uid' => $member_id));
if ($client_info->operate_state != newMemberCheckStateEnum::LOCKED) {
return new result(false, 'Invalid Id!');
}
if ($client_info->operator_id != $this->user_id) {
return new result(false, 'Param Error!');
}
$chk = $m_um_user_operator_task->checkCurrentTask($member_id, operateTypeEnum::NEW_CLIENT);
if (!$chk) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
if ($verify_state == 'abandon') {//取消任务
$client_info->operator_id = 0;
$client_info->operate_state = newMemberCheckStateEnum::CREATE;
$client_info->operate_remark = '';
$client_info->update_time = Now();
$rt_1 = $client_info->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 0;
$msg = 'Abandon Successful!';
} elseif ($verify_state == 'allot') {
$m_um_user = M('um_user');
$co_info = $m_um_user->find(array('uid' => $credit_officer_id));
$client_info->operate_state = newMemberCheckStateEnum::ALLOT;
$client_info->operate_remark = $remark;
$client_info->co_id = $credit_officer_id;
$client_info->co_name = $co_info['user_name'];
$client_info->update_time = Now();
$rt_1 = $client_info->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 100;
} else {
$client_info->operate_state = $verify_state == 'pass' ? newMemberCheckStateEnum::PASS : newMemberCheckStateEnum::CLOSE;
$client_info->operate_remark = $remark;
if ($verify_state == newMemberCheckStateEnum::CLOSE) {
$client_info->member_state = memberStateEnum::CANCEL;
}
$client_info->update_time = Now();
$rt_1 = $client_info->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 100;
}
$rt_2 = $m_um_user_operator_task->updateTaskState($member_id, operateTypeEnum::NEW_CLIENT, $task_state);
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, $rt_2->MSG);
}
$conn->submitTransaction();
return new result(true, $msg ?: 'Handle Successful!');
}
/**
* 贷款申请
*/
public function requestLoanOp()
{
Tpl::showPage('request_loan');
}
/**
* 获取申请列表
* @param $p
* @return array
*/
public function getRequestLoanListOp($p)
{
$verify_state = intval($p['verify_state']);
$r = new ormReader();
$sql = "SELECT la.* FROM loan_apply la WHERE 1 = 1";
if ($verify_state == 2) {
$sql .= " AND la.state >= " . $verify_state;
} else {
$sql .= " AND la.state = " . $verify_state;
}
if (trim($p['search_text'])) {
$sql .= " AND la.applicant_name like '%" . trim($p['search_text']) . "%' OR la.contact_phone '" . trim($p['search_text']) . "'";
}
$sql .= " ORDER BY la.uid DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
$apply_source = (new loanApplySourceEnum)->Dictionary();
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
"current_user" => $this->user_id,
"verify_state" => $verify_state,
"apply_source" => $apply_source,
);
}
/**
* 贷款申请审核
*/
public function operateRequestLoanOp()
{
$uid = intval($_GET['uid']);
$m_loan_apply = M('loan_apply');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$is_handle_task = $m_um_user_operator_task->isHandleTask($uid, operateTypeEnum::REQUEST_LOAN);
if (!$is_handle_task) {
showMessage('You can\'t deal with new task before finish the suspended task.');
}
$row = $m_loan_apply->getRow($uid);
if (!$row) {
showMessage('Invalid Id!');
}
if ($row->state > loanApplyStateEnum::CREATE) {
showMessage('The request has been audited!');
}
if ($row->state == loanApplyStateEnum::LOCKED && $row->operator_id != $this->user_id) {
showMessage('Other operator have been reprocessed!');
}
if ($row->state == loanApplyStateEnum::CREATE) {
$conn = ormYo::Conn();
$conn->startTransaction();
$row->state = loanApplyStateEnum::LOCKED;
$row->operator_id = $this->user_id;
$row->operator_name = $this->user_name;
$row->update_time = Now();
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
showMessage($rt_1->MSG);
}
$rt_2 = $m_um_user_operator_task->insertTask($uid, operateTypeEnum::REQUEST_LOAN);
if (!$rt_2->STS) {
$conn->rollback();
showMessage($rt_2->MSG);
}
$conn->submitTransaction();
$this->getProcessingTask();
}
Tpl::output('apply_info', $row);
$apply_source = (new loanApplySourceEnum)->Dictionary();
Tpl::output('apply_source', $apply_source);
$m_site_branch = M('site_branch');
$branch_list = $m_site_branch->orderBy('uid DESC')->select(array('status' => 1));
Tpl::output('branch_list', $branch_list);
Tpl::showpage('request_loan.audit');
}
/**
* 贷款申请处理
* @param $p
* @return result
*/
public function submitRequestLoanOp($p)
{
$uid = intval($p['uid']);
$verify_state = trim($p['verify_state']);
$remark = trim($p['remark']);
$credit_officer_id = intval($p['credit_officer_id']);
$m_loan_apply = M('loan_apply');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$loan_apply = $m_loan_apply->getRow(array('uid' => $uid));
if (!$loan_apply) {
return new result(false, 'Invalid Id!');
}
if ($loan_apply->state != loanApplyStateEnum::LOCKED) {
return new result(false, 'Invalid Id!');
}
if ($loan_apply->operator_id != $this->user_id) {
return new result(false, 'Param Error!');
}
$chk = $m_um_user_operator_task->checkCurrentTask($uid, operateTypeEnum::REQUEST_LOAN);
if (!$chk) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
if ($verify_state == 'abandon') {
$loan_apply->operator_id = 0;
$loan_apply->operator_name = '';
$loan_apply->operator_remark = '';
$loan_apply->state = loanApplyStateEnum::CREATE;
$loan_apply->update_time = Now();
$rt_1 = $loan_apply->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 0;
$msg = 'Abandon Successful!';
} elseif ($verify_state == 'allot') {
$m_um_user = M('um_user');
$co_info = $m_um_user->find(array('uid' => $credit_officer_id));
$loan_apply->state = loanApplyStateEnum::ALLOT_CO;
$loan_apply->operator_remark = $remark;
$loan_apply->credit_officer_id = $credit_officer_id;
$loan_apply->credit_officer_name = $co_info['user_name'];
$loan_apply->update_time = Now();
$rt_1 = $loan_apply->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 100;
} else {
$loan_apply->state = loanApplyStateEnum::OPERATOR_REJECT;
$loan_apply->operator_remark = $remark;
$loan_apply->update_time = Now();
$rt_1 = $loan_apply->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$task_state = 100;
}
$rt_2 = $m_um_user_operator_task->updateTaskState($uid, operateTypeEnum::REQUEST_LOAN, $task_state);
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, $rt_2->MSG);
}
$conn->submitTransaction();
return new result(true, $msg ?: 'Handle Successful!');
}
/**
* 添加贷款申请
*/
public function addRequestLoanOp()
{
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$m_loan_apply = M('loan_apply');
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$rt = $m_loan_apply->addApply($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('operator', 'requestLoan', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('operator', 'addRequestLoan', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type'));
Tpl::output('mortgage_type', $define_arr['mortgage_type']);
$apply_source = (new loanApplySourceEnum)->Dictionary();
Tpl::output('request_source', $apply_source);
Tpl::showpage('request_loan.add');
}
}
/**
* Certification File
*/
public function certificationFileOp()
{
$type = trim($_GET['type']) ?: certificationTypeEnum::ID;
Tpl::output('type', $type);
$certification_type = enum_langClass::getCertificationTypeEnumLang();
Tpl::output('title', $certification_type[$type]);
Tpl::showPage("certification");
}
public function getCertificationListOp($p)
{
$r = new ormReader();
$sql1 = "select verify.*,member.login_code,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid where 1=1 ";
$sql1 .= " and verify.cert_type = " . intval($p['cert_type']);
$sql1 .= " and verify.verify_state = " . intval($p['verify_state']);
if (trim($p['member_name'])) {
$sql1 .= " and (member.login_code like '%" . $p['member_name'] . "%')";
}
$sql1 .= " ORDER BY verify.uid desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql1, $pageNumber, $pageSize);
$rows = $data->rows;
$list = array();
foreach ($rows as $row) {
$sql = "select * from member_verify_cert_image where cert_id='" . $row['uid'] . "'";
$images = $r->getRows($sql);
$row['cert_images'] = $images;
$list[] = $row;
}
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $list,
"total" => $total,
"cur_uid" => $this->user_id,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 审核资料详情
* @throws Exception
*/
public function certificationDetailOp()
{
$uid = intval($_GET['uid']);
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$is_handle_task = $m_um_user_operator_task->isHandleTask($uid, operateTypeEnum::CERTIFICATION_FILE);
if (!$is_handle_task) {
showMessage('You can\'t deal with new task before finish the suspended task.');
}
$sample_images = global_settingClass::getCertSampleImage();
Tpl::output('cert_sample_images', $sample_images);
$r = new ormReader();
$m_member_verify_cert = M('member_verify_cert');
$row = $m_member_verify_cert->getRow(array('uid' => $uid));
if (!$row) {
showMessage('Invalid Id!');
}
if ($row->verify_state > certStateEnum::CREATE) {
showMessage('The request has been audited!');
}
if ($row->verify_state == certStateEnum::LOCK && $row->auditor_id != $this->user_id) {
showMessage('Other operator have been reprocessed!');
}
$data = $row->toArray();
$ID = $m_member_verify_cert->getRow(array('member_id' => $data['member_id'], 'cert_type' => certificationTypeEnum::ID, 'verify_state' => 10));
if ($data['cert_type'] == certificationTypeEnum::FAIMILYBOOK && !$ID) {
showMessage('Please verify the identity card information', getUrl('operator', 'certification', array('cert_type' => certificationTypeEnum::FAIMILYBOOK), false, BACK_OFFICE_SITE_URL));
}
$sql = "select * from member_verify_cert where uid != " . $data['uid'] . " and member_id = " . $data['member_id'] . " and cert_type = " . $data['cert_type'] . " order by uid desc";
$history = $r->getRows($sql);
foreach ($history as $k => $v) {
$sql = "select * from member_verify_cert_image where cert_id='" . $v['uid'] . "'";
$images = $r->getRows($sql);
$v['cert_images'] = $images;
$history[$k] = $v;
}
if ($row['verify_state'] == certStateEnum::CREATE) {
$conn = ormYo::Conn();
$conn->startTransaction();
$row->verify_state = certStateEnum::LOCK;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->auditor_time = Now();
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
showMessage($rt_1->MSG);
}
$rt_2 = $m_um_user_operator_task->insertTask($uid, operateTypeEnum::CERTIFICATION_FILE);
if (!$rt_2->STS) {
$conn->rollback();
showMessage($rt_2->MSG);
}
$conn->submitTransaction();
$this->getProcessingTask();
}
$sql = "select verify.*,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid where verify.uid = " . $uid;
$info = $r->getRow($sql);
$sql = "select * from member_verify_cert_image where cert_id=" . $uid;
$images = $r->getRows($sql);
$info['cert_images'] = $images;
Tpl::output('info', $info);
Tpl::output('history', $history);
if ($ID) {
Tpl::output('IDInfo', $ID->toArray());
}
$certification_type = enum_langClass::getCertificationTypeEnumLang();
Tpl::output('certification_type', $certification_type);
Tpl::output('title', $certification_type[$row->cert_type]);
switch ($row->cert_type) {
case certificationTypeEnum::MOTORBIKE :
case certificationTypeEnum::RESIDENT_BOOK :
case certificationTypeEnum::ID :
case certificationTypeEnum::PASSPORT :
case certificationTypeEnum::FAIMILYBOOK :
case certificationTypeEnum::HOUSE :
case certificationTypeEnum::CAR :
case certificationTypeEnum::LAND :
Tpl::showPage("certification.detail");
break;
case certificationTypeEnum::WORK_CERTIFICATION :
$m_work = new member_workModel();
$extend_info = $m_work->getRow(array(
'cert_id' => $row->uid
));
Tpl::output('extend_info', $extend_info);
Tpl::showPage('certification.work.detail');
break;
default:
showMessage('Not supported type');
}
}
/**
* 资料认证
* @return result
* @throws Exception
*/
public function certificationConfirmOp()
{
$p = array_merge(array(), $_GET, $_POST);
$obj_validate = new Validate();
$obj_validate->deliverparam = $p;
$error = $obj_validate->validate();
if ($error != '') {
showMessage($error, '', 'html', 'error');
}
$uid = intval($p['uid']);
$m_member_verify_cert = M('member_verify_cert');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$row = $m_member_verify_cert->getRow(array('uid' => $uid));
if (!$row) {
showMessage('Invalid Id!');
}
if ($row->verify_state != certStateEnum::LOCK) {
showMessage('Invalid Id!');
}
if ($row->auditor_id != $this->user_id) {
showMessage('Param Error!');
}
$chk = $m_um_user_operator_task->checkCurrentTask($uid, operateTypeEnum::CERTIFICATION_FILE);
if (!$chk) {
showMessage('Param Error!');
}
$cert_type = $row->cert_type;
$conn = ormYo::Conn();
$conn->startTransaction();
$rt_2 = $m_um_user_operator_task->updateTaskState($uid, operateTypeEnum::CERTIFICATION_FILE, 100);
if (!$rt_2->STS) {
$conn->rollback();
showMessage($rt_2->MSG);
}
//存认证log
$m_member_cert_log = new member_cert_logModel();
$rt_3 = $m_member_cert_log->insertCertLog($uid, 1);
if (!$rt_3->STS) {
$conn->rollback();
showMessage($rt_3->MSG);
}
switch ($cert_type) {
case certificationTypeEnum::HOUSE :
case certificationTypeEnum::CAR :
case certificationTypeEnum::LAND :
case certificationTypeEnum::MOTORBIKE:
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$p['insert'] = false;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
if ($p['verify_state'] == certStateEnum::PASS) {
$asset_state = assetStateEnum::CERTIFIED;
} else {
$asset_state = assetStateEnum::INVALID;
}
// 更新资产认证状态
$m_asset = new member_assetsModel();
$asset = $m_asset->getRow(array('cert_id' => $row['uid']));
if ($asset) {
$asset->asset_state = $asset_state;
$asset->update_time = Now();
$up = $asset->update();
if (!$up->STS) {
$conn->rollback();
showMessage('Update asset state fail', getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
}
$message = 'Successful';
$conn->submitTransaction();
break;
case certificationTypeEnum::RESIDENT_BOOK :
case certificationTypeEnum::ID :
case certificationTypeEnum::PASSPORT :
case certificationTypeEnum::FAIMILYBOOK :
// 更新状态
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
if ($cert_type == certificationTypeEnum::ID) {
$p['insert'] = true;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
if ($p['verify_state'] == certStateEnum::PASS) {
// 修改会员表身份证信息
$m_member = new memberModel();
$member = $m_member->getRow($row->member_id);
if (!$member) {
$conn->rollback();
showMessage('Error member', getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
$id_en_name_json = json_encode(array('family_name' => $p['en_family_name'], 'given_name' => $p['en_given_name']));
$id_kh_name_json = json_encode(array('family_name' => $p['kh_family_name'], 'given_name' => $p['kh_given_name']));
$member->initials = strtoupper(substr($p['en_family_name'], 0, 1));
$member->display_name = $p['en_family_name'] . ' ' . $p['en_given_name'];
$member->kh_display_name = $p['kh_family_name'] . ' ' . $p['kh_given_name'];
$member->id_sn = $row['cert_sn'];
$member->id_type = $p['id_type'];
$member->nationality = $p['nationality'];
$member->id_en_name_json = $id_en_name_json;
$member->id_kh_name_json = $id_kh_name_json;
$member->id_address1 = $p['id_address1'];
$member->id_address2 = $p['id_address2'];
$member->id_address3 = $p['id_address3'];
$member->id_address4 = $p['id_address4'];
$member->id_expire_time = $p['cert_expire_time'];
$up = $member->update();
if (!$up->STS) {
$conn->rollback();
showMessage('Update member ID sn fail', getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
}
} else {
$p['insert'] = false;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
}
$message = 'Successful';
$conn->submitTransaction();
break;
case certificationTypeEnum::WORK_CERTIFICATION :
$p['insert'] = false;
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
$m_work = new member_workModel();
$extend_info = $m_work->getRow(array(
'cert_id' => $row->uid
));
if ($p['verify_state'] == certStateEnum::PASS) {
$work_state = workStateStateEnum::VALID;
} else {
$work_state = workStateStateEnum::INVALID;
}
if ($extend_info) {
$extend_info->state = $work_state;
$up = $extend_info->update();
if (!$up->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
}
// 如果通过
if ($p['verify_state'] == certStateEnum::PASS) {
// 如果是政府员工,更新member表
if ($extend_info->is_government) {
$m_member = new memberModel();
$member = $m_member->getRow($extend_info->member_id);
if ($member) {
$member->is_government = 1;
$up = $member->update();
if (!$up->STS) {
$conn->rollback();
showMessage($ret->MSG, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
}
}
}
$message = 'Successful';
$conn->submitTransaction();
break;
default:
$message = 'Not supported type';
$conn->rollback();
}
showMessage($message, getUrl('operator', 'certificationFile', array('cert_type' => $cert_type), false, BACK_OFFICE_SITE_URL));
}
/**
* 取消任务
* @param $p
* @return result
*/
public function abandonCertificationFileOp($p)
{
$uid = intval($p['uid']);
$m_member_verify_cert = M('member_verify_cert');
$m_um_user_operator_task = new um_user_operator_taskModel($this->user_id);
$row = $m_member_verify_cert->getRow(array('uid' => $uid));
if (!$row) {
return new result(false, 'Invalid Id!');
}
if ($row->verify_state != certStateEnum::LOCK) {
return new result(false, 'Invalid Id!');
}
if ($row->auditor_id != $this->user_id) {
return new result(false, 'Param Error!');
}
$chk = $m_um_user_operator_task->checkCurrentTask($uid, operateTypeEnum::CERTIFICATION_FILE);
if (!$chk) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
$row->auditor_id = 0;
$row->auditor_name = '';
$row->verify_remark = '';
$row->verify_state = certStateEnum::CREATE;
$row->update_time = Now();
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, $rt_1->MSG);
}
$rt_2 = $m_um_user_operator_task->updateTaskState($uid, operateTypeEnum::CERTIFICATION_FILE, 0);
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, $rt_2->MSG);
}
$conn->submitTransaction();
return new result(true, 'Abandon Successful');
}
public function grantCreditOp()
{
Tpl::showPage('grant.credit');
}
public function getGrandCreditListOp($p)
{
$r = new ormReader();
if (trim($p['type'] == 'all')) {
$sql = "SELECT cm.uid uid FROM client_member cm WHERE cm.member_state != 0";
if (trim($p['search_text'])) {
$sql .= " AND cm.display_name LIKE '%" . trim($p['search_text']) . "%' OR cm.login_code LIKE '%" . trim($p['search_text']) . "%' OR cm.phone_id LIKE '%" . trim($p['search_text']) . "%'";
}
$sql .= " ORDER BY cm.uid DESC";
} else {
$sql = "SELECT cm.uid uid,max(mcl.create_time) last_cert_time FROM client_member cm INNER JOIN member_verify_cert mvc ON cm.uid = mvc.member_id INNER JOIN member_cert_log mcl ON mvc.uid = mcl.cert_id WHERE cm.member_state != 0 AND cm.member_state != 20 AND mcl.state = 0";
if (trim($p['search_text'])) {
$sql .= " AND cm.display_name LIKE '%" . trim($p['search_text']) . "%' OR cm.login_code LIKE '%" . trim($p['search_text']) . "%' OR cm.phone_id LIKE '%" . trim($p['search_text']) . "%'";
}
$sql .= " GROUP BY cm.uid ORDER BY last_cert_time DESC";
}
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
if ($rows) {
$member_ids = array_column($rows, 'uid');
$member_id_str = "(" . implode(',', $member_ids) . ")";
$sql = "SELECT client.*,loan.uid load_uid,loan.allow_multi_contract,c.credit,c.credit_balance FROM client_member client LEFT JOIN loan_account loan ON loan.obj_guid = client.obj_guid LEFT JOIN member_credit c ON c.member_id=client.uid WHERE client.uid IN $member_id_str ORDER BY client.uid DESC";
$member_list = $r->getRows($sql);
$member_list = resetArrayKey($member_list, 'uid');
foreach ($rows as $key => $row) {
$row = array_merge(array(), $row, $member_list[$row['uid']]);
$rows[$key] = $row;
}
}
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 修改信用额度
* @throws Exception
*/
public function editCreditOp()
{
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
$m_member = new memberModel();
$m_core_dictionary = M('core_dictionary');
$member = $m_member->getRow(array(
'obj_guid' => intval($p['obj_guid'])
));
if (!$member) {
showMessage('No member');
}
$setting = $m_core_dictionary->getDictionary('global_settings');
$setting = my_json_decode($setting['dict_value']);
if ($p['credit'] > $setting['operator_credit_maximum']) {
showMessage('Credit limit.');
}
$m_loan_account = new loan_accountModel();
$rt = $m_loan_account->getCreditInfo(intval($p['obj_guid']));
$data = $rt->DATA;
$m_credit = new member_creditModel();
$member_credit = $m_credit->getRow(array(
'member_id' => $member['uid']
));
$credit_reference = credit_loanClass::getCreditLevelList();
$cert_lang = enum_langClass::getCertificationTypeEnumLang();
foreach ($credit_reference as $k => $v) {
$item = $v;
$cert_list = $item['cert_list'];
foreach ($cert_list as $key => $value) {
$cert_list[$key] = $cert_lang[$value];
}
$item['cert_list'] = $cert_list;
$credit_reference[$k] = $item;
}
Tpl::output('credit_reference_value', $credit_reference);
$sql = "SELECT loan.*,client.uid as member_id,client.display_name,client.alias_name,client.phone_id,client.email FROM loan_account as loan left join client_member as client on loan.obj_guid = client.obj_guid where loan.obj_guid = '" . intval($p['obj_guid']) . "'";
$info = $r->getRow($sql);
if ($p['form_submit'] == 'ok') {
$conn = ormYo::Conn();
$conn->startTransaction();
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$p['before_credit'] = $member_credit['credit'];
$rt = $m_loan_account->editCredit($p);
if (!$rt->STS) {
unset($p['form_submit']);
$conn->rollback();
showMessage($rt->MSG, getUrl('operator', 'editCredit', $p, false, BACK_OFFICE_SITE_URL));
}
$sql = "SELECT mcl.uid FROM member_cert_log mcl INNER JOIN member_verify_cert mvc ON mvc.uid = mcl.cert_id WHERE mcl.state = 0 AND mvc.member_id = " . $info['member_id'];
$log_id_list = $r->getRows($sql);
if ($log_id_list) {
$log_ids = array_column($log_id_list, 'uid');
$log_id_str = '(' . implode(',', $log_ids) . ')';
$sql = "UPDATE member_cert_log SET state = 100,update_time = '" . Now() . "' WHERE uid IN $log_id_str";
$rt_1 = $r->conn->execute($sql);
if (!$rt_1->STS) {
unset($p['form_submit']);
$conn->rollback();
showMessage($rt_1->MSG, getUrl('operator', 'editCredit', $p, false, BACK_OFFICE_SITE_URL));
}
}
$conn->submitTransaction();
showMessage($rt->MSG, getUrl('operator', 'grantCredit', array(), false, BACK_OFFICE_SITE_URL));
} else {
$m_loan_approval = M('loan_approval');
$approvaling = $m_loan_approval->getRow(array('obj_guid' => intval($p['obj_guid']), 'state' => 0));//申请中
if ($approvaling) {
Tpl::output('approval_info', $approvaling);
}
$member_id = $member['uid'];
$re = memberClass::getMemberSimpleCertResult($member_id);
if (!$re->STS) {
showMessage('Error: ' . $re->MSG);
}
$verifys = $re->DATA;
$verify_field = enum_langClass::getCertificationTypeEnumLang();
Tpl::output("verify_field", $verify_field);
//获取co advice
$m_member_credit_suggest = M('member_credit_suggest');
$credit_suggest = $m_member_credit_suggest->orderBy('uid DESC')->find(array('member_id' => $info['member_id']));
Tpl::output("credit_suggest", $credit_suggest);
$sql = "SELECT SUM(valuation) assets_valuation FROM member_assets WHERE member_id = " . $info['member_id'] . " AND asset_state = 100";
$assets_valuation = $r->getOne($sql);
Tpl::output("assets_valuation", $assets_valuation);
$sql = "SELECT asset_type,SUM(valuation) assets_valuation FROM member_assets WHERE member_id = " . $info['member_id'] . " AND asset_state = 100 GROUP BY asset_type ORDER BY asset_type ASC";
$assets_valuation_type = $r->getRows($sql);
Tpl::output("assets_valuation_type", $assets_valuation_type);
Tpl::output('info', $info);
Tpl::output("verifys", $verifys);
Tpl::output('credit_info', $member_credit);
Tpl::output('loan_info', $data);
Tpl::showPage("grant.credit.edit");
}
}
/**
* 获取client
* @param $p
* @return result
*/
public function getClientInfoOp($p)
{
$country_code = trim($p['country_code']);
$phone = trim($p['phone']);
$format_phone = tools::getFormatPhone($country_code, $phone);
$contact_phone = $format_phone['contact_phone'];
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('phone_id' => $contact_phone, 'is_verify_phone' => 1));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
// if ($client_info->member_state == memberStateEnum::LOCKING || $client_info->member_state == memberStateEnum::CANCEL) {
// return new result(false, 'This account is not available!');
// }
$client_info['member_state'] = L('client_member_state_' . $client_info['member_state']);//使用这个状态值
return new result(true, '', $client_info);
}
/**
* 挂失页面
*/
public function requestLockOp()
{
Tpl::showPage("request.lock");
}
/**
* 挂失操作
* @param $p
* @return result
*/
public function lockMemberOp($p)
{
$uid = intval($p['uid']);
$m_client_member = M('client_member');
$row = $m_client_member->getRow(array('uid' => $uid));
if (!$row) {
return new result(false, 'No eligible clients!');
}
if ($row->member_state == memberStateEnum::LOCKING || $row->member_state == memberStateEnum::CANCEL) {
return new result(false, 'This account is not available!');
}
$row->member_state = memberStateEnum::LOCKING;
$row->update_time = Now();
$rt = $row->update();
if ($rt->STS) {
return new result(true, 'Lock successfully');
} else {
return new result(false, 'Lock failure');
}
}
/**
* 挂失列表
* @param $p
* @return result
*/
public function lockListOp()
{
$r = new ormReader();
$sql = "SELECT * FROM client_member WHERE member_state=20 ORDER BY update_time DESC ";
$data = $r->getRows($sql);
$data->member_state = 1;
Tpl::output('data', $data);
Tpl::showPage('lock.list');
}
public function complaintAdviceOp()
{
Tpl::showPage('complaint.advice');
}
/**
* 增加投诉或建议
*/
public function addComplaintAdviceOp()
{
Tpl::showPage('complaint.advice.add');
}
/**
* 获取投诉建议列表
*/
public function getComplaintAdviceListOp($p)
{
$search_text = trim($p['search_text']);
$r = new ormReader();
$sql = "SELECT * FROM complaint_advice ";
if ($search_text) {
$sql .= " WHERE complaint_advice.type like '%" . $search_text . "%'";
}
$sql .= " ORDER BY create_time DESC";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 新增投诉或建议
*/
public function saveComplaintAdviceOp()
{
$type = $_POST['type'];
$title = $_POST['title'];
$content = $_POST['content'];
$contact_name = $_POST['contact_name'];
$country_code = $_POST['country_code'];
$phone_number = $_POST['phone_number'];
$format_phone = tools::getFormatPhone($country_code, $phone_number);
$contact_phone = $format_phone['contact_phone'];
$create_time = Now();
$state = complaintAdviceEnum::CREATE;
$arr = array(
'type' => $type,
'title' => $title,
'content' => $content,
'contact_name' => $contact_name,
'contact_phone' => $contact_phone,
'create_time' => $create_time,
'state' => $state
);
$m_complaint_advice = M("complaint_advice");
$r = $m_complaint_advice->insert($arr);
if ($r->STS) {
showMessage('Add successfully', getUrl('operator', 'complaintAdvice', array(0), false, BACK_OFFICE_SITE_URL));
} else {
showMessage('Add failure');
}
}
/**
*投诉建议详情
*/
public function detailsOp()
{
$uid = $_GET['uid'];
$r = new ormReader();
$sql = 'SELECT * FROM complaint_advice WHERE uid=' . $uid;
$data = $r->getRow($sql);
Tpl::output('data', $data);
Tpl::showPage('complaint.advice.details');
}
}
<file_sep>/framework/weixin_baike/backoffice/templates/default/report/client.detail.php
<link href="<?php echo BACK_OFFICE_SITE_URL ?>/resource/css/report.css?v=5" rel="stylesheet" type="text/css"/>
<style>
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Client</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('report', 'client', array(), false, BACK_OFFICE_SITE_URL)?>"><span>List</span></a></li>
<li><a class="current"><span>Detail</span></a></li>
</ul>
</div>
</div>
<div class="container">
<div class="business-condition">
<form class="form-inline" id="frm_search_condition">
<table class="search-table">
<tr>
<td>
<?php include(template("widget/inc_condition_datetime")); ?>
</td>
</tr>
</table>
</form>
</div>
<div class="business-content">
<div class="business-list">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
btn_search_onclick();
});
var uid = '<?php echo intval($output['uid'])?>';
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 20;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var _values = $('#frm_search_condition').getValues();
_values.pageNumber = _pageNumber;
_values.pageSize = _pageSize;
_values.uid = uid;
yo.dynamicTpl({
tpl: "report/client.detail.list",
dynamic: {
api: "report",
method: "getClientDetail",
param: _values
},
callback: function (_tpl) {
$(".business-list").html(_tpl);
}
});
}
</script>
<file_sep>/framework/weixin_baike/counter/templates/default/service/add.request.loan.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css" rel="stylesheet" type="text/css"/>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js"></script>
<style>
.mortgage_type .col-sm-4 {
margin-top: 7px;
padding-left: 0px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
#select_area .col-sm-6:nth-child(2n+1) {
padding-left: 0px;
margin-bottom: 10px;
}
#select_area .col-sm-6:nth-child(2n) {
padding-right: 0px;
margin-bottom: 10px;
}
.container{
margin-top: 30px;
width: 800px !important;
margin-left: 60px;
}
button{
border-radius:0px !important;
}
.button{
padding:25px 280px;
}
</style>
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="register-div">
<div class="basic-info">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Add Request</h5>
</div>
<div class="content">
<form class="form-horizontal" method="post">
<input type="hidden" name="form_submit" value="ok">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Applicant Name'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="applicant_name" placeholder="" value="<?php echo $_GET['applicant_name']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Apply Amount'?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%">
<input type="number" class="form-control" name="apply_amount" value="<?php echo $_GET['apply_amount']?>">
<span class="input-group-addon" style="min-width: 60px;border-left: 0;border-radius: 0">$</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Contact Phone' ?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%;">
<select class="form-control" name="country_code" id="" style="width: 20%;">
<?php echo tools::getCountryCodeOptions('855'); ?>
</select>
<input type="text" class="form-control" name="phone_number" value="<?php echo $_GET['contact_phone'] ?>" placeholder="" style="width: 80%;">
<div class="error_msg"></div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Time'?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%;">
<input type="number" class="form-control" name="loan_time" value="<?php echo $_GET['loan_time'] ?>" placeholder="" style="width: 70%;">
<select class="form-control" name="loan_time_unit" id="" style="width: 30%;">
<?php $unit = (new loanPeriodUnitEnum())->toArray();$time_lang = enum_langClass::getLoanTimeUnitLang(); foreach( $unit as $key=>$value ){ ?>
<option value="<?php echo $value; ?>"><?php echo $time_lang[$value]; ?></option>
<?php } ?>
</select>
<div class="error_msg"></div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Purpose'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="loan_purpose" placeholder="" value="<?php echo $_GET['loan_purpose']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Mortgage'?></label>
<div class="col-sm-9 mortgage_type">
<?php foreach ($output['mortgage_type']['item_list'] as $key => $item) { ?>
<label class="col-sm-4">
<input type="checkbox" name="mortgage[]" value="<?php echo $item; ?>"><?php echo $item; ?>
</label>
<?php } ?>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Location' ?></label>
<div class="col-sm-9" id="select_area">
</div>
<div class="col-sm-9 col-sm-offset-3">
<input type="text" class="form-control" name="address_detail" placeholder="Detailed Address" value="">
<input type="hidden" name="address_region" value="">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="form-group button">
<button type="button" class="btn btn-danger" style="min-width: 80px;"><i class="fa fa-check"></i><?php echo 'Save' ?></button>
<button type="button" class="btn btn-default" style="min-width: 80px;margin-left: 10px" onclick="javascript:history.go(-1);"><i class="fa fa-reply"></i><?php echo 'Back' ?></button>
</div>
</div>
<script>
$(function () {
getArea(0);
$('#select_area').delegate('select', 'change', function () {
var _value = $(this).val();
$('input[name="address_id"]').val(_value);
$(this).closest('div').nextAll().remove();
if (_value != 0 && $(this).find('option[value="' + _value + '"]').attr('is-leaf') != 1) {
getArea(_value);
}
})
$('.btn-danger').click(function () {
if (!$(".form-horizontal").valid()) {
return;
}
var _address_region = '';
$('#select_area select').each(function () {
if ($(this).val() != 0) {
_address_region += $(this).find('option:selected').text() + ' ';
}
})
$('input[name="address_region"]').val(_address_region);
$('.form-horizontal').submit();
})
})
// 贷款申请列表
function getArea(uid) {
yo.dynamicTpl({
tpl: "service/area.list",
control:"counter_base",
dynamic: {
api: "service",
method: "getAreaList",
param: {uid: uid}
},
callback: function (_tpl) {
$("#select_area").append(_tpl);
}
})
}
// 验证是否输入
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group').find('.error_msg'));
},
rules: {
applicant_name: {
required: true
},
apply_amount: {
required: true
},
loan_purpose: {
required: true
},
contact_phone: {
required: true
}
},
messages: {
applicant_name: {
required: '<?php echo 'Required!'?>'
},
apply_amount: {
required: '<?php echo 'Required!'?>'
},
loan_purpose: {
required: '<?php echo 'Required!'?>'
},
contact_phone: {
required: '<?php echo 'Required!'?>'
}
}
});
</script><file_sep>/framework/api_test/apis/microbank/credit.loan.credit.calculator.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/16
* Time: 11:16
*/
class creditLoanCreditCalculatorApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Credit calculator";
$this->description = "信用额度计算器";
$this->url = C("bank_api_url") . "/credit_loan.credit.calculator.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("values", "多个值用,隔开,如 1,2,16,32, 各类型的计算值 身份证 1 户口本 2 家庭关系4 工作证明8 政府员工16 汽车资产证明 32 房屋资产证明 64
土地 128 护照 256 居住证 512 摩托车 1024", '1,32,64', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '理论信用值,如 5000 '
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.logout.php
<?php
/**
* Created by PhpStorm.
* User: hh
* Date: 2018/3/18
* Time: 上午 11:53
*/
class officerLogoutApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Officer logout";
$this->description = "业务员登陆退出";
$this->url = C("bank_api_url") . "/officer.logout.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1, true);
$this->parameters[]= new apiParameter("token", "token", '', true);
$this->parameters[]= new apiParameter("client_type", "终端类型", 'android',true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/13
* Time: 14:24
*/
class loanContractDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Detail";
$this->description = "贷款合同详细";
$this->url = C("bank_api_url") . "/loan.contract.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", '合同id', 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'contract_id' => '合同id',
'is_can_repay' => '是否可进行还款,0 不能 1 能',
'loan_amount' => '贷款金额',
'currency' => '货币类型',
'loan_period_value' => '贷款周期',
'loan_period_unit' => '贷款周期单位 year 年 month 月 day 日',
'repayment_type' => '还款方式',
'repayment_period' => '还款周期',
'interest_rate' => '利率值',
'interest_rate_type' => '利率类型',
'interest_rate_unit' => '利率周期,yearly 年 monthly 月 daily 日',
'due_date' => '还款日',
'due_date_type' => '还款日类型,once 一次还,日期 yearly 每年(周期的月-日) monthly 每月多少号 weekly 每周几(0-6)daily 每天',
'admin_fee' => '管理费',
'insurance_fee' => '保险费',
'operation_fee' => '总计运营费',
'total_interest' => '合计利息',
'actual_receive_amount' => '实发款金额',
'total_repayment' => '总计应还本金+利息',
'lending_time' => '贷款时间',
'contract_info' => '合同详细信息',
'loan_product_info' => '贷款产品信息',
'interest_info' => '贷款利率信息',
'size_rate' => '基本利率信息',
'special_rate' => '特殊利率信息',
'loan_disbursement_scheme' =>array(
'des' => '放款计划',
'state' => 'state含义 0 新创建 10 执行中 11 失败 100 完成',
'disbursable_date' => '应放款时间',
) ,
'loan_installment_scheme' => array(
'des' =>'还款计划',
'state' => 'state含义 0 新创建 10 执行中 11 失败 100 完成',
'receivable_date' => '应还款时间',
'penalty_start_date' => '罚款开始时间',
'amount' => '应还本息',
'actual_payment_amount' => '实际还款金额',
'penalty' => '应还罚金',
'last_repayment_time' => '上次还款时间',
'done_time' => '还清时间'
),
'bind_insurance' => '绑定的保险合同',
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/report/client.detail.list.php
<div class="important-info-1 clearfix">
<div class="info">
<p class="name">
<?php echo $data['client_info']['display_name']?:$data['client_info']['login_code']?>
</p>
<p>
<span>Credit Line:
<span style="font-weight: 700"> <?php echo ncAmountFormat($data['client_info']['credit']) ?></span>
</span>
<span style="margin-left: 50px">Create Time: <?php echo timeFormat($data['client_info']['create_time'])?></span>
</p>
</div>
<div class="statistical-report clearfix">
<div class="item">
Loan Number
<p><?php echo $data['client_info']['loan_number']?:0?></p>
</div>
<div class="item">
Loan Amount
<p><?php echo ncAmountFormat($data['client_info']['loan_amount'])?></p>
</div>
<div class="item">
Interest Amount
<p><?php echo ncAmountFormat($data['client_info']['total_interest'])?></p>
</div>
<div class="item">
Admin Fee Amount
<p><?php echo ncAmountFormat($data['client_info']['total_admin_fee'])?></p>
</div>
<div class="item">
Unpaid Amount
<p><?php echo ncAmountFormat($data['client_info']['unpaid_amount'])?></p>
</div>
</div>
</div>
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'SN'; ?></td>
<td><?php echo 'Loan Product'; ?></td>
<td><?php echo 'Apply Amount'; ?></td>
<td><?php echo 'Disbursement Amount'; ?></td>
<td><?php echo 'Receive Amount'; ?></td>
<td><?php echo 'Received Amount'; ?></td>
<td><?php echo 'Unreceived Amount'; ?></td>
<td><?php echo 'Loan time'; ?></td>
<td><?php echo 'State'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php if($data['data']){?>
<?php foreach($data['data'] as $row){?>
<tr>
<td><?php echo $row['contract_sn']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo ncAmountFormat($row['apply_amount']); ?></td>
<td><?php echo ncAmountFormat($row['disbursement_amount']); ?></td>
<td><?php echo ncAmountFormat($row['receive_amount']); ?></td>
<td><?php echo ncAmountFormat($row['received_amount']); ?></td>
<td><?php echo ncAmountFormat($row['unreceived_amount']); ?></td>
<td><?php echo dateFormat($row['start_date']) . '--' . dateFormat($row['end_date']); ?></td>
<td>
<?php echo $lang['loan_contract_state_' . $row['state']]; ?>
</td>
</tr>
<?php }?>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/api_test/apis/microbank/ace.verify.client.account.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/30
* Time: 18:11
*/
// ace.verify.client.account
class aceVerifyClientAccountApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Ace verify account";
$this->description = "验证账号是否ACE会员";
$this->url = C("bank_api_url") . "/ace.verify.client.account.php";
$this->parameters = array();
$this->parameters[] = new apiParameter('account','ACE账号','+86-18902461905',true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '0 否 1 是'
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.cert.work.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 11:02
*/
class officerSubmitCertWorkApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Work cert";
$this->description = "工作证明";
$this->url = C("bank_api_url") . "/officer.submit.cert.work.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("company_name", "公司名称", '', true);
$this->parameters[]= new apiParameter("company_address", "公司地址", '', true);
$this->parameters[]= new apiParameter("position", "职位", '', true);
$this->parameters[]= new apiParameter("is_government", "是否政府员工 是1 否 0", 0, true);
$this->parameters[]= new apiParameter("work_card", "工作卡,文件流", '', true);
$this->parameters[]= new apiParameter("employment_certification", "雇佣证明,文件流", '', true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_result' => '基本信息',
'extend_info' => '扩展信息'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.savings.bill.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/17
* Time: 10:48
*/
class memberSavingsBillListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member bill list";
$this->description = "客户账单";
$this->url = C("bank_api_url") . "/member.savings.bill.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("page_num", "页数", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("currency", "币种", '');
$this->parameters[]= new apiParameter("min_amount", "最低金额", 500);
$this->parameters[]= new apiParameter("max_amount", "最高金额", 5000);
$this->parameters[]= new apiParameter("start_date", "开始日期", '2018-02-01');
$this->parameters[]= new apiParameter("end_date", "结束日期", '2018-04-01');
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'2018-03' => array(
'month' => '',
'summary' => array(
'credit' => '合计收入',
'debit' => '合计支出'
),
'list' => array(
array(
'uid' => '流水ID',
'category' => '分类',
'trading_type' => '交易类型',
'subject' => '标题',
'credit' => '收入',
'debit' => '支出'
)
)
),
'2018-02'
)
);
}
}<file_sep>/framework/weixin_baike/data/model/loan_writtenoff.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/28
* Time: 14:57
*/
class loan_writtenoffModel extends tableModelBase
{
public function __construct()
{
parent::__construct('loan_writtenoff');
}
}<file_sep>/framework/weixin_baike/data/model/member_guarantee.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/18
* Time: 16:59
*/
class member_guaranteeModel extends tableModelBase
{
function __construct()
{
parent::__construct('member_guarantee');
}
}<file_sep>/framework/weixin_baike/data/model/passbook.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/26
* Time: 17:28
*/
class passbookModel extends tableModelBase
{
function __construct()
{
parent::__construct('passbook');
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.cert.motorbike.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 11:06
*/
class officerSubmitCertMotorbikeApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member asset motorbike cert";
$this->description = "摩托车认证";
$this->url = C("bank_api_url") . "/officer.submit.cert.asset.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("type", "认证类型,固定值 motorbike", 'motorbike', true);
$this->parameters[]= new apiParameter("motorbike_photo", "摩托车照片,文件流", null, true);
$this->parameters[]= new apiParameter("certificate_front", "摩托车证件正面照,文件流", null, true);
$this->parameters[]= new apiParameter("certificate_back", "摩托车证件背面照,文件流", null, true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_result' => '基本信息',
'extend_info' => '扩展信息'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/phone.code.cd.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/8
* Time: 11:54
*/
class phoneCodeCdApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Phone Code Cooltime";
$this->description = "发送短信的冷却时间";
$this->url = C("bank_api_url") . "/phone.code.cd.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("country_code", "国家编码", '86', true);
$this->parameters[]= new apiParameter("phone", "电话号码", '18902461905', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '0 不在冷却中 >0 剩余时间(秒)'
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/request_loan.add.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css" rel="stylesheet" type="text/css"/>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js"></script>
<style>
.mortgage_type .col-sm-4 {
margin-top: 7px;
padding-left: 0px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
#select_area .col-sm-6:nth-child(2n+1) {
padding-left: 0px;
margin-bottom: 10px;
}
#select_area .col-sm-6:nth-child(2n) {
padding-right: 0px;
margin-bottom: 10px;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Request To Loan</h3>
<ul class="tab-base">
<li>
<a href="<?php echo getUrl('operator', 'requestLoan', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a>
</li>
<li><a class="current"><span>Add</span></a></li>
</ul>
</div>
</div>
<div class="container" style="width: 600px;">
<form class="form-horizontal" method="post">
<input type="hidden" name="form_submit" value="ok">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Applicant Name'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="applicant_name" placeholder="" value="<?php echo $_GET['applicant_name']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Apply Amount'?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%">
<input type="number" class="form-control" name="apply_amount" value="<?php echo $_GET['apply_amount']?>">
<span class="input-group-addon" style="min-width: 60px;border-left: 0">$</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Time'?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%;">
<input type="number" class="form-control" name="loan_time" value="<?php echo $_GET['contact_phone'] ?>" placeholder="" style="width: 70%;">
<select class="form-control" name="loan_time_unit" id="" style="width: 30%;">
<?php $unit = (new loanPeriodUnitEnum())->toArray();$time_lang = enum_langClass::getLoanTimeUnitLang(); foreach( $unit as $key=>$value ){ ?>
<option value="<?php echo $value; ?>"><?php echo $time_lang[$value]; ?></option>
<?php } ?>
</select>
<div class="error_msg"></div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Contact Phone' ?></label>
<div class="col-sm-9">
<div class="input-group" style="width: 100%;">
<select class="form-control" name="country_code" id="" style="width: 20%;">
<?php echo tools::getCountryCodeOptions('855'); ?>
</select>
<input type="text" class="form-control" name="phone_number" value="<?php echo $_GET['contact_phone'] ?>" placeholder="" style="width: 80%;">
<div class="error_msg"></div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Purpose'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="loan_purpose" placeholder="" value="<?php echo $_GET['loan_purpose']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Mortgage'?></label>
<div class="col-sm-9 mortgage_type">
<?php foreach ($output['mortgage_type']['item_list'] as $key => $item) { ?>
<label class="col-sm-4">
<input type="checkbox" name="mortgage[]" value="<?php echo $item; ?>"><?php echo $item; ?>
</label>
<?php } ?>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Location' ?></label>
<div class="col-sm-9">
<div id="select_area">
</div>
<div>
<input type="text" class="form-control" name="address_detail" placeholder="Detailed Address" value="">
<input type="hidden" name="address_region" value="">
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Request Source' ?></label>
<div class="col-sm-9">
<select class="form-control" name="request_source">
<?php foreach($output['request_source'] as $key => $source){ if($key == loanApplySourceEnum::MEMBER_APP || $key == loanApplySourceEnum::OPERATOR_APP) continue;?>
<option value="<?php echo $key?>"><?php echo ucwords(strtolower($source))?></option>
<?php }?>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-col-sm-9" style="padding-left: 20px">
<button type="button" class="btn btn-danger" style="min-width: 80px;"><i class="fa fa-check"></i><?php echo 'Save' ?></button>
<button type="button" class="btn btn-default" style="min-width: 80px;margin-left: 10px" onclick="javascript:history.go(-1);"><i class="fa fa-reply"></i><?php echo 'Back' ?></button>
</div>
</div>
</form>
</div>
</div>
<script>
$(function () {
// $('.datepicker').datetimepicker({
// language: 'zh',
// weekStart: 1,
// todayBtn: 1,
// autoclose: 1,
// todayHighlight: 1,
// startView: 2,
// forceParse: 0,
// showMeridian: 1,
// minuteStep: 1
// }).on('changeDate', function (ev) {
// $(this).datetimepicker('hide');
// });
getArea(0);
$('#select_area').delegate('select', 'change', function () {
var _value = $(this).val();
$('input[name="address_id"]').val(_value);
$(this).closest('div').nextAll().remove();
if (_value != 0 && $(this).find('option[value="' + _value + '"]').attr('is-leaf') != 1) {
getArea(_value);
}
})
$('.btn-danger').click(function () {
if (!$(".form-horizontal").valid()) {
return;
}
var _address_region = '';
$('#select_area select').each(function () {
if ($(this).val() != 0) {
_address_region += $(this).find('option:selected').text() + ',';
}
})
$('input[name="address_region"]').val(_address_region);
$('.form-horizontal').submit();
})
})
function getArea(uid) {
yo.dynamicTpl({
tpl: "setting/area.list",
dynamic: {
api: "region",
method: "getAreaList",
param: {uid: uid}
},
callback: function (_tpl) {
$("#select_area").append(_tpl);
}
})
}
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group').find('.error_msg'));
},
rules: {
applicant_name: {
required: true
},
apply_amount: {
required: true
},
loan_time: {
required: true
},
loan_purpose: {
required: true
},
phone_number: {
required: true
}
},
messages: {
applicant_name: {
required: '<?php echo 'Required!'?>'
},
apply_amount: {
required: '<?php echo 'Required!'?>'
},
loan_time: {
required: '<?php echo 'Required!'; ?>'
},
loan_purpose: {
required: '<?php echo 'Required!'?>'
},
phone_number: {
required: '<?php echo 'Required!'?>'
}
}
});
</script><file_sep>/framework/weixin_baike/backoffice/templates/default/report/contract.list.php
<div class="important-info clearfix">
<div class="item">
<p>Apply Amount</p>
<div class="c"><?php echo ncAmountFormat($data['amount']['apply_amount'])?></div>
</div>
<div class="item">
<p>Disbursement Amount</p>
<div class="c"><?php echo ncAmountFormat($data['amount']['disbursement_amount'])?></div>
</div>
<div class="item">
<p>Receive Amount</p>
<div class="c"><?php echo ncAmountFormat($data['amount']['receive_amount'])?></div>
</div>
<div class="item">
<p>Received Amount</p>
<div class="c"><?php echo ncAmountFormat($data['amount']['received_amount'])?></div>
</div>
<div class="item">
<p>Unreceived Amount</p>
<div class="c"><?php echo ncAmountFormat($data['amount']['unreceived_amount'])?></div>
</div>
</div>
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'SN'; ?></td>
<td><?php echo 'Member'; ?></td>
<td><?php echo 'Product Name'; ?></td>
<td><?php echo 'Apply Amount'; ?></td>
<td><?php echo 'Disbursement Amount'; ?></td>
<td><?php echo 'Receive Amount'; ?></td>
<td><?php echo 'Received Amount'; ?></td>
<td><?php echo 'Unreceived Amount'; ?></td>
<td><?php echo 'Loan time'; ?></td>
<td><?php echo 'State'; ?></td>
<td><?php echo 'Function'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php if($data['data']){?>
<?php foreach($data['data'] as $row){?>
<tr>
<td><?php echo $row['contract_sn']; ?></td>
<td><?php echo $row['display_name']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo ncAmountFormat($row['apply_amount']); ?></td>
<td><?php echo ncAmountFormat($row['disbursement_amount']); ?></td>
<td><?php echo ncAmountFormat($row['receive_amount']); ?></td>
<td><?php echo ncAmountFormat($row['received_amount']); ?></td>
<td><?php echo ncAmountFormat($row['unreceived_amount']); ?></td>
<td><?php echo dateFormat($row['start_date']) . '--' . dateFormat($row['end_date']); ?></td>
<td>
<?php echo $lang['loan_contract_state_' . $row['state']]; ?> </td>
<td>
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="#" >
<span><i class="fa fa-search"></i>Detail</span>
</a>
</div>
</td>
</tr>
<?php }?>
<tr style="font-weight: 700">
<td colspan="2"><?php echo 'Current Total'; ?></td>
<td><?php echo ncAmountFormat($data['current_amount']['apply_amount']); ?></td>
<td><?php echo ncAmountFormat($data['current_amount']['disbursement_amount']); ?></td>
<td><?php echo ncAmountFormat($data['current_amount']['receive_amount']); ?></td>
<td><?php echo ncAmountFormat($data['current_amount']['received_amount']); ?></td>
<td><?php echo ncAmountFormat($data['current_amount']['unreceived_amount']); ?></td>
<td colspan="3"></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/api_test/apis/microbank/member.get.biz.account.handler.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 17:27
*/
class memberGetBizAccountHandlerApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member biz handler";
$this->description = "会员存取款账户";
$this->url = C("bank_api_url") . "/member.get.biz.account.handler.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'handler_list' => array(
'@description' => '没有为null',
array(
'uid' => 'Handler Id',
'handler_name' => '账户名称',
'handler_account' => '账户账号',
'handler_phone' => '电话',
'bank_name' => '银行名称',
'bank_code' => '银行编码',
)
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/email.verify.confirm.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/8
* Time: 10:39
*/
class emailVerifyConfirmApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Email Verify";
$this->description = "邮箱验证确认页面(html页面)";
$this->url = C("bank_api_url") . "/email.verify.confirm.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("vid", "邮箱验证id", '1', true);
$this->parameters[]= new apiParameter("vkey", "邮箱验证key", '<KEY>', true);
$url = $this->url.'?vid=1&vkey=<KEY>';
$this->return = array(
'url' => "查看结果页面:<a href='{$url}' target='_blank'>$url</a>",
);
}
}<file_sep>/framework/api_test/apis/test.ace.api/ace.collect.finish.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 17:54
*/
class aceCollectFinishApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.transfer.member2partner.finish";
$this->description = "Finish transfering money from signed member to his signed partner (for return loan).";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=collect_finish";
$this->parameters = array();
$this->parameters[]= new apiParameter("transfer_id", "Disburse Start 获得的事务ID", null, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)'
);
}
}<file_sep>/framework/weixin_baike/counter/control/entry_index.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2017/10/16
* Time: 10:44
*/
class entry_indexControl extends counter_baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setLayout("book_layout");
Tpl::setDir("layout");
Tpl::output("html_title", "Counter Office");
Tpl::output("user_info", $this->user_info);
Tpl::output("menu_items", $this->getResetMenu());
}
public function indexOp()
{
$r = new ormReader();
$sql = "SELECT sd.depart_name,sb.branch_name FROM site_depart sd INNER JOIN site_branch sb ON sd.branch_id = sb.uid WHERE sd.uid = " . intval($this->user_info['depart_id']);
$department_info = $r->getRow($sql);
Tpl::output('department_info', $department_info);
Tpl::showPage("null_layout");
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.guarantee.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/magnifier/magnifier.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div">
<div class="basic-info">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Guarantee Relation</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Relationship</label>
<div class="col-sm-8">
<select class="form-control" name="relationship">
<option value="0">Please Select</option>
<?php foreach($output['guarantee_relationship']['item_list'] as $key => $val){?>
<option value="<?php echo $key?>"><?php echo $val;?></option>
<?php }?>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Member Account</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="member_account" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="col-sm-6 form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Member Account</label>
<div class="col-sm-8">
<div class="input-group">
<span class="input-group-addon" style="padding: 0;border: 0;">
<select class="form-control" name="country_code" style="min-width: 80px;height: 30px">
<option value="855">+855</option>
<option value="66">+66</option>
<option value="86">+86</option>
<option value="84">+84</option>
</select>
</span>
<input type="text" class="form-control" id="phone" name="phone" value="" placeholder="">
</div>
<div class="error_msg"></div>
</div>
</div>
</form>
</div>
</div>
<div class="operation" style="margin-bottom: 40px">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
<div class="certification-history">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Guarantor</h5>
</div>
<div class="content guarantor" style="padding: 0;border-bottom: 1px solid #D5D5D5;">
</div>
</div>
<div class="certification-history">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Apply Guarantor</h5>
</div>
<div class="content apply_guarantor" style="padding: 0;border-bottom: 1px solid #D5D5D5;">
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script>
$(document).ready(function () {
btn_search_onclick('guarantor');
btn_search_onclick('apply_guarantor');
});
function btn_search_onclick(type) {
var uid = $('input[name="client_id"]').val();
yo.dynamicTpl({
tpl: "member/guarantee.list",
control: "counter_base",
dynamic: {
api: "member",
method: "getGuarantorList",
param: {uid: uid, type: type}
},
callback: function (_tpl) {
if(type == 'guarantor'){
$(".certification-history .guarantor").html(_tpl);
}else {
$(".certification-history .apply_guarantor").html(_tpl);
}
}
});
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveGuarantorAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
error.appendTo(element.closest('.form-group').find('.error_msg'));
},
rules : {
relationship : {
chkRelationship : true
},
member_account : {
required : true
},
phone : {
required : true
}
},
messages : {
relationship : {
chkRelationship : 'Required!'
},
member_account : {
required : 'Required!'
},
phone : {
required : 'Required!'
}
}
});
jQuery.validator.addMethod("chkRelationship", function (value, element) {
if (!value || value == 0) {
return false;
} else {
return true;
}
});
</script><file_sep>/framework/weixin_baike/entry_desktop/templates/default/widget/app.common.js.php
<script type="text/javascript">
var app = {};
app.today = function () {
return "<?php echo date("Y-m-d");?>";
};
app.now = function () {
return "<?php echo date("Y-m-d H:i:s");?>";
};
app.yesterday = function () {
return "<?php echo date("Y-m-d",time()-3600*24);?>";
};
app.before30days = function () {
return "<?php echo date("Y-m-d",time()-3600*24*30);?>";
};
app.monday = function () {
return "<?php echo date('Y-m-d',(time()-((date('w')==0?7:date('w'))-1)*86400));?>";
};
app.lastMonday = function () {
return "<?php echo (date("l",time())=="Monday")?date("Y-m-d",strtotime("last monday")):date("Y-m-d",strtotime('-1 week last monday'));?>";
};
app.lastSunday = function () {
return "<?php echo date('Y-m-d',strtotime('last sunday'));?>"
};
app.firstDayOfMonth = function () {
return "<?php echo date('Y-m-d',strtotime(date('Y-m', time()).'-01 00:00:00'));?>"
};
app.firstDayOfLastMonth = function () {
return "<?php echo date('Y-m-d',strtotime('-1 month', strtotime(date('Y-m', time()).'-01 00:00:00')));?>"
};
app.lastDayOfLastMonth = function () {
return "<?php echo date('Y-m-d',strtotime(date('Y-m', time()).'-01 00:00:00')-86400);?>";
};
app.waiting = function () {
$("body").waiting();
};
app.unmask = function () {
$("body").unmask();
};
app.initWindow = function () {
window.init_SubPage = function () {
};
};
app.debug_state = "<?php echo C('debug');?>";
app.sid = "<?php echo $_REQUEST['_s'];?>";
app.logout = function () {
yo.loadData({
_c: "apiMain",
_m: "logout",
param: {},
callback: function (_o) {
window.location.reload();
}
});
};
app.loadMenu = function (_key, _dir, _e) {
if (_e) {
$("#span_menu_title").text($(_e).attr("my_title"));
$("#span_menu_up_title").text($(_e).attr("up_title"));
$(".right-menu-item").removeClass("list-group-item-white").addClass("list-group-item-orange");
$(_e).removeClass("list-group-item-orange").addClass("list-group-item-white");
}
app.initWindow();
var _mainStage = $("#divMainStage");
_mainStage.waiting();
_mainStage.data("page_key", _key);
yo.loadTpl({
tpl: _key,
ext: {tpl_dir: _dir},
callback: function (_tpl) {
_mainStage.html(_tpl);
_mainStage.unmask();
//初始化page
init_SubPage();//默认这些页面都有这个初始入口
}
})
};
//初始化相关元素高度
function init() {
$("body").height($(window).height() - 80);
$("#iframe-main").height($(window).height() - 90);
$("#sidebar").height($(window).height() - 50);
}
$(function () {
init();
$(window).resize(function () {
init();
})
$('#search .fa-align-justify').click(function () {
if($("#sidebar").is(":hidden")){
$("#sidebar").show();
$("#content").css('margin-left','220px');
}else{
$("#sidebar").hide();
$("#content").css('margin-left','0px');
}
})
$('#sidebar ul li').first().find('a').click();
<?php if(!$output['is_operator']){?>
$('#sidebar ul li').first().find('ul li').first().find('a').click();
<?php }?>
if (window != top) {
top.location.href = location.href;
}
setInterval(getTaskNum,30000);
});
function goPage(newURL) {
if (newURL != "") {
if (newURL == "-") {
resetMenu();
} else {
document.location.href = newURL;
}
}
}
function resetMenu() {
document.gomenu.selector.selectedIndex = 2;
}
function playHint() {
$('#task-hint')[0].play();
}
function getTaskNum() {
yo.loadData({
_c: "index",
_m: "getTaskNum",
param: {},
callback: function (_o) {
if (_o.STS) {
playHint();
var data = _o.DATA;
$(".new_client .label-important").text(data.new_client);
$(".request_loan .label-important").text(data.request_loan);
$(".certification_file .label-important").first().text(data.certification_file);
for (var i = 1; i <= Object.keys(data.certification_file_arr).length; ++i) {
$(".certification_file .type_" + i + " .sub-num").text(data.certification_file_arr[i]);
}
} else {
alert(_o.MSG);
}
}
});
}
</script><file_sep>/framework/weixin_baike/data/model/site_bank.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 11:20
*/
class site_bankModel extends tableModelBase
{
public function __construct()
{
parent::__construct('site_bank');
}
/**
* 添加收款账号
* @param $p
* @return result
*/
public function addReceiveAccount($p)
{
$bank_code = trim($p['bank_code']);
$currency = trim($p['currency']);
$bank_account_no = trim($p['bank_account_no']);
$bank_account_name = trim($p['bank_account_name']);
$bank_account_phone = trim($p['bank_account_phone']);
$account_state = intval($p['account_state']);
$allow_client_deposit = intval($p['allow_client_deposit']);
$branch_ids = $p['branch_id'];
$creator_id = intval($p['creator_id']);
$creator_name = trim($p['creator_name']);
$chk_account = $this->find(array('bank_code' => $bank_code, 'bank_account_no' => $bank_account_no));
if ($chk_account) {
return new result(false, 'The account already exists!');
}
$m_common_bank_lists = M('common_bank_lists');
$bank_info = $m_common_bank_lists->find(array('bank_code' => $bank_code));
$bank_name = $bank_info['bank_name'];
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$row = $this->newRow();
$row->bank_code = $bank_code;
$row->bank_name = $bank_name;
$row->currency = $currency;
$row->bank_account_no = $bank_account_no;
$row->bank_account_name = $bank_account_name;
$row->bank_account_phone = $bank_account_phone;
$row->account_state = $account_state;
$row->allow_client_deposit = $allow_client_deposit;
$row->creator_id = $creator_id;
$row->creator_name = $creator_name;
$row->create_time = Now();
$rt = $row->insert();
if (!$rt->STS) {
$conn->rollback();
return new result(false, 'Add failed!' . $rt->MSG);
}
$row->obj_guid = generateGuid($rt->AUTO_ID, objGuidTypeEnum::BANK_ACCOUNT);
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Add failed--' . $rt_1->MSG);
}
$m_site_bank_branch = M('site_bank_branch');
foreach ($branch_ids as $branch_id) {
$row = $m_site_bank_branch->newRow();
$row->bank_id = $rt->AUTO_ID;
$row->branch_id = $branch_id;
$rt_2 = $row->insert();
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, 'Add failed!' . $rt_2->MSG);
}
}
$conn->submitTransaction();
return new result(true, 'Add successful!');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 编辑收款账号
* @param $p
* @return result
*/
public function editReceiveAccount($p)
{
$uid = intval($p['uid']);
$bank_code = trim($p['bank_code']);
$currency = trim($p['currency']);
$bank_account_no = trim($p['bank_account_no']);
$bank_account_name = trim($p['bank_account_name']);
$bank_account_phone = trim($p['bank_account_phone']);
$account_state = intval($p['account_state']);
$allow_client_deposit = intval($p['allow_client_deposit']);
$branch_ids = $p['branch_id'];
$chk_account = $this->find(array('bank_code' => $bank_code, 'bank_account_no' => $bank_account_no, 'uid' => array('neq', $uid)));
if ($chk_account) {
return new result(false, 'The account already exists!');
}
$m_common_bank_lists = M('common_bank_lists');
$bank_info = $m_common_bank_lists->find(array('bank_code' => $bank_code));
$bank_name = $bank_info['bank_name'];
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$row = $this->getRow($uid);
$row->bank_code = $bank_code;
$row->bank_name = $bank_name;
$row->currency = $currency;
$row->bank_account_no = $bank_account_no;
$row->bank_account_name = $bank_account_name;
$row->bank_account_phone = $bank_account_phone;
$row->account_state = $account_state;
$row->allow_client_deposit = $allow_client_deposit;
$row->update_time = Now();
$rt = $row->update();
if (!$rt->STS) {
$conn->rollback();
return new result(false, 'Update failed!' . $rt->MSG);
}
$m_site_bank_branch = M('site_bank_branch');
$rt_1 = $m_site_bank_branch->delete(array('bank_id' => $uid));
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Update failed!' . $rt_1->MSG);
}
foreach ($branch_ids as $branch_id) {
$row = $m_site_bank_branch->newRow();
$row->bank_id = $uid;
$row->branch_id = $branch_id;
$rt_2 = $row->insert();
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, 'Update failed!' . $rt_2->MSG);
}
}
$conn->submitTransaction();
return new result(true, 'Update successful!');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
public function deleteReceiveAccount($uid)
{
$row = $this->getRow($uid);
if (!$row) {
return new result(true, 'Update successful!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try{
$rt = $row->delete();
if (!$rt->STS) {
$conn->rollback();
return new result(true, 'Remove failed!');
}
$m_site_bank_branch = M('site_bank_branch');
$rt_1 = $m_site_bank_branch->delete(array('bank_id' => $uid));
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Remove failed!' . $rt_1->MSG);
}
$conn->submitTransaction();
return new result(true, 'Remove successful!');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/partner/bank.php
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Bank</h3>
<ul class="tab-base">
<li><a class="current"><span>List</span></a></li>
<li><a href="<?php echo getUrl('partner', 'addPartner', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>Add</span></a></li>
</ul>
</div>
</div>
<div class="container">
<div class="business-content">
<div class="business-list">
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Bank Name'; ?></td>
<td><?php echo 'Bank Code'; ?></td>
<?php foreach ($output['currency_list'] as $key => $currency) { ?>
<td><?php echo 'Balance(' . $key . ')'; ?></td>
<?php } ?>
<td><?php echo 'Last Check Time'; ?></td>
<td><?php echo 'Function'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach ($output['partner_list'] as $partner) { ?>
<tr>
<td>
<?php echo $partner['partner_name'] ?><br/>
</td>
<td>
<?php echo $partner['partner_code'] ?><br/>
</td>
<?php foreach ($partner['balance'] as $key => $balance) { ?>
<td>
<?php echo ncAmountFormat($balance, false, $key) ?>
</td>
<?php } ?>
<td>
<?php echo timeFormat($partner['last_check_time']) ?><br/>
</td>
<td>
<a class="btn btn-default" style="padding: 6px 12px" href="<?php echo getUrl('partner', 'checkTrace', array('uid' => $partner['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<i class="fa fa-address-card-o"></i>
Detail
</a>
<a class="btn btn-default" style="padding: 6px 12px" href="<?php echo getUrl('partner', 'editPartner', array('uid' => $partner['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<i class="fa fa-edit"></i>
Edit
</a>
<a class="btn btn-default" style="padding: 6px 12px" href="<?php echo getUrl('partner', 'deletePartner', array('uid' => $partner['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<i class="fa fa-trash"></i>
Delete
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div><file_sep>/framework/api_test/apis/microbank/credit.loan.level.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/15
* Time: 10:08
*/
class creditLoanLevelApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Credit loan level";
$this->description = "信用贷等级";
$this->url = C("bank_api_url") . "/credit_loan.loan.level.php";
$this->parameters = array();
$this->parameters[] = new apiParameter('level_type','all 全部 0 member 1 商家',0,true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_list_des' =>'cert_list 类型 1 身份证 2 户口本 3 护照 4 房产 5 汽车资产 6 工作证明 7 公务员(合在工作)8 家庭关系证明 9 土地',
0 => array(
'level_type' => '等级类型',
'min_amount' => '最低金额',
'max_amount' => '最高金额',
'disburse_time' => '放款时间',
'disburse_time_unit' => '放款时间单位 1 分钟 2小时 3 天',
'cert_list' => array(
1,2,
),
),
1 => array(
'level_type' => '等级类型',
'min_amount' => '最低金额',
'max_amount' => '最高金额',
'disburse_time' => '放款时间',
'disburse_time_unit' => '放款时间单位 1 分钟 2小时 3 天',
'cert_list' => array(1,2,4,5)
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/member_assets.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/10
* Time: 17:38
*/
class member_assetsModel extends tableModelBase
{
function __construct()
{
parent::__construct('member_assets');
}
}<file_sep>/framework/weixin_baike/wap/control/credit.php
<?php
class creditControl {
public function __construct(){
Language::read('act,label,tip');
Tpl::setLayout('empty_layout');
Tpl::setDir('credit');
}
public function indexOp(){
$member_id = cookie('member_id');
if(!$member_id){
@header("Location: ".getUrl('login', 'index', array(), false, WAP_SITE_URL)."");
}
$data['member_id'] = $member_id;
$data['token'] = cookie('token');
$url = ENTRY_API_SITE_URL.'/member.message.unread.count.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
Tpl::output('msgcount', $rt['DATA']);
$url = ENTRY_API_SITE_URL.'/credit.loan.index.page.php';
$data['page_num'] = 1;
$data['page_size'] = 10;
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
Tpl::output('credit_info', $rt['DATA']['credit_info']);
Tpl::output('product_id', $rt['DATA']['product_id']);
Tpl::output('rate_list', $rt['DATA']['rate_list']);
Tpl::output('html_title', L('label_credit'));
Tpl::output('header_title', L('label_wap_name'));
Tpl::output('nav_footer', 'credit');
Tpl::showPage('index');
}
public function getRatetDataOp(){
$data = $_POST;
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$url = ENTRY_API_SITE_URL.'/credit.loan.index.page.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'), $rt['DATA']);
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function certListOp(){
$url = ENTRY_API_SITE_URL.'/member.credit.cert.list.php';
$data = array();
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
$credit = array();
if($rt['STS']){
$credit = $rt['DATA'];
}
Tpl::output('credit', $credit);
Tpl::output('html_title', 'Get Credit');
Tpl::output('header_title', 'Get Credit');
Tpl::showPage('cerification_list');
}
public function getCertedResultOp(){
$url = ENTRY_API_SITE_URL.'/member.certed.result.php';
$data = array();
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$data['type'] = $_POST['type'];
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'), array('cert_id' => $rt['DATA']['cert_result']['uid'], 'state' => $rt['DATA']['cert_result']['verify_state']));
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function certTypeListOp(){
$type = $_GET['type'];
$url = ENTRY_API_SITE_URL.'/member.certed.result.php';
$data = array();
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$data['type'] = $type;
$page = 'certtype.list';
switch ($type) {
case certificationTypeEnum::CAR :
Tpl::output('html_title', L('label_vehicle_property'));
Tpl::output('header_title', L('label_vehicle_property'));
break;
case certificationTypeEnum::LAND :
Tpl::output('html_title', L('label_landg_property'));
Tpl::output('header_title', L('label_landg_property'));
break;
case certificationTypeEnum::HOUSE :
Tpl::output('html_title', L('label_housing_property'));
Tpl::output('header_title', L('label_housing_property'));
break;
case certificationTypeEnum::MOTORBIKE :
Tpl::output('html_title', L('label_motorcycle_asset_certificate'));
Tpl::output('header_title', L('label_motorcycle_asset_certificate'));
break;
case certificationTypeEnum::GUARANTEE_RELATIONSHIP :
$url = ENTRY_API_SITE_URL.'/member.guarantee.list.php';
Tpl::output('html_title', 'Guarantee Relation');
Tpl::output('header_title', 'Guarantee Relation');
$page = 'certtype.list.relationship';
break;
default:
Tpl::output('html_title', L('label_vehicle_property'));
Tpl::output('header_title', L('label_vehicle_property'));
break;
}
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
Tpl::output('list', $rt['DATA']);
Tpl::showPage($page);
}
public function cerificationOp(){
$type = $_GET['type'];
$cert_id = $_GET['cert_id'];
Tpl::output('type', $type);
Tpl::output('token', cookie('token'));
Tpl::output('cert_id', $cert_id?:0);
Tpl::output('member_id', cookie('member_id'));
switch ($type) {
case certificationTypeEnum::ID :
Tpl::output('html_title', L('label_id_card'));
Tpl::output('header_title', L('label_id_card'));
Tpl::showPage('cerification.id');
break;
case certificationTypeEnum::FAIMILYBOOK :
Tpl::output('html_title', L('label_family_book'));
Tpl::output('header_title', L('label_family_book'));
Tpl::showPage('cerification.familybook');
break;
case certificationTypeEnum::PASSPORT : //1111
Tpl::output('html_title', L('label_family_book'));
Tpl::output('header_title', L('label_family_book'));
Tpl::showPage('cerification.familybook');
break;
case certificationTypeEnum::HOUSE :
Tpl::output('html_title', L('label_housing_property'));
Tpl::output('header_title', L('label_housing_property'));
Tpl::showPage('cerification.house');
break;
case certificationTypeEnum::CAR :
Tpl::output('html_title', L('label_vehicle_property'));
Tpl::output('header_title', L('label_vehicle_property'));
Tpl::showPage('cerification.car');
break;
case certificationTypeEnum::WORK_CERTIFICATION :
Tpl::output('html_title', L('label_working_certificate'));
Tpl::output('header_title', L('label_working_certificate'));
Tpl::showPage('cerification.work');
break;
case certificationTypeEnum::CIVIL_SERVANT : //1111
Tpl::output('html_title', L('label_landg_property'));
Tpl::output('header_title', L('label_landg_property'));
Tpl::showPage('cerification.land');
break;
case certificationTypeEnum::FAMILY_RELATIONSHIP :
$url = ENTRY_API_SITE_URL.'/system.config.init.php';
$rt = curl_post($url, array());
$rt = json_decode($rt, true);
Tpl::output('guarantee_relationship', $rt['DATA']['user_define']['guarantee_relationship']);
Tpl::output('html_title', 'Add Member');
Tpl::output('header_title', 'Add Member');
Tpl::showPage('cerification.relationshop');
break;
case certificationTypeEnum::LAND :
Tpl::output('html_title', L('label_landg_property'));
Tpl::output('header_title', L('label_landg_property'));
Tpl::showPage('cerification.land');
break;
case certificationTypeEnum::RESIDENT_BOOK :
$url = ENTRY_API_SITE_URL.'/member.certed.result.php';
$data = array();
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$data['type'] = $type;
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
Tpl::output('data', $rt);
Tpl::output('html_title', L('label_resident_book'));
Tpl::output('header_title', L('label_resident_book'));
Tpl::showPage('cerification.residentbook');
break;
case certificationTypeEnum::MOTORBIKE : //11111
Tpl::output('html_title', L('label_motorcycle_asset_certificate'));
Tpl::output('header_title', L('label_motorcycle_asset_certificate'));
Tpl::showPage('cerification.motorcycle');
break;
default:
Tpl::showPage('index');
break;
}
}
public function showCertCheckInfoOp(){
$type = $_GET['type'];
$state = $_GET['state'];
$cert_id = $_GET['cert_id'];
Tpl::output('type', $type);
Tpl::output('state', $state);
Tpl::output('cert_id', $cert_id);
Tpl::output('token', cookie('token'));
Tpl::output('member_id', cookie('member_id'));
switch ($type) {
case certificationTypeEnum::ID :
Tpl::output('html_title', L('label_id_card'));
Tpl::output('header_title', L('label_id_card'));
Tpl::showPage('cerification.id.check');
break;
case certificationTypeEnum::FAIMILYBOOK :
Tpl::output('html_title', L('label_family_book'));
Tpl::output('header_title', L('label_family_book'));
Tpl::showPage('cerification.familybook.check');
break;
case certificationTypeEnum::WORK_CERTIFICATION :
Tpl::output('html_title', L('label_working_certificate'));
Tpl::output('header_title', L('label_working_certificate'));
Tpl::showPage('cerification.work.check');
break;
case certificationTypeEnum::CAR :
Tpl::output('html_title', L('label_vehicle_property'));
Tpl::output('header_title', L('label_vehicle_property'));
Tpl::showPage('cerification.car.check');
break;
case certificationTypeEnum::LAND :
Tpl::output('html_title', L('label_landg_property'));
Tpl::output('header_title', L('label_landg_property'));
Tpl::showPage('cerification.land.check');
break;
case certificationTypeEnum::HOUSE :
Tpl::output('html_title', L('label_housing_property'));
Tpl::output('header_title', L('label_housing_property'));
Tpl::showPage('cerification.house.check');
break;
default:
Tpl::showPage('index');
break;
}
}
public function historyOp(){
Tpl::output('html_title', L('label_credit_history'));
Tpl::output('header_title', L('label_credit_history'));
Tpl::showPage('history');
}
public function getCreditHistoryDataOp(){
$data = $_POST;
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$url = ENTRY_API_SITE_URL.'/member.credit.release.list.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'), $rt['DATA']);
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function helpOp(){
Tpl::output('html_title', L('label_help'));
Tpl::output('header_title', L('label_help'));
Tpl::showPage('help');
}
public function creditLoanOp(){
$data = array();
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$url = ENTRY_API_SITE_URL.'/member.credit.cert.list.php';
$rt = curl_post($url, $data);
$credit = json_decode($rt, true);
$credit_info = $credit['DATA']['credit_info'];
Tpl::output('credit_info', $credit_info);
$data1 = array();
$data1['loan_product_id'] = $_GET['product_id'];
$url1 = ENTRY_API_SITE_URL.'/credit_loan.bind.insurance.php';
$insurance_info = curl_post($url1, $data1);
$insurance_info = json_decode($insurance_info, true);
Tpl::output('insurance_info', $insurance_info['DATA']);
$url2 = ENTRY_API_SITE_URL.'/member.ace.account.info.php';
$ace_info = curl_post($url2, $data);
$ace_info = json_decode($ace_info, true);
Tpl::output('ace_info', $ace_info['DATA']);
$url = ENTRY_API_SITE_URL.'/loan.propose.get.php';
$rt = curl_post($url, array());
$rt = json_decode($rt, true);
Tpl::output('purpose', $rt['DATA']);
Tpl::output('html_title', L('label_withdraw'));
Tpl::output('header_title', L('label_withdraw'));
Tpl::showPage('credit_loan');
}
public function submitWithdrawOp(){
$data = $_POST;
$data['token'] = cookie('token');
$data['member_id'] = cookie('member_id');
$url = ENTRY_API_SITE_URL.'/credit_loan.withdraw.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'), array('contract_id' => $rt['DATA']['contract_id']));
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function withdrawConfirmOp(){
$contract_id = $_GET['contract_id'];
$data = array();
$data['token'] = cookie('token');
$data['contract_id'] = $contract_id;
$url = ENTRY_API_SITE_URL.'/loan.contract.detail.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
Tpl::output('detail', $rt['DATA']);
Tpl::output('html_title', L('label_withdraw'));
Tpl::output('header_title', L('label_withdraw'));
Tpl::showPage('credit_loan.confirm');
}
public function ajaxSubmitConfirmWithdrawOp(){
$data = $_POST;
$data['token'] = cookie('token');
$url = ENTRY_API_SITE_URL.'/credit_loan.contract.confirm.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'));
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function withdrawSuccessOp(){
Tpl::output('html_title', L('label_wap_name'));
Tpl::output('header_title', L('label_wap_name'));
Tpl::showPage('credit_loan.success');
}
public function ajaxAddRelationshipOp(){
$data = $_POST;
$data['member_id'] = cookie('member_id');
$data['token'] = cookie('token');
$url = ENTRY_API_SITE_URL.'/member.add.guarantee.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'));
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function ajaxGuaranteeConfirmOp(){
$data = $_POST;
$data['member_id'] = cookie('member_id');
$data['token'] = cookie('token');
$url = ENTRY_API_SITE_URL.'/member.guarantee.confirm.php';
$rt = curl_post($url, $data);
$rt = json_decode($rt, true);
if($rt['STS']){
return new result(true, L('tip_success'));
}else{
return new result(false, L('tip_code_'.$rt['CODE']));
}
}
public function helpCreditOp(){
Language::set($_GET['lang']);
Tpl::output('html_title', L('label_what_credit'));
Tpl::output('header_title', L('label_what_credit'));
Tpl::showPage('help_credit');
}
public function helpGetCreditOp(){
Language::set($_GET['lang']);
Tpl::output('html_title', L('label_how_to_get_credit'));
Tpl::output('header_title', L('label_how_to_get_credit'));
Tpl::showPage('help_credit.get');
}
}
<file_sep>/framework/api_test/apis/microbank/loan.contract.schema.repayment.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/22
* Time: 17:03
*/
// loan.contract.schema.repayment.detail
class loanContractSchemaRepaymentDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract schema repayment detail";
$this->description = "贷款合同计划还款详细";
$this->url = C("bank_api_url") . "/loan.contract.schema.repayment.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("schema_id", "计划id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/weixin_baike/data/model/loan_disbursement_scheme.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/30
* Time: 13:08
*/
class loan_disbursement_schemeModel extends tableModelBase
{
function __construct()
{
parent::__construct('loan_disbursement_scheme');
}
}<file_sep>/framework/api_test/apis/entry/member.get.php
<?php
class memberGetApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Get Member";
$this->description = "获取Member信息";
$this->url = C("entry_api_url") . "/member.get.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("game_id", "调用方游戏ID", '6', true);
$this->parameters[]= new apiParameter("member_id", "member ID", '1', true);
$this->parameters[]= new apiParameter("access_token", "授权令牌", "9<PASSWORD>46feb3<PASSWORD>", true);
$this->parameters[]= new apiParameter("sign", "参数签名,计算方式:md5(所有参数按字母顺序排列的\$k=\$v使用&连接后字符串 . \$sign_key)", "", true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => 'API返回数据',
'member_id' => 'Member ID,和传入参数一样',
'member_name' => '<NAME>',
'currency' => 'Member所使用的货币',
'exchange_rate' => 'Member货币的汇率',
'bet_limit_min' => '最小下注限制',
'bet_limit_max' => '最大下注限制'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.asset.cert.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/13
* Time: 16:40
*/
class memberAssetCertApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member asset cert";
$this->description = "会员资产认证";
$this->url = C("bank_api_url") . "/member.cert.asset.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("type", "认证类型:摩托车 motorbike 房屋 house 汽车 car 土地 land,其他参数查看具体api介绍", 'house', true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_result' => '基本信息',
'extend_info' => '扩展信息'
)
);
}
}<file_sep>/framework/weixin_baike/api/control/officer.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/1
* Time: 15:18
*/
class officerControl extends bank_apiControl
{
// operator app 操作类
public function loginOp()
{
$params = array_merge($_GET,$_POST);
$user_code = trim($params['user_code']);
$password = trim($params['password']);
$client_type = $params['client_type'];
if( !$user_code || !$password ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_user = new um_userModel();
$user = $m_user->getRow(array(
'user_code' => $user_code
));
if( !$user ){
return new result(false,'No user',null,errorCodesEnum::USER_NOT_EXISTS);
}
if( md5($password) != $user->password ){
return new result(false,'Password error',null,errorCodesEnum::PASSWORD_ERROR);
}
if( $user->user_status != 1 ){
return new result(false,'User locked',null,errorCodesEnum::USER_LOCKED);
}
// 检查职位
$user_position = @json_decode($user->user_position,true);
if( !in_array(userPositionEnum::CREDIT_OFFICER,$user_position) ){
return new result(false,'No login access',null,errorCodesEnum::NO_LOGIN_ACCESS);
}
// 创建登陆日志
$now = Now();
$ip = getIp();
$user->last_login_time = $now;
$user->last_login_ip = $ip;
$up = $user->update();
if( !$up->STS ){
return new result(false,'Db error',null,errorCodesEnum::DB_ERROR);
}
$m_user_log = new um_user_logModel();
$re = $m_user_log->recordLogin($user->uid,$client_type);
if( !$re->STS ){
return new result(false,'Db error',null,errorCodesEnum::DB_ERROR);
}
// 创建token
$token = md5($user_code.time());
$m_user_token = new um_user_tokenModel();
$user_token = $m_user_token->newRow();
$user_token->user_id = $user->uid;
$user_token->user_code = $user->user_code;
$user_token->token = $token;
$user_token->client_type = $client_type;
$user_token->create_time = $now;
$user_token->login_time = $now;
$insert = $user_token->insert();
if( !$insert->STS ){
return new result(false,'Db error',null,errorCodesEnum::DB_ERROR);
}
$user_info = $user->toArray();
unset($user_info['password']);
return new result(true,'success',array(
'user_info' => $user_info,
'token' => $token
));
}
public function logoutOp()
{
$params = array_merge($_GET,$_POST);
$officer_id = $params['officer_id'];
$token = $params['token'];
$client_type = $params['client_type'];
// 记录日志
$m_log = new um_user_logModel();
$log = $m_log->orderBy('uid desc ')->getRow(array(
'user_id' => $officer_id,
'client_type' => $client_type
));
if( $log ){
$log->logout_time = Now();
$log->update_time = Now();
$log->update();
}
//销毁token(所有,单设备支持)
$sql = "delete from um_user_token where user_id='$officer_id' ";
$del = $m_log->conn->execute($sql);
if( !$del->STS ){
return new result(false,'Logout fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true);
}
public function submitMemberCertIdOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::idVerifyCert($params,certSourceTypeEnum::OPERATOR);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function submitMemberCertFamilyBookOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::familyBookVerifyCert($params,certSourceTypeEnum::OPERATOR);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function submitMemberCertResidentBookOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::residentBookCert($params,certSourceTypeEnum::OPERATOR);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function submitMemberCertWorkOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::workCert($params,certSourceTypeEnum::OPERATOR);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function submitMemberCertAssetsOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::assetCert($params,certSourceTypeEnum::OPERATOR);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function searchMemberOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member = memberClass::searchMember($params);
return new result(true,'success',$member);
}
public function getMemberAllCertResultOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$re = memberClass::getMemberCertStateOrCount($member_id);
return $re;
}
public function getMemberCertDetailInfoOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::getMemberCertResult($params);
return $re;
}
public function getCoFollowedMemberOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$r = new ormReader();
$sql = "select m.*,c.credit,c.credit_balance from member_follow_officer f left join client_member m on m.uid=f.member_id
left join member_credit c on c.member_id=m.uid where f.officer_id='$officer_id'
and f.is_active='1' ";
$list = $r->getRows($sql);
return new result(true,'success',$list);
}
/** 为客户提交贷款申请
* @return result
*/
public function addLoanRequestOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$member_id = intval($params['member_id']);
$amount = round($params['amount'],2);
$currency = $params['currency'];
$loan_time = intval($params['loan_time']);
$loan_time_unit = $params['loan_time_unit'];
if( $amount<=0 || !$member_id || !$currency || $loan_time<=0 || !$loan_time_unit ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_user = new um_userModel();
$officer = $m_user->getRow($officer_id);
if( !$officer ){
return new result(false,'Invalid operator',null,errorCodesEnum::USER_NOT_EXISTS);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$applicant_name = $member->display_name?:($member->login_code?:'Unknown');
$applicant_address = null; // member 地址
$contact_phone = $member->phone_id;
$m_apply = new loan_applyModel();
$apply = $m_apply->newRow();
$apply->member_id = $member_id;
$apply->applicant_name = $applicant_name;
$apply->applicant_address = $applicant_address;
$apply->apply_amount = $amount;
$apply->currency = $currency;
$apply->loan_time = $loan_time;
$apply->loan_time_unit = $loan_time_unit;
$apply->contact_phone = $contact_phone;
$apply->apply_time = Now();
$apply->request_source = loanApplySourceEnum::OPERATOR_APP;
$apply->credit_officer_id = $officer_id;
$apply->creator_id = $officer_id;
$apply->creator_name = $officer->user_name;
$insert = $apply->insert();
if( !$insert->STS ){
return new result(false,'Apply fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$apply);
}
public function addMemberGuaranteeRequestOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$country_code = $params['country_code'];
$phone = $params['phone'];
$relation_type = $params['relation_type'];
$guarantee_member_account = trim($params['guarantee_member_account']);
$m_member = new memberModel();
$o_member = $m_member->getRow($member_id);
if( !$o_member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$relate_member = $m_member->getRow(array(
'login_code' => $guarantee_member_account
));
if( !$relate_member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$m_guarantee = new member_guaranteeModel();
$new_row = $m_guarantee->newRow();
$new_row->member_id = $member_id;
$new_row->relation_member_id = $relate_member->uid;
$new_row->relation_type = $relation_type;
$new_row->create_time = Now();
$new_row->relation_state = memberGuaranteeStateEnum::CREATE;
$insert = $new_row->insert();
if( !$insert->STS ){
return new result(false,'Add fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$new_row);
}
public function getMemberGuaranteeListOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$list = memberClass::getMemberPassedGuaranteeList($member_id);
return new result(true,'success',$list);
}
public function getMemberLoanRequestListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$page_num = $params['page_num'] ?: 1;
$page_size = $params['page_size'] ?: 10000;
$r = new ormReader();
$sql = "select * from loan_apply where member_id='$member_id' order by apply_time desc ";
$list = $r->getPage($sql,$page_num,$page_size);
return new result(true, 'success', array(
'total_num' => $list->count,
'total_pages' => $list->pageCount,
'current_page' => $page_num,
'page_size' => $page_size,
'list' => $list->rows
));
}
public function getCoBoundLoanRequestOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$state = $params['state'];
$page_num = $params['page_num'] ?: 1;
$page_size = $params['page_size'] ?: 10000;
$r = new ormReader();
$where_str = '';
switch ( $state ){
case 1:
// 待处理
$where_str .= " and state in('".loanApplyStateEnum::ALLOT_CO."','".loanApplyStateEnum::CO_HANDING."') ";
break;
case 2:
// 拒绝的
$where_str .= " and state='".loanApplyStateEnum::CO_CANCEL."' ";
break;
case 3:
// 通过的
$where_str .= " and state='".loanApplyStateEnum::CO_APPROVED."' ";
break;
default:
break;
}
// 将CO该处理的排在前面
$sql = "select * from loan_apply where credit_officer_id='$officer_id' $where_str order by
state not in ('".loanApplyStateEnum::ALLOT_CO."','".loanApplyStateEnum::CO_HANDING."'), apply_time desc ";
$list = $r->getPage($sql,$page_num,$page_size);
return new result(true, 'success', array(
'total_num' => $list->count,
'total_pages' => $list->pageCount,
'current_page' => $page_num,
'page_size' => $page_size,
'list' => $list->rows
));
}
public function getLoanRequestDetailOp()
{
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$m_loan_apply = new loan_applyModel();
$apply = $m_loan_apply->find(array(
'uid' => $request_id
));
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
return new result(true,'success',array(
'request_detail' => $apply
));
}
public function getAllLoanProductOp()
{
$m = new loan_productModel();
$sql = "select uid product_id,product_code,product_name from loan_product where state='".loanProductStateEnum::ACTIVE."' ";
$list = $m->reader->getRows($sql);
return new result(true,'success',array(
'list' => $list
));
}
public function loanRequestBindMemberOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$member_id = $params['member_id'];
$m_loan_apply = new loan_applyModel();
$apply = $m_loan_apply->getRow($request_id);
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
// 绑定client
$apply->member_id = $member_id;
$apply->update_time = Now();
$up = $apply->update();
if( !$up->STS ){
return new result(false,'Bind fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',array(
'request_detail' => $apply
));
}
public function loanRequestCheckOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$officer_id = $params['officer_id'];
$check_result = intval($params['check_result']);
$remark = $params['remark'];
$m_user = new um_userModel();
$m_loan_apply = new loan_applyModel();
$apply = $m_loan_apply->getRow($request_id);
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$user = $m_user->getRow($officer_id);
if( !$user ){
return new result(false,'No user',null,errorCodesEnum::USER_NOT_EXISTS);
}
if( $apply->state == loanApplyStateEnum::OPERATOR_REJECT
|| $apply->state == loanApplyStateEnum::CO_CANCEL
){
return new result(false,'Have canceled',null,errorCodesEnum::HAVE_CANCELED);
}
// 处理过了
if( $apply->state >= loanApplyStateEnum::CO_APPROVED ){
return new result(false,'Handle yet',null,errorCodesEnum::HAVE_HANDLED);
}
if( $check_result == 1 ){
$apply->state = loanApplyStateEnum::CO_HANDING;
}else{
$apply->state = loanApplyStateEnum::CO_CANCEL;
}
$apply->co_id = $user->uid;
$apply->co_name = $user->user_name;
$apply->co_remark = $remark;
$apply->update_time = Now();
$up = $apply->update();
if( !$up->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',array(
'request_detail' => $apply
));
}
public function loanRequestBindProductOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$product_id = $params['product_id'];
$repayment_type = $params['repayment_type'];
$repayment_period = $params['repayment_period'];
$m_loan_apply = new loan_applyModel();
$apply = $m_loan_apply->getRow($request_id);
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
if( $apply->state != loanApplyStateEnum::CO_HANDING ){
return new result(false,'Un-match operation',null,errorCodesEnum::UN_MATCH_OPERATION);
}
$m_member = new memberModel();
$member = $m_member->find(array(
'uid' => intval($apply->member_id)
));
if( !$member ){
return new result(false,'Un-match operation',null,errorCodesEnum::UN_MATCH_OPERATION);
}
$m_loan_product = new loan_productModel();
$product = $m_loan_product->getRow($product_id);
if( !$product ){
return new result(false,'No loan product',null,errorCodesEnum::NO_LOAN_PRODUCT);
}
// 检查是否支持的还款方式
$repayment_type_arr = (new interestPaymentEnum())->toArray();
if( !in_array($repayment_type,$repayment_type_arr) ){
return new result(false,'Un-supported type',null,errorCodesEnum::NOT_SUPPORTED);
}
if( $repayment_type != interestPaymentEnum::SINGLE_REPAYMENT ){
$repayment_period_arr = (new interestRatePeriodEnum())->toArray();
if( !in_array($repayment_period,$repayment_period_arr) ){
return new result(false,'Un-supported type',null,errorCodesEnum::NOT_SUPPORTED);
}
}
// 先写入记录
$apply->product_id = $product->uid;
$apply->product_name = $product->product_name;
$apply->repayment_type = $repayment_type;
$apply->repayment_period = $repayment_period;
$apply->state = loanApplyStateEnum::CO_HANDING;
$apply->update_time = Now();
$up = $apply->update();
if( !$up->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
$return = array(
'request_detail' => $apply,
'interest_info' => null
);
// 计算贷款天数
$loan_days_re = loan_baseClass::calLoanDays($apply->loan_time,$apply->loan_time_unit);
if( !$loan_days_re->STS ){
return new result(true,'success',$return);
}
$loan_days = $loan_days_re->DATA;
$extend_info = $member;
// 查询利率信息
$re = loan_baseClass::getLoanInterestDetail($product_id,$apply->apply_amount,$apply->currency,$loan_days,$repayment_type,$repayment_period,$extend_info);
if( !$re->STS ){
return new result(true,'success',$return);
}
$data = $re->DATA;
$interest_info = $data['interest_info'];
$return['interest_info'] = $interest_info;
$return['size_rate'] = $data['size_rate'];
$return['special_rate'] = $data['special_rate'];
// todo 是否在这步就写入利率信息等
$apply->interest_rate = $interest_info['interest_rate'];
$apply->interest_rate_type = $interest_info['interest_rate_type']?1:0;
$apply->interest_rate_unit = $interest_info['interest_rate_unit'];
$apply->interest_min_value = round($interest_info['interest_min_value'],2);
$apply->operation_fee = $interest_info['operation_fee'];
$apply->operation_fee_type = $interest_info['operation_fee_type']?1:0;
$apply->operation_fee_unit = $interest_info['operation_fee_unit'];
$apply->operation_min_value = round($interest_info['operation_min_value'],2);
$apply->admin_fee = $interest_info['admin_fee']?:0;
$apply->admin_fee_type = $interest_info['admin_fee_type']?:0;
$apply->loan_fee = $interest_info['loan_fee']?:0;
$apply->loan_fee_type = $interest_info['loan_fee_type']?:0;
$apply->is_full_interest = $interest_info['is_full_interest']?:0;
$apply->prepayment_interest = $interest_info['prepayment_interest']?:0;
$apply->prepayment_interest_type = $interest_info['prepayment_interest_type']?:0;
$apply->penalty_rate = $interest_info['penalty_rate']?:$product->penalty_rate;
$apply->penalty_divisor_days = $interest_info['penalty_divisor_days']?:$product->penalty_divisor_days;
$apply->grace_days = intval($interest_info['grace_days']);
$apply->update_time = Now();
$up = $apply->update();
if( !$up->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$return);
}
public function loanRequestCoApprovedOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$request_id = $params['request_id'];
$m_loan_apply = new loan_applyModel();
$apply = $m_loan_apply->getRow($request_id);
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
if( $apply->state != loanApplyStateEnum::CO_HANDING ){
return new result(false,'Un-match operation',null,errorCodesEnum::UN_MATCH_OPERATION);
}
// 未完成全部步骤
if( !$apply->member_id || !$apply->product_id || !$apply->interest_rate ){
return new result(false,'Un-match operation',null,errorCodesEnum::UN_MATCH_OPERATION);
}
$preview = (new loan_baseClass())->loanPreviewBeforeCreateContract($apply->apply_amount,$apply->currency,$apply->loan_time,$apply->loan_time_unit,$apply->repayment_type,$apply->repayment_period,$apply);
if( !$preview->STS ){
return new result(false,'Un-match operation',null,errorCodesEnum::UN_MATCH_OPERATION);
}
$data = $preview->DATA;
$apply->state = loanApplyStateEnum::CO_APPROVED;
$apply->update_time = Now();
$up = $apply->update();
if( !$up->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
$return = array(
'request_detail' => $apply,
'preview_info' => $data
);
return new result(true,'success',$return);
}
public function getBoundMemberLoanContractListOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$r = new ormReader();
$page_num = $params['page_num'] ?: 1;
$page_size = $params['page_size'] ?: 10000;
$sql = "select c.*,m.obj_guid member_guid,m.login_code,m.display_name,m.kh_display_name from member_follow_officer o inner join client_member m on m.uid=o.member_id
inner join loan_account a on a.obj_guid=m.obj_guid inner join loan_contract c on c.account_id=a.uid
where o.officer_id='$officer_id' and o.is_active='1' and c.state>='".loanContractStateEnum::PENDING_DISBURSE."' order by c.create_time desc ";
$list = $r->getPage($sql,$page_num,$page_size);
return new result(true, 'success', array(
'total_num' => $list->count,
'total_pages' => $list->pageCount,
'current_page' => $page_num,
'page_size' => $page_size,
'list' => $list->rows
));
}
public function getLoanContractDetailOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
$re = loan_contractClass::getLoanContractDetailInfo($contract_id);
return $re;
}
/** 签到
* @return result
*/
public function signInOp()
{
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$coord_x = $params['coord_x'];
$coord_y = $params['coord_y'];
if( !$officer_id || !$coord_x || !$coord_y ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_user = new um_userModel();
$user = $m_user->getRow($officer_id);
if( !$user ){
return new result(false,'No user',null,errorCodesEnum::USER_NOT_EXISTS);
}
$location = $params['location'];
$remark = $params['remark'];
$m = new um_user_trackModel();
$track = $m->newRow();
$track->user_id = $user->uid;
$track->user_name = $user->user_name;
$track->coord_x = $coord_x;
$track->coord_y = $coord_y;
$track->location = $location;
$track->remark = $remark;
$track->sign_day = date('Y-m-d');
$track->sign_time = Now();
$in = $track->insert();
if( !$in->STS ){
return new result(false,'Db error',null,errorCodesEnum::DB_ERROR);
}
return new result(true);
}
public function getOfficerFootprintOp()
{
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$date = trim($params['date']);
$r = new ormReader();
$sql = "select * from um_user_track where user_id='$officer_id' and sign_day='$date' order by sign_time asc";
$lists = $r->getRows($sql);
return new result(true,'success',$lists);
}
public function getOfficerFootprintListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
$page_num = intval($params['page_num'])?:1;
$page_size = intval($params['page_size'])?:100000;
$r = new ormReader();
$sql = "select *,DATE_FORMAT(sign_time,'%Y-%m') sign_month from um_user_track where user_id='$officer_id' group by sign_day order by sign_time desc ";
$re = $r->getPage($sql,$page_num,$page_size);
return new result(true,'success',array(
'total_num' => $re->count,
'total_pages' => $re->pageCount,
'current_page' => $page_num,
'page_size' => $page_size,
'list' => $re->rows
));
}
public function getOfficerBaseInfoOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = $params['officer_id'];
if( $officer_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m = new um_userModel();
$info = $m->getRow($officer_id);
if( !$info ){
return new result(false,'No user ',null,errorCodesEnum::USER_NOT_EXISTS);
}
$info = $info->toArray();
unset($info['password']);
return new result(true,'success',array(
'user_info' => $info
));
}
public function getMemberAssetsEvaluateOp(){
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$r = new ormReader();
$sql = "SELECT a.* from member_verify_cert as m RIGHT JOIN member_assets as a ON m.uid = a.cert_id
WHERE m.member_id = $member_id AND a.asset_state = 100 ORDER BY a.create_time desc ";
$list = $r->getRows($sql);
$sql1 = "SELECT sum(a.valuation) as total from member_verify_cert as m RIGHT JOIN member_assets as a ON m.uid = a.cert_id
WHERE m.member_id = $member_id AND a.asset_state = 100 ";
$total = $r->getRow($sql1);
return new result(true,'success',array(
'total_amount' => $total['total'],
'list' => $list
));
}
public function getMemberAssetDetailOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$asset_id = $params['asset_id'];
$m = new member_assetsModel();
$asset = $m->getRow($asset_id);
if( !$asset ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
return new result(true,'success',array(
'asset_detail' => $asset
));
}
public function submitMemberAssetsEvaluateOp(){
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$amount = $params['valuation'];
$officer_id = $params['officer_id'];
if( $amount <= 0 ){
return new result(false,'Invalid amount',null,errorCodesEnum::INVALID_AMOUNT);
}
$m_member_assets = new member_assetsModel();
$assets = $m_member_assets->getRow($params['id']);
if( !$assets ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$officer = (new um_userModel())->getRow($officer_id);
if( !$officer ){
return new result(false,'No user',null,errorCodesEnum::USER_NOT_EXISTS);
}
$assets->valuation = $amount;
$assets->remark = $params['remark'];
$assets->update_time = Now();
$up = $assets->update();
if( !$up->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
// 标记member
$member = (new memberModel())->getRow($assets->member_id);
if( $member ){
$member->co_id = $officer_id;
$member->co_name = $officer->user_name;
$member->co_state = 1;
$member->co_remark = 'Asset evaluation';
$member->update_time = Now();
$member->update();
}
// 推送消息
$m_log = new member_cert_logModel();
$m_log->insertCertLog($assets->uid,2);
return new result(true,'success',array(
'request_detail' => $assets
));
}
public function submitMemberSuggestCreditOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
$officer_id = intval($params['officer_id']);
$monthly_repayment_ability = round($params['monthly_repayment_ability'],2);
$suggest_credit = round($params['suggest_credit']);
$remark = $params['remark'];
if( !$member_id || !$officer_id || $monthly_repayment_ability<=0 || $suggest_credit <=0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$officer = (new um_userModel())->getRow($officer_id);
$m = new member_credit_suggestModel();
$insert = $m->insert(array(
'member_id' => $member_id,
'user_id' => $officer_id,
'user_name' => $officer['user_name'],
'monthly_repayment_ability' => $monthly_repayment_ability,
'suggest_credit' => $suggest_credit,
'remark' => $remark,
'create_time' => Now()
));
if( !$insert->STS ){
return new result(false,'Handle fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function getMemberWorkDetailOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
$m = new member_workModel();
$work = $m->orderBy('uid desc')->getRow(array(
'member_id' => $member_id
));
return new result(true,'success',array(
'work_detail' => $work
));
}
public function getMemberAssessmentOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
// 会员评估
$data = memberClass::getMemberAssessment($member_id);
return new result(true,'success',$data);
}
public function getTaskSummaryOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = intval($params['officer_id']);
$r = new ormReader();
// 待处理贷款申请
$sql = " select count(*) from loan_apply where credit_officer_id='$officer_id' and state
in('".loanApplyStateEnum::ALLOT_CO."','".loanApplyStateEnum::CO_HANDING."') ";
$loan_apply_num = $r->getOne($sql);
return new result(true,'success',array(
'task_loan_apply' => $loan_apply_num
));
}
public function getMemberResidencePlaceOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$member = (new memberModel())->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$m_address = new common_addressModel();
$address = $m_address->getRow(array(
'obj_type' => objGuidTypeEnum::CLIENT_MEMBER,
'obj_guid' => $member->obj_guid,
'address_category' => addressCategoryEnum::MEMBER_RESIDENCE_PLACE
));
return new result(true,'success',array(
'address_info' => $address
));
}
public function editMemberResidencePlaceOp()
{
$re = $this->checkOperator();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$officer_id = intval($params['officer_id']);
$member_id = $params['member_id'];
$member = (new memberModel())->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$type = addressCategoryEnum::MEMBER_RESIDENCE_PLACE;
$id1 = intval($params['id1']);
$id2 = intval($params['id2']);
$id3 = intval($params['id3']);
$id4 = intval($params['id4']);
$full_text = $params['full_text'];
$cord_x = round($params['cord_x'],6);
$cord_y = round($params['cord_y'],6);
$m_address = new common_addressModel();
if( $params['address_id'] ){
$address = $m_address->getRow($params['address_id']);
if( !$address ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$address->id1 = $id1;
$address->id2 = $id2;
$address->id3 = $id3;
$address->id4 = $id4;
$address->coord_x = $cord_x;
$address->coord_y = $cord_y;
$address->full_text = $full_text;
$address->create_time = Now();
$up = $address->update();
if( !$up->STS ){
return new result(false,'Edit fail:'.$up->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$address);
}else{
$new_row = $m_address->newRow();
$new_row->obj_type = objGuidTypeEnum::CLIENT_MEMBER;
$new_row->obj_guid = $member->obj_guid;
$new_row->address_category = $type;
$new_row->id1 = $id1;
$new_row->id2 = $id2;
$new_row->id3 = $id3;
$new_row->id4 = $id4;
$new_row->coord_x = $cord_x;
$new_row->coord_y = $cord_y;
$new_row->full_text = $full_text;
$new_row->create_time = Now();
$insert = $new_row->insert();
if( !$insert->STS ){
return new result(false,'Add fail:'.$insert->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$new_row);
}
}
}<file_sep>/framework/weixin_baike/api/control/member.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 10:44
*/
class memberControl extends bank_apiControl
{
/** 弃用
* app注册member
* @return result
*/
public function createOp()
{
$params = array_merge(array(),$_GET,$_POST);
// 设置必须的参数
if(
empty($params['login_code']) || empty($params['family_name']) || empty($params['given_name']) || empty($params['password'])
|| empty($params['phone']) || empty($params['country_code'] )
)
{
return new result(false,'Lack of param',null,errorCodesEnum::DATA_LACK);
}
// 验证短信验证码
$sms_id = $params['sms_id'];
$sms_code = $params['sms_code'];
$m_verify_code = new phone_verify_codeModel();
$row = $m_verify_code->getRow(array(
'uid' => $sms_id,
'verify_code' => $sms_code
));
if( !$row ){
return new result(false,'SMS code error',null,errorCodesEnum::SMS_CODE_ERROR);
}
$params['is_verify_phone'] = 1;
$conn = ormYo::Conn();
$conn->startTransaction();
try{
$rt = memberClass::addMember($params);
if( !$rt->STS ){
$conn->rollback();
return $rt;
}
$member = $rt->DATA;
$conn->submitTransaction();
return new result(true,'Success',$member);
}catch(Exception $e){
$conn->rollback();
return new result(false,$e->getMessage(),null,errorCodesEnum::DB_ERROR);
}
}
/** 电话注册
* @return result
*/
public function phoneRegisterOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::phoneRegister($params);
}
public function phoneRegisterNewOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::phoneRegisterNew($params);
}
public function checkLoginAccountIsExistOp()
{
$params = array_merge(array(),$_GET,$_POST);
$login_code = $params['login_code'];
$is = memberClass::checkLoginAccountIsExist($login_code);
return new result(true,'success',array(
'is_exist' => $is
));
}
/** 注册信息修改
* @return result
*/
public function editRegisterInfoOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::editRegisterMemberInfo($params);
}
public function verifyLoginPasswordOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$password = $params['<PASSWORD>'];
return memberClass::verifyLoginPassword($member_id,$password);
}
/** 密码登陆
* @return result
*/
public function passwordLoginOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::passwordLogin($params);
}
/** 手势密码登陆
* @return result
*/
public function gestureLoginOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::gestureLogin($params);
}
/** 指纹登陆
* @return result
*/
public function fingerprintLoginOp()
{
$params = array_merge(array(),$_GET,$_POST);
return memberClass::fingerprintLogin($params);
}
/** 暂停使用
* member app 登陆
* @return result
*/
public function appLoginOp()
{
return new result(false);
$params = array_merge(array(),$_GET,$_POST);
if( empty($params['login_code']) ){ // 第三方登陆的不会有密码 login_password
return new result(false,'Invalid param',null,errorCodesEnum::DATA_LACK);
}
$m_member = new memberModel();
$client_id = $params['client_id']?intval($params['client_id']):0;
$client_type = $params['client_type'];
// passport 通行的方式
$pass_type = isset($params['passport_type'])?$params['passport_type']:0;
$rt = memberClass::checkPassport(array(
'login_code' => $params['login_code'],
'login_password' => $params['login_password']
),$pass_type);
if( !$rt->STS ){
return new result(false,'Login fail',null,errorCodesEnum::UNEXPECTED_DATA);
}
$o_member = $rt->DATA;
$member = $m_member->getRow($o_member['uid']); // 防止错误返回
if( !$member ){
return new result(false,'Login fail',null,errorCodesEnum::UNEXPECTED_DATA);
}
$login_ip = getIp();
$member->last_login_time = Now();
$member->last_login_ip = $login_ip;
$member->update();
// 创建token令牌
$m_member_token = new member_tokenModel();
$token_row = $m_member_token->newRow();
$token_row->member_id = $member->uid;
$token_row->login_code = $member->login_code;
$token_row->token = md5($params['login_code'].time());
$token_row->create_time = Now();
$token_row->login_time = Now();
$token_row->client_type = $params['client_type'];
$insert = $token_row->insert();
if( !$insert->STS ){
return new result(false,'Create token fail',null,errorCodesEnum::DB_ERROR);
}
$m_member_login_log = new member_login_logModel();
$log = $m_member_login_log->newRow();
$log->member_id = $member->uid;
$log->client_id = $client_id;
$log->client_type = $client_type;
$log->login_time = Now();
$log->login_ip = $login_ip;
$log->login_area = ''; // todo ip获取区域?
$insert = $log->insert();
if( !$insert->STS ){
return new result(false,'Log error',null,errorCodesEnum::DB_ERROR);
}
$member_info = $member->toArray();
unset($member_info['login_password']);
$member_info['grade_code'] = '';
$member_info['grade_caption'] = '';
$m_member_grade = new member_gradeModel();
$grade_info = $m_member_grade->getRow(array(
'grade_code' => $member->member_grade,
));
if( $grade_info ){
$member_info['grade_code'] = $grade_info->grade_code;
$member_info['grade_caption'] = $grade_info->grade_caption;
}
return new result(true,'Login success',array(
'token' => $token_row->token,
'member_info' => $member_info
));
}
/**
* APP 退出登录
* @return result
*/
public function appLogoutOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
if( !isset($params['member_id']) || !isset($params['client_type']) ){
return new result(false,'Param lack',null,errorCodesEnum::DATA_LACK);
}
if( !$member_id ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
// 销毁token
$m_member_token = new member_tokenModel();
$where = " member_id='$member_id' ";
$m_member_token->deleteWhere($where);
$m_login_log = new member_login_logModel();
$login_log = $m_login_log->orderBy('uid desc')->getRow(array(
'member_id' => $member_id,
'client_type' => $params['client_type'],
));
if( $login_log ){
$login_log->logout_time = Now();
$login_log->update_time = Now();
}
return new result(true,'success');
}
/**
* 忘记密码,重置密码
* @return result
*/
public function resetPwdOp()
{
$params = array_merge(array(),$_GET,$_POST);
$type = $params['type'];
switch( $type ){
case 'sms':
$rt = memberClass::resetPwdBySms($params);
return $rt;
break;
default:
$rt = new result(false,'Not supported type',null,errorCodesEnum::NOT_SUPPORTED);
return $rt;
}
}
public function getMemberBaseInfoOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$member_info = memberClass::getMemberBaseInfo($member_id);
return new result(true,'success',$member_info);
}
/** 身份证认证
* @return result
*/
public function idVerifyCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::idVerifyCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
/** 户口本认证
* @return result
*/
public function familyBookCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::familyBookVerifyCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
/** 居住证认证
* @return result
*/
public function residentBookCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::residentBookCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
/** 家庭关系认证
* @return result
*/
public function familyRelationshipCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::familyRelationshipCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
/** 工作认证
* @return result
*/
public function workCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::workCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
/** 资产认证
* @return result
*/
public function assetCertOp()
{
set_time_limit(120);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::assetCert($params,0);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function bindAceAccountOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::bindLoanAceAccount($params);
return $re;
}
public function editLoanAceAccountInfoOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::editLoanBindAceAccountInfo($params);
return $re;
}
/** 贷款业务的
* @return result
*/
public function getMemberAceAccountInfoOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$re = memberClass::getMemberLoanAceAccountInfo($member_id);
return $re;
}
public function message_listOp() {
$re = $this->checkToken();
if (!$re->STS) return $re;
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if ($member_id <=0){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$page_num = $params['page_num'];
$page_size = $params['page_size'];
return member_messageClass::getReceivedMessages($member_id, $page_num, $page_size);
}
public function message_unread_countOp() {
$re = $this->checkToken();
if (!$re->STS) return $re;
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if ($member_id <=0){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
return member_messageClass::getUnreadMessagesCount($member_id);
}
public function message_readOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <=0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$message_id = $params['message_id'];
return member_messageClass::readMessage($member_id,$message_id);
}
public function message_deleteOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <=0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$messages = $params['message_id_list'];
return member_messageClass::deleteMessages($member_id,$messages);
}
public function loanContractListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <=0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$re = memberClass::getLoanContractList($params);
return $re;
}
public function changePwdOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::changePassword($params);
return $re;
}
public function getCertedResultOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::getMemberCertResult($params);
return $re;
}
public function getAccountIndexInfoOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$re = memberClass::getMemberAccountSumInfo($member_id);
return $re;
}
public function getInsuranceContractListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::getInsuranceContractList($params);
return $re;
}
public function getMemberLoanApplyListOp()
{
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::getMemberLoanApplyList($params);
return $re;
}
public function getCreditHistoryOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
return memberClass::getMemberCreditHistory($params);
}
public function editAvatorOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( empty($_FILES['avator']) ){
return new result(false,'No upload image',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$default_dir = 'avator/'.$member_id;
$upload = new UploadFile();
$upload->set('save_path',null);
$upload->set('default_dir',$default_dir);
$re = $upload->server2upun('avator');
if( $re == false ){
return new result(false,'Upload photo fail',null,errorCodesEnum::API_FAILED);
}
$img_path = $upload->full_path;
$member->member_image = $img_path;
$member->member_icon = $img_path;
$up = $member->update();
if( !$up->STS ){
return new result(false,'Edit fail:'.$up->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,array(
'member_image' => $member->member_image,
'member_icon' => $member->member_icon
));
}
public function editLoginCodeOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$login_code = $params['login_code'];
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::editMemberLoginCode($member_id,$login_code);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function editNicknameOp()
{
return new result(false,'Function close',null,errorCodesEnum::FUNCTION_CLOSED);
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$nickname = $params['nickname'];
if( !$member_id || !$nickname ){
return new result(false,'');
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$member->nickname = $nickname;
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Edit fail:'.$up->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,$member);
}
public function getMemberQrcodeImageOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$url = ENTRY_API_SITE_URL.'/member.qrcode.image.php?member_id='.$member_id;
return new result(true,'success',$url);
}
public function setGesturePasswordOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$gesture_pwd = trim($params['gesture_password']);
if( !$member_id || !$gesture_pwd ){
return new result(false,'Invalid Param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$member->gesture_password = <PASSWORD>;
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Set fail:'.$up->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$member);
}
public function setFingerprintOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$fingerprint = trim($params['fingerprint']);
if( !$member_id || !$fingerprint ){
return new result(false,'Invalid Param',null,errorCodesEnum::INVALID_PARAM);
}
// url解码
$fingerprint = urldecode($fingerprint);
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$member->fingerprint = $fingerprint;
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Set fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',array(
'fingerprint' => $fingerprint
));
}
public function setTradingPasswordOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$trading_password = $params['trading_password'];
$login_password = $params['login_password'];
$id_no = $params['id_no'];
if( !$member_id || !$trading_password || !$login_password || !$id_no ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
// 验证登陆密码
if( $member->login_password != md5($<PASSWORD>) ){
return new result(false,'Login password error',null,errorCodesEnum::PASSWORD_ERROR);
}
// 验证身份证号
if( !$member->id_sn ){
return new result(false,'Not certificate ID',null,errorCodesEnum::NOT_CERTIFICATE_ID);
}
$last_no = substr($member->id_sn,-4);
if( $last_no != $id_no ){
return new result(false,'ID sn error',null,errorCodesEnum::ID_SN_ERROR);
}
// 两次密码是否一致
if( $member->trading_password ){
if( $member->trading_password == md5($<PASSWORD>) ){
return new result(false,'Same password',null,errorCodesEnum::SAME_PASSWORD);
}
}
$member->trading_password = md5($<PASSWORD>);
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Set fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true);
}
public function isSetTradingPasswordOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$return = memberClass::isSetTradingPassword($member_id);
return new result(true,'success',$return);
}
public function setTradingPasswordVerifyAmountOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$amount = $params['amount'];
$currency = $params['currency'];
if( !$member_id || !$amount || !$currency ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
if( !$member->trading_password ){
return new result(false,'Not set trading password',null,errorCodesEnum::NOT_SET_TRADING_PASSWORD);
}
$member->trading_verify_amount = round($amount,2);
$member->trading_verify_currency = $currency;
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Db error',null,errorCodesEnum::DB_ERROR);
}
return new result(true);
}
public function getLoanBindAutoDeductionAccountOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
return memberClass::getLoanBindAutoDeductionAccount($member_id);
}
public function forgotGestureOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$member->gesture_password = <PASSWORD>;
$member->update_time = Now();
$up = $member->update();
if( !$up->STS ){
return new result(false,'Reset fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',array(
'gesture_password' => $member['gesture_password']
));
}
public function assetDeleteOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$asset_id = $params['asset_id'];
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::deleteAsset($member_id,$asset_id);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function deleteFamilyRelationshipOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$relation_id = $params['relation_id'];
$conn = ormYo::Conn();
try{
$conn->startTransaction();
$re = memberClass::deleteFamilyRelationship($member_id,$relation_id);
if( $re->STS ){
$conn->submitTransaction();
return $re;
}else{
$conn->rollback();
return $re;
}
}catch ( Exception $e ){
return new result(false,$e->getMessage(),null,errorCodesEnum::UNEXPECTED_DATA);
}
}
public function getMemberLoanSummaryOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$own_re = memberClass::getMemberLoanSummary($member_id,1);
if( !$own_re->STS ){
return $own_re;
}
$own_loan_summary = $own_re->DATA;
$guarantee_loan_re = memberClass::getMemberLoanSummary($member_id,2);
if( !$guarantee_loan_re->STS ){
return $guarantee_loan_re;
}
$guarantee_loan_summary = $guarantee_loan_re->DATA;
return new result(true,'success',array(
'own_loan_summary' => $own_loan_summary,
'as_guarantee_loan_summary' => $guarantee_loan_summary
));
}
/** 添加担保人
* @return result
*/
public function addGuaranteeOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$country_code = $params['country_code'];
$phone = $params['phone'];
$relation_type = $params['relation_type'];
$guarantee_member_account = trim($params['guarantee_member_account']);
$m_member = new memberModel();
$o_member = $m_member->getRow($member_id);
if( !$o_member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$relate_member = $m_member->getRow(array(
'login_code' => $guarantee_member_account
));
if( !$relate_member ){
return new result(false,'No member',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$m_guarantee = new member_guaranteeModel();
$new_row = $m_guarantee->newRow();
$new_row->member_id = $member_id;
$new_row->relation_member_id = $relate_member->uid;
$new_row->relation_type = $relation_type;
$new_row->create_time = Now();
$new_row->relation_state = memberGuaranteeStateEnum::CREATE;
$insert = $new_row->insert();
if( !$insert->STS ){
return new result(false,'Add fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function guaranteeConfirmOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$uid = $params['uid'];
$state = $params['state'];
$m_guarantee = new member_guaranteeModel();
$row = $m_guarantee->getRow(array(
'relation_member_id' => $member_id,
'uid' => $uid
));
if( !$row ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
if( $state == 0 ){
$row->relation_state = memberGuaranteeStateEnum::REJECT;
}else{
$row->relation_state = memberGuaranteeStateEnum::ACCEPT;
}
$row->update_time = Now();
$up = $row->update();
if( !$up->STS ){
return new result(false,'Update fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function getMemberGuaranteeListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
// 担保人列表
$r = new ormReader();
$sql = "select g.*,m.display_name,m.kh_display_name,m.member_icon,m.member_image,m.phone_id,d.item_name_json relation_type_name_json from member_guarantee g left join client_member m on m.uid=g.relation_member_id
left join core_definition d on d.item_code=g.relation_type and d.category='".userDefineEnum::GUARANTEE_RELATIONSHIP."' where g.member_id='$member_id' and g.relation_state='".memberGuaranteeStateEnum::ACCEPT."' ";
$list1 = $r->getRows($sql);
// 作为担保人的(申请+通过的)
$sql = "select g.*,m.display_name,m.kh_display_name,m.member_icon,m.member_image,m.phone_id,d.item_name_json relation_type_name_json from member_guarantee g left join client_member m on m.uid=g.member_id
left join core_definition d on d.item_code=g.relation_type and d.category='".userDefineEnum::GUARANTEE_RELATIONSHIP."' where g.relation_member_id='$member_id' and g.relation_state in('".memberGuaranteeStateEnum::CREATE."','".memberGuaranteeStateEnum::ACCEPT."') ";
$list2 = $r->getRows($sql);
return new result(true,'success',array(
'guarantee_list' => $list1,
'apply_list' => $list2
));
}
public function queryMemberCreditOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$credit = memberClass::getCreditBalance($member_id);
return new result(true,'success',$credit);
}
public function getMemberCreditProcessOp()
{
$params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id'])?:0;
return memberClass::getMemberCreditProcess($member_id);
}
public function getMemberLoanReceivedRecordOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$list = memberClass::getLoanReceivedRecord($member_id);
return new result(true,'success',$list);
}
public function getMemberLoanRepaymentRecordOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$list = memberClass::getLoanRepaymentRecord($member_id);
return new result(true,'success',$list);
}
public function bindBankAccountOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$re = memberClass::memberBindBankAccount($params);
return $re;
}
public function getBindBankListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
if( $member_id <= 0 ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$list = member_handlerClass::getMemberBindBankList($member_id);
return new result(true,'success',array(
'list' => $list
));
}
public function getMemberMortgageGoodsListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$list = memberClass::getMemberMortgagedGoodsList($member_id);
return new result(true,'success',array(
'list' => $list
));
}
public function deleteBindBankOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$bind_id = $params['bind_id'];
$m_handler = new member_account_handlerModel();
$handler = $m_handler->getRow(array(
'uid' => $bind_id,
'member_id' => $member_id
));
if( !$handler ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$handler->state = accountHandlerStateEnum::HISTORY;
$handler->update_time = Now();
$up = $handler->update();
if( !$up->STS ){
return new result(false,'Delete fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function prepaymentApplyCancelOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$apply_id = $params['apply_id'];
$m = new loan_prepayment_applyModel();
$apply = $m->getRow($apply_id);
if( !$apply ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
if( $apply->state != prepaymentApplyStateEnum::CREATE ){
return new result(false,'Handling...',null,errorCodesEnum::HANDLING_LOCKED);
}
$delete = $apply->delete();
if( !$delete->STS ){
return new result(false,'Cancel fail',null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success');
}
public function getSavingsBalanceOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$memberObject = new objectMemberClass($member_id);
$cny_balance = $memberObject->getSavingsAccountBalance();
return new result(true,'success',array(
'savings_balance' => $cny_balance
));
}
/** 存取款绑定账户
* @return result
*/
public function getMemberBizAccountHandlerOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
// 暂时只支持ACE
$m = new member_account_handlerModel();
$handler_list = $m->select(array(
'member_id' =>$member_id,
'handler_type' => memberAccountHandlerTypeEnum::PARTNER_ASIAWEILUY,
'is_verified' => 1,
'state' => accountHandlerStateEnum::ACTIVE
));
$list = array();
foreach( $handler_list as $handler ){
$handler['handler_account'] = maskInfo($handler['handler_account']);
$list[] = $handler;
}
return new result(true,'success',array(
'handler_list' => $list
));
}
public function addMemberAddressOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge(array(),$_GET,$_POST);
$member_id = $params['member_id'];
$member = (new memberModel())->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$id1 = intval($params['id1']);
$id2 = intval($params['id2']);
$id3 = intval($params['id3']);
$id4 = intval($params['id4']);
$full_text = $params['full_text'];
$m_address = new common_addressModel();
$new_row = $m_address->newRow();
$new_row->obj_type = objGuidTypeEnum::CLIENT_MEMBER;
$new_row->obj_guid = $member->obj_guid;
$new_row->id1 = $id1;
$new_row->id2 = $id2;
$new_row->id3 = $id3;
$new_row->id4 = $id4;
$new_row->full_text = $full_text;
$new_row->create_time = Now();
$insert = $new_row->insert();
if( !$insert->STS ){
return new result(false,'Add fail:'.$insert->MSG,null,errorCodesEnum::DB_ERROR);
}
return new result(true,'success',$new_row);
}
}
<file_sep>/README.md
# fri_community
Just a community
<file_sep>/framework/api_test/apis/microbank/email.verify.send.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/8
* Time: 10:48
*/
class emailVerifySendApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Email Verify Send";
$this->description = "发送验证邮件";
$this->url = C("bank_api_url") . "/email.verify.send.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("email", "邮箱地址", '32<EMAIL>', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/member.repayment.request.cancel.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/7
* Time: 14:05
*/
// member.repayment.request.cancel
class memberRepaymentRequestCancelApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Repayment Apply Cancel";
$this->description = "贷款还款申请取消";
$this->url = C("bank_api_url") . "/member.repayment.request.cancel.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("request_id", "请求ID", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/app.version.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/13
* Time: 17:32
*/
class appVersionApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "App Version";
$this->description = "获取APP的最新版本信息";
$this->url = C("bank_api_url") . "/app.version.php";
$this->parameters = array();
$this->parameters[] = new apiParameter('app_name','APP名称','smarithiesak-member',true);
$this->parameters[] = new apiParameter('version','客户端版本','1.0.0',false);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'返回数据' => '最新版本信息',
'app_name' => 'bank_member_app',
'version' => '2.5.3',
'download_url' => '下载地址,bank.mekong24.com/data/bank_member_app/1.0.0/bank_member_app.apk',
'is_required' => '是否必须下载,是1 否0',
'remark' => '备注',
'creator_id' => '发布人id',
'creator_name' => '发布人名称',
'create_time' => '发布时间',
/*'newest_version' => array(
'返回数据' => '最新版本信息',
'app_name' => 'bank_member_app',
'version' => '2.5.3',
'download_url' => '下载地址,bank.mekong24.com/data/bank_member_app/1.0.0/bank_member_app.apk',
'is_required' => '是否必须下载,是1 否0',
'remark' => '备注',
'creator_id' => '发布人id',
'creator_name' => '发布人名称',
'create_time' => '发布时间'
),
'update_version' => array(
'返回数据' => '必须更新版本信息',
'app_name' => 'bank_member_app',
'version' => '2.4.1',
'download_url' => '下载地址,bank.mekong24.com/data/bank_member_app/1.0.0/bank_member_app.apk',
'is_required' => '是否必须下载,是1 否0',
'remark' => '备注',
'creator_id' => '发布人id',
'creator_name' => '发布人名称',
'create_time' => '发布时间'
)*/
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.suggest.member.credit.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 15:52
*/
class officerSubmitSuggestMemberCreditApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member credit suggest";
$this->description = "客户授信推介";
$this->url = C("bank_api_url") . "/officer.submit.suggest.member.credit.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", '', 1, true);
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("monthly_repayment_ability", "月还款能力", 500, true);
$this->parameters[]= new apiParameter("suggest_credit", "推介信用值", 1000, true);
$this->parameters[]= new apiParameter("remark", "备注", '');
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array()
);
}
}<file_sep>/framework/api_test/apis/officer_app/co.sign.in.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/28
* Time: 13:48
*/
class coSignInApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "CO sign in";
$this->description = "签到";
$this->url = C("bank_api_url") . "/co.sign.in.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1, true);
$this->parameters[]= new apiParameter("coord_x", "经度", 23.325412, true);
$this->parameters[]= new apiParameter("coord_y", "纬度", 48.212365, true);
$this->parameters[]= new apiParameter("location", "地理位置", 'A street', true);
$this->parameters[]= new apiParameter("remark", "备注", 'remark');
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/weixin_baike/data/model/passbook_account_flow.model.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/3/1
* Time: 15:40
*/
class passbook_account_flowModel extends tableModelBase {
public function __construct()
{
parent::__construct('passbook_account_flow');
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/certification.list.php
<div>
<table class="table verify-table">
<tbody class="table-body">
<?php foreach ($data['data'] as $key => $row) { ?>
<tr>
<td class="magnifier<?php echo $key; ?>" style="width: 380px;">
<div class="magnifier" index="<?php echo $key; ?>">
<div class="magnifier-container" style="display:none;">
<div class="images-cover"></div>
<div class="move-view"></div>
</div>
<div class="magnifier-assembly">
<div class="magnifier-btn">
<span class="magnifier-btn-left"><</span>
<span class="magnifier-btn-right">></span>
</div>
<!--按钮组-->
<div class="magnifier-line">
<ul class="clearfix animation03">
<?php foreach ($row['cert_images'] as $value) { ?>
<li>
<a target="_blank" href="<?php echo $value['image_url']; ?>">
<div class="small-img">
<img src="<?php echo $value['image_url']; ?>"/>
</div>
</a>
</li>
<?php } ?>
</ul>
</div>
<!--缩略图-->
</div>
<div class="magnifier-view"></div>
<!--经过放大的图片显示容器-->
</div>
</td>
<td>
<div class="cert-info">
<p><label class="lab-name">Name :</label><a
href="<?php echo getUrl('client', 'clientDetail', array('uid' => $row['member_id'], 'show_menu' => 'client-client'), false, BACK_OFFICE_SITE_URL) ?>"><?php echo $row['login_code'] ?></a>
</p>
<p><label class="lab-name">Source Type:</label><?php if ($row['source_type'] == 0) {
echo 'Self Submission';
} else {
echo 'Teller Submission';
} ?></p>
<p><label class="lab-name">Submit Time:</label><?php echo timeFormat($row['create_time']); ?>
</p>
<p><label class="lab-name">Remark:</label><?php echo $row['verify_remark'] ?: '/'; ?></p>
</div>
</td>
<td>
<div class="verify-state">
<div class="title">
Verify State
</div>
<div class="content">
<?php if ($row['verify_state'] == 0) { ?>
<div class="state">Not Verified</div>
<?php } elseif ($row['verify_state'] == 10) { ?>
<div class="state">Have Passed</div>
<?php } elseif ($row['verify_state'] == 100) { ?>
<div class="state">Refuse</div>
<?php } else { ?>
<?php if ($data['cur_uid'] == $row['auditor_id']) { ?>
<div class="state"><span class="locking"><i class="fa fa-gavel"></i>Auditing</span>
</div>
<?php } else { ?>
<div class="state other">
<p><i class="fa fa-user"></i><?php echo $row['auditor_name']; ?></p>
<span class="locking">Auditing</span></div>
<?php } ?>
<?php } ?>
<?php if($row['verify_state'] == 0 || $data['cur_uid'] == $row['auditor_id']){?>
<div class="custom-btn-group">
<a title="<?php echo $lang['common_edit']; ?>" class="custom-btn custom-btn-secondary"
href="<?php echo getUrl('operator', 'certificationDetail', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL) ?>">
<span><i class="fa fa-vcard-o"></i>Audit</span>
</a>
</div>
<?php } else {?>
<button class="btn btn-default" disabled style="padding: 4px 12px;">
<span><i class="fa fa-vcard-o"></i>Audit</span>
</button>
<?php }?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<hr>
<?php include_once(template("widget/inc_content_pager")); ?>
<script>
$('.magnifier-btn-left').on('click', function () {
var el = $(this).parents('.magnifier'), thumbnail = el.find('.magnifier-line > ul'), index = $(this).index();
move(el, thumbnail, index);
});
$('.magnifier-btn-right').on('click', function () {
var el = $(this).parents('.magnifier'), thumbnail = el.find('.magnifier-line > ul'), index = $(this).index();
move(el, thumbnail, index);
});
function move(magnifier, thumbnail, _boole) {
magnifier.index = _boole;
(_boole) ? magnifier.index++ : magnifier.index--;
var thumbnailImg = thumbnail.find('>*'), lineLenght = thumbnailImg.length;
var _deviation = Math.ceil(magnifier.width() / thumbnailImg.width() / 2);
if (lineLenght < _deviation) {
return false;
}
(magnifier.index < 0) ? magnifier.index = 0 : (magnifier.index > lineLenght - _deviation) ? magnifier.index = lineLenght - _deviation : magnifier.index;
var endLeft = (thumbnailImg.width() * magnifier.index) - thumbnailImg.width();
thumbnail.css({
'left': ((endLeft > 0) ? -endLeft : 0) + 'px'
});
}
</script>
<file_sep>/framework/weixin_baike/inc.authority.php
<?php
/**
* Created by PhpStorm.
* User: DELL
* Date: 2016/8/30
* Time: 17:09
*/
class authEnum extends Enum
{
/* back office权限设置开始*/
const AUTH_HOME_MONITOR = "home_monitor";
const AUTH_USER_BRANCH = "user_branch";
const AUTH_USER_ROLE = "user_role";
const AUTH_USER_USER = "user_user";
const AUTH_USER_LOG = "user_log";
const AUTH_USER_POINT_EVENT = "user_pointEvent";
const AUTH_USER_POINT_PERIOD = "user_pointPeriod";
const AUTH_USER_DEPARTMENT_POINT = "user_departmentPoint";
const AUTH_CLIENT_CLIENT = "client_client";
const AUTH_CLIENT_CERIFICATION = "client_cerification";
const AUTH_CLIENT_BLACK_LIST = "client_blackList";
const AUTH_CLIENT_GRADE = "client_grade";
const AUTH_PARTNER_BANK = "partner_bank";
const AUTH_PARTNER_DEALER = "partner_dealer";
const AUTH_LOAN_PRODUCT = "loan_product";
const AUTH_LOAN_CREDIT = "loan_credit";
const AUTH_LOAN_APPROVAL = "loan_approval";
const AUTH_LOAN_APPLY = "loan_apply";
const AUTH_LOAN_REQUEST_TO_PREPAYMENT = "loan_requestToPrepayment";
const AUTH_LOAN_REQUEST_TO_REPAYMENT = "loan_requestToRepayment";
const AUTH_LOAN_CONTRACT = "loan_contract";
const AUTH_LOAN_WRITE_OFF = "loan_writeOff";
const AUTH_LOAN_OVERDUE = "loan_overdue";
const AUTH_LOAN_DEDUCTING_PENALTIES = "loan_deductingPenalties";
const AUTH_INSURANCE_PRODUCT = "insurance_product";
const AUTH_INSURANCE_CONTRACT = "insurance_contract";
const AUTH_SETTING_COMPANY_INFO = "setting_companyInfo";
const AUTH_SETTING_CREDIT_LEVEL = 'setting_creditLevel';
const AUTH_SETTING_CREDIT_PROCESS = 'setting_creditProcess';
const AUTH_SETTING_GLOBAL = "setting_global";
const AUTH_REGION_LIST = "region_list";
const AUTH_SETTING_SHORT_CODE = "setting_shortCode";
const AUTH_SETTING_CODING_RULE = "setting_codingRule";
const AUTH_SETTING_RESET_SYSTEM = "setting_resetSystem";
const AUTH_FINANCIAL_BANK_ACCOUNT = "financial_bankAccount";
const AUTH_FINANCIAL_EXCHANGE_RATE = "financial_exchangeRate";
const AUTH_REPORT_OVERVIEW = "report_overview";
const AUTH_REPORT_CLIENT_LIST = "report_clientList";
const AUTH_REPORT_CONTRACT_LIST = "report_contractList";
const AUTH_REPORT_CREDIT_LIST = "report_creditList";
const AUTH_REPORT_TODAY_REPORT = "report_todayReport";
const AUTH_REPORT_LOAN_LIST = "report_loanList";
const AUTH_REPORT_REPAYMENT_LIST = "report_repaymentList";
const AUTH_REPORT_ASSET_LIABILITY = "report_assetLiability";
const AUTH_REPORT_PROFIT_REPORT = "report_profitReport";
const AUTH_EDITOR_HELP = "editor_help";
const AUTH_TOOLS_CALCULATOR = "tools_calculator";
const AUTH_TOOLS_SMS = "tools_sms";
const AUTH_POINT_EVENT = "point_event";
const AUTH_POINT_POINT_RECORD = "point_pointRecord";
const AUTH_POINT_USER_POINT = "point_userPoint";
const AUTH_DEV_APP_VERSION = "dev_appVersion";
const AUTH_DEV_FUNCTION_SWITCH = "dev_functionSwitch";
const AUTH_DEV_RESET_PASSWORD = "<PASSWORD>";
/* back office权限设置结束*/
/*counter权限设置开始*/
const AUTH_MEMBER_REGISTER = "member_register";
const AUTH_MEMBER_DOCUMENT_COLLECTION = "member_documentCollection";
const AUTH_MEMBER_FINGERPRINT_COLLECTION = "member_fingerprintCollection";
const AUTH_MEMBER_LOAN = "member_loan";
const AUTH_MEMBER_DEPOSIT = "member_deposit";
const AUTH_MEMBER_WITHDRAWAL = "member_withdrawal";
const AUTH_MEMBER_PROFILE = "member_profile";
const AUTH_COMPANY_INDEX = "company_index";
const AUTH_SERVICE_REQUEST_LOAN = "service_requestLoan";
const AUTH_SERVICE_CURRENCY_EXCHANGE = "service_currencyExchange";
const AUTH_MORTGAGE_INDEX = "mortgage_index";
const AUTH_CASH_CASH_ON_HAND = "cash_cashOnHand";
const AUTH_CASH_CASH_IN_VAULT = "cash_cashInVault";
/*counter权限设置结束*/
}
interface IauthGroup
{
function getGroupKey();
function getGroupName();
function getAuthList();
}
class authGroup_home implements IauthGroup
{
function getGroupKey()
{
return "home";//menu的key值
}
function getGroupName()
{
return "home";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_HOME_MONITOR
);
}
}
class authGroup_user implements IauthGroup
{
function getGroupKey()
{
return "user";//menu的key值
}
function getGroupName()
{
return "user";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_USER_BRANCH,
// authEnum::AUTH_USER_DEPARTMENT,
authEnum::AUTH_USER_ROLE,
authEnum::AUTH_USER_USER,
authEnum::AUTH_USER_LOG,
authEnum::AUTH_USER_POINT_EVENT,
authEnum::AUTH_USER_POINT_PERIOD,
authEnum::AUTH_USER_DEPARTMENT_POINT,
);
}
}
class authGroup_client implements IauthGroup
{
function getGroupKey()
{
return "client";//menu的key值
}
function getGroupName()
{
return "client";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_CLIENT_CLIENT,
authEnum::AUTH_CLIENT_CERIFICATION,
authEnum::AUTH_CLIENT_BLACK_LIST,
authEnum::AUTH_CLIENT_GRADE,
);
}
}
class authGroup_partner implements IauthGroup
{
function getGroupKey()
{
return "partner";//menu的key值
}
function getGroupName()
{
return "partner";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_PARTNER_BANK,
authEnum::AUTH_PARTNER_DEALER,
);
}
}
class authGroup_loan implements IauthGroup
{
function getGroupKey()
{
return "loan";//menu的key值
}
function getGroupName()
{
return "loan";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_LOAN_PRODUCT,
authEnum::AUTH_LOAN_CREDIT,
authEnum::AUTH_LOAN_APPROVAL,
authEnum::AUTH_LOAN_APPLY,
authEnum::AUTH_LOAN_REQUEST_TO_PREPAYMENT,
authEnum::AUTH_LOAN_REQUEST_TO_REPAYMENT,
authEnum::AUTH_LOAN_CONTRACT,
authEnum::AUTH_LOAN_WRITE_OFF,
authEnum::AUTH_LOAN_OVERDUE,
authEnum::AUTH_LOAN_DEDUCTING_PENALTIES,
);
}
}
class authGroup_insurance implements IauthGroup
{
function getGroupKey()
{
return "insurance";//menu的key值
}
function getGroupName()
{
return "insurance";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_INSURANCE_PRODUCT,
authEnum::AUTH_INSURANCE_CONTRACT,
);
}
}
class authGroup_setting implements IauthGroup
{
function getGroupKey()
{
return "setting";//menu的key值
}
function getGroupName()
{
return "setting";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_SETTING_COMPANY_INFO,
authEnum::AUTH_SETTING_CREDIT_LEVEL,
authEnum::AUTH_SETTING_CREDIT_PROCESS,
authEnum::AUTH_SETTING_GLOBAL,
authEnum::AUTH_REGION_LIST,
// authEnum::AUTH_SETTING_SYSTEM_DEFINE,
authEnum::AUTH_SETTING_SHORT_CODE,
authEnum::AUTH_SETTING_CODING_RULE,
authEnum::AUTH_SETTING_RESET_SYSTEM
);
}
}
class authGroup_report implements IauthGroup
{
function getGroupKey()
{
return "report";//menu的key值
}
function getGroupName()
{
return "report";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_REPORT_OVERVIEW,
authEnum::AUTH_REPORT_CLIENT_LIST,
authEnum::AUTH_REPORT_CONTRACT_LIST,
authEnum::AUTH_REPORT_CREDIT_LIST,
authEnum::AUTH_REPORT_TODAY_REPORT,
authEnum::AUTH_REPORT_LOAN_LIST,
authEnum::AUTH_REPORT_REPAYMENT_LIST,
authEnum::AUTH_REPORT_ASSET_LIABILITY,
authEnum::AUTH_REPORT_PROFIT_REPORT,
);
}
}
class authGroup_editor implements IauthGroup
{
function getGroupKey()
{
return "editor";//menu的key值
}
function getGroupName()
{
return "editor";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_EDITOR_HELP,
);
}
}
class authGroup_tools implements IauthGroup
{
function getGroupKey()
{
return "tools";//menu的key值
}
function getGroupName()
{
return "tools";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_TOOLS_CALCULATOR,
authEnum::AUTH_TOOLS_SMS,
);
}
}
class authGroup_financial implements IauthGroup
{
function getGroupKey()
{
return "financial";//menu的key值
}
function getGroupName()
{
return "financial";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_FINANCIAL_BANK_ACCOUNT,
authEnum::AUTH_FINANCIAL_EXCHANGE_RATE
);
}
}
class authGroup_dev implements IauthGroup
{
function getGroupKey()
{
return "dev";//menu的key值
}
function getGroupName()
{
return "dev";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_DEV_APP_VERSION,
authEnum::AUTH_DEV_FUNCTION_SWITCH,
authEnum::AUTH_DEV_RESET_PASSWORD,
);
}
}
/*counter 开始*/
class authGroup_counter_member implements IauthGroup
{
function getGroupKey()
{
return "member";//menu的key值
}
function getGroupName()
{
return "member";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_MEMBER_REGISTER,
authEnum::AUTH_MEMBER_DOCUMENT_COLLECTION,
authEnum::AUTH_MEMBER_FINGERPRINT_COLLECTION,
authEnum::AUTH_MEMBER_LOAN,
authEnum::AUTH_MEMBER_DEPOSIT,
authEnum::AUTH_MEMBER_WITHDRAWAL,
authEnum::AUTH_MEMBER_PROFILE,
);
}
}
class authGroup_counter_company implements IauthGroup
{
function getGroupKey()
{
return "company";//menu的key值
}
function getGroupName()
{
return "company";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_COMPANY_INDEX,
);
}
}
class authGroup_counter_service implements IauthGroup
{
function getGroupKey()
{
return "service";//menu的key值
}
function getGroupName()
{
return "service";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_SERVICE_REQUEST_LOAN,
authEnum::AUTH_SERVICE_CURRENCY_EXCHANGE,
);
}
}
class authGroup_counter_mortgage implements IauthGroup
{
function getGroupKey()
{
return "mortgage";//menu的key值
}
function getGroupName()
{
return "mortgage";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_MORTGAGE_INDEX,
);
}
}
class authGroup_counter_cash_on_hand implements IauthGroup
{
function getGroupKey()
{
return "cash_on_hand";//menu的key值
}
function getGroupName()
{
return "cash_on_hand";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_CASH_CASH_ON_HAND,
);
}
}
class authGroup_counter_cash_in_vault implements IauthGroup
{
function getGroupKey()
{
return "cash_in_vault";//menu的key值
}
function getGroupName()
{
return "cash_in_vault";//取语言包
}
function getAuthList()
{
return array(
authEnum::AUTH_CASH_CASH_IN_VAULT,
);
}
}
/*counter 结束*/
<file_sep>/framework/weixin_baike/backoffice/control/client.php
<?php
class clientControl extends baseControl{
public function __construct(){
parent::__construct();
Language::read('certification');
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "User List");
$verify_field = enum_langClass::getCertificationTypeEnumLang();
Tpl::output("verify_field", $verify_field);
Tpl::setDir("client");
}
public function clientOp(){
Tpl::showPage("client");
}
public function getLoanBalance($uid = 0){
$r = new ormReader();
$sql1 = "select contract_id,sum(receivable_principal) as count from loan_installment_scheme where state != ".schemaStateTypeEnum::CREATE." and state != ".schemaStateTypeEnum::COMPLETE." GROUP BY contract_id";
$rows = $r->getRows($sql1);
$sum_arr = array();
foreach ($rows as $key => $value) {
$sum_arr[$value['contract_id']] = $value['count'];
}
$sql2 = "SELECT uid,account_id from loan_contract";
if($uid){
$sql2 = "SELECT uid,account_id from loan_contract where account_id = ".$uid;
}
$rows2 = $r->getRows($sql2);
$acc_loan_balance = array();
foreach ($rows2 as $key => $value) {
if($acc_loan_balance[$value['account_id']]){
$acc_loan_balance[$value['account_id']]['sum'] += $sum_arr[$value['uid']];
}else{
$acc_loan_balance[$value['account_id']]['sum'] = $sum_arr[$value['uid']];
}
}
return $acc_loan_balance;
}
public function getClientListOp($p){
$r = new ormReader();
$sql = "SELECT loan.*,client.uid as member_id,client.obj_guid as o_guid,client.display_name,client.alias_name,client.phone_id,client.email,client.create_time FROM client_member as client left join loan_account as loan on loan.obj_guid = client.obj_guid where 1 = 1 ";
if ($p['member_item']) {
$sql .= " and loan.obj_guid = " . $p['member_item'];
}
if ($p['member_name']) {
$sql .= ' and client.display_name like "%' . $p['member_name'] . '%"';
}
if ($p['ck']) {
$sql .= ' and client.create_time > "'.date("Y-m-d").'"';
}
if ($p['phone']) {
$sql .= " and client.phone_id = " . $p['phone'];
}
$sql .= " ORDER BY client.create_time desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("client.list");
}
public function clientDetailOp(){
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
$m_client_black = M('client_black');
$contract_info = array();
$member_id = intval($p['uid']);
if( !$member_id ){
showMessage('Client Error');
}
$sql = "SELECT client.*,loan.uid as loan_uid FROM client_member as client left join loan_account as loan on loan.obj_guid = client.obj_guid where client.uid = " . $p['uid'];
$data = $r->getRow($sql);
if(!$data){
showMessage('Client Error','','html','error');
}
$loan_uid = $data['loan_uid'] ? : 0;
$sql2 = "SELECT contract.*,product.product_code,product.product_name,product.product_description FROM loan_contract as contract left join loan_product as product on contract.product_id = product.uid where contract.account_id = ".$loan_uid." order by contract.uid desc";
$contracts = $r->getRows($sql2);
$sql2 = "SELECT contract.* FROM insurance_contract as contract left join insurance_account as account on contract.account_id = account.uid where account.obj_guid = ".$data['obj_guid']." order by contract.uid desc";
$insurance_contracts = $r->getRows($sql2);
//*这是request loan的次数
$sql = "SELECT count(uid) as count from loan_apply where member_id = ".$p['uid'];
$count = $r->getRow($sql);
$loan_count = $data['count'];
$contract_info['all_enquiries'] = $loan_count;
//*这是第一次发放贷款的日期
$sql = "select c.uid,d.create_time from loan_contract c LEFT JOIN loan_disbursement d on c.uid = d.contract_id where c.account_id = ".$loan_uid." ORDER BY d.create_time desc limit 1";
$count = $r->getRow($sql);
$create_time = $data['create_time'];
$contract_info['earliest_loan_issue_date'] = $create_time;
$loan_summary = memberClass::getMemberLoanSummary($p['uid'], 1);
$guarantee_loan_summary = memberClass::getMemberLoanSummary($p['uid'], 2);
Tpl::output("contract_info", $contract_info);
Tpl::output("loan_summary", $loan_summary->DATA);
Tpl::output("guarantee_loan_summary", $guarantee_loan_summary->DATA);
$cert_type_lang = enum_langClass::getCertificationTypeEnumLang();
Tpl::output('cert_type_lang',$cert_type_lang);
$re = memberClass::getMemberSimpleCertResult($member_id);
if (!$re->STS) {
showMessage('Error: ' . $re->MSG);
}
$verifys = $re->DATA;
$credit_info = memberClass::getCreditBalance(intval($p['uid']));
Tpl::output("detail", $data);
Tpl::output('credit_info',$credit_info);
Tpl::output("verifys", $verifys);
Tpl::output("contracts", $contracts);
Tpl::output("insurance_contracts", $insurance_contracts);
$sql = "select uid, type, list from client_black";
$types = $r->getRows($sql);
foreach ($types as $key => $value) {
$members = $value['list'];
$members = $members ? explode(',', $members) : array();
$types[$key]['check'] = false;
if(in_array($p['uid'], $members)){
$types[$key]['check'] = true;
}
unset($types[$key]['list']);
}
Tpl::output("black", $types);
if($data['id_address1']){
$arr = array($data['id_address1'],$data['id_address2'],$data['id_address3'],$data['id_address4']);
$adds = implode(',',$arr)?:0;
$sql = "select uid,node_text,node_text_alias from core_tree where uid in(".$adds.")";
$address = $r->getRows($sql);
$addr = array();
foreach ($address as $key => $value) {
$addr[$value['uid']] = $value;
}
Tpl::output("addr", $addr);
}
Tpl::showPage("client.detail");
}
public function editClientBlackFieldOp($p){
$p = array_merge(array(), $_GET, $_POST);
$m_client_black = M('client_black');
$data = $m_client_black->getBlackInfo($p['obj_guid']);
if($data->STS){
$param = json_decode($data->DATA['type'], true);
foreach ($param as $key => $value) {
if($key == $p['filed']){
$param[$key] = $p['state'];
}
}
$param['obj_guid'] = $p['obj_guid'];
$param['auditor_id'] = $this->user_id;
$param['auditor_name'] = $this->user_name;
$rt = $m_client_black->updateBlack($param);
}else{
$param = array('t1'=> 0, 't2'=> 0, 't3'=> 0, 't4' => 0, 't5' => 0);
foreach ($param as $key => $value) {
if($key == $p['filed']){
$param[$key] = $p['state'];
}
}
$param['obj_guid'] = $p['obj_guid'];
$param['auditor_id'] = $this->user_id;
$param['auditor_name'] = $this->user_name;
$rt = $m_client_black->insertBlack($param);
}
if ($rt->STS) {
return new result(true, 'Edit Success!');
} else {
return new result(false, 'Invalid Member!');
}
}
public function cerificationOp(){
Tpl::showPage("cerification");
}
public function getCerificationListOp($p){
$r = new ormReader();
/*$sql = "select max(uid) as uid,member_id,cert_type from member_verify_cert group by member_id,cert_type";
$ids = $r->getRows($sql);
// 处理无数据的bug
if( count($ids) < 1 ){
$ids = array(0);
}
$ids = array_column($ids, 'uid');
$ids = implode(',', $ids)?:0;
$sql1 = "select verify.*,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid WHERE verify.uid in (".$ids.") ";
*/
// 不分组了,家庭关系有多条
$sql1 = "select verify.*,member.login_code,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid where 1=1 ";
if ($p['cert_type'] != 0) {
$sql1 .= " and verify.cert_type = '".$p['cert_type']."' " ;
}
if ($p['verify_state'] == 1) {
$sql1 .= " and (verify.verify_state = 0 or verify.verify_state = -1 ) ";
}
if ($p['verify_state'] == 10) {
$sql1 .= " and verify.verify_state = " . $p['verify_state'];
}
if ($p['verify_state'] == 100) {
$sql1 .= " and verify.verify_state = " . $p['verify_state'];
}
if ($p['member_name']) {
$name = ' (member.login_code like "%' . $p['member_name'] . '%" )';
$sql1 .= " and " . $name;
}
$sql1 .= " ORDER BY verify.uid desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql1, $pageNumber, $pageSize);
$rows = $data->rows;
$list = array();
// 取图片
foreach( $rows as $row ){
$sql = "select * from member_verify_cert_image where cert_id='".$row['uid']."'";
$images = $r->getRows($sql);
$row['cert_images'] = $images;
$list[] = $row;
}
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $list,
"total" => $total,
"cur_uid" => $this->user_id,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("cerification.list");
}
public function cerificationDetailOp(){
$sample_images = global_settingClass::getCertSampleImage();
Tpl::output('cert_sample_images',$sample_images);
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
$m_member_verify_cert = M('member_verify_cert');
$row = $m_member_verify_cert->getRow(array('uid' => $p['uid']));
$data = $row->toArray();
$ID = $m_member_verify_cert->getRow(array('member_id' => $data['member_id'], 'cert_type' => certificationTypeEnum::ID, 'verify_state' => 10));
if( $data['cert_type'] == certificationTypeEnum::FAIMILYBOOK && !$ID ){
showMessage('Please verify the identity card information', getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
$sql = "select * from member_verify_cert where uid != ".$data['uid']." and member_id = ".$data['member_id']." and cert_type = ".$data['cert_type']." order by uid desc";
$history = $r->getRows($sql);
// image
foreach( $history as $k=>$v ){
$sql = "select * from member_verify_cert_image where cert_id='".$v['uid']."'";
$images = $r->getRows($sql);
$v['cert_images'] = $images;
$history[$k] = $v;
}
if ($row['verify_state'] == -1) {
// 用row,可及时更新状态
// 超时放开,让别人可审 1小时
if( ( strtotime($row['auditor_time']) + 3600 ) < time() ){
$row ->verify_state = -1;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->auditor_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
} elseif ($row['verify_state'] == 0) {
$row ->verify_state = -1;
$row->auditor_id = $this->user_id;
$row->auditor_name = $this->user_name;
$row->auditor_time = Now();
$up = $row->update();
if (!$up->STS) {
showMessage($up->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
$sql = "select verify.*,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid where verify.uid = " . $p['uid'];
$info = $r->getRow($sql);
// image
$sql = "select * from member_verify_cert_image where cert_id='".$info['uid']."'";
$images = $r->getRows($sql);
$info['cert_images'] = $images;
Tpl::output('info', $info);
if($ID){
Tpl::output('IDInfo', $ID->toArray());
}
Tpl::output('history', $history);
$lock = false;
if ( $row['verify_state'] && $this->user_id != $row['auditor_id']) {
//审核中
$lock = true;
}
Tpl::output('lock', $lock);
$cert_type = $row->cert_type;
switch( $cert_type ){
case certificationTypeEnum::MOTORBIKE:
case certificationTypeEnum::RESIDENT_BOOK :
case certificationTypeEnum::ID :
case certificationTypeEnum::PASSPORT :
case certificationTypeEnum::FAIMILYBOOK :
case certificationTypeEnum::HOUSE :
case certificationTypeEnum::CAR :
case certificationTypeEnum::LAND :
Tpl::showPage("cerification.detail");
break;
case certificationTypeEnum::WORK_CERTIFICATION :
$m_work = new member_workModel();
$extend_info = $m_work->getRow(array(
'cert_id' => $row->uid
));
Tpl::output('extend_info',$extend_info);
Tpl::showPage('certification.work.detail');
break;
default:
showMessage('Not supported type', getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
public function cerifycationConfirmOp(){
$p = array_merge(array(), $_GET, $_POST);
$obj_validate = new Validate();
$obj_validate->deliverparam = $p;
$error = $obj_validate->validate();
if ($error != ''){
showMessage($error,'','html','error');
}
$m_member_verify_cert = M('member_verify_cert');
$row = $m_member_verify_cert->getRow(array('uid' => $p['uid']));
if (!$row->toArray()) {
return new result(false, 'Invalid Id!');
}
$data = $row->toArray();
$cert_type = $row->cert_type;
// 审核过的不会再审核
if( $row->verify_state == certStateEnum::PASS || $row->verify_state == certStateEnum::NOT_PASS ){
Tpl::showPage("cerification");
}
switch( $cert_type ){
case certificationTypeEnum::HOUSE :
case certificationTypeEnum::CAR :
case certificationTypeEnum::LAND :
case certificationTypeEnum::MOTORBIKE:
// 资产的审核
// 更新状态
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$p['insert'] = false;
$ret = $m_member_verify_cert->updateState($p);
if( !$ret->STS ){
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
if( $p['verify_state'] == certStateEnum::PASS ){
$asset_state = assetStateEnum::CERTIFIED;
}else{
$asset_state = assetStateEnum::INVALID;
}
// 更新资产认证状态
$m_asset = new member_assetsModel();
$asset = $m_asset->getRow(array(
'cert_id' => $row['uid']
));
if( $asset ){
$asset->asset_state = $asset_state;
$asset->update_time = Now();
$up = $asset->update();
if( !$up->STS ){
showMessage('Update asset state fail',getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
Tpl::showPage("cerification");
break;
case certificationTypeEnum::RESIDENT_BOOK :
case certificationTypeEnum::ID :
case certificationTypeEnum::PASSPORT :
case certificationTypeEnum::FAIMILYBOOK :
//更新原来通过的为过期状态
/*$sql = "update member_verify_cert set verify_state='".certStateEnum::EXPIRED."' where member_id='".$row['member_id']."'
and cert_type='".$row['cert_type']."' and verify_state='".certStateEnum::PASS."' ";
$up = $m_member_verify_cert->conn->execute($sql);
if( !$up->STS ){
showMessage('Update history cert fail',getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}*/
// 更新状态
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
if( $cert_type == certificationTypeEnum::ID ){
$p['insert'] = true;
$ret = $m_member_verify_cert->updateState($p);
if( !$ret->STS ){
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
if( $p['verify_state'] == certStateEnum::PASS ){
// 修改会员表身份证信息
$m_member = new memberModel();
$member = $m_member->getRow($row->member_id);
if( !$member ){
showMessage('Error member',getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
$id_en_name_json = json_encode(array('family_name'=>$p['en_family_name'],'given_name'=>$p['en_given_name']));
$id_kh_name_json = json_encode(array('family_name'=>$p['kh_family_name'],'given_name'=>$p['kh_given_name']));
$member->initials = strtoupper(substr($p['en_family_name'],0,1));
$member->display_name = $p['en_family_name'].' '.$p['en_given_name'];
$member->kh_display_name = $p['kh_family_name'].' '.$p['kh_given_name'];
$member->id_sn = $row['cert_sn'];
$member->id_type = $p['id_type'];
$member->nationality = $p['nationality'];
$member->id_en_name_json = $id_en_name_json;
$member->id_kh_name_json = $id_kh_name_json;
$member->id_address1 = $p['id_address1'];
$member->id_address2 = $p['id_address2'];
$member->id_address3 = $p['id_address3'];
$member->id_address4 = $p['id_address4'];
$member->id_expire_time = $p['cert_expire_time'];
$up = $member->update();
if( !$up->STS ){
showMessage('Update member ID sn fail',getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
}else{
$p['insert'] = false;
$ret = $m_member_verify_cert->updateState($p);
if( !$ret->STS ){
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
Tpl::showPage("cerification");
break;
case certificationTypeEnum::WORK_CERTIFICATION :
$p['insert'] = false;
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
//更新原来通过的为过期状态
/*$sql = "update member_verify_cert set verify_state='".certStateEnum::EXPIRED."' where member_id='".$row['member_id']."'
and cert_type='".$row['cert_type']."' and verify_state='".certStateEnum::PASS."' ";
$up = $m_member_verify_cert->conn->execute($sql);
if( !$up->STS ){
showMessage('Update history cert fail',getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}*/
$m_work = new member_workModel();
$extend_info = $m_work->getRow(array(
'cert_id' => $row->uid
));
// 更新扩展信息
// 当前只能有一条合法的,其余的更新为历史
/*$sql = "update member_work set state='".workStateStateEnum::HISTORY."' where member_id='".$extend_info->member_id."' and state='".workStateStateEnum::VALID."' ";
$up = $m_work->conn->execute($sql);
if (!$up->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}*/
if( $p['verify_state'] == certStateEnum::PASS ){
$work_state = workStateStateEnum::VALID;
}else{
$work_state = workStateStateEnum::INVALID;
}
if( $extend_info ){
$extend_info->state = $work_state;
$up = $extend_info->update();
if (!$up->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
// 如果通过
if( $p['verify_state'] == certStateEnum::PASS ){
// 如果是政府员工,更新member表
if( $extend_info->is_government ){
$m_member = new memberModel();
$member = $m_member->getRow($extend_info->member_id);
if( $member ){
$member->is_government = 1;
$up = $member->update();
if (!$up->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
}
}
Tpl::showPage("cerification");
break;
/*case certificationTypeEnum::FAMILY_RELATIONSHIP :
$p['insert'] = false;
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
// 更新扩展表信息
if( $p['verify_state'] == certStateEnum::PASS ){
$state = memberFamilyStateEnum::APPROVAL;
}else{
$state = memberFamilyStateEnum::INVALID;
}
$m_family = new member_familyModel();
$extend_info = $m_family->getRow(array(
'cert_id' => $row->uid
));
if( $extend_info ){
$extend_info->relation_cert_sn = $p['relation_cert_sn'];
$extend_info->relation_state = $state;
$up = $extend_info->update();
if (!$up->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
Tpl::showPage("cerification");
break;*/
default:
showMessage('Not supported type', getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
}
}
public function cerifycationCancelOp(){
$p = array_merge(array(), $_GET, $_POST);
$m_member_verify_cert = M('member_verify_cert');
$p['verify_state'] = 0;
$p['auditor_id'] = 0;
$p['auditor_name'] = '';
$ret = $m_member_verify_cert->updateState($p);
if (!$ret->STS) {
showMessage($ret->MSG, getUrl('client', 'cerification', array(), false, BACK_OFFICE_SITE_URL));
} else {
Tpl::showPage("cerification");
}
}
public function blackListOp(){
$r = new ormReader();
$sql = "select * from client_black";
$types = $r->getRows($sql);
foreach ($types as $key => $value) {
$types[$key]['child'] = '';
if($value['list']){
$types[$key]['count'] = count(explode(',',$value['list']));
}
}
Tpl::output('types', $types);
Tpl::showPage("black");
}
public function getBlackClientListOp($p){
$r = new ormReader();
$sql = "select uid,display_name from client_member";
$list = $r->getRows($sql);
$sql1 = "select * from client_black where type = ".$p['type'];
$black = $r->getRow($sql1);
$members = $black['list'];
$members = $members ? explode(',', $members) : array();
foreach ($list as $key => $value) {
$list[$key]['check'] = false;
if(in_array($value['uid'], $members)){
$list[$key]['check'] = true;
}
}
return new result(true, '', $list);
}
public function getBlackListOp($p){
$r = new ormReader();
$sql = "select member.*,black.type as black from client_member as member left join client_black as black on member.obj_guid = black.obj_guid";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
$sql1 = "select * from client_black";
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("black.list");
}
public function addBlackClientOp(){
$p = array_merge(array(), $_GET, $_POST);
Tpl::output('type', $p['type']);
Tpl::showPage("black_add");
}
public function getAddBlackClientOp($p){
$r = new ormReader();
$sql = "select * from client_black where type = ".$p['type'];
$item = $r->getRow($sql);
$ids = $item['list']?:0;
$sql1 = "select uid,obj_guid,display_name,member_icon from client_member WHERE uid not in (".$ids.") ";
if ($p['obj_guid']) {
$sql1 .= " and obj_guid = " . $p['obj_guid'];
}
if ($p['member_name']) {
$sql1 .= ' and display_name like "%' . $p['member_name'] . '%"';
}
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 15;
$data = $r->getPage($sql1, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("black_add.list");
}
public function removeBlackClientOp(){
$p = array_merge(array(), $_GET, $_POST);
Tpl::output('type', $p['type']);
Tpl::showPage("black_remove");
}
public function getRemoveBlackClientOp($p){
$r = new ormReader();
$sql = "select * from client_black where type = ".$p['type'];
$item = $r->getRow($sql);
$ids = $item['list']?:0;
$sql1 = "select uid,obj_guid,display_name,member_icon from client_member WHERE uid in (".$ids.") ";
if ($p['obj_guid']) {
$sql1 .= " and obj_guid = " . $p['obj_guid'];
}
if ($p['member_name']) {
$sql1 .= ' and display_name like "%' . $p['member_name'] . '%"';
}
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 15;
$data = $r->getPage($sql1, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
Tpl::showPage("black_remove.list");
}
public function updateBlackClientListOp($p){
$m_client_black = M('client_black');
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$rt = $m_client_black->updateBlack($p);
if ($rt->STS) {
return new result(true);
} else {
return new result(false);
}
}
public function updateBlackClientTypeOp($p){
$m_client_black = M('client_black');
$row = $m_client_black->getRow(array('type' => $p['type']));
$members = $row?$row->toArray()['list']:'';
$members = $members ? explode(',', $members) : array();
$index = array_search($p['uid'], $members);
if($p['state']){//添加到黑名单
if($index === false){
array_push($members, $p['uid']);
}else{
return new result(true);
}
}else{//移出黑名单
if($index !== false){
unset($members[$index]);
}else{
return new result(true);
}
}
$list = implode(',', $members);
$p['list'] = $list;
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
$rt = $m_client_black->updateBlack($p);
if ($rt->STS) {
return new result(true);
} else {
return new result(false);
}
}
public function editBlackOp(){
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
$m_client_member = M('client_member');
$m_client_black = M('client_black');
if ($p['form_submit'] == 'ok') {
unset($p['form_submit']);
unset($p['op']);
unset($p['act']);
$data = $m_client_black->getBlackInfo($p['obj_guid']);
$p['auditor_id'] = $this->user_id;
$p['auditor_name'] = $this->user_name;
if($data->STS){
$rt = $m_client_black->updateBlack($p);
}else{
$rt = $m_client_black->insertBlack($p);
}
if ($rt->STS) {
showMessage($rt->MSG, getUrl('client', 'blackList', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->MSG, getUrl('client', 'editBlack', $p, false, BACK_OFFICE_SITE_URL));
}
}else{
$row = $m_client_member->getRow(array('uid' => $p['uid']));
$data = $row->toArray();
if (!$data) {
showMessage('Client Not Exist', getUrl('loan', 'credit', array(), false, BACK_OFFICE_SITE_URL));
}
$sql = "SELECT loan.*,client.display_name,client.alias_name,client.phone_id,client.email FROM loan_account as loan left join client_member as client on loan.obj_guid = client.obj_guid where loan.obj_guid = '" . $data['obj_guid'] . "'";
$info = $r->getRow($sql);
Tpl::output('info', $info);
$blacks = $m_client_black->getBlackInfo($data['obj_guid']);
$blacks = $blacks->DATA;
$black = json_decode($blacks['type'], true);
Tpl::output('black', $black);
Tpl::showPage("black.edit");
}
}
public function creditReportOp(){
$r = new ormReader();
$p = array_merge(array(), $_GET, $_POST);
if ($p['obj_guid']) {
$sql = "SELECT client.*,loan.uid as loan_uid,loan.credit FROM loan_account as loan left join client_member as client on loan.obj_guid = client.obj_guid where client.obj_guid = " . $p['obj_guid'];
$data = $r->getRow($sql);
$sql1 = "SELECT * FROM member_verify_cert where member_id = " . $data['uid'];
$rows = $r->getRows($sql1);
$sql2 = "SELECT * FROM loan_approval where obj_guid = " . $data['obj_guid'] . " ORDER BY uid desc";
$credit_list = $r->getRows($sql2);
$sql3 = "SELECT repayment.uid,repayment.state FROM loan_contract as contract right JOIN loan_repayment as repayment on contract.uid = repayment.contract_id"
." where contract.account_id = ".$data['loan_uid']." and repayment.state = 100";
$remayment_list = $r->getRows($sql3);
$sql4 = "SELECT scheme.uid FROM loan_contract as contract left JOIN loan_installment_scheme as scheme on contract.uid = scheme.contract_id"
." where contract.account_id = ".$data['loan_uid']." and contract.state >= 20 and scheme.state != 100 and '".date("Y-m-d H:m:s")."' > scheme.penalty_start_date";
$breach_list = $r->getRows($sql4);
}
$verifys = array();
foreach ($rows as $key => $value) {
$verifys[$value['cert_type']] = $value;
}
Tpl::output("detail", $data);
Tpl::output("verifys_list", $rows);
Tpl::output("verifys", $verifys);
Tpl::output('credit_list', $credit_list);
Tpl::output('remayment_count', count($remayment_list));
Tpl::output('default_count', count($breach_list));
Tpl::showPage("client.report");
}
public function gradeOp(){
$r = new ormReader();
$sql = "select * from member_grade";
$rows = $r->getRows($sql);
Tpl::output('list', $rows);
Tpl::showPage("grade");
}
public function addGradeOp(){
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$m_member_grade = M('member_grade');
unset($p['form_submit']);
unset($p['op']);
unset($p['act']);
$p['creator_id'] = $this->user_id;
$p['creator_name'] = $this->user_name;
$rt = $m_member_grade->insertGrade($p);
if ($rt->STS) {
showMessage($rt->MSG, getUrl('client', 'grade', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->MSG, getUrl('client', 'grade', $p, false, BACK_OFFICE_SITE_URL));
}
}else{
Tpl::showPage("grade.add");
}
}
}
<file_sep>/framework/weixin_baike/api/control/credit_loan.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/28
* Time: 10:36
*/
class credit_loanControl extends bank_apiControl
{
public function calculatorOp()
{
$params = array_merge(array(),$_GET,$_POST);
$loan_amount = $params['amount'];
if( $loan_amount < 100 ){
return new result(false,'Amount not supported',null,errorCodesEnum::NOT_SUPPORTED);
}
$loan_time = intval($params['loan_period']); // 单位月
if( $loan_time < 1 ){
return new result(false,'Time not supported',null,errorCodesEnum::NOT_SUPPORTED);
}
$year_interest = $params['interest']/100;
if( $year_interest <= 0 ){
return new result(false,'Interest not supported',null,errorCodesEnum::NOT_SUPPORTED);
}
$payment_type = $params['repayment_type'];
switch( $payment_type ){
case interestPaymentEnum::FIXED_PRINCIPAL :
$schema = loan_calculatorClass::fixed_principle_getPaymentSchemaByFixInterest($loan_amount,$year_interest/12,$loan_time,0);
break;
case interestPaymentEnum::ANNUITY_SCHEME :
$schema = loan_calculatorClass::annuity_schema_getPaymentSchemaByFixInterest($loan_amount,$year_interest/12,$loan_time,0);
break;
case interestPaymentEnum::SINGLE_REPAYMENT :
$schema = loan_calculatorClass::single_repayment_getPaymentSchemaByFixInterest($loan_amount,$year_interest/12,$loan_time,0);
break;
case interestPaymentEnum::FLAT_INTEREST :
$schema = loan_calculatorClass::flat_interest_getPaymentSchemaByFixInterest($loan_amount,$year_interest/12,$loan_time,0);
break;
case interestPaymentEnum::BALLOON_INTEREST :
$schema = loan_calculatorClass::balloon_interest_getPaymentSchemaByFixInterest($loan_amount,$year_interest/12,$loan_time,0);
break;
default:
return new result(false,'Not supported payment type',errorCodesEnum::NOT_SUPPORTED);
}
if( !$schema->STS ){
return new result(false,'Calculate fail',null,errorCodesEnum::UNEXPECTED_DATA);
}
$pay_schema = $schema->DATA;
return new result(true,'success',array(
'total_summation' => array(
'payment_period' => ($pay_schema['payment_total']['total_period_pay']),
'total_interest' => ($pay_schema['payment_total']['total_interest']),
'payment_total' => ($pay_schema['payment_total']['total_payment']),
),
'payment_schema' => $pay_schema['payment_schema']
));
}
public function getCreditAndCertListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = $params = array_merge(array(),$_GET,$_POST);
$member_id = intval($params['member_id']);
$credit = memberClass::getCreditBalance($member_id);
$creditLoan = new credit_loanClass();
$re = $creditLoan->creditLoanMemberCertDetail($params);
if( !$re->STS ){
return $re;
}
$product_id = $re->DATA['product_id'];
$cert_list = $re->DATA['cert_list'];
return new result(true,'success',array(
'credit_info' => $credit,
'product_id' => $product_id,
'cert_list' => $cert_list
));
}
public function loanPreviewOp()
{
$params = $params = array_merge(array(),$_GET,$_POST);
$creditLoan = new credit_loanClass();
$re = $creditLoan->loanPreview($params);
return $re;
}
public function getLoanProposeOp()
{
$m = new core_definitionModel();
$rows = $m->select(array(
'category' => 'loan_use'
));
return new result(true,'success',$rows);
}
/** 信用贷提现(合同创建)
* @return result
*/
public function creditLoanWithdrawOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = $params = array_merge(array(),$_GET,$_POST);
$creditLoan = new credit_loanClass();
$re = $creditLoan->withdraw($params);
return $re;
}
/** 创建合同API 暂时不使用
* @return result
*/
public function createContractOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
set_time_limit(120);
$params = $params = array_merge(array(),$_GET,$_POST);
$creditLoan = new credit_loanClass();
$re = $creditLoan->createContract($params);
return $re;
}
/** 信用贷合同确认
* @return result
*/
public function contractConfirmOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = $params = array_merge(array(),$_GET,$_POST);
$contract_id = $params['contract_id'];
if( !$contract_id ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$creditLoan = new credit_loanClass();
$re = $creditLoan->confirmContract($contract_id);
return $re;
}
/** 获取绑定的保险产品
* @return result
*/
public function getLoanBindInsuranceListOp()
{
$params = $params = array_merge(array(),$_GET,$_POST);
$creditLoan = new credit_loanClass();
$re = $creditLoan->getBindInsuranceProduct($params);
return $re;
}
public function getCreditLoanLevelOp()
{
$params = $params = array_merge(array(),$_GET,$_POST);
$type = $params['level_type'];
switch( $type ){
case 0:
$level_type = creditLevelTypeEnum::MEMBER;
break;
case 1:
$level_type = creditLevelTypeEnum::MERCHANT;
break;
default:
$level_type = 'all';
}
$list = credit_loanClass::getCreditLevelList($level_type);
return new result(true,'success',$list);
}
public function creditLimitCalculatorOp()
{
$params = $params = array_merge(array(),$_GET,$_POST);
$re = loan_baseClass::creditLimitCalculator($params);
return $re;
}
public function creditLoanIndexOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$param = array_merge(array(),$_GET,$_POST);
$member_id = $param['member_id'];
$credit_balance = memberClass::getCreditBalance($member_id);
$product_id = 0;
$credit_loan_product = credit_loanClass::getProductInfo();
if( $credit_loan_product ){
$product_id = $credit_loan_product['uid'];
//return new result(false,'No release product',null,errorCodesEnum::NO_LOAN_PRODUCT);
}
// 获取最低月利率
$m_rate = new loan_product_size_rateModel();
$rate_list = $m_rate->getRows(array(
'product_id' => $product_id
));
$new_value = array();
foreach( $rate_list as $rate ){
$interest_rate = $rate['interest_rate'];
$interest_re = loan_baseClass::interestRateConversion($interest_rate,$rate['interest_rate_unit'],interestRatePeriodEnum::MONTHLY);
if( $interest_re->STS ){
$interest_rate = $interest_re->DATA;
}
$operate_rate = $rate['operation_fee'];
$operate_re = loan_baseClass::interestRateConversion($operate_rate,$rate['operation_fee_unit'],interestRatePeriodEnum::MONTHLY);
if( $operate_re->STS ){
$operate_rate = $operate_re->DATA;
}
$new_value[] = $interest_rate+$operate_rate;
}
// 值升序
asort($new_value);
$monthly_min_rate = isset($new_value[0])?$new_value[0]:0.00;
$monthly_min_rate = round($monthly_min_rate,2);
$monthly_min_rate_desc = $monthly_min_rate.'%';
// 获取会员下期应还款
$next_schema = memberClass::getMemberLoanNextRepaymentSchema($member_id);
if( $next_schema ){
$next_repayment_amount = $next_schema['amount']-$next_schema['actual_payment_amount'];
$next_schema['next_repayment_amount'] = $next_repayment_amount;
}
return new result(true,'success',array(
'product_id' => $product_id,
'credit_info' => $credit_balance,
'monthly_min_rate' => $monthly_min_rate_desc,
'next_repayment_schema' => $next_schema
));
}
public function getProductRateCreditLevelOp()
{
$param = array_merge(array(),$_GET,$_POST);
$rate_id = $param['rate_id'];
$m_rate = new loan_product_size_rateModel();
$rate = $m_rate->getRow($rate_id);
if( !$rate ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$level = credit_loanClass::getCreditLevelByAmount($rate['loan_size_max'],$rate['currency']);
return new result(true,'success',$level);
}
public function getLoanMaxMonthOp()
{
$param = array_merge(array(),$_GET,$_POST);
$product_id = $param['product_id'];
$re = credit_loanClass::getLoanMaxMonthByDefaultWay($product_id);
return $re;
}
}<file_sep>/framework/test/desktop/control/test.php
<?php
class testControl
{
public function test1Op()
{
var_dump($_SESSION);
echo("<br/>");
echo(session_id());
setSessionVar("test1", "123");
echo(" After Set ");
echo(session_id());
echo("<br/>");
var_dump($_SESSION);
}
public function test2Op()
{
var_dump($_SESSION);
}
public function test3Op()
{
var_dump($_SESSION);
echo("<br/>");
echo(session_id());
$_SESSION['test3'] = "aaa";
echo(" After Set ");
echo(session_id());
echo("<br/>");
var_dump($_SESSION);
}
/**
* Add Seven
*/
public function iosTestOp()
{
$key = trim($_REQUEST['key']);
$m_test = M('test');
$row = $m_test->find(array('key' => $key));
if (!$row) {
return new result(false, 'Invalid Key!');
}
$data = array(
'value' => $row['value']
);
return new result(true, '', $data);
}
public function iosAddTestOp()
{
$key = trim($_REQUEST['key']);
$value = trim($_REQUEST['value']);
if (empty($key) || empty($value)) {
return new result(false, 'Param error!');
}
$m_test = M('test');
$row = $m_test->getRow(array('key' => $key));
if ($row) {
return new result(false, 'Key Existed!');
}
$row = $m_test->newRow();
$row->key = $key;
$row->value = $value;
$row->update_time = Now();
$rt = $row->insert();
return $rt;
}
public function iosEditTestOp()
{
$key = trim($_REQUEST['key']);
$value = trim($_REQUEST['value']);
$m_test = M('test');
$row = $m_test->getRow(array('key' => $key));
if (!$row) {
return new result(false, 'Invalid Key!');
}
$row->value = $value;
$row->update_time = Now();
$rt = $row->update();
return $rt;
}
}<file_sep>/framework/weixin_baike/backoffice/control/editor.php
<?php
/**
* Created by PhpStorm.
* User: Seven
* Date: 2018/1/4
* Time: 16:06
*/
class editorControl extends baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Editor");
Tpl::setDir("editor");
}
/**
* 帮助文档
*/
public function helpOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('help');
}
/**
* 获取帮助文档列表
* @param $p
* @return array
*/
public function getHelpListOp($p)
{
$search_text = trim($p['search_text']);
$type = intval($p['type']);
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT * FROM common_cms WHERE (create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "')";
if ($search_text) {
$sql .= ' AND (help_title like "%' . $search_text . '%")';
}
if ($type == 1) {
$sql .= " AND is_system = 0";
} elseif ($type == 2) {
$sql .= " AND is_system = 1";
}
$sql .= ' ORDER BY sort DESC,uid DESC';
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize
);
}
public function editHelpOp()
{
$p = array_merge(array(), $_GET, $_POST);
$uid = intval($_GET['uid']);
$m_common_cms = M('common_cms');
$help = $m_common_cms->find(array('uid' => $uid));
if (!$help) {
showMessage('Invalid Id!');
}
if ($p['form_submit'] == 'ok') {
$update = array(
'uid' => $uid,
'category' => $p['category'],
'help_title' => trim($p['help_title']),
'help_content' => $p['help_content'],
'state' => intval($p['is_show']) ? 100 : 10,
'sort' => intval($p['sort']),
'handler_id' => $this->user_id,
'handler_name' => $this->user_name,
'handle_time' => Now(),
);
$rt = $m_common_cms->update($update);
if ($rt->STS) {
showMessage('Edit Successful!', getUrl('editor', 'help', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->MSG);
}
} else {
$help_category = (new helpCategoryEnum())->Dictionary();
Tpl::output('help_category', $help_category);
Tpl::output('help', $help);
Tpl::showpage('help.edit');
}
}
public function addSystemHelpOp()
{
$p = array_merge(array(), $_GET, $_POST);
if ($p['form_submit'] == 'ok') {
$m_common_cms = M('common_cms');
$category = $p['category'];
$help_title = trim($p['help_title']);
$help_content = $p['help_content'];
$state = intval($p['is_show']) ? 100 : 10;
$sort = intval($p['sort']);
if (!$category || !$help_title || !$help_content) {
showMessage('Invalid Param!');
}
$row = $m_common_cms->newRow();
$row->category = $category;
$row->help_title = $help_title;
$row->help_content = $help_content;
$row->handler_id = $this->user_id;
$row->handler_name = $this->user_name;
$row->create_time = Now();
$row->handle_time = Now();
$row->state = $state;
$row->sort = $sort;
$row->is_system = 1;
$rt = $row->insert();
if ($rt->STS) {
showMessage('Add Successful!', getUrl('editor', 'help', array(), false, BACK_OFFICE_SITE_URL));
} else {
unset($p['form_submit']);
showMessage($rt->MSG, getUrl('editor', 'addSystemHelp', $p, false, BACK_OFFICE_SITE_URL));
}
} else {
$help_category = (new helpCategoryEnum())->Dictionary();
Tpl::output('help_category', $help_category);
Tpl::showpage('help.add');
}
}
}<file_sep>/framework/api_test/apis/microbank/member.is.set.trading.password.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/24
* Time: 17:27
*/
// member.is.set.trading.password
class memberIsSetTradingPasswordApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member is set trading password ";
$this->description = "会员是否设置交易密码";
$this->url = C("bank_api_url") . "/member.is.set.trading.password.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'is_set' => '0 否 1 是',
'verify_amount' => '启用密码金额',
'currency' => '金额货币'
)
);
}
}<file_sep>/framework/weixin_baike/counter/control/member.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/25
* Time: 11:27
*/
class memberControl extends counter_baseControl
{
public function __construct()
{
parent::__construct();
Language::read('member');
Tpl::setDir('member');
Tpl::setLayout('home_layout');
$this->outputSubMenu('member');
}
public function registerOp()
{
Tpl::showPage('register');
}
/**
* 发送验证码
* @param $p
* @return result
*/
public function sendVerifyCodeForRegisterOp($p)
{
$country_code = trim($p['country_code']);
$phone_number = trim($p['phone']);
$format_phone = tools::getFormatPhone($country_code, $phone_number);
$contact_phone = $format_phone['contact_phone'];
// 检查合理性
if (!isPhoneNumber($contact_phone)) {
return new result(false, 'Invalid phone', null, errorCodesEnum::INVALID_PARAM);
}
// 判断是否被其他member注册过
$m_member = new memberModel();
$row = $m_member->getRow(array(
'phone_id' => $contact_phone,
));
if ($row) {
return new result(false, 'The phone number has been registered.');
}
$rt = $this->sendVerifyCodeOp($p);
if ($rt->STS) {
return new result(true, L('tip_success'), $rt->DATA);
} else {
return new result(false, L('tip_code_' . $rt->CODE), array('code' => $rt->CODE, 'msg' => $rt->MSG));
}
}
/**
* 发送验证码
* @param $p
* @return result
*/
public function sendVerifyCodeOp($p)
{
$data = $p;
$url = ENTRY_API_SITE_URL . '/phone.code.send.php';
$rt = curl_post($url, $data);
debug($rt);
$rt = json_decode($rt, true);
if ($rt['STS']) {
return new result(true, L('tip_success'), $rt['DATA']);
} else {
return new result(false, L('tip_code_' . $rt['CODE']));
}
}
/**
* 注册账号
* @param $p
* @return result
*/
public function registerClientOp($p)
{
$p['open_source'] = 1;
$p['password'] = $p['<PASSWORD>'];
$p['login_code'] = $p['login_account'];
$p['sms_id'] = $p['verify_id'];
$p['sms_code'] = $p['verify_code'];
$rt = memberClass::phoneRegisterNew($p);
return $rt;
}
/**
* 证件采集
*/
public function documentCollectionOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if ($client_info) {
$format_phone = tools::separatePhone($client_info['phone_id']);
Tpl::output('phone_arr', $format_phone);
}
Tpl::showPage('document.collection');
}
/**
* 获取client信息
* @param $p
* @return result
*/
public function getClientInfoOp($p)
{
$country_code = trim($p['country_code']);
$phone = trim($p['phone']);
$format_phone = tools::getFormatPhone($country_code, $phone);
$contact_phone = $format_phone['contact_phone'];
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('phone_id' => $contact_phone, 'is_verify_phone' => 1));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
$m_member_verify_cert = M('member_verify_cert');
$member_verify_cert = $m_member_verify_cert->select(array('member_id' => $client_info['uid'], 'verify_state' => array('<=', certStateEnum::PASS)));
foreach ($member_verify_cert as $val) {
switch ($val['cert_type']) {
case certificationTypeEnum::ID:
$client_info['identity_authentication'] = $val['verify_state'] == 10 ? 1 : 0;
break;
case certificationTypeEnum::FAIMILYBOOK:
$client_info['family_book'] = $val['verify_state'] == 10 ? 1 : 0;
break;
case certificationTypeEnum::WORK_CERTIFICATION:
$client_info['working_certificate'] = $val['verify_state'] == 10 ? 1 : 0;
break;
case certificationTypeEnum::RESIDENT_BOOK:
$client_info['resident_book'] = $val['verify_state'] == 10 ? 1 : 0;
break;
default:
}
}
if (!isset($client_info['identity_authentication'])) {
$client_info['identity_authentication'] = 0;
}
if (!isset($client_info['family_book'])) {
$client_info['family_book'] = 0;
}
if (!isset($client_info['working_certificate'])) {
$client_info['working_certificate'] = 0;
}
if (!isset($client_info['resident_book'])) {
$client_info['resident_book'] = 0;
}
$r = new ormReader();
$sql = "SELECT cert_type,COUNT(uid) cert_num FROM member_verify_cert WHERE member_id = " . $client_info['uid'] . " AND verify_state = " . certStateEnum::PASS . " GROUP BY cert_type";
$member_assets = $r->getRows($sql);
foreach ($member_assets as $val) {
switch ($val['cert_type']) {
case certificationTypeEnum::CAR:
$client_info['vehicle_property'] = $val['cert_num'];
break;
case certificationTypeEnum::LAND:
$client_info['land_property'] = $val['cert_num'];
break;
case certificationTypeEnum::HOUSE:
$client_info['housing_property'] = $val['cert_num'];;
break;
case certificationTypeEnum::MOTORBIKE:
$client_info['motorcycle_asset_certificate'] = $val['cert_num'];;
break;
default:
}
}
if (!isset($client_info['vehicle_property'])) {
$client_info['vehicle_property'] = 0;
}
if (!isset($client_info['land_property'])) {
$client_info['land_property'] = 0;
}
if (!isset($client_info['housing_property'])) {
$client_info['housing_property'] = 0;
}
if (!isset($client_info['motorcycle_asset_certificate'])) {
$client_info['motorcycle_asset_certificate'] = 0;
}
$sql = "SELECT COUNT(uid) guarantee_num FROM member_guarantee WHERE member_id = " . $client_info['uid'] . " AND relation_state = 100";
$guarantee_num = $r->getOne($sql);
$client_info['guarantee_num'] = intval($guarantee_num);
return new result(true, '', $client_info);
}
/**
* 身份证信息
*/
public function identityAuthenticationOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
$country_code = (new nationalityEnum)->Dictionary();
Tpl::output('country_code', $country_code);
Tpl::showPage('document.identity.authentication');
}
/**
* 获取地址选项
* @param $p
* @return array
*/
public function getAreaListOp($p)
{
$pid = intval($p['uid']);
$m_core_tree = M('core_tree');
$list = $m_core_tree->getChildByPid($pid, 'region');
return array('list' => $list);
}
/**
* 保存身份证信息
* @param $p
* @return result
*/
public function saveIdentityAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$id_number = trim($p['id_number']);
$expire_date = date('Y-m-d', strtotime($p['expire_date']));
$gender = intval($p['gender']);
$civil_status = intval($p['civil_status']);
$birthday = date('Y-m-d', strtotime($p['birthday']));
$birth_country = trim($p['birth_country']);
$birth_province = intval($p['birth_province']);
$birth_district = intval($p['birth_district']);
$birth_commune = intval($p['birth_commune']);
$birth_village = intval($p['birth_village']);
$address = trim($p['address']);
$kh_family_name = trim($p['kh_family_name']);
$kh_given_name = trim($p['kh_given_name']);
$kh_second_name = trim($p['kh_second_name']);
$kh_third_name = trim($p['kh_third_name']);
$en_family_name = trim($p['en_family_name']);
$en_given_name = trim($p['en_given_name']);
$en_second_name = trim($p['en_second_name']);
$en_third_name = trim($p['en_third_name']);
$handheld_img = trim($p['handheld_img']);
$frontal_img = trim($p['frontal_img']);
$back_img = trim($p['back_img']);
$m_client_member = M('client_member');
$row = $m_client_member->getRow($uid);
if (!$row) {
return new result(false, 'Invalid Id!');
}
if (!$id_number || !$birth_country || !$handheld_img || !$frontal_img || !$back_img || $birth_province == 0 || $birth_district == 0 || $birth_commune == 0 || $birth_village == 0 || !$address) {
return new result(false, 'Param Error!');
}
$row->id_sn = $id_number;
$row->nationality = $birth_country;
$row->id_en_name_json = my_json_encode(
array(
'en_family_name' => $en_family_name,
'en_given_name' => $en_given_name,
'en_second_name' => $en_second_name,
'en_third_name' => $en_third_name,
)
);
$row->id_kh_name_json = my_json_encode(
array(
'kh_family_name' => $kh_family_name,
'kh_given_name' => $kh_given_name,
'kh_second_name' => $kh_second_name,
'kh_third_name' => $kh_third_name,
)
);
$row->initials = strtoupper(substr($en_family_name, 0, 1));
$row->display_name = $en_family_name . ' ' . $en_given_name;
$row->kh_display_name = $kh_family_name . ' ' . $kh_given_name;
$row->gender = $gender;
$row->civil_status = $civil_status;
$row->birthday = $birthday;
$row->id_address1 = $birth_province;
$row->id_address2 = $birth_district;
$row->id_address3 = $birth_commune;
$row->id_address4 = $birth_village;
$row->id_expire_time = $expire_date;
$row->update_time = Now();
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$sql = "UPDATE member_verify_cert SET verify_state='" . certStateEnum::EXPIRED . "' WHERE member_id='" . $uid . "'
AND cert_type='" . certificationTypeEnum::ID . "' AND verify_state='" . certStateEnum::PASS . "' ";
$up = $m_client_member->conn->execute($sql);
if (!$up->STS) {
$conn->rollback();
return new result(false, 'Update history cert fail');
}
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Save Failed!');
}
$m_member_verify_cert = M('member_verify_cert');
$m_member_verify_cert_image = M('member_verify_cert_image');
$row_cert = $m_member_verify_cert->newRow();
$row_cert->member_id = $uid;
$row_cert->cert_type = certificationTypeEnum::ID;
$row_cert->cert_name = $row->display_name;
$row_cert->cert_sn = $id_number;
$row_cert->cert_addr = $address;
$row_cert->cert_expire_time = $expire_date;
$row_cert->source_type = 1;
$row_cert->verify_state = certStateEnum::PASS;
$row_cert->auditor_id = $this->user_id;
$row_cert->auditor_name = $this->user_name;
$row_cert->auditor_time = Now();
$row_cert->create_time = Now();
$rt_2 = $row_cert->insert();
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, 'Save Failed!');
}
$cert_images = array(
certImageKeyEnum::ID_HANDHELD => $handheld_img,
certImageKeyEnum::ID_FRONT => $frontal_img,
certImageKeyEnum::ID_BACK => $back_img,
);
foreach ($cert_images as $key => $img) {
$row_cert_img = $m_member_verify_cert_image->newRow();
$row_cert_img->cert_id = $rt_2->AUTO_ID;
$row_cert_img->image_key = $key;
$row_cert_img->image_url = $img;
$row_cert_img->image_sha = sha1_file($img);
$rt_3 = $row_cert_img->insert();
if (!$rt_3->STS) {
$conn->rollback();
return new result(false, 'Save Failed!');
}
}
$conn->submitTransaction();
return new result(true, 'Save Successful!', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 工作证明信息
* @return result
*/
public function workAuthenticationOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.work.authentication');
}
/**
* 保存工作证明
* @param $p
* @return result
*/
public function saveWorkAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$company_name = trim($p['company_name']);
$company_address = trim($p['company_address']);
$position = trim($p['position']);
$is_government = intval($p['is_government']);
$working_certificate = trim($p['working_certificate']);
$work_employment_certification = trim($p['work_employment_certification']);
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
if (!$company_name || !$company_address || !$position || !$working_certificate || !$work_employment_certification) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try {
//更新原来通过的为过期状态
$sql = "update member_verify_cert set verify_state='" . certStateEnum::EXPIRED . "' where member_id='" . $uid . "'
and cert_type='" . certificationTypeEnum::WORK_CERTIFICATION . "' and verify_state='" . certStateEnum::PASS . "' ";
$up = $m_client_member->conn->execute($sql);
if (!$up->STS) {
$conn->rollback();
return new result(false, 'Update history cert fail');
}
// 当前只能有一条合法的,其余的更新为历史
$sql = "update member_work set state='" . workStateStateEnum::HISTORY . "' where member_id='" . $uid . "' and state='" . workStateStateEnum::VALID . "' ";
$up = $m_client_member->conn->execute($sql);
if (!$up->STS) {
$conn->rollback();
return new result(false, 'Update history cert fail');
}
$m_cert = new member_verify_certModel();
$m_work = new member_workModel();
$m_image = new member_verify_cert_imageModel();
$new_row = $m_cert->newRow();
$new_row->member_id = $uid;
$new_row->cert_type = certificationTypeEnum::WORK_CERTIFICATION;
$new_row->verify_state = certStateEnum::PASS;
$new_row->source_type = 1;
$new_row->auditor_id = $this->user_id;
$new_row->auditor_name = $this->user_name;
$new_row->auditor_time = Now();
$new_row->create_time = Now();
$insert = $new_row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Save Failed');
}
$cert_images = array(
certImageKeyEnum::WORK_CARD => $working_certificate,
certImageKeyEnum::WORK_EMPLOYMENT_CERTIFICATION => $work_employment_certification,
);
foreach ($cert_images as $key => $img) {
$row = $m_image->newRow();
$row->cert_id = $new_row->uid;
$row->image_key = $key;
$row->image_url = $img;
$row->image_sha = sha1_file($img);;
$insert = $row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Add cert image fail');
}
}
$row = $m_work->newRow();
$row->cert_id = $new_row->uid;
$row->member_id = $uid;
$row->company_name = $company_name;
$row->company_addr = $company_address;
$row->position = $position;
$row->is_government = $is_government;
$row->create_time = Now();
$in = $row->insert();
if (!$in->STS) {
$conn->rollback();
return new result(false, 'Add work cert fail');
}
$client_info->is_government = $is_government;
$client_info->update_time = Now();
$rt = $client_info->update();
if (!$rt->STS) {
$conn->rollback();
return new result(false, 'Add work cert fail');
}
$conn->submitTransaction();
return new result(true, 'Save Successful!', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 户口簿信息
* @return result
*/
public function familyBookAuthenticationOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.family.book.authentication');
}
/**
* 保存户口簿信息
* @param $p
* @return result
*/
public function saveFamilyBookAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$family_book_front = trim($p['family_book_front']);
$family_book_back = trim($p['family_book_back']);
$family_book_household = trim($p['family_book_household']);
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
if (!$family_book_front || !$family_book_back || !$family_book_household) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try {
//更新原来通过的为过期状态
$sql = "update member_verify_cert set verify_state='" . certStateEnum::EXPIRED . "' where member_id='" . $uid . "'
and cert_type='" . certificationTypeEnum::FAIMILYBOOK . "' and verify_state='" . certStateEnum::PASS . "' ";
$up = $m_client_member->conn->execute($sql);
if (!$up->STS) {
$conn->rollback();
return new result(false, 'Update history cert fail');
}
$m_cert = new member_verify_certModel();
$m_image = new member_verify_cert_imageModel();
$new_row = $m_cert->newRow();
$new_row->member_id = $uid;
$new_row->cert_type = certificationTypeEnum::FAIMILYBOOK;
$new_row->verify_state = certStateEnum::PASS;
$new_row->source_type = 1;
$new_row->auditor_id = $this->user_id;
$new_row->auditor_name = $this->user_name;
$new_row->auditor_time = Now();
$new_row->create_time = Now();
$insert = $new_row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Save Failed');
}
$cert_images = array(
certImageKeyEnum::FAMILY_BOOK_FRONT => $family_book_front,
certImageKeyEnum::FAMILY_BOOK_BACK => $family_book_back,
certImageKeyEnum::FAMILY_BOOK_HOUSEHOLD => $family_book_household,
);
foreach ($cert_images as $key => $img) {
$row = $m_image->newRow();
$row->cert_id = $new_row->uid;
$row->image_key = $key;
$row->image_url = $img;
$row->image_sha = sha1_file($img);;
$insert = $row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Add cert image fail');
}
}
$conn->submitTransaction();
return new result(true, 'Save Successful!', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 暂住证
*/
public function residentBookAuthenticationOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.resident.book.authentication');
}
/**
* 保存居住证信息
* @param $p
* @return result
*/
public function saveResidentBookAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$resident_book_front = trim($p['resident_book_front']);
$resident_book_back = trim($p['resident_book_back']);
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
if (!$resident_book_front || !$resident_book_back) {
return new result(false, 'Param Error!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try {
//更新原来通过的为过期状态
$sql = "update member_verify_cert set verify_state='" . certStateEnum::EXPIRED . "' where member_id='" . $uid . "'
and cert_type='" . certificationTypeEnum::RESIDENT_BOOK . "' and verify_state='" . certStateEnum::PASS . "' ";
$up = $m_client_member->conn->execute($sql);
if (!$up->STS) {
$conn->rollback();
return new result(false, 'Update history cert fail');
}
$m_cert = new member_verify_certModel();
$m_image = new member_verify_cert_imageModel();
$new_row = $m_cert->newRow();
$new_row->member_id = $uid;
$new_row->cert_type = certificationTypeEnum::RESIDENT_BOOK;
$new_row->verify_state = certStateEnum::PASS;
$new_row->source_type = 1;
$new_row->auditor_id = $this->user_id;
$new_row->auditor_name = $this->user_name;
$new_row->auditor_time = Now();
$new_row->create_time = Now();
$insert = $new_row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Save Failed');
}
$cert_images = array(
certImageKeyEnum::RESIDENT_BOOK_FRONT => $resident_book_front,
certImageKeyEnum::RESIDENT_BOOK_BACK => $resident_book_back,
);
foreach ($cert_images as $key => $img) {
$row = $m_image->newRow();
$row->cert_id = $new_row->uid;
$row->image_key = $key;
$row->image_url = $img;
$row->image_sha = sha1_file($img);;
$insert = $row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Add cert image fail');
}
}
$conn->submitTransaction();
return new result(true, 'Save Successful!', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 汽车证明
*/
public function vehiclePropertyAuthenticateOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.vehicle.property.authentication');
}
/**
* 保存汽车资产证明
* @param $p
* @return result
*/
public function saveVehiclePropertyAuthenticationOp($p)
{
$car_cert_front = trim($p['car_cert_front']);
$car_cert_back = trim($p['car_cert_back']);
$car_front = trim($p['car_front']);
$car_back = trim($p['car_back']);
if (!$car_cert_front || !$car_cert_back || !$car_front || !$car_back) {
return new result(false, 'Param Error!');
}
$p['cert_type'] = certificationTypeEnum::CAR;
$p['cert_images'] = array(
certImageKeyEnum::CAR_CERT_FRONT => $car_cert_front,
certImageKeyEnum::CAR_CERT_BACK => $car_cert_back,
certImageKeyEnum::CAR_FRONT => $car_front,
certImageKeyEnum::CAR_BACK => $car_back,
);
return $this->addVerifyCert($p);
}
/**
* 获取历史记录
* @param $p
* @return array
*/
public function getCertificationListOp($p)
{
$uid = intval($p['uid']);
$cert_type = intval($p['cert_type']);
$r = new ormReader();
$sql1 = "select verify.*,member.login_code,member.display_name,member.phone_id,member.email from member_verify_cert as verify left join client_member as member on verify.member_id = member.uid where 1=1 ";
if ($uid) {
$sql1 .= " and verify.member_id = $uid";
}
if ($cert_type) {
$sql1 .= " and verify.cert_type = $cert_type";
}
$sql1 .= " ORDER BY verify.uid desc";
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql1, $pageNumber, $pageSize);
$rows = $data->rows;
$list = array();
// 取图片
foreach ($rows as $row) {
$sql = "select * from member_verify_cert_image where cert_id='" . $row['uid'] . "'";
$images = $r->getRows($sql);
$row['cert_images'] = $images;
$list[] = $row;
}
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $list,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize,
);
}
/**
* 土地证明
*/
public function landPropertyAuthenticateOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.land.property.authentication');
}
/**
* 保存土地证明
* @param $p
* @return result
*/
public function saveLandPropertyAuthenticationOp($p)
{
$land_property_card = trim($p['land_property_card']);
$land_trading_record = trim($p['land_trading_record']);
if (!$land_property_card || !$land_trading_record) {
return new result(false, 'Param Error!');
}
$p['cert_type'] = certificationTypeEnum::LAND;
$p['cert_images'] = array(
certImageKeyEnum::CAR_CERT_FRONT => $land_property_card,
certImageKeyEnum::CAR_CERT_BACK => $land_trading_record,
);
return $this->addVerifyCert($p);
}
public function housingPropertyAuthenticateOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.housing.property.authentication');
}
/**
* 保存房产信息
* @param $p
* @return result
*/
public function saveHousingPropertyAuthenticationOp($p)
{
$house_property_card = trim($p['house_property_card']);
$house_relationships_certify = trim($p['house_relationships_certify']);
$house_front = trim($p['house_front']);
$house_side_face = trim($p['house_side_face']);
$house_front_road = trim($p['house_front_road']);
$house_inside = trim($p['house_inside']);
if (!$house_property_card || !$house_relationships_certify || !$house_front || !$house_side_face || !$house_front_road || !$house_inside) {
return new result(false, 'Param Error!');
}
$p['cert_type'] = certificationTypeEnum::HOUSE;
$p['cert_images'] = array(
certImageKeyEnum::HOUSE_PROPERTY_CARD => $house_property_card,
certImageKeyEnum::HOUSE_RELATIONSHIPS_CERTIFY => $house_relationships_certify,
certImageKeyEnum::HOUSE_FRONT => $house_front,
certImageKeyEnum::HOUSE_SIDE_FACE => $house_side_face,
certImageKeyEnum::HOUSE_FRONT_ROAD => $house_front_road,
certImageKeyEnum::HOUSE_INSIDE => $house_inside,
);
return $this->addVerifyCert($p);
}
/**
* 摩托车
*/
public function motorcyclePropertyAuthenticateOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
Tpl::showPage('document.motorcycle.property.authentication');
}
/**
* 保存房产信息
* @param $p
* @return result
*/
public function saveMotorcyclePropertyAuthenticationOp($p)
{
$motorbike_cert_front = trim($p['motorbike_cert_front']);
$motorbike_cert_back = trim($p['motorbike_cert_back']);
$motorbike_photo = trim($p['motorbike_photo']);
if (!$motorbike_cert_front || !$motorbike_cert_back || $motorbike_photo) {
return new result(false, 'Param Error!');
}
$p['cert_type'] = certificationTypeEnum::MOTORBIKE;
$p['cert_images'] = array(
certImageKeyEnum::MOTORBIKE_CERT_FRONT => $motorbike_cert_front,
certImageKeyEnum::MOTORBIKE_CERT_BACK => $motorbike_cert_back,
certImageKeyEnum::MOTORBIKE_PHOTO => $motorbike_photo,
);
return $this->addVerifyCert($p);
}
/**
* 保存资产证明信息
* @param $param
* @return result
*/
private function addVerifyCert($param)
{
$uid = intval($param['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$m_cert = new member_verify_certModel();
$m_image = new member_verify_cert_imageModel();
$new_row = $m_cert->newRow();
$new_row->member_id = $uid;
$new_row->cert_type = $param['cert_type'];
$new_row->verify_state = certStateEnum::PASS;
$new_row->source_type = 1;
$new_row->auditor_id = $this->user_id;
$new_row->auditor_name = $this->user_name;
$new_row->auditor_time = Now();
$new_row->create_time = Now();
$insert = $new_row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Save Failed');
}
$cert_images = $param['cert_images'];
foreach ($cert_images as $key => $img) {
$row = $m_image->newRow();
$row->cert_id = $new_row->uid;
$row->image_key = $key;
$row->image_url = $img;
$row->image_sha = sha1_file($img);;
$insert = $row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Add cert image fail');
}
}
$conn->submitTransaction();
return new result(true, 'Save Successful!', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 担保相关
*/
public function guaranteeAuthenticateOp()
{
$client_id = intval($_GET['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
if (!$client_info) {
showPage('No eligible clients!');
}
Tpl::output('client_info', $client_info);
$m_core_definition = new core_definitionModel();
$define_arr = $m_core_definition->getDefineByCategory(array('guarantee_relationship'));
Tpl::output("guarantee_relationship", $define_arr['guarantee_relationship']);
Tpl::showPage('document.guarantee.authentication');
}
/**
* 保存担保人
* @param $p
* @return result
*/
public function saveGuarantorAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$relationship = $p['relationship'];
$member_account = trim($p['member_account']);
$country_code = trim($p['country_code']);
$phone = trim($p['phone']);
$format_phone = tools::getFormatPhone($country_code, $phone);
$contact_phone = $format_phone['contact_phone'];
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
$guarantor = $m_client_member->find(array('login_code' => $member_account, 'phone_id' => $contact_phone));
if (!$guarantor || $guarantor['uid'] == $uid) {
return new result(false, 'Guarantor information error.');
}
$m_member_guarantee = M('member_guarantee');
$chk = $m_member_guarantee->find(array('member_id' => $uid, 'relation_member_id' => $guarantor['uid'], 'relation_state' => array('neq', 11)));
if ($chk) {
return new result(false, 'The guarantor already exists.');
}
$row = $m_member_guarantee->newRow();
$row->member_id = $uid;
$row->relation_member_id = $guarantor['uid'];
$row->relation_type = $relationship;
$row->create_time = Now();
$row->relation_state = 0;
$rt = $row->insert();
if ($rt->STS) {
return new result(true, 'Add Successful.', array('url' => getUrl('member', 'documentCollection', array('client_id' => $uid), false, ENTRY_COUNTER_SITE_URL)));
} else {
return new result(false, 'Add Failed.');
}
}
/**
* 获取担保记录
* @param $p
* @return array
*/
public function getGuarantorListOp($p)
{
$uid = intval($p['uid']);
$type = trim($p['type']);
$r = new ormReader();
if ($type == 'guarantor') {
$sql = "select mg.*,cm.display_name,phone_id from member_guarantee mg LEFT JOIN client_member cm ON mg.relation_member_id = cm.uid WHERE mg.member_id = $uid AND relation_state != 11 order by mg.uid desc";
} else {
$sql = "select mg.*,cm.display_name,phone_id from member_guarantee mg LEFT JOIN client_member cm ON mg.relation_member_id = cm.uid WHERE mg.relation_member_id = $uid AND relation_state != 11 order by mg.uid desc";
}
$rows = $r->getRows($sql);
return array(
"sts" => true,
"data" => $rows,
);
}
/**
* 指纹录入
*/
public function fingerprintCollectionOp()
{
Tpl::showPage('fingerprint.collection');
}
/**
* 获取指纹信息
* @param $p
* @return result
*/
public function getClientFingermarkOp($p)
{
$country_code = trim($p['country_code']);
$phone = trim($p['phone']);
$format_phone = tools::getFormatPhone($country_code, $phone);
$contact_phone = $format_phone['contact_phone'];
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('phone_id' => $contact_phone, 'is_verify_phone' => 1));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
$m_common_fingerprint_library = M('common_fingerprint_library');
$fingerprint_info = $m_common_fingerprint_library->find(array('obj_uid' => $client_info['obj_guid'], 'obj_type' => objGuidTypeEnum::CLIENT_MEMBER));
if ($fingerprint_info) {
$client_info['feature_img'] = $fingerprint_info['feature_img'];
$client_info['certification_status'] = 'Registered';
$client_info['certification_time'] = timeFormat($fingerprint_info['create_time']);
} else {
$client_info['feature_img'] = 'resource/img/member/photo.png';
$client_info['certification_status'] = 'Unregistered';
$client_info['certification_time'] = '';
}
return new result(true, '', $client_info);
}
/**
* 保存指纹
* @param $p
* @return result
*/
public function saveFeatureAuthenticationOp($p)
{
$uid = intval($p['client_id']);
$feature_img = $p['feature_img'];
$m_client_member = M('client_member');
$client_info = $m_client_member->getRow(array('uid' => $uid));
if (!$client_info) {
return new result(false, 'No eligible clients!');
}
$m_common_fingerprint_library = M('common_fingerprint_library');
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$fingerprint = $m_common_fingerprint_library->getRow(array('obj_uid' => $client_info['obj_guid'], 'obj_type' => objGuidTypeEnum::CLIENT_MEMBER));
if ($fingerprint) {
$rt_1 = $fingerprint->delete();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Add Failed!1');
}
}
$fingerprint_row = $m_common_fingerprint_library->newRow();
$fingerprint_row->obj_type = objGuidTypeEnum::CLIENT_MEMBER;
$fingerprint_row->obj_uid = $client_info['obj_guid'];
$fingerprint_row->finger_index = 1;
$fingerprint_row->feature_img = $feature_img;
$fingerprint_row->feature_img = $feature_img;
$fingerprint_row->create_time = Now();
$rt_2 = $fingerprint_row->insert();
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, 'Add Failed!2');
}
$client_info->fingerprint = $feature_img;
$client_info->update_time = Now();
$rt_3 = $client_info->update();
if (!$rt_3->STS) {
$conn->rollback();
return new result(false, 'Add Failed!3');
}
$conn->submitTransaction();
return new result(false, 'Add Successful!');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}
/**
* 贷款
*/
public function loanOp()
{
$uid = $_GET['uid'];
if ($uid) {
$info = $this->getContractInfoOp(array(), $uid);
Tpl::output('loan_info', $info['data']);
}
Tpl::showpage('loan');
}
/**
* 获取合同信息
* @param $p
* @param $uid
* @return array
*/
public function getContractInfoOp($p, $uid)
{
$uid = $uid ?: intval($p['search_text']);
$r = new ormReader();
$sql = "SELECT contract.*,account.obj_guid,product.product_code,product.product_name,product.product_description,product.product_feature,member.uid as member_id,member.display_name,member.alias_name,member.phone_id,member.email FROM loan_contract as contract"
. " inner join loan_account as account on contract.account_id = account.uid"
. " left join client_member as member on account.obj_guid = member.obj_guid"
. " left join loan_product as product on contract.product_id = product.uid where contract.uid = " . $uid;
$info = $r->getRow($sql);
if (!$info) {
return array(
"sts" => true,
"data" => array(),
);
}
$sql = "select count(uid) left_period,sum(receivable_principal) left_principal from loan_installment_scheme where contract_id='$uid' and state !='" . schemaStateTypeEnum::COMPLETE . "' ";
$row = $r->getRow($sql);
$info['left_period'] = $row['left_period'];
$info['left_principal'] = $row['left_principal'] > $info['receivable_principal'] ? $info['receivable_principal'] : $row['left_principal'];
$sql1 = "select * from loan_disbursement_scheme where contract_id = " . $uid;
$disbursement = $r->getRows($sql1);
$info["disbursement"] = $disbursement;
$sql2 = "select * from loan_installment_scheme where contract_id = " . $uid;
$installment = $r->getRows($sql2);
$penalties_total = 0;
$time = date('Y-m-d 23:59:59', time());
$repayment_arr = array();
foreach ($installment as $key => $val) {
if ($val['penalty_start_date'] <= $time && $val['state'] != schemaStateTypeEnum::COMPLETE) {
$penalties = loan_baseClass::calculateSchemaRepaymentPenalties($val['uid']);
$val['penalties'] = $penalties;
$penalties_total += $penalties;
$installment[$key] = $val;
}
if ($val['receivable_date'] <= $time && $val['state'] != schemaStateTypeEnum::COMPLETE) {
$repayment_arr[] = $val;
}
}
$info['penalties_total'] = $penalties_total;
$info['installment'] = $installment;
$insurance_arr = $this->getInsurancePrice($p['uid']);
$info['insurance'] = $insurance_arr;
$info['repayment_arr'] = $repayment_arr;
return array(
"sts" => true,
"data" => $info,
);
}
public function getInsurancePrice($uid = 0)
{
$r = new ormReader();
$sql1 = "select loan_contract_id,sum(price) as price from insurance_contract GROUP BY loan_contract_id";
if ($uid) {
$sql1 = "select loan_contract_id,sum(price) as price from insurance_contract where loan_contract_id = " . $uid . " GROUP BY loan_contract_id";
}
$insurance = $r->getRows($sql1);
$insurance_arr = array();
foreach ($insurance as $key => $value) {
$insurance_arr[$value['loan_contract_id']] = $value;
}
return $insurance_arr;
}
/**
* 确认还款
* @param $p
* @return result
*/
public function submitRepaymentOp($p)
{
$uid = intval($p['uid']);
$repayment_total = round($p['repayment_total'], 2);
$remark = trim($p['remark']);
$currency = $p['currency'] ? $p['currency'] : currencyEnum::USD;
$class_user = new userClass();
$user_info = $class_user->getUserInfo($this->user_id);
$payment_info = array(
'branch_id' => $user_info->DATA['branch_id'],
'teller_id' => $this->user_id,
'teller_name' => $this->user_name,
'creator_id' => $this->user_id,
'creator_name' => $this->user_name,
'remark' => $remark
);
$rt = loan_contractClass::schemaManualRepayment($uid, $repayment_total, $currency, repaymentWayEnum::CASH, Now(), $payment_info);
if ($rt->STS) {
return new result(true, 'Repayment successful!');
} else {
return new result(false, 'Repayment failure!');
}
}
/**
* 添加新合同
*/
public function addContractOp()
{
Tpl::output('show_menu', 'loan');
Tpl::showpage('contract.add.one');
}
/**
* 获取贷款请求信息
* @param $p
* @return array
*/
public function getRequestInfoOp($p)
{
$uid = intval($p['search_text']);
$m_loan_apply = M('loan_apply');
$info = $m_loan_apply->find(array('uid' => $uid));
if ($info) {
return array(
"sts" => true,
"data" => $info,
);
} else {
return array(
"sts" => true,
"data" => array(),
);
}
}
/**
* 根据申请创建合同
* @param $p
* @return result
*/
public function createContractOp($p)
{
$uid = intval($p['uid']);
$obj_user = new objectUserClass($this->user_id);
$rt = $obj_user->createContractByApply($uid);
if ($rt->STS) {
$data = $rt->DATA;
$contract_id = $data['Contract'];
return new result(true, '', array('url' => getUrl('member', 'showCreateContract', array('uid' => $contract_id), false, ENTRY_COUNTER_SITE_URL)));
} else {
return new result(false, $rt->MSG);
}
}
public function showMortgageOp($uid)
{
Tpl::output('show_menu', 'loan');
$uid = intval($_GET['uid']);
$info = $this->getContractInfoOp(array(), $uid);
$contract_info = $info['data'];
Tpl::output('contract_info', $contract_info);
//担保人
$r = new ormReader();
$sql = 'SELECT mg.*,cm.display_name,cm.login_code FROM member_guarantee mg LEFT JOIN client_member cm ON mg.relation_member_id = cm.uid WHERE mg.relation_state = 100 AND mg.member_id = ' . $contract_info['member_id'];
$guarantor_list = $r->getRows($sql);
Tpl::output('guarantor_list', $guarantor_list);
//抵押物
$sql = "SELECT cert.*,cert_image.image_url FROM member_verify_cert AS cert LEFT JOIN member_verify_cert_image AS cert_image ON cert_image.cert_id = cert.uid WHERE cert.verify_state = 10";
$sql .= " AND cert.member_id = " . $contract_info['member_id'] . " AND cert.cert_type IN(" . certificationTypeEnum::HOUSE . ',' . certificationTypeEnum::LAND . ',' . certificationTypeEnum::CAR . ',' . certificationTypeEnum::MOTORBIKE . ")";
$sql .= " ORDER BY cert.cert_type ASC";
$rows = $r->getRows($sql);
$list = array();
// 取图片
foreach ($rows as $row) {
if (isset($list[$row['uid']])) {
$list[$row['uid']]['img_list'][] = $row['image_url'];
} else {
$list[$row['uid']] = $row;
$list[$row['uid']]['img_list'][] = $row['image_url'];
}
}
Tpl::output('mortgage_list', $list);
Tpl::showPage("loan.mortgage");
}
/**
* 展示新创建合同,进行修改
*/
public function showCreateContractOp()
{
Tpl::output('show_menu', 'loan');
$uid = intval($_GET['uid']);
$info = $this->getContractInfoOp(array(), $uid);
$contract_info = $info['data'];
Tpl::output('contract_info', $contract_info);
//担保人
$r = new ormReader();
$sql = 'SELECT mg.*,cm.display_name,cm.login_code FROM member_guarantee mg LEFT JOIN client_member cm ON mg.relation_member_id = cm.uid WHERE mg.relation_state = 100 AND mg.member_id = ' . $contract_info['member_id'];
$guarantor_list = $r->getRows($sql);
Tpl::output('guarantor_list', $guarantor_list);
//抵押物
$sql = "SELECT cert.*,cert_image.image_url FROM member_verify_cert AS cert LEFT JOIN member_verify_cert_image AS cert_image ON cert_image.cert_id = cert.uid WHERE cert.verify_state = 10";
$sql .= " AND cert.member_id = " . $contract_info['member_id'] . " AND cert.cert_type IN(" . certificationTypeEnum::HOUSE . ',' . certificationTypeEnum::LAND . ',' . certificationTypeEnum::CAR . ',' . certificationTypeEnum::MOTORBIKE . ")";
$sql .= " ORDER BY cert.cert_type ASC";
$rows = $r->getRows($sql);
$list = array();
// 取图片
foreach ($rows as $row) {
if (isset($list[$row['uid']])) {
$list[$row['uid']]['img_list'][] = $row['image_url'];
} else {
$list[$row['uid']] = $row;
$list[$row['uid']]['img_list'][] = $row['image_url'];
}
}
Tpl::output('mortgage_list', $list);
Tpl::showPage('contract.add.two');
}
/**
* 确认合同
* @param $p
* @return result
*/
public function submitContractOp()
{
$param = array_merge(array(), $_GET, $_POST);
$uid = intval($_GET['uid']);
$guarantor_id = $param['guarantor_id'];
$mortgage_id = $param['mortgage_id'];
$scan_img = $param['scan_img'];
$obj_user = new objectUserClass($this->user_id);
$rt = $obj_user->editContractAndConfirmToExecute($uid, $guarantor_id, $mortgage_id, $scan_img);
if (!$rt->STS) {
showMessage($rt->MSG);
}
$url = getUrl('member', 'loan', array(), false, ENTRY_COUNTER_SITE_URL);
showMessage('Submit successfully!', $url);
}
public function profileOp()
{
$client_id = intval($_GET['client_id']);
if ($client_id) {
$r = new ormReader();
$sql = "select cm.*,mg.grade_code from client_member cm LEFT JOIN member_grade mg ON cm.member_grade = mg.uid WHERE cm.uid = " . $client_id;
$client_info = $r->getRow($sql);
Tpl::output('client_info', $client_info);
}
Tpl::showPage("profile");
}
/**
* 发送验证码
* @param $p
* @return result
*/
public function sendVerifyCodeByUidOp($p)
{
$client_id = intval($p['client_id']);
$m_client_member = M('client_member');
$client_info = $m_client_member->find(array('uid' => $client_id));
$phone_arr = tools::separatePhone($client_info['phone_id']);
$param = array();
$param['country_code'] = $phone_arr[0];
$param['phone'] = $phone_arr[1];
$rt = $this->sendVerifyCodeOp($param);
if ($rt->STS) {
return new result(true, L('tip_success'), $rt->DATA);
} else {
return new result(false, L('tip_code_' . $rt->CODE), array('code' => $rt->CODE, 'msg' => $rt->MSG));
}
}
/**
* 修改登录密码*/
public function changeLoginPwdOp()
{
$uid = $_GET["uid"];
$r = new ormReader();
$sql = "select cm.*,mg.grade_code from client_member cm LEFT JOIN member_grade mg ON cm.member_grade = mg.uid WHERE cm.uid = " . $uid;
$client_info = $r->getRow($sql);
Tpl::output('client_info', $client_info);
Tpl::output('show_menu', 'profile');
Tpl::showPage("change.login.pwd");
}
/**
* 登录密码*/
public function verifyChangeLoginPwdOp()
{
$member_id = intval($_POST['client_id']);
$old_pwd = trim($_POST['old_pwd']);
$new_pwd = trim($_POST['new_pwd']);
$verify_id = intval($_POST['verify_id']);
$verify_code = trim($_POST['verify_code']);
$m_client_member = M('client_member');
$row = $m_client_member->getRow($member_id);
if (!$row) {
showMessage('Invalid Id!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
if ($verify_code) {
$m_verify_code = new phone_verify_codeModel();
$row = $m_verify_code->getRow(array(
'uid' => $verify_id,
'verify_code' => $verify_code,
'state' => 0
));
if (!$row) {
$conn->rollback();
showMessage('SMS code error!');
}
$row->state = 1;
$rt = $row->update();
if (!$rt->STS) {
$conn->rollback();
showMessage('SMS code error!' . $rt->MSG);
}
} else {
if (empty($old_pwd)) {
$conn->rollback();
showMessage('To change the password, must enter the verification code or the original password.');
}
if (md5($old_pwd) != $row->login_password) {
$conn->rollback();
showMessage('Old password error!');
}
}
$rt = memberClass::commonUpdateMemberPassword($member_id, $new_pwd);
if ($rt->STS) {
$conn->submitTransaction();
showMessage('Change password successfully!', getUrl('member', 'profile', array('client_id' => $member_id), false, ENTRY_COUNTER_SITE_URL));
} else {
$conn->rollback();
showMessage('Change password failed!');
}
}
/**
* 修改交易密码*/
public function changeTradePwdOp()
{
$uid = $_GET["uid"];
$r = new ormReader();
$sql = "select cm.*,mg.grade_code from client_member cm LEFT JOIN member_grade mg ON cm.member_grade = mg.uid WHERE cm.uid = " . $uid;
$client_info = $r->getRow($sql);
Tpl::output('client_info', $client_info);
Tpl::output('show_menu', 'profile');
Tpl::showPage("change.trade.pwd");
}
/**
* 交易密码*/
public function verifyChangeTradePwdOp()
{
$member_id = intval($_POST['client_id']);
$old_pwd = trim($_POST['old_pwd']);
$new_pwd = trim($_POST['new_pwd']);
$verify_id = intval($_POST['verify_id']);
$verify_code = trim($_POST['verify_code']);
$m_client_member = M('client_member');
$row = $m_client_member->getRow($member_id);
if (!$row) {
showMessage('Invalid Id!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
if ($verify_code) {
$m_verify_code = new phone_verify_codeModel();
$row = $m_verify_code->getRow(array(
'uid' => $verify_id,
'verify_code' => $verify_code,
'state' => 0
));
if (!$row) {
$conn->rollback();
showMessage('SMS code error!');
}
$row->state = 1;
$rt = $row->update();
if (!$rt->STS) {
$conn->rollback();
showMessage('SMS code error!' . $rt->MSG);
}
} else {
if (empty($old_pwd)) {
$conn->rollback();
showMessage('To change the password, must enter the verification code or the original password.');
}
if (md5($old_pwd) != $row->trading_password) {
$conn->rollback();
showMessage('Old password error!');
}
}
$rt = memberClass::commonUpdateMemberTradePassword($member_id, $new_pwd);
if ($rt->STS) {
$conn->submitTransaction();
showMessage('Change Trade password successfully!', getUrl('member', 'profile', array('client_id' => $member_id), false, ENTRY_COUNTER_SITE_URL));
} else {
$conn->rollback();
showMessage('Change Trade password failed!');
}
}
/**
* 修改手机号码*/
public function changePhoneNumOp()
{
$uid = $_GET["uid"];
$r = new ormReader();
$sql = "select cm.*,mg.grade_code from client_member cm LEFT JOIN member_grade mg ON cm.member_grade = mg.uid WHERE cm.uid = " . $uid;
$client_info = $r->getRow($sql);
Tpl::output('client_info', $client_info);
Tpl::output('show_menu', 'profile');
Tpl::showPage("change.phone.num");
}
public function verifyChangePhoneNumOp()
{
$country_code = trim($_POST['country_code']);
$phone_number = trim($_POST['new_num']);
$format_phone = tools::getFormatPhone($country_code, $phone_number);
$contact_phone = $format_phone['contact_phone'];
// 检查合理性
if (!isPhoneNumber($contact_phone)) {
return new result(false, 'Invalid phone', null, errorCodesEnum::INVALID_PARAM);
}
// 判断是否被其他member注册过
$m_member = new memberModel();
$row = $m_member->getRow(array(
'phone_id' => $contact_phone,
));
if ($row) {
return new result(false, 'The phone number has been registered.');
}
$member_id = intval($_POST['client_id']);
$old_pwd = trim($_POST['<PASSWORD>']);
$verify_id = intval($_POST['verify_id']);
$verify_code = trim($_POST['verify_code']);
$m_client_member = M('client_member');
$row = $m_client_member->getRow($member_id);
if (!$row) {
showMessage('Invalid Id!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
if ($verify_code) {
$m_verify_code = new phone_verify_codeModel();
$row = $m_verify_code->getRow(array(
'uid' => $verify_id,
'verify_code' => $verify_code,
'state' => 0
));
if (!$row) {
$conn->rollback();
showMessage('SMS code error!');
}
$row->state = 1;
$rt = $row->update();
if (!$rt->STS) {
$conn->rollback();
showMessage('SMS code error!' . $rt->MSG);
}
} else {
if (empty($old_pwd)) {
$conn->rollback();
showMessage('To change the phone number, must enter the verification code or the login password.');
}
if (md5($old_pwd) != $row->login_password) {
$conn->rollback();
showMessage('login password error!');
}
}
$rt = memberClass::commonUpdateMemberPhoneNum($member_id, $contact_phone);
if ($rt->STS) {
$conn->submitTransaction();
showMessage('Change Phone Number successfully!', getUrl('member', 'profile', array('client_id' => $member_id), false, ENTRY_COUNTER_SITE_URL));
} else {
$conn->rollback();
showMessage('Change Phone Number failed!');
}
}
public function depositOp()
{
Tpl::showPage("coming.soon");
}
public function withdrawalOp()
{
Tpl::showPage("coming.soon");
}
public function submitPrepaymentOp($p)
{
$contract_id = $p['contract_id'];
$prepayment_type = $p['prepayment_type'];
$repay_period = $p["repay_period"];
$amount = $p["amount"];
$arr = array(
'contract_id' => $contract_id,
'prepayment_type' => $prepayment_type,
"repay_period" => $repay_period,
'amount' => $amount
);
$rt = loan_contractClass::prepaymentPreview($arr);
if ($rt->STS) {
return new result(true, 'Submit successfully');
} else {
return new result(false, 'Submit Submit failed');
}
}
}<file_sep>/framework/weixin_baike/data/model/loan_repayment.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/2
* Time: 15:48
*/
class loan_repaymentModel extends tableModelBase
{
public function __construct()
{
parent::__construct('loan_repayment');
}
}<file_sep>/framework/core/templates/widget/inc_upload_upyun.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/webuploader/webuploader.min.js"></script>
<link href="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/webuploader/webuploader.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript">
var site_url = "<?php echo getUrl('base','getUploadParam',array(),false,PROJECT_SITE_URL)?>";
var upload_url = "<?php echo C('upyun_param')['target_url']?>";
var upyun_url = "<?php echo UPYUN_SITE_URL.DS?>";
var swf_url = "<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/webupload/Uploader.swf";
function webuploader2upyun(upload_id, default_dir) {
var uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
swf: swf_url,
// 文件接收服务端。
server: upload_url,
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#' + upload_id,
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/jpg,image/jpeg,image/png'
},
method: 'POST'
});
uploader.on('beforeFileQueued', function (e) {
$.get(site_url, {default_dir: default_dir}, function (response) {
var obj = $.parseJSON(response);
uploader.option('formData', {
'policy': obj.policy,
'signature': obj.signature
});
uploader.upload();
});
})
// 文件上传成功
uploader.on('uploadSuccess', function (file, response) {
var img_name = response.url.split('/').pop();
$('input[name=' + upload_id + ']').val(img_name);
$('input[id=txt_' + upload_id + ']').val(img_name);
$('#show_' + upload_id).attr('src', upyun_url + response.url).show();
if ($('.show_' + upload_id + '_div').length > 0) {
$('.show_' + upload_id + '_div').css('display', 'block');
}
});
// 文件上传失败
uploader.on('uploadError', function (file) {
alert('Upload Fail!');
});
}
</script>
<file_sep>/framework/api_test/apis/microbank/member.get.bind.bank.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/6
* Time: 15:26
*/
// member.get.bind.bank.list
class memberGetBindBankListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member bind bank list";
$this->description = "会员绑定银行卡";
$this->url = C("bank_api_url") . "/member.get.bind.bank.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '没有为null',
array(
'uid' => 'Handler Id',
'handler_name' => '账户名称',
'handler_account' => '账户账号',
'handler_phone' => '电话',
'bank_logo' => '银行logo图片',
'bank_name' => '银行名称',
'bank_currency' => '银行支持币种',
'bank_code' => '银行编码',
'bank_detail_info' => '银行详细信息',
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.guarantee.request.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/8
* Time: 17:24
*/
// officer.submit.guarantee.request
class officerSubmitGuaranteeRequestApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Add guarantee";
$this->description = "客户添加担保人申请";
$this->url = C("bank_api_url") . "/officer.submit.guarantee.request.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "申请的会员id", 1, true);
$this->parameters[]= new apiParameter("country_code", "国家码", '855', true);
$this->parameters[]= new apiParameter("phone", "电话", '325481', true);
$this->parameters[]= new apiParameter("guarantee_member_account", "担保人会员账号", 'test', true);
$this->parameters[]= new apiParameter("relation_type", "关系类型", 'son', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array()
);
}
}<file_sep>/framework/weixin_baike/data/model/passbook_account.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/26
* Time: 17:29
*/
class passbook_accountModel extends tableModelBase
{
function __construct()
{
parent::__construct('passbook_account');
}
}<file_sep>/framework/api_test/apis/microbank/member.insurance.contract.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/16
* Time: 12:33
*/
class memberInsuranceContractListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Insurance Contract List";
$this->description = "会员保险合同列表";
$this->url = C("bank_api_url") . "/member.insurance.contract.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("type", "合同类型 1 全部合同 2 进行中的合同 3 待审核 4 过期合同 ", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'uid' => '合同id',
'contract_sn' => '合同编号',
'currency' => '货币',
'price' => '保险价格',
'start_insured_amount' => '初保金额',
'tax_fee' => '税费',
'start_date' => '开始时间',
'end_date' => '结束时间,null 为永久有效',
'state' => '合同状态',
),
array()
)
)
);
}
}<file_sep>/framework/weixin_baike/api/control/savings.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/13
* Time: 10:14
*/
/** 储蓄账户操作类
* Class savingsControl
*/
class savingsControl extends bank_apiControl
{
public function requestWithdrawOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge($_GET,$_POST);
$member_id = $params['member_id'];
$amount = round($params['amount'],2);
$currency = $params['currency'];
$handler_id = $params['handler_id'];
$trading_password = $params['trading_password'];
$remark = $params['remark'];
if( !$member_id || $amount<=0 || !$currency || !$handler_id ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_handler = new member_account_handlerModel();
$handler = $m_handler->getRow($handler_id);
if( !$handler ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$memberObject = new objectMemberClass($member_id);
$re = $memberObject->savingsRequestWithdraw($amount,$currency,$handler_id,$remark,$trading_password);
return $re;
}
public function requestDepositOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge($_GET,$_POST);
$member_id = $params['member_id'];
$amount = round($params['amount'],2);
$currency = $params['currency'];
$handler_id = $params['handler_id'];
$remark = $params['remark'];
if( !$member_id || $amount<=0 || !$currency || !$handler_id ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$memberObject = new objectMemberClass($member_id);
$re = $memberObject->savingsRequestDeposit($amount,$currency,$handler_id,$remark);
return $re;
}
public function getMemberBillListOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge($_GET,$_POST);
$member_id = $params['member_id'];
$currency = $params['currency'];
$page_num = $params['page_num']?:1;
$page_size = $params['page_size']?:100000;
$m_member = new memberModel();
$member = $m_member->getRow($member_id);
if( !$member ){
return new result(false,'Member not exist',null,errorCodesEnum::MEMBER_NOT_EXIST);
}
$passbook = passbookClass::getSavingsPassbookOfMemberGUID($member->obj_guid);
$book_id = $passbook->getBookId();
$where = " acc.book_id='$book_id' ";
if( $currency ){
$where .= " and acc.currency='$currency' ";
}
if( $params['min_amount'] ){
$min_amount = round($params['min_amount'],2);
$where .= " and ( (af.credit+af.debit) >= '$min_amount' ) ";
}
if( $params['max_amount'] ){
$max_amount = round($params['max_amount'],2);
$where .= " and ( (af.credit+af.debit) <= '$max_amount' ) ";
}
if( $params['start_date'] ){
$start_date = date('Y-m-d 00:00:00',strtotime($params['start_date']));
$where .= " and af.create_time>='$start_date' ";
}
if( $params['end_date'] ){
$end_date = date('Y-m-d 23:59:59',strtotime($params['end_date']));
$where .= " and af.create_time<='$end_date' ";
}
$r = new ormReader();
$sql = "select af.*,date_format(af.create_time,'%Y-%m') date_month,acc.currency,t.category,t.trading_type,t.subject from passbook_account_flow af left join passbook_trading t on t.uid=af.trade_id
left join passbook_account acc on acc.uid=af.account_id where $where order by af.create_time desc ";
$page = $r->getPage($sql,$page_num,$page_size);
$list = $page->rows;
// 统计各月的合计,去除分页的bug
$sum_sql = "select sum(af.credit) total_credit,sum(af.debit) total_debit,date_format(af.create_time,'%Y-%m') date_month from passbook_account_flow af left join passbook_trading t on t.uid=af.trade_id
left join passbook_account acc on acc.uid=af.account_id where $where group by date_format(af.create_time,'%Y-%m') ";
$month_list = $r->getRows($sum_sql);
$month_total = array();
foreach( $month_list as $v ){
$month_total[$v['date_month']] = $v;
}
$f_list = array();
$trading_type_lang = enum_langClass::getPassbookTradingTypeLang();
foreach( $list as $item ){
$item['trading_type'] = ($trading_type_lang[$item['trading_type']])?:$item['trading_type'];
$month = $item['date_month'];
if( $f_list[$month] ){
$f_list[$month]['summary']['credit'] += $item['credit'];
$f_list[$month]['summary']['debit'] += $item['debit'];
$f_list[$month]['list'][] = $item;
}else{
$f_list[$month] = array(
'month' => $month,
'summary' => array(
'credit' => $item['credit'],
'debit' => $item['debit']
),
'list' => array($item)
);
}
}
foreach( $f_list as $month=>$v ){
$f_list[$month]['summary'] = array(
'credit' => $month_total[$month]['total_credit'],
'debit' => $month_total[$month]['total_debit']
);
}
// 去掉键值
$f_list = array_values($f_list);
$data = array(
'total_num' => $page->count,
'total_pages' => $page->pageCount,
'current_page' => $page_num,
'page_size' => $page_size,
'list' => $f_list
);
return new result(true,'success',$data);
}
public function getBillDetailOp()
{
$re = $this->checkToken();
if( !$re->STS ){
return $re;
}
$params = array_merge($_GET,$_POST);
$bill_id = $params['bill_id'];
$m = new passbook_accountModel();
$sql = "select f.*,t.category,t.trading_type,t.subject from passbook_account_flow f left join passbook_trading t on t.uid=f.trade_id
where f.uid='$bill_id' ";
$flow_info = $m->reader->getRow($sql);
if( !$flow_info ){
return new result(false,'No bill',null,errorCodesEnum::BILL_NOT_EXIST);
}
$trading_type_lang = enum_langClass::getPassbookTradingTypeLang();
$flow_info['trading_type'] = ($trading_type_lang[$flow_info['trading_type']])?:$flow_info['trading_type'];
$account_info = $m->getRow($flow_info['account_id']);
return new result(true,'success',array(
'bill_detail' => $flow_info,
'account_info' => $account_info
));
}
}<file_sep>/framework/api_test/apis/microbank/member.loan.apply.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/19
* Time: 9:28
*/
class memberLoanApplyListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Loan Apply List";
$this->description = "会员贷款申请列表";
$this->url = C("bank_api_url") . "/member.loan.apply.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
//$this->parameters[]= new apiParameter("type", "类型 1 全部 2 执行中 3 待审核 4 逾期合同 ", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'uid' => 'id',
'member_id' => '会员id',
'product_id' => '产品id',
'product_name' => '产品名称',
'applicant_name' => '申请人',
'apply_amount' => '申请金额',
'currency' => '货币',
'contact_phone' => '联系电话',
'loan_propose' => '贷款目的',
'apply_time' => '申请时间',
'state' => '处理状态 0新建 10 处理中 20 处理完成'
)
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/co.add.loan.request.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/8
* Time: 17:01
*/
class coAddLoanRequestApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Co add loan request";
$this->description = "CO为客户提交贷款申请";
$this->url = C("bank_api_url") . "/co.add.loan.request.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1, true);
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("amount", "金额", 500, true);
$this->parameters[]= new apiParameter("currency", "币种", 'USD', true);
$this->parameters[]= new apiParameter("loan_time", "贷款时间", 6, true);
$this->parameters[]= new apiParameter("loan_time_unit", "贷款时间单位", 'month', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '申请信息',
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.loan.contract.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/13
* Time: 11:25
*/
class memberLoanContractListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Loan Contract List";
$this->description = "会员贷款合同列表";
$this->url = C("bank_api_url") . "/member.loan.contract.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("loan_type", "贷款类型 0 自己的贷款 1 担保的贷款 ", 0, true);
$this->parameters[]= new apiParameter("type", "合同类型 1 全部合同 2 执行中的合同 3 待审核 4 逾期合同 5 完成的合同(还款完成) 6 正常执行无逾期的 20 信用贷全部合同", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'uid' => '合同id',
'contract_sn' => '合同编号',
'apply_amount' => '申请金额',
'currency' => '货币',
'start_date' => '开始时间',
'end_date' => '结束时间',
'state' => '合同状态',
'left_period' => '剩余未还期数',
'left_principal' => '剩余未还本金',
),
array()
)
)
);
}
}<file_sep>/framework/api_test/apis/test.ace.api/ace.bind.start.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 17:33
*/
class aceBindStartApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.member.sign.start";
$this->description = "Member sign apply. ACE will send SMS to verify the application. \nThe phone number should belong to some member which is NOT the signed-member of the partner.";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=bind_start";
$this->parameters = array();
$this->parameters[]= new apiParameter("ace_account", "Member Phone Number", "+86-15928677642", true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'sign_id' => '绑定事务编号,Finish时使用'
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/apply.audit.old.php
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Request To Loan</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('loan', 'apply', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL)?>"><span>Unprocessed</span></a></li>
<li><a href="<?php echo getUrl('loan', 'apply', array('type' => 'processed'), false, BACK_OFFICE_SITE_URL)?>"><span>Processed</span></a></li>
<li><a class="current"><span>Audit</span></a></li>
</ul>
</div>
</div>
<div class="container" style="width: 600px;">
<form class="form-horizontal" method="post">
<input type="hidden" name="form_submit" value="ok">
<input type="hidden" name="uid" value="<?php echo $output['apply_info']['uid']?>">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Name'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $output['apply_info']['applicant_name']?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Product'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $output['apply_info']['product_name']?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Applied Amount'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo ncAmountFormat($output['apply_info']['apply_amount'])?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Loan Use'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $output['apply_info']['loan_propose']?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Contact Phone'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $output['apply_info']['contact_phone']?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Apply Time'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo timeFormat($output['apply_info']['apply_time'])?>" disabled>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Audit Remark'?></label>
<div class="col-sm-9">
<textarea class="form-control" name="remark" style="height: 100px;"></textarea>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-col-sm-9" style="padding-left: 15px">
<button type="button" class="btn btn-danger" style="min-width:80px"><?php echo 'Audit' ?></button>
<button type="button" class="btn btn-default" onclick="javascript:history.go(-1);" style="min-width:80px"><?php echo 'Back'?></button>
</div>
</div>
</form>
</div>
</div>
<script>
$(function(){
$('.btn-danger').click(function () {
$('.form-horizontal').submit();
})
/*window.onbeforeunload = function(){
var uid = $('input[name="uid"]').val();
if(!uid){
return false;
}
yo.loadData({
_c: 'loan',
_m: 'unlockedApply',
param: {uid: uid},
callback: function (_o) {
if (!_o.STS) {
return false;
}
}
})
}*/
})
</script>
<file_sep>/framework/weixin_baike/data/model/passbook_trading.model.php
<?php
class passbook_tradingModel extends tableModelBase
{
function __construct()
{
parent::__construct('passbook_trading');
}
}<file_sep>/framework/weixin_baike/backoffice/control/setting.php
<?php
class settingControl extends baseControl
{
public function __construct()
{
parent::__construct();
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Company Info");
Tpl::setDir("setting");
Language::read('setting,certification');
$verify_field = enum_langClass::getCertificationTypeEnumLang();
Tpl::output("cert_verify_lang", $verify_field);
}
/**
* 查看公司信息
*/
public function companyInfoOp()
{
$m_core_dictionary = M('core_dictionary');
$data = $m_core_dictionary->getDictionary('company_config');
if ($data) {
tpl::output('company_config', my_json_decode($data['dict_value']));
}
Tpl::showPage("company.info");
}
/**
* 修改公司信息
*/
public function editCompanyInfoOp()
{
$m_core_dictionary = M('core_dictionary');
if ($_POST['form_submit'] == 'ok') {
$param = $_POST;
unset($param['form_submit']);
if (empty($param['hotline'])) {
$param['hotline'] = array();
} else {
$param['hotline'] = array_unique($param['hotline']);
}
$rt = $m_core_dictionary->updateDictionary('company_config', my_json_encode($param));
if ($rt->STS) {
showMessage($rt->MSG, getUrl('setting', 'companyInfo', array(), false, BACK_OFFICE_SITE_URL));
} else {
showMessage($rt->MSG);
}
} else {
$data = $m_core_dictionary->getDictionary('company_config');
if ($data) {
$company_config = my_json_decode($data['dict_value']);
tpl::output('company_config', $company_config);
}
$address_id = $company_config['address_id'];
$m_core_tree = M('core_tree');
$region_list = $m_core_tree->getParentAndBrotherById($address_id, 'region');
Tpl::output('region_list', $region_list);
Tpl::showPage("company.edit");
}
}
/**
* 编码规则
*/
public function codingRuleOp()
{
var_dump('Todo soon');
// Tpl::showPage("coding_rule");
}
/**
* 配置设置
*/
public function globalOp()
{
$p = array_merge(array(), $_GET, $_POST);
$m_core_dictionary = M('core_dictionary');
if ($p['form_submit'] == 'ok') {
$param = $_POST;
unset($param['form_submit']);
$param['credit_register'] = round($param['credit_register'], 2);
$param['credit_without_approval'] = round($param['credit_without_approval'], 2);
$param['credit_system_limit'] = round($param['credit_system_limit'], 2);
$param['withdrawal_single_limit'] = round($param['withdrawal_single_limit'], 2);
$param['withdrawal_monitor_limit'] = round($param['withdrawal_monitor_limit'], 2);
$param['operator_credit_maximum'] = round($param['operator_credit_maximum'], 2);
$param['date_format'] = intval($param['date_format']);
$param['is_trade_password'] = intval($param['is_trade_password']);
$param['is_create_savings_account'] = intval($param['is_create_savings_account']);
$rt = $m_core_dictionary->updateDictionary('global_settings', my_json_encode($param));
showMessage($rt->MSG);
} else {
$data = $m_core_dictionary->getDictionary('global_settings');
if ($data) {
tpl::output('global_settings', my_json_decode($data['dict_value']));
}
Tpl::showPage("global.setting");
}
}
/**
* 系统枚举定义
* 弃用
*/
public function systemDefineOp()
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->initSystemDefine();
if (!$rt->STS) {
showMessage('Init Failure!');
} else {
Tpl::showpage('system.define');
}
}
/**
* 获取define列表
* @param $p
* @return mixed
*/
public function getDefineListOp($p)
{
$m_core_definition = M('core_definition');
$define_list = $m_core_definition->getDefineList($p);
return $define_list;
}
/**
* 修改define 分类名称
* @param $p
*/
public function editCategoryNameOp($p)
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->editCategoryName($p);
return $rt;
}
/**
* 编辑define item
* @param $p
* @return mixed
*/
public function editDefineItemOp($p)
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->editDefineItem($p);
return $rt;
}
/**
* user.define
*/
public function shortCodeOp()
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->initUserDefine();
if (!$rt->STS) {
showMessage('Init Failure!');
} else {
$lang_list = C('lang_type_list');
Tpl::output('lang_list', $lang_list);
Tpl::showpage('user.define');
}
}
/**
* 添加define item
* @param $p
* @return mixed
*/
public function addDefineItemOp($p)
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->addDefineItem($p);
return $rt;
}
/**
* 移除define item
* @param $p
* @return mixed
*/
public function removeDefineItemOp($p)
{
$m_core_definition = M('core_definition');
$rt = $m_core_definition->removeDefineItem($p);
return $rt;
}
public function creditLevelOp()
{
$return = credit_loanClass::getCreditLevelList();
$type_lang = array(
creditLevelTypeEnum::MEMBER => 'Member',
creditLevelTypeEnum::MERCHANT => 'Merchant'
);
Tpl::output('credit_level', $return);
Tpl::output('level_type_lang', $type_lang);
Tpl::showPage('credit.level.list');
}
public function addCreditLevelOp()
{
$params = array_merge(array(), $_GET, $_POST);
if ($params['form_submit'] == 'ok') {
$min_amount = $params['min_amount'];
$max_amount = $params['max_amount'];
$cert_list = $params['cert_list'];
if ($min_amount < 0 || $max_amount <= 0) {
showMessage('Amount Invalid');
}
if ($min_amount >= $max_amount) {
showMessage('Min amount more than max amount');
}
if (empty($cert_list)) {
showMessage('Did not select certification');
}
$conn = ormYo::Conn();
try {
$conn->startTransaction();
$re = credit_loanClass::addCreditLevel($params);
if (!$re->STS) {
$conn->rollback();
showMessage('Add fail');
}
$conn->submitTransaction();
showMessage('Add success', getUrl('setting', 'creditLevel', array(), false, BACK_OFFICE_SITE_URL));
} catch (Exception $e) {
showMessage('Add fail');
}
}
Tpl::showPage('credit.level.add');
}
public function editCreditLevelOp()
{
$params = array_merge(array(), $_GET, $_POST);
if ($params['form_submit'] == 'ok') {
$min_amount = $params['min_amount'];
$max_amount = $params['max_amount'];
$cert_list = $params['cert_list'];
if ($min_amount < 0 || $max_amount <= 0) {
showMessage('Amount Invalid');
}
if ($min_amount >= $max_amount) {
showMessage('Min amount more than max amount');
}
if (empty($cert_list)) {
showMessage('Did not select certification');
}
$conn = ormYo::Conn();
try {
$conn->startTransaction();
$re = credit_loanClass::editCreditLevel($params);
if (!$re->STS) {
$conn->rollback();
showMessage('Edit fail');
}
$conn->submitTransaction();
showMessage('Edit success');
} catch (Exception $e) {
showMessage('Edit fail');
}
} else {
$uid = $params['uid'];
if (!$uid) {
showMessage('Invalid param');
}
$m_level = new loan_credit_cert_levelModel();
$row = $m_level->getRow($uid);
if (!$row) {
showMessage('No data!');
}
$sql = "select cert_type from loan_credit_level_cert_list where cert_level_id='$uid' ";
$cert_list = array();
$list = $m_level->reader->getRows($sql);
foreach ($list as $v) {
$cert_list[] = $v['cert_type'];
}
$level_info = $row->toArray();
$level_info['cert_list'] = $cert_list;
Tpl::output('level_info', $level_info);
Tpl::showPage('credit.level.edit');
}
}
public function deleteCreditLevelOp($p)
{
$id = $p['id'];
return credit_loanClass::deleteCreditLevel($id);
}
public function creditProcessOp()
{
$all_dict = global_settingClass::getAllDictionary();
Tpl::output('all_dict',$all_dict);
Tpl::showPage('credit.process.list');
}
public function openCreditProcessOp($p)
{
$type = $p['type'];
$m = new core_dictionaryModel();
switch( $type )
{
case 1:
$row = $m->getRow(array(
'dict_key' => 'close_credit_fingerprint_cert',
));
if( $row ){
if( $row->dict_value == 0 ){
return new result(false,'Is opened!');
}
$row->dict_value = 0;
$up = $row->update();
if( !$up->STS ){
return new result(false,'Open fail!');
}
return new result(true,'Success!');
}else{
$row = $m->newRow();
$row->dict_key = 'close_credit_fingerprint_cert';
$row->dict_value = 0;
$insert = $row->insert();
if( !$insert->STS ){
return new result(false,'Open fail!');
}
return new result(true,'Success!');
}
break;
case 2:
$row = $m->getRow(array(
'dict_key' => 'close_credit_authorized_contract',
));
if( $row ){
if( $row->dict_value == 0 ){
return new result(false,'Is opened!');
}
$row->dict_value = 0;
$up = $row->update();
if( !$up->STS ){
return new result(false,'Open fail!');
}
return new result(true,'Success!');
}else{
$row = $m->newRow();
$row->dict_key = 'close_credit_authorized_contract';
$row->dict_value = 0;
$insert = $row->insert();
if( !$insert->STS ){
return new result(false,'Open fail!');
}
return new result(true,'Success!');
}
break;
default:
return new result(false,'Unknown function');
break;
}
}
public function closeCreditProcessOp($p)
{
$type = $p['type'];
$m = new core_dictionaryModel();
switch( $type )
{
case 1:
$row = $m->getRow(array(
'dict_key' => 'close_credit_fingerprint_cert',
));
if( $row ){
if( $row->dict_value == 1 ){
return new result(false,'Is Closed!');
}
$row->dict_value = 1;
$up = $row->update();
if( !$up->STS ){
return new result(false,'Close fail!');
}
return new result(true,'Success!');
}else{
$row = $m->newRow();
$row->dict_key = 'close_credit_fingerprint_cert';
$row->dict_value = 1;
$insert = $row->insert();
if( !$insert->STS ){
return new result(false,'Close fail!');
}
return new result(true,'Success!');
}
break;
case 2:
$row = $m->getRow(array(
'dict_key' => 'close_credit_authorized_contract',
));
if( $row ){
if( $row->dict_value == 1 ){
return new result(false,'Is Closed!');
}
$row->dict_value = 1;
$up = $row->update();
if( !$up->STS ){
return new result(false,'Close fail!');
}
return new result(true,'Success!');
}else{
$row = $m->newRow();
$row->dict_key = 'close_credit_authorized_contract';
$row->dict_value = 1;
$insert = $row->insert();
if( !$insert->STS ){
return new result(false,'Close fail!');
}
return new result(true,'Success!');
}
break;
default:
return new result(false,'Unknown function');
break;
}
}
/**
* 获取地址选项
* @param $p
* @return array
*/
public function getAreaListOp($p)
{
$pid = intval($p['uid']);
$m_core_tree = M('core_tree');
$list = $m_core_tree->getChildByPid($pid, 'region');
return array('list' => $list);
}
/**
* 重置系统
*/
public function resetSystemOp()
{
Tpl::showPage('reset.system');
}
public function resetSystemConfirmOp()
{
$is_can = intval(getConf('is_open_reset_system'));
if( $is_can !== 1 ){
return new result(false,'Function closed!');
}
// todo 检查操作人权限
$re = global_settingClass::resetSystemData();
if( $re == true ){
return new result(true,'success');
}else{
return new result(false,'Reset fail!');
}
}
}
<file_sep>/framework/weixin_baike/counter/templates/default/member/contract.info.php
<style>
.rightbox,.prepayment_amount,.prepayment_periods,#prepayment_type,#pay_type{
text-align: right;
padding-right: 10px;
}
.redstar{
color: red;
}
.title{
font-size: 15px;
font-weight: bold;
}
tr{
border-bottom:1px solid gainsboro;
margin-bottom: 3px;
}
#prepayment_type,#pay_type,.prepayment_amount,.prepayment_periods{
border: none;
}
</style>
<?php $info = $data['data']; ?>
<?php if($info){?>
<table class="table contract-table">
<tbody class="table-body">
<tr>
<td><label class="control-label">Client-ID</label></td>
<td><?php echo $info['member_id'] ?></td>
<td colspan="2" class="contract-btn">
<button class="btn btn-default" onclick="prepayment_btn()">Prepayment</button>
<button class="btn btn-default" onclick="repayment_btn()">Repayment</button>
<a class="btn btn-default" href="<?php echo getUrl('member', 'showMortgage',array('uid'=>$info['uid']), false, ENTRY_COUNTER_SITE_URL);?>">Mortgage</a>
</td>
</tr>
<tr>
<td><label class="control-label">Client-Name</label></td>
<td><?php echo $info['display_name'] ?></td>
<td><label class="control-label">Disbursement</label></td>
<td style="position: relative">
<em style="padding-left: 0px"><?php echo count($info['disbursement']) . ' Periods' ?></em>
<div class="loan-exp-wrap">
<div class="pos">
<em class="triangle-up"></em>
<table class="loan-exp-table">
<tr class="t">
<td>Amount</td>
<td></td>
<td>Principal</td>
<td></td>
<td>Annual Fee</td>
<td></td>
<td>Interest</td>
<td></td>
<td>Admin Fee</td>
<td></td>
<td>Operation Fee</td>
<td></td>
<td>Insurance Fee</td>
<td></td>
<td>Execute Time</td>
</tr>
<?php foreach ($info['disbursement'] as $key => $value) { ?>
<tr class="a">
<td class="y"><?php echo $value['amount']; ?></td>
<td> = </td>
<td><?php echo $value['principal']; ?></td>
<td> - </td>
<td><?php echo $value['deduct_annual_fee']; ?></td>
<td> - </td>
<td><?php echo $value['deduct_interest']; ?></td>
<td> - </td>
<td><?php echo $value['deduct_admin_fee']; ?></td>
<td> - </td>
<td><?php echo $value['deduct_operation_fee']; ?></td>
<td> - </td>
<td><?php echo round($value['deduct_insurance_fee'], 2); ?></td>
<td> </td>
<td><?php echo timeFormat($value['execute_time']); ?></td>
</tr>
<?php }?>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td><label class="control-label">Client-Phone</label></td>
<td><?php echo $info['phone_id'] ?></td>
<td><label class="control-label">Installment</label></td>
<td style="position:relative;">
<em style="padding-left: 0px"><?php echo count($info['installment']) . ' Periods' ?></em>
<div class="loan-exp-wrap">
<div class="pos">
<em class="triangle-up"></em>
<table class="loan-exp-table">
<tr class="t">
<td>Amount</td>
<td></td>
<td>Principal</td>
<td></td>
<td>Interest</td>
<td></td>
<td>Admin Fee</td>
<td></td>
<td>Operation Fee</td>
<td></td>
<td>Penalties</td>
<td></td>
<td>Repayment Time</td>
</tr>
<?php foreach ($info['installment'] as $key => $value) { ?>
<tr class="a">
<td class="y"><?php echo $value['amount']; ?></td>
<td> = </td>
<td><?php echo $value['receivable_principal']; ?></td>
<td> + </td>
<td><?php echo $value['receivable_interest']; ?></td>
<td> + </td>
<td><?php echo $value['receivable_admin_fee']; ?></td>
<td> + </td>
<td><?php echo $value['receivable_operation_fee']; ?></td>
<td> + </td>
<td><?php echo round($value['penalties'], 2) ?></td>
<td> </td>
<td><?php echo timeFormat($value['receivable_date']); ?></td>
</tr>
<?php }?>
</table>
</div>
</div>
</td>
</tr>
<tr>
<td><label class="control-label">Contract No.</label></td>
<td colspan="3"><?php echo $info['contract_sn'] ?></td>
</tr>
<tr>
<td><label class="control-label">Status</label></td>
<td colspan="3">
<?php switch ($info['state']) {
case loanContractStateEnum::CREATE :
$label = 'Create';
break;
case loanContractStateEnum::PENDING_APPROVAL :
$label = 'Pending Approval';
break;
case loanContractStateEnum::PENDING_DISBURSE :
$label = 'Pending Disburse';
break;
case loanContractStateEnum::PROCESSING :
$label = 'Ongoing';
break;
case loanContractStateEnum::PAUSE :
$label = 'Pause';
break;
case loanContractStateEnum::COMPLETE :
$label = 'Complete';
break;
case loanContractStateEnum::WRITE_OFF :
$label = 'Write Off';
break;
default:
$label = 'Write Off';
break;
}
echo $label;
?>
</td>
</tr>
<tr>
<td><label class="control-label">Product Name</label></td>
<td colspan="3"><?php echo $info['product_name'] ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Limit</label></td>
<td colspan="3" class="money-style"><?php echo ncAmountFormat($info['apply_amount']) ?></td>
</tr>
<tr>
<td><label class="control-label">Outstanding Balance</label></td>
<td colspan="3" class="money-style"><?php echo '$1000.00' ?></td>
</tr>
<tr>
<td><label class="control-label">Period</label></td>
<td colspan="3"><?php echo $info['loan_period_value'] . ' ' . $info['loan_period_unit'] ?></td>
</tr>
<tr>
<td><label class="control-label">Repayment Type</label></td>
<td colspan="3"><?php echo ucwords(str_replace('_', ' ', $info['repayment_type'])) ?></td>
</tr>
<tr>
<td><label class="control-label">Interest Rate</label></td>
<td colspan="3"><?php echo ($info['interest_rate_type'] == 1 ? "$" . $info['interest_rate'] : $info['interest_rate'] . '%') . ' Per ' . $info['interest_rate_unit'] ?></td>
</tr>
<tr>
<td><label class="control-label">Operation Fee</label></td>
<td colspan="3"><?php echo ($info['operation_fee_type'] == 1 ? "$" . $info['operation_fee'] : $info['operation_fee'] . '%') . ' Per ' . $info['operation_fee_unit'] ?></td>
</tr>
<tr>
<td><label class="control-label">Admin Fee</label></td>
<td colspan="3"><?php echo $info['admin_fee_type'] == 1 ? "$" . $info['admin_fee'] : $info['admin_fee'] . '%' ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Fee</label></td>
<td colspan="3"><?php echo $info['loan_fee_type'] == 1 ? "$" . $info['loan_fee'] : $info['loan_fee'] . '%' ?></td>
</tr>
<tr>
<td><label class="control-label">Insurance Fee</label></td>
<td colspan="3"><?php echo ncAmountFormat($info['insurance'][$info['uid']]['price']) ?></td>
</tr>
<tr>
<td><label class="control-label">Due Date</label></td>
<td colspan="3"><?php echo dateFormat($info['end_date']) ?></td>
</tr>
</tbody>
</table>
<!--prepaymentModal-->
<div class="modal" id="prepaymentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" style="width: 700px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?php echo 'Prepayment'?></h4>
</div>
<div>
<form class="col-sm-12" id="prepayment_form">
<input type="hidden" id='contract_id' name="contract_id" value="<?php $info['uid']?>">
<table class="table">
<tr>
<td><span class="title"><?php echo 'Need Prepayment' ?></span></td>
<td class="rightbox"><span><?php echo 8?></span></td>
</tr>
<tr>
<td><span class="title"><?php echo 'Rest Periods' ?></span></td>
<td class="rightbox"><span><?php echo 6?></span></td>
</tr>
<tr>
<td><span class="title"><?php echo 'Rest Principal' ?></span></td>
<td class="rightbox"><span><?php echo 50?></span></td>
</tr>
<tr>
<td><span class="redstar">*</span><span class="title"><?php echo 'Prepayment Type' ?></span></td>
<td class="rightbox">
<select name="prepayment_type" id="prepayment_type" onchange="chooseType()">
<option id="full" value="1">Full Payment </option>
<option id="partial" value="0">Partial Payment </option>
</select>
</td>
</tr>
<tr id="part_prepayment">
<td><span class="redstar">*</span><span class="title"><?php echo 'Partial Payment' ?></span></td>
<td class="rightbox">
<select id="pay_type" name='prepayment_type' onchange="chooseMethod()">
<option id="pay_type_periods">Partial By Periods</option>
<option id="pay_type_amount">Partial By Amount</option>
</select>
</td>
</tr>
<tr id="prepayment_periods">
<td><span class="required-options-xing">*</span><span class="title"><?php echo 'Prepayment Periods' ?></span></td>
<td class="rightbox"><input class='prepayment_periods' type="text" value="" name="repay_period" placeholder="Please input Periods"></td>
</tr>
<tr id="prepayment_amount">
<td><span class="redstar">*</span><span class="title"><?php echo 'Prepayment Amount' ?></span></td>
<td class="rightbox"><input class='prepayment_amount' type="text" value="" name="amount" placeholder="Please input Amount"></td>
</tr>
</table>
</form>
</div>
<div class="modal-footer" style="text-align: center;">
<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo 'Cancel'?></button>
<button type="button" class="btn btn-danger" onclick="submit_prepayment()"><?php echo 'Submit'?></button>
</div>
</div>
</div>
</div>
<!--repaymentModal-->
<div class="modal" id="repaymentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" style="width: 700px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?php echo 'Repayment'?></h4>
</div>
<div class="modal-body">
<div class="modal-form">
<form class="form-horizontal" id="repayment_form">
<input name="uid" value="<?php echo $info['uid']?>" type="hidden">
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Contract Sn' ?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="<?php echo $info['contract_sn']?>" id="scheme_name" readonly>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing"></span><?php echo 'Expired Repayment'; ?></label>
<div class="col-sm-9">
<table class="table table-bordered">
<thead>
<tr class="table-header" style="background: #EFEFEF">
<td>Scheme Name</td>
<td>Repayment Total</td>
<td>Principal And Interest</td>
<td>Penalties</td>
</tr>
</thead>
<tbody class="table-body">
<?php if(!$info['repayment_arr']){?>
<tr>
<td colspan="4">Null</td>
</tr>
<?php }else{ ?>
<?php
$repayment_total = 0;
$principal_interest_total = 0;
$penalties_total = 0;
foreach ($info['repayment_arr'] as $scheme){?>
<tr>
<td>
<?php echo $scheme['scheme_name']?>
</td>
<td>
<?php $repayment = $scheme['amount'] + $scheme['penalties'] - $scheme['actual_payment_amount'];
$repayment_total += $repayment;
echo ncAmountFormat($repayment)?>
</td>
<td>
<?php $principal_interest = ($scheme['amount'] - $scheme['actual_payment_amount']) > 0 ? $scheme['amount'] - $scheme['actual_payment_amount'] : 0;
$principal_interest_total += $principal_interest;
echo ncAmountFormat($principal_interest)?>
</td>
<td>
<?php $penalties_total += $scheme['penalties'];
echo ncAmountFormat($scheme['penalties'])?>
</td>
</tr>
<?php }?>
<tr style="font-weight: 700">
<td>
<?php echo 'Total' ?>
</td>
<td>
<?php echo ncAmountFormat($repayment_total) ?>
</td>
<td>
<?php echo ncAmountFormat($principal_interest_total) ?>
</td>
<td>
<?php echo ncAmountFormat($penalties_total) ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Repayment Total' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="repayment_total" value="">
<span class="input-group-addon" style="min-width: 55px;border-left: 0;border-radius: 0">$</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Remark' ?></label>
<div class="col-sm-9">
<input type="text" class="form-control" value="" name="remark">
<div class="error_msg"></div>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer" style="text-align: center;">
<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo 'Cancel'?></button>
<button type="button" class="btn btn-danger" onclick="submit_repayment()"><?php echo 'Submit'?></button>
</div>
</div>
</div>
</div>
<?php }else{?>
<div style="min-height: 200px;padding: 5px 20px">Null</div>
<?php }?>
<script>
$(function () {
$('#part_prepayment').hide();
$('#prepayment_amount').hide();
$('#prepayment_periods').hide();
})
function chooseType(){
if( $("#partial").prop('selected')){
$("#part_prepayment").show();
if($('#pay_type_periods').prop('selected')){
$("#prepayment_periods").show();
}else{
$("#prepayment_amount").show();
}
}else {
$('#part_prepayment').hide();
$("#prepayment_amount").hide();
$("#prepayment_periods").hide();
}
}
function chooseMethod(){
if($('#pay_type_amount').prop('selected')){
$("#prepayment_amount").show();
}else{
$("#prepayment_amount").hide();
}
if($('#pay_type_periods').prop('selected')){
$("#prepayment_periods").show();
}else{
$("#prepayment_periods").hide();
}
}
// function submit_prepayment() {
// var values = $("#prepayment_form").getValues();
// yo.loadData({
// _c: "member",
// _m: "submitRepayment",
// param: values,
// callback: function (_o) {
// alert(_o.MSG);
// if (_o.STS) {
// btn_search_onclick();
// }
// }
//
// })
</script>
<file_sep>/framework/weixin_baike/api/control/loan_product.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/6
* Time: 17:24
*/
class loan_productControl extends bank_apiControl
{
/**
* 取得贷款产品列表
* @return result
*/
public function getProductListOp()
{
// 产品少,不分页了
$param = array_merge(array(),$_GET,$_POST);
$m = new loan_productModel();
$list = $m->field('uid,product_code,product_name,product_description')->orderBy('uid asc')->getRows(array(
'state' => loanProductStateEnum::ACTIVE
));
$return = array();
foreach( $list as $v){
// 计算产品最低月利率
$min = loan_productClass::getMinMonthlyRate($v['uid']);
$v['min_rate'] = $min;
$v['min_rate_desc'] = $min.'%';
$return[] = $v;
}
return new result(true,'success',$return);
}
public function getProductDetailInfoOp()
{
$param = array_merge(array(),$_GET,$_POST);
$product_id = $param['product_id'];
$product_detail = loan_productClass::getProductDetailInfo($product_id);
if( !$product_detail ){
return new result(false,'No product',null,errorCodesEnum::NO_LOAN_PRODUCT);
}
return new result(true,'success',$product_detail);
}
public function getProductDesRateListOp()
{
$param = array_merge(array(),$_GET,$_POST);
$product_id = $param['product_id'];
$currency = $param['currency'];
$page_num = $param['page_num'];
$page_size = $param['page_size'];
$re = loan_productClass::getProductDescribeRateList($product_id,$page_num,$page_size,$currency);
return new result(true,'success',$re);
}
}<file_sep>/framework/execute_sql/data/config/conf.dora.php
<?php
$config['db_conf']=array(
"db_local"=>array(
"db_type"=>"mysql",
"db_host"=>"localhost",
"db_user"=>"root",
"db_pwd"=>"",
"db_name"=>"loan",
"db_port"=>3306
),
"db_remote" => array(
"db_type"=>"mysql",
"db_host"=>"172.16.31.10",
"db_user"=>"demo",
"db_pwd"=>"<PASSWORD>",
"db_name"=>"bank_demo",
"db_port"=>3306
)
);
$config['author'] = "Dora";
$config['debug']=true;
$config['site_root'] = 'http://localhost/microbank';
$config['global_resource_site_url'] = "http://localhost/microbank/resource";
$config['project_resource_site_url'] = "http://localhost/microbank/entry/resource";
$config['entry_api_url'] = "http://localhost/microbank/entry/api/v1";
$config['session']['save_handler'] = 'redis';
$config['session']['save_path'] = 'tcp://127.0.0.1:6379?weight=1&persistent=1&prefix=PHPREDIS_SESSION_DEMO&database=11';
<file_sep>/framework/api_test/apis/microbank/system.config.init.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 14:19
*/
class systemConfigInitApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System config init ";
$this->description = "系统一些配置初始化";
$this->url = C("bank_api_url") . "/system.config.init.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'user_define' => array(
'@description' =>
'用户定义的选项有多语言返回,格式如下 ,key含义 loan_use 贷款用途 gender 性别 marital_status 婚姻状态 occupation 职业 family_relationship 家庭关系 guarantee_relationship 担保人关系类型 ',
'loan_use' => array(
array(
'uid' => 'ID',
'category' => '分类',
'category_name' => '分类名称',
'category_name_json' => '分类名称多语言',
'item_name' => '项目名称',
'item_name_json' => '项目名称多语言 en 英语 kh 柬语 zh_cn 中文',
'item_code' => '项目简码',
'item_desc' => '项目描述',
'item_value' => '项目计算值',
'is_system' => '是否系统内置'
)
),
),
'system_define' => array(
'@description' =>
'系统内置的只有值,没有语言 key含义 currency 币种 repayment_type 还款方式 repayment_period 还款周期 credit_loan_level 贷款时间单位 loan_time_unit',
'repayment_type' => array(
"single_repayment","fixed_principal","annuity_scheme","flat_interest","balloon_interest"
),
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.message.read.php
<?php
class memberMessageReadApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Read Messages";
$this->description = "会员读取消息";
$this->url = C("bank_api_url") . "/member.message.read.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("message_id", "消息ID", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '消息详细属性',
'message_id' => '消息id',
'message_type' => '消息类型',
'sender_type' => '发送者类型',
'sender_id' => '发送者ID',
'sender_name' => '发送者名称',
'message_title' => '消息标题',
'message_body' => '消息内容',
'message_time' => '消息时间'
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/language/en/operator.php
<?php
$lang['operator_task_state_0'] = 'Create';
$lang['operator_task_state_10'] = 'Locked';
$lang['operator_task_state_11'] = 'Close';
$lang['operator_task_state_100'] = 'Pass';
$lang['client_member_state_0'] = 'Write Off';
$lang['client_member_state_1'] = 'Create';
$lang['client_member_state_10'] = 'Checked';
$lang['client_member_state_20'] = 'Locking';
$lang['client_member_state_100'] = 'Verified';<file_sep>/framework/api_test/apis/microbank/member.bind.bank.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/6
* Time: 13:41
*/
// member.bind.bank
class memberBindBankApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member bind bank";
$this->description = "会员绑定银行卡";
$this->url = C("bank_api_url") . "/member.bind.bank.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("bank_id", "银行编号ID", 1, true);
$this->parameters[]= new apiParameter("account_name", "账户名称", 'test', true);
$this->parameters[]= new apiParameter("account_no", "账户账号", '611254155488632', true);
$this->parameters[]= new apiParameter("country_code", "银行为wing时传,国家码", '855', false);
$this->parameters[]= new apiParameter("phone_number", "银行为wing时传,电话号码", '1236547', false);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/test.ace.api/ace.collect.start.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 17:43
*/
class aceCollectStartApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.transfer.member2partner.start";
$this->description = "Transfer money from signed member to his signed partner (for return loan).";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=collect_start";
$this->parameters = array();
$this->parameters[]= new apiParameter("ace_account", "Member Phone Number", "+86-15928677642", true);
$this->parameters[]= new apiParameter("amount", "金额", "100", true);
$this->parameters[]= new apiParameter("currency", "货币", "USD", true);
$this->parameters[]= new apiParameter("description", "交易描述", "Installment Test");
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'transfer_id' => '事务编号,finish时使用'
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.identity.authentication.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="authenticate-div">
<div class="basic-info">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Id Card Information</h5>
</div>
<div class="content">
<form class="form-horizontal" id="basic-info">
<input type="hidden" name="client_id" value="<?php echo $output['client_info']['uid']; ?>">
<div class="col-sm-6">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Id Number</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="id_number" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Expire Date</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="expire_date" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Gender</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" name="gender" value="0" checked>Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" value="1">Female
</label>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Marital Status</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" name="civil_status" value="1" checked>Married
</label>
<label class="radio-inline">
<input type="radio" name="civil_status" value="0">Unmarried
</label>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Date Of Birth</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="birthday" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Birth Country</label>
<div class="col-sm-8">
<select class="form-control" name="birth_country">
<?php foreach ($output['country_code'] as $key => $code) { ?>
<option value="<?php echo $key; ?>"><?php echo $code; ?></option>
<?php } ?>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Birth Province</label>
<div class="col-sm-8">
<select class="form-control" name="birth_province" disabled>
<option value="0">Please Select</option>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Birth District</label>
<div class="col-sm-8">
<select class="form-control" name="birth_district" disabled>
<option>Please Select</option>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Birth Commune</label>
<div class="col-sm-8">
<select class="form-control" name="birth_commune" disabled>
<option>Please Select</option>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Birth Village</label>
<div class="col-sm-8">
<select class="form-control" name="birth_village" disabled>
<option>Please Select</option>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing">*</span>Address</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="address" value="">
<div class="error_msg"></div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label" style="color: #c49e35;text-align: left;font-size: 14px"><span class="required-options-xing"></span>Khmer Name</label>
<div class="col-sm-8" style="height: 30px">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Family Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="kh_family_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Given Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="kh_given_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Second Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="kh_second_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Third Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="kh_third_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label" style="color: #c49e35;text-align: left;font-size: 14px"><span class="required-options-xing"></span>English Name</label>
<div class="col-sm-8" style="height: 30px">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Family Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="en_family_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Given Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="given_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Second Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="second_name" value="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label"><span class="required-options-xing"></span>Third Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="third_name" value="">
<div class="error_msg"></div>
</div>
</div>
</div>
<input type="hidden" name="handheld_img" value="">
<input type="hidden" name="frontal_img" value="">
<input type="hidden" name="back_img" value="">
</form>
</div>
</div>
<div class="scene-photo">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Scene Photo</h5>
</div>
<div class="content">
<div class="snapshot_div" id="handheld" onclick="callWin_snapshot_slave();">
<img src="resource/img/member/photo.png">
<div>Handheld ID Card</div>
</div>
<div class="snapshot_div" id="frontal" onclick="callWin_snapshot_master('frontal');">
<img src="resource/img/member/photo.png">
<div>Frontal ID Card</div>
</div>
<div class="snapshot_div" id="back" onclick="callWin_snapshot_master('back');">
<img src="resource/img/member/photo.png">
<div>Back ID Card</div>
</div>
<div class="snapshot_msg error_msg">
<div class="handheld_img"></div>
<div class="frontal_img"></div>
<div class="back_img"></div>
</div>
</div>
</div>
<div class="operation">
<a class="btn btn-default" href="<?php echo getUrl('member', 'documentCollection', array('client_id' => $output['client_info']['uid']), false, ENTRY_COUNTER_SITE_URL); ?>">Back</a>
<button class="btn btn-primary" onclick="submit_form()">Submit</button>
</div>
</div>
</div>
</div>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/bootstrap-datepicker/bootstrap-datepicker.js"></script>
<script>
var upyun_url = '<?php echo C('upyun_param')['upyun_url']?>/';
function callWin_snapshot_slave() {
if (window.external) {
try {
var _img_path = window.external.getSnapshot("1");
if (_img_path != "" && _img_path != null) {
_img_path = getUPyunImgUrl(_img_path);
$("#handheld img").attr("src", _img_path);
$('input[name="handheld_img"]').val(_img_path);
}
} catch (ex) {
alert(ex.Message);
}
}
}
function callWin_snapshot_master(type){
if(window.external){
try{
var _img_path= window.external.getSnapshot("0");
if(_img_path!="" && _img_path!=null){
$("#" + type + " img").attr("src",getUPyunImgUrl(_img_path));
$('input[name="' + type + '_img"]').val(_img_path);
}
}catch (ex){
alert(ex.Message);
}
}
}
function getUPyunImgUrl(_img_path) {
return upyun_url + _img_path;
}
$(function () {
getArea(0, 1);
$('[name="birthday"]').datepicker({
format: 'yyyy-mm-dd'
});
$('[name="expire_date"]').datepicker({
format: 'yyyy-mm-dd'
});
$('select[name="birth_province"]').change(function () {
var val = $(this).val();
getArea(val, 2);
});
$('select[name="birth_district"]').change(function () {
var val = $(this).val();
getArea(val, 3);
});
$('select[name="birth_commune"]').change(function () {
var val = $(this).val();
getArea(val,4);
});
})
function getArea(uid, lev) {
var _option = '<option>Please Select</option>'
if (lev == 1) {
$('select[name="birth_province"]').html(_option).attr('disabled', true);
$('select[name="birth_district"]').html(_option).attr('disabled', true);
$('select[name="birth_commune"]').html(_option).attr('disabled', true);
$('select[name="birth_village"]').html(_option).attr('disabled', true);
} else if (lev == 2) {
$('select[name="birth_district"]').html(_option).attr('disabled', true);
$('select[name="birth_commune"]').html(_option).attr('disabled', true);
$('select[name="birth_village"]').html(_option).attr('disabled', true);
} else if (lev == 3) {
$('select[name="birth_commune"]').html(_option).attr('disabled', true);
$('select[name="birth_village"]').html(_option).attr('disabled', true);
} else {
$('select[name="birth_village"]').html(_option).attr('disabled', true);
}
yo.dynamicTpl({
tpl: "member/area.list",
control: "counter_base",
dynamic: {
api: "member",
method: "getAreaList",
param: {uid: uid}
},
callback: function (_tpl) {
if (lev == 1) {
$('select[name="birth_province"]').html(_tpl).attr('disabled', false);
} else if (lev == 2) {
$('select[name="birth_district"]').html(_tpl).attr('disabled', false);
} else if (lev == 3) {
$('select[name="birth_commune"]').html(_tpl).attr('disabled', false);
} else {
$('select[name="birth_village"]').html(_tpl).attr('disabled', false);
}
}
})
}
function submit_form() {
if (!$("#basic-info").valid()) {
return;
}
var values = $('#basic-info').getValues();
yo.loadData({
_c: 'member',
_m: 'saveIdentityAuthentication',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
setTimeout(window.location.href = _o.DATA.url, 1000);
} else {
alert(_o.MSG);
}
}
});
}
$('#basic-info').validate({
errorPlacement: function(error, element){
var name = $(element).attr('name');
if (name == 'handheld_img' || name == 'frontal_img' || name == 'back_img') {
error.appendTo($('.snapshot_msg .' + name));
} else {
error.appendTo(element.closest('.form-group').find('.error_msg'));
}
},
rules : {
id_number : {
required : true
},
expire_date : {
required : true
},
birthday : {
required : true
},
birth_country : {
required : true
},
birth_province : {
chkSelect : true
},
birth_district : {
chkSelect : true
},
birth_commune : {
chkSelect : true
},
birth_village : {
chkSelect : true
},
address : {
required : true
},
handheld_img : {
required : true
},
frontal_img : {
required : true
},
back_img : {
required : true
}
},
messages : {
id_number : {
required : 'Required'
},
expire_date : {
required : 'Required'
},
birthday : {
required : 'Required'
},
birth_country : {
required : 'Required'
},
birth_province : {
chkSelect : 'Required'
},
birth_district : {
chkSelect : 'Required'
},
birth_commune : {
chkSelect : 'Required'
},
birth_village : {
chkSelect : 'Required'
},
address : {
required : 'Required'
},
handheld_img : {
required : 'Handheld id card must be uploaded!'
},
frontal_img : {
required : 'Frontal id card must be uploaded!'
},
back_img : {
required : 'Back ID Card must be uploaded!'
}
}
});
jQuery.validator.addMethod("chkSelect", function (value, element) {
if (value > 0) {
return true;
} else {
return false;
}
});
</script><file_sep>/framework/weixin_baike/counter/templates/default/widget/app.menu.left.php
<div id="sidebar" style="OVERFLOW-Y: auto; OVERFLOW-X:hidden;">
<ul>
<?php foreach ($output['menu_items'] as $k_c => $s_item) {
$first_child = array_shift($s_item['child']);
$args = explode(',', $first_child['args']); ?>
<li class="submenu">
<a href="#" class="menu_a"
link="<?php echo getUrl($args[1], $args[2], array(), false, C('site_root') . DS . $args[0]); ?>">
<img class="tab-default"
src="<?php echo ENTRY_COUNTER_SITE_URL . '/resource/img/counter-icon/tab_' . $k_c . '.png' ?>">
<img class="tab-active"
src="<?php echo ENTRY_COUNTER_SITE_URL . '/resource/img/counter-icon/tab_' . $k_c . '_active.png' ?>">
<span><?php echo $s_item['title'] ?></span>
</a>
</li>
<?php } ?>
</ul>
</div>
<!--sidebar-menu--><file_sep>/framework/api_test/apis/microbank/loan.contract.get.prepayment.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/19
* Time: 18:29
*/
// loan.contract.get.prepayment.detail
class loanContractGetPrepaymentDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract prepayment detail";
$this->description = "贷款合同提前还款信息";
$this->url = C("bank_api_url") . "/loan.contract.get.prepayment.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", "合同id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_overdue_amount' => '逾期计划总额',
'next_repayment_date' => '最近还款日',
'next_repayment_amount' => '最近应还款金额(本金+利息)',
'total_left_principal' => '可提前还剩余本金',
'total_left_periods' => '可提前还的剩余期数',
'total_need_pay' => array(
'@description' => '必还统计',
'total' => '合计必还总额',
'principal' => '合计应还本金',
'interest' => '合计应还利息',
'penalty' => '合计应还罚金'
),
'last_prepayment_request' => array(
'@description' => '上次申请结果,没有为null',
'uid' => '请求id',
'contract_id' => '合同id',
'amount' => '申请应还总金额',
'currency' => '币种',
'prepayment_type' => '提前还款方式',
'repay_period' => '申请偿还期数',
'principal_amount' => '申请提前还本金',
'fee_amount' => '申请提前还本金手续费',
'apply_time' => '申请时间',
'state' => '状态 0 新建 10 审核中 11 审核拒绝 20 审核通过 30 已付款 40 钱到账,未处理合同 100 合同提前还款处理完成 101 合同提前还款处理失败 '
),
'prepayment_payment_record' => array(
'@description' => '还款申请记录',
array(
'amount' => '金额',
'currency' => '币种',
'create_time' => '时间',
'state' => '处理状态,0 新加 20 处理中 21 收钱失败 30 已收钱 100 处理成功',
)
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/member_authorized_contract.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/6
* Time: 9:54
*/
class member_authorized_contractModel extends tableModelBase
{
function __construct()
{
parent::__construct('member_authorized_contract');
}
}<file_sep>/framework/weixin_baike/script/control/loan.php
<?php
class loanControl {
public function __construct()
{
}
public function disbursementTestOp()
{
$r = new ormReader();
$sql = "select s.* from loan_disbursement_scheme s left join loan_contract c on c.uid=s.contract_id
where c.state>='".loanContractStateEnum::PENDING_DISBURSE."' and c.state<'".loanContractStateEnum::COMPLETE."'
and s.state in ('".schemaStateTypeEnum::CREATE."','".schemaStateTypeEnum::FAILURE."')
and s.disbursable_date <= '".date('Y-m-d H:i:s')."' order by s.uid desc ";
$schema = $r->getRow($sql);
print_r($schema);
$ret = array(
'succeed' => 0,
'failed' => 0,
'skipped' => 0
);
$rt = loan_baseClass::loanDisbursementSchemaExecute($schema['uid']);
if (!$rt->STS) {
logger::record("exec_disbursement_schema_script", $rt->MSG . "\n" . my_json_encode($schema) );
$ret['failed'] += 1;
} else {
$ret['succeed'] += 1;
}
print_r($rt);
}
public function exec_disbursement_schemaOp() {
$r = new ormReader();
$sql = "select s.* from loan_disbursement_scheme s left join loan_contract c on c.uid=s.contract_id
where c.state>='".loanContractStateEnum::PENDING_DISBURSE."' and c.state<'".loanContractStateEnum::COMPLETE."'
and s.state in ('".schemaStateTypeEnum::CREATE."','".schemaStateTypeEnum::FAILURE."')
and s.disbursable_date <= '".date('Y-m-d H:i:s')."' ";
$tasks = $r->getRows($sql);
$ret = array(
'succeed' => 0,
'failed' => 0,
'skipped' => 0
);
foreach ($tasks as $schema) {
$rt = loan_baseClass::loanDisbursementSchemaExecute($schema['uid']);
if (!$rt->STS) {
logger::record("exec_disbursement_schema_script", $rt->MSG . "\n" . my_json_encode($schema) );
$ret['failed'] += 1;
} else {
$ret['succeed'] += 1;
}
}
return new result(true, null, $ret);
}
}<file_sep>/framework/api_test/apis/microbank/member.message.list.php
<?php
class memberMessageListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Message List";
$this->description = "会员收到的消息列表";
$this->url = C("bank_api_url") . "/member.message.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("page_num", "页码", 1, true);
$this->parameters[]= new apiParameter("page_size", "每页条数", 20, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_num' => '总条数',
'total_pages' => '总页数',
'current_page' => '当前页',
'page_size' => '每页条数',
'list' => array(
array(
'message_id' => '消息id',
'message_type' => '消息类型',
'sender_type' => '发送者类型',
'sender_id' => '发送者ID',
'sender_name' => '发送者名称',
'message_title' => '消息标题',
'message_body' => '消息内容',
'message_time' => '消息时间',
'message_state' => '消息状态',
'is_read' => '是否已读',
'read_time' => '阅读时间'
),
array()
)
)
);
}
}<file_sep>/framework/weixin_baike/api/control/bank_app.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/13
* Time: 17:26
*/
class bank_appControl extends bank_apiControl
{
/**
* 获取APP的最新版本信息
* @return result
*/
public function getVersionOp()
{
$params = array_merge(array(),$_GET,$_POST);
$app_name = $params['app_name'];
$version = $params['version'];
$version = $version?:'';
$download_url = getConf('app_download_url');
if( !$download_url ){
return new result(false,'Download url config error',null,errorCodesEnum::CONFIG_ERROR);
}
$download_url = rtrim($download_url,'/');
if( !$app_name ){
return new result(false,'Lack of param',null,errorCodesEnum::DATA_LACK);
}
$m = new common_app_versionModel();
$newest_version = $m->orderBy('uid desc')->getRow(array(
'app_name' => $app_name
));
if( $newest_version ){
$newest_version->download_url = $download_url.'/'.$newest_version->download_url;
}else{
$newest_version = null;
}
$update_version = $m->orderBy('uid desc')->getRow(array(
'app_name' => $app_name,
'is_required' => 1
));
// 没有需要更新的版本,返回最新版本
if( !$update_version ){
return new result(true,'success',$newest_version);
}
// 版本低于需要更新的版本,强制更新最新版本
if( $version < $update_version->version ){
$newest_version->is_required = 1;
return new result(true,'success',$newest_version);
}
// 版本高于需要更新的版本,选择性更新到最新版本
return new result(true,'success',$newest_version);
/*return new result(true,'success',array(
'newest_version' => $newest_version,
'update_version' => $update_version
));*/
}
}<file_sep>/framework/api_test/apis/microbank/member.edit.login_code.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/9
* Time: 17:35
*/
class memberEditLogin_codeApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Edit Login Code";
$this->description = "会员修改登陆账号";
$this->url = C("bank_api_url") . "/member.edit.profile.login_code.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("login_code", "登陆账号", 'test', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'login_code' => '登陆账号',
)
);
}
}<file_sep>/framework/weixin_baike/data/model/member_token.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/2
* Time: 11:23
*/
class member_tokenModel extends tableModelBase
{
public function __construct()
{
parent::__construct('member_token');
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/approval.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'CID';?></td>
<td><?php echo 'Name';?></td>
<td><?php echo 'Before Credit';?></td>
<td><?php echo 'Approval Credit';?></td>
<td><?php echo 'Repayment Ability';?></td>
<td><?php echo 'Remark';?></td>
<td><?php echo 'Type';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Function';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<a href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$row['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>"><?php echo $row['obj_guid'] ?></a>
</td>
<td>
<a href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$row['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>"><?php echo $row['display_name'] ?></a>
</td>
<td>
<?php echo $row['before_credit'] ?>
</td>
<td>
<?php echo $row['current_credit'] ?>
</td>
<td>
<?php echo $row['approval_repayment_ability'] ?>
</td>
<td>
<?php echo $row['remark'] ?>
</td>
<td>
<?php if($row['type'] == 0){echo 'First Credit';}elseif($row['type'] == 1){echo 'Raise';}else{echo 'Down';} ?>
</td>
<td>
<?php if($row['state'] == 0){
echo '<span class="locking">Auditings</span>';
}elseif($row['state']==1){
echo 'Passed';
}else{
echo 'Refuse';
} ?>
</td>
<td>
<div class="custom-btn-group">
<a title="<?php echo $lang['common_edit'] ;?>" class="custom-btn custom-btn-secondary" href="<?php echo getUrl('loan', 'approvalEdit', array('uid'=>$row['a_uid']), false, BACK_OFFICE_SITE_URL)?>">
<span><i class="fa fa-vcard-o"></i>Audit</span>
</a>
</div>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<hr>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/request_loan.list.php
<style>
.verify-table .locking {
color: red;
font-style: normal;
}
.verify-table .locking i {
margin-right: 3px;
}
</style>
<?php
$loanApplySourceLang = enum_langClass::getLoanApplySourceLang();
$loanApplyStateLang = enum_langClass::getLoanApplyStateLang();
?>
<div>
<table class="table verify-table">
<thead>
<tr class="table-header">
<td><?php echo 'Name';?></td>
<td><?php echo 'Loan Product';?></td>
<td><?php echo 'Applied Amount';?></td>
<td><?php echo 'Loan Purpose';?></td>
<td><?php echo 'Loan Mortgage';?></td>
<td><?php echo 'Contact Phone';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Apply Source';?></td>
<td><?php echo 'Apply Time';?></td>
<?php if ($data['verify_state'] != loanApplyStateEnum::CREATE) { ?>
<td><?php echo 'Operator';?></td>
<?php } ?>
<?php if ($data['verify_state'] > loanApplyStateEnum::CREATE) { ?>
<td><?php echo 'Operator Remark';?></td>
<?php } ?>
<?php if ($data['verify_state'] > loanApplyStateEnum::OPERATOR_REJECT) { ?>
<td><?php echo 'Credit Officer';?></td>
<?php } ?>
<?php if ($data['verify_state'] < loanApplyStateEnum::OPERATOR_REJECT) { ?>
<td><?php echo 'Function';?></td>
<?php } ?>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<?php if( $row['member_id'] ){ ?>
<a href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$row['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>"><?php echo $row['applicant_name'] ?></a>
<?php }else{ ?>
<span><?php echo $row['applicant_name'] ?></span>
<?php } ?>
</td>
<td>
<?php echo $row['product_name']?>
</td>
<td>
<?php echo ncAmountFormat($row['apply_amount'])?>
</td>
<td>
<?php echo $row['loan_purpose']?>
</td>
<td>
<?php echo $row['mortgage']; ?>
</td>
<td>
<?php echo $row['contact_phone']?>
</td>
<td>
<?php echo $loanApplyStateLang[$row['state']]; ?>
</td>
<td>
<?php echo $loanApplySourceLang[$row['request_source']]; ?>
</td>
<td>
<?php echo timeFormat($row['apply_time'])?>
</td>
<?php if ($data['verify_state'] != loanApplyStateEnum::CREATE) { ?>
<td>
<?php echo $row['operator_name']?>
</td>
<?php } ?>
<?php if ($data['verify_state'] > loanApplyStateEnum::CREATE) { ?>
<td>
<?php echo $row['operator_remark']?>
</td>
<?php } ?>
<?php if ($data['verify_state'] > loanApplyStateEnum::OPERATOR_REJECT) { ?>
<td><?php echo $row['co_name']; ?></td>
<?php } ?>
<?php if ($data['verify_state'] < loanApplyStateEnum::OPERATOR_REJECT) { ?>
<td>
<?php if ($row['state'] == loanApplyStateEnum::CREATE || $row['operator_id'] == $data['current_user']) { ?>
<div class="custom-btn-group">
<a title="" class="custom-btn custom-btn-secondary" href="<?php echo getUrl('operator', 'operateRequestLoan', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL)?>">
<span><i class="fa fa-check-circle-o"></i><?php echo $row['state'] == loanApplyStateEnum::CREATE ? 'Get' : 'Handle'?></span>
</a>
</div>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/api_test/apis/microbank/loan.contract.schema.disbursement.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/25
* Time: 17:49
*/
// loan.contract.schema.disbursement.detail
class loanContractSchemaDisbursementDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract schema disbursement detail";
$this->description = "贷款合同放款计划放款详细";
$this->url = C("bank_api_url") . "/loan.contract.schema.disbursement.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("schema_id", "放款计划id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.loan.repayment.record.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/6
* Time: 13:34
*/
// member.loan.repayment.record
class memberLoanRepaymentRecordApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Loan repayment record";
$this->description = "会员贷款还款记录";
$this->url = C("bank_api_url") . "/member.loan.repayment.record.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
array(
'contract_id' => '合同ID,如45',
'contract_sn' => '合同编号,如1-1000024-002-7',
'amount' => '金额,如990',
'currency' => '币种,如USD',
'month_time' => '月时间,如2018-02',
'day_time' => '日时间,如02-06 13:26',
'create_time' => '详细时间,如2018-02-06 13:26:57',
)
)
);
}
}<file_sep>/framework/weixin_baike/counter/templates/default/member/document.collection.php
<link href="<?php echo ENTRY_COUNTER_SITE_URL; ?>/resource/css/member.css" rel="stylesheet" type="text/css"/>
<div class="page">
<?php require_once template('widget/sub.menu.nav'); ?>
<div class="container">
<div class="collection-div">
<div class="basic-info">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Basic Information</h5>
</div>
<div class="content">
<div class="col-sm-6">
<div class="input-group" style="width: 300px">
<span class="input-group-addon" style="padding: 0;border: 0;">
<select class="form-control" name="country_code" style="min-width: 80px;height: 30px">
<option value="855" <?php echo $output['phone_arr'][0] == 855 ? 'selected' : ''?>>+855</option>
<option value="66" <?php echo $output['phone_arr'][0] == 66 ? 'selected' : ''?>>+66</option>
<option value="86" <?php echo $output['phone_arr'][0] == 86 ? 'selected' : ''?>>+86</option>
</select>
</span>
<input type="text" class="form-control" id="phone" name="phone" value="<?php echo $output['phone_arr'][1];?>" placeholder="">
<span class="input-group-btn">
<button type="button" class="btn btn-default" id="btn_search" style="height: 30px;line-height: 14px;border-radius: 0">
<i class="fa fa-search"></i>
Search
</button>
</span>
</div>
<div class="search-other">
<img src="resource/img/member/phone.png">
<img src="resource/img/member/qr-code.png">
<img src="resource/img/member/bank-card.png">
</div>
</div>
<div class="col-sm-6">
<dl class="account-basic clearfix">
<dt class="pull-left">
<p class="account-head">
<img id="member-icon" src="resource/img/member/bg-member.png" class="avatar-lg">
</p>
</dt>
<dd class="pull-left margin-large-left">
<input type="hidden" id="client_id" name="client_id" value="">
<p class="text-small">
<span class="show pull-left base-name marginright3">Login Account</span>:
<span class="marginleft10" id="login-account"><?php echo $client_info['login_account']?></span>
</p>
<p class="text-small">
<span class="show pull-left base-name marginright3">Khmer Name</span>:
<span class="marginleft10" id="khmer-name"><?php echo $client_info['kh_display_name']?></span>
</p>
<p class="text-small">
<span class="show pull-left base-name marginright3">English Name</span>:
<span class="marginleft10" id="english-name"><?php echo $client_info['display_name']?></span>
</p>
<p class="text-small">
<span class="show pull-left base-name marginright3">Member Grade</span>:
<span class="marginleft10" id="member-grade"><?php echo $client_info['member_grade']?></span>
</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="authentication-information">
<div class="ibox-title">
<h5><i class="fa fa-id-card-o"></i>Authentication Information</h5>
</div>
<div class="content">
<form class="form-horizontal">
<div class="personal-info">
<div class="form-group">
<label class="col-sm-4 control-label">Personal Information: </label>
<div class="col-sm-8" id="identity_authentication">
<?php if ($member_info['identity_authentication']) { ?>
<i class="fa fa-check-square-o"></i>
<?php } else { ?>
<i class="fa fa-square-o"></i>
<?php } ?>
<span>Identity Authentication</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="family_book">
<?php if ($member_info['family_book']) { ?>
<i class="fa fa-check-square-o"></i>
<?php } else { ?>
<i class="fa fa-square-o"></i>
<?php } ?>
<span>Family Book</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="working_certificate">
<?php if ($member_info['working_certificate']) { ?>
<i class="fa fa-check-square-o"></i>
<?php } else { ?>
<i class="fa fa-square-o"></i>
<?php } ?>
<span>Working Certificate</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="resident_book">
<?php if ($member_info['resident_book']) { ?>
<i class="fa fa-check-square-o"></i>
<?php } else { ?>
<i class="fa fa-square-o"></i>
<?php } ?>
<span>Resident Book</span>
<a class="function">【Collect】</a>
</div>
</div>
</div>
<div class="assets-certification">
<div class="form-group">
<label class="col-sm-4 control-label">Assets Certification: </label>
<div class="col-sm-8" id="vehicle_property">
<span>Vehicle Property</span>
<span class="num">0</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="land_property">
<span>Land Property</span>
<span class="num">0</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="housing_property">
<span>Housing Property</span>
<span class="num">0</span>
<a class="function">【Collect】</a>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8" id="motorcycle_asset_certificate">
<span>Motorcycle Asset Certificate</span>
<span class="num">0</span>
<a class="function">【Collect】</a>
</div>
</div>
</div>
<div class="relationships">
<div class="form-group">
<label class="col-sm-4 control-label">Relationships: </label>
<div class="col-sm-8" id="family_relation_authentication">
<span>Family Relation Authentication</span>
<span class="num">0</span>
<a class="function">【Collect】</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
search_click();
$('#btn_search').click(function () {
search_click()
})
$('#identity_authentication .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'identityAuthentication', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#working_certificate .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'workAuthentication', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#family_book .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'familyBookAuthentication', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#resident_book .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'residentBookAuthentication', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#vehicle_property .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'vehiclePropertyAuthenticate', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#land_property .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'landPropertyAuthenticate', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#housing_property .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'housingPropertyAuthenticate', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#motorcycle_asset_certificate .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'motorcyclePropertyAuthenticate', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
$('#family_relation_authentication .function').click(function () {
var client_id = $('#client_id').val();
if (!client_id) {
return;
}
window.location.href = '<?php echo getUrl('member', 'guaranteeAuthenticate', array('nav_op' => 'documentCollection'), false, ENTRY_COUNTER_SITE_URL);?>&client_id=' + client_id;
})
})
function search_click() {
var country_code = $('select[name="country_code"]').val();
var phone = $('#phone').val();
if (!$.trim(phone)) {
return;
}
yo.loadData({
_c: 'member',
_m: 'getClientInfo',
param: {country_code: country_code, phone: phone},
callback: function (_o) {
if (_o.STS) {
var data = _o.DATA;
$('#member-icon').attr('src', data.member_icon ? data.member_icon : 'resource/img/member/bg-member.png');
$('#client_id').val(data.uid);
$('#login-account').html(data.login_code);
$('#khmer-name').html(data.kh_display_name);
$('#english-name').html(data.display_name);
if (data.identity_authentication) {
$('#identity_authentication i').removeClass('fa-square-o').addClass('fa-check-square-o');
} else {
$('#identity_authentication i').removeClass('fa-check-square-o').addClass('fa-square-o');
}
if (data.family_book) {
$('#family_book i').removeClass('fa-square-o').addClass('fa-check-square-o');
} else {
$('#family_book i').removeClass('fa-check-square-o').addClass('fa-square-o');
}
if (data.working_certificate) {
$('#working_certificate i').removeClass('fa-square-o').addClass('fa-check-square-o');
} else {
$('#working_certificate i').removeClass('fa-check-square-o').addClass('fa-square-o');
}
if (data.resident_book) {
$('#resident_book i').removeClass('fa-square-o').addClass('fa-check-square-o');
} else {
$('#resident_book i').removeClass('fa-check-square-o').addClass('fa-square-o');
}
$('#vehicle_property .num').html(data.vehicle_property);
$('#land_property .num').html(data.land_property);
$('#housing_property .num').html(data.housing_property);
$('#motorcycle_asset_certificate .num').html(data.motorcycle_asset_certificate);
$('#family_relation_authentication .num').html(data.guarantee_num);
} else {
alert(_o.MSG);
}
}
});
}
</script><file_sep>/framework/api_test/apis/test.ace.api/ace.test.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 16:56
*/
class aceTestApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.hello";
$this->description = "To test if the service is normal or not.";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=test";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => ''
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.prepayment.preview.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/16
* Time: 17:32
*/
// loan.contract.prepayment.preview
class loanContractPrepaymentPreviewApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Prepayment Preview";
$this->description = "提前还款预览";
$this->url = C("bank_api_url") . "/loan.contract.prepayment.preview.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", "合同id", 1, true);
$this->parameters[]= new apiParameter("prepayment_type", "提前还款类型 0 部分还款 1 全额还款 2 固定期数", 0, true);
$this->parameters[]= new apiParameter("repay_period", "固定期数参数,偿还期数 ", 2);
$this->parameters[]= new apiParameter("amount", "部分还款参数,本金金额", '100');
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'need_pay' => array(
'@description' => '应正常还的部分信息',
'total_overdue_amount' => '逾期计划总额',
'next_repayment_date' => '最近还款日',
'next_repayment_amount' => '最近应还款金额(本金+利息)',
'total_left_principal' => '可提前还剩余本金',
'total_left_periods' => '可提前还的剩余期数',
'total_need_pay' => array(
'@description' => '必还统计',
'total' => '合计必还总额',
'principal' => '合计应还本金',
'interest' => '合计应还利息',
'penalty' => '合计应还罚金'
),
),
'prepayment_principal' => '提前还款本金金额',
'prepayment_fee' => '提前还款手续费',
'total_prepayment_amount' => '合计总额',
'left_schema' => '剩余计划'
)
);
}
}<file_sep>/framework/weixin_baike/mobile/control/base.php
<?php
class baseControl extends control{
public $user_id;
public $user_name;
public $user_info;
public $auth_list;
function __construct(){
parent::__construct();
}
}
<file_sep>/framework/weixin_baike/entry_desktop/control/base.php
<?php
class baseControl extends control
{
public $user_id;
public $user_name;
public $user_info;
public $auth_list;
public $user_position;
function __construct()
{
parent::__construct();
Language::read('auth');
$user = userBase::Current();
$user_info = $user->property->toArray();
$user_info['user_position'] = my_json_decode($user_info['user_position']);
$this->user_info = $user_info;
$this->user_id = $user_info['uid'];
$this->user_name = $user_info['user_code'];
$this->user_position = $user_info['user_position'];
$auth_arr = $user->getAuthList();
$this->auth_list = $auth_arr['back_office'];
}
protected function getProcessingTask(){
//是否有进行的任务
if (in_array(userPositionEnum::OPERATOR, $this->user_position)) {
$m_um_user_operator_task = M('um_user_operator_task');
$processing_task = $m_um_user_operator_task->find(array('user_id' => $this->user_id, 'task_state' => 10));
if (!$processing_task) {
$processing_task = array(
'url' => '',
'title' => "<None>"
);
Tpl::output('processing_task', $processing_task);
} else {
if ($processing_task['task_type'] == operateTypeEnum::NEW_CLIENT) {
$processing_task = array(
'url' => getUrl('operator', 'checkNewClient', array('uid' => $processing_task['task_id'], 'show_menu_a' => $processing_task['task_type']), false, BACK_OFFICE_SITE_URL),
'title' => "<New Register>"
);
} else if ($processing_task['task_type'] == operateTypeEnum::REQUEST_LOAN) {
$processing_task = array(
'url' => getUrl('operator', 'operateRequestLoan', array('uid' => $processing_task['task_id'], 'show_menu_a' => $processing_task['task_type']), false, BACK_OFFICE_SITE_URL),
'title' => "<Request Loan>"
);
} else if ($processing_task['task_type'] == operateTypeEnum::CERTIFICATION_FILE) {
$m_member_verify_cert = M('member_verify_cert');
$verify_cert = $m_member_verify_cert->find(array('uid' => $processing_task['task_id']));
$processing_task = array(
'url' => getUrl('operator', 'certificationDetail', array('uid' => $processing_task['task_id'], 'show_menu_a' => $processing_task['task_type'], 'show_menu_b' => $verify_cert['cert_type']), false, BACK_OFFICE_SITE_URL),
'title' => "<Certification File>"
);
}
Tpl::output('processing_task', $processing_task);
}
}
}
/**
* 根据权限获取menu
* @return array
*/
protected function getResetMenu()
{
if (in_array(userPositionEnum::OPERATOR, $this->user_position)) {
Language::read('certification');
$index_menu = $this->getOperatorMenu();
$certification_type = enum_langClass::getCertificationTypeEnumLang();
unset($certification_type[certificationTypeEnum::GUARANTEE_RELATIONSHIP]);
$index_menu['certification_file']['child'] = $certification_type;
return $index_menu;
} else {
$index_menu = $this->getIndexMenu();
foreach ($index_menu as $key => $menu) {
foreach ($menu['child'] as $k => $child) {
$argc = explode(',', $child['args']);
$auth = $argc[1] . '_' . $argc[2];
if (!in_array($auth, $this->auth_list)) {
unset($index_menu[$key]['child'][$k]);
}
}
if (empty($index_menu[$key]['child'])) {
unset($index_menu[$key]);
}
}
return $index_menu;
}
}
/**
* 定义menu
* @return array
*/
private function getIndexMenu()
{
$indexMenu = array(
'home' => array(
"title" => "Home",
'child' => array(
array('args' => 'microbank/backoffice,home,monitor', 'title' => 'Monitor')
)
),
'user' => array(
"title" => 'Hr',
'child' => array(
array('args' => 'microbank/backoffice,user,branch', 'title' => 'Branch'),
array('args' => 'microbank/backoffice,user,role', 'title' => 'Role'),
array('args' => 'microbank/backoffice,user,user', 'title' => 'User'),
array('args' => 'microbank/backoffice,user,log', 'title' => 'User Log'),
array('args' => 'microbank/backoffice,user,pointEvent', 'title' => 'Point Event'),
array('args' => 'microbank/backoffice,user,pointPeriod', 'title' => 'Point Period'),
array('args' => 'microbank/backoffice,user,departmentPoint', 'title' => 'Department Point'),
)
),
'client' => array(
"title" => 'Client',
'child' => array(
array('args' => 'microbank/backoffice,client,client', 'title' => 'Client'),
array('args' => 'microbank/backoffice,client,cerification', 'title' => 'Certification File'),
array('args' => 'microbank/backoffice,client,blackList', 'title' => 'Black List'),
array('args' => 'microbank/backoffice,client,grade', 'title' => 'Grade'),
)
),
'partner' => array(
"title" => 'Partner',
'child' => array(
array('args' => 'microbank/backoffice,partner,bank', 'title' => 'Bank'),
array('args' => 'microbank/backoffice,partner,dealer', 'title' => 'Dealer'),
)
),
'loan' => array(
"title" => 'Loan',
'child' => array(
array('args' => 'microbank/backoffice,loan,product', 'title' => 'Product'),
array('args' => 'microbank/backoffice,loan,credit', 'title' => 'Grant Credit'),
array('args' => 'microbank/backoffice,loan,approval', 'title' => 'Approval Credit'),
array('args' => 'microbank/backoffice,loan,apply', 'title' => 'Request To Loan'),
array('args' => 'microbank/backoffice,loan,requestToPrepayment', 'title' => 'Request To Prepayment'),
array('args' => 'microbank/backoffice,loan,requestToRepayment', 'title' => 'Repayment'),
array('args' => 'microbank/backoffice,loan,contract', 'title' => 'Contract'),
array('args' => 'microbank/backoffice,loan,writeOff', 'title' => 'Write Off'),
array('args' => 'microbank/backoffice,loan,overdue', 'title' => 'Overdue'),
array('args' => 'microbank/backoffice,loan,deductingPenalties', 'title' => 'Deducting Penalties'),
)
),
'insurance' => array(
"title" => 'Insurance',
'child' => array(
array('args' => 'microbank/backoffice,insurance,product', 'title' => 'Insurance Product'),
array('args' => 'microbank/backoffice,insurance,contract', 'title' => 'Insurance Contract'),
)
),
'setting' => array(
"title" => 'Setting',
'child' => array(
array('args' => 'microbank/backoffice,setting,companyInfo', 'title' => 'Company Info'),
array('args' => 'microbank/backoffice,setting,creditLevel', 'title' => 'Credit Level'),
array('args' => 'microbank/backoffice,setting,creditProcess', 'title' => 'Credit Process'),
array('args' => 'microbank/backoffice,setting,global', 'title' => 'Global'),
array('args' => 'microbank/backoffice,region,list', 'title' => 'Region'),
// array('args' => 'microbank/backoffice,setting,systemDefine', 'title' => 'System Define'),
array('args' => 'microbank/backoffice,setting,shortCode', 'title' => 'Short Code'),
array('args' => 'microbank/backoffice,setting,codingRule', 'title' => 'Coding Rule'),
array('args' => 'microbank/backoffice,setting,resetSystem', 'title' => 'Reset System'),
)
),
'financial' => array(
"title" => 'Financial',
'child' => array(
array('args' => 'microbank/backoffice,financial,bankAccount', 'title' => 'Bank Account'),
array('args' => 'microbank/backoffice,financial,exchangeRate', 'title' => 'Exchange Rate'),
)
),
'report' => array(
"title" => 'Report',
'child' => array(
array('args' => 'microbank/backoffice,report,reportOverview', 'title' => 'Overview'),
array('args' => 'microbank/backoffice,report,clientList', 'title' => 'Client List'),
array('args' => 'microbank/backoffice,report,contractList', 'title' => 'Contract List'),
array('args' => 'microbank/backoffice,report,creditList', 'title' => 'Credit List'),
array('args' => 'microbank/backoffice,report,todayReport', 'title' => 'Today\'s Report'),
array('args' => 'microbank/backoffice,report,loanList', 'title' => 'Loan List'),
array('args' => 'microbank/backoffice,report,repaymentList', 'title' => 'Repayment List'),
array('args' => 'microbank/backoffice,report,assetLiability', 'title' => 'Asset Liability'),
array('args' => 'microbank/backoffice,report,profit', 'title' => 'Profit'),
)
),
'editor' => array(
"title" => 'Editor',
'child' => array(
array('args' => 'microbank/backoffice,editor,help', 'title' => 'Cms')
)
),
'tools' => array(
"title" => 'Tools',
'child' => array(
array('args' => 'microbank/backoffice,tools,calculator', 'title' => 'Calculator'),
array('args' => 'microbank/backoffice,tools,sms', 'title' => 'SMS'),
)
),
'dev' => array(
"title" => 'Dev',
'child' => array(
array('args' => 'microbank/backoffice,dev,appVersion', 'title' => 'App Version'),
array('args' => 'microbank/backoffice,dev,functionSwitch', 'title' => 'Function Switch'),
array('args' => 'microbank/backoffice,dev,resetPassword', 'title' => 'Reset Password'),
)
)
);
return $indexMenu;
}
/**
* 定义menu
* @return array
*/
private function getOperatorMenu()
{
$indexMenu = array(
'new_client' => array(
"title" => "New Client",
'args' => "microbank/backoffice,operator,newClient"
),
'request_loan' => array(
"title" => "Request Loan",
'args' => "microbank/backoffice,operator,requestLoan"
),
'certification_file' => array(
"title" => "Certification File",
'args' => "microbank/backoffice,operator,certificationFile"
),
'grant_credit' => array(
"title" => "Grant Credit",
'args' => "microbank/backoffice,operator,grantCredit"
),
'request_lock' => array(
"title" => "Request To Lock",
'args' => "microbank/backoffice,operator,requestLock"
),
'complaint_advice' => array(
"title" => "Complaint and Advice",
'args' => "microbank/backoffice,operator,addComplaintAdvice"
)
);
return $indexMenu;
}
/**
* 获取任务数
* @return result
*/
public function getTaskNumOp()
{
$r = new ormReader();
$sql = "SELECT COUNT(uid) new_client_num FROM client_member WHERE operate_state = 0 AND member_state != 0";
$new_client_num = $r->getOne($sql);
$sql = "SELECT COUNT(uid) request_loan FROM loan_apply WHERE state = " . loanApplyStateEnum::CREATE;
$request_loan = $r->getOne($sql);
$sql = "SELECT COUNT(uid) num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::ID . " THEN 1 ELSE 0 END) id_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::PASSPORT . " THEN 1 ELSE 0 END) passport_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::FAIMILYBOOK . " THEN 1 ELSE 0 END) family_book_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::WORK_CERTIFICATION . " THEN 1 ELSE 0 END) work_certification_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::CAR . " THEN 1 ELSE 0 END) car_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::HOUSE . " THEN 1 ELSE 0 END) house_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::LAND . " THEN 1 ELSE 0 END) land_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::RESIDENT_BOOK . " THEN 1 ELSE 0 END) resident_book_num,"
. " SUM(CASE WHEN cert_type =" . certificationTypeEnum::MOTORBIKE . " THEN 1 ELSE 0 END) motorbike_num"
. " FROM member_verify_cert WHERE verify_state = 0";
$cert_file = $r->getRow($sql);
$cert_file_arr = array(
certificationTypeEnum::ID => intval($cert_file['id_num']),
certificationTypeEnum::PASSPORT => intval($cert_file['passport_num']),
certificationTypeEnum::FAIMILYBOOK => intval($cert_file['family_book_num']),
certificationTypeEnum::WORK_CERTIFICATION => intval($cert_file['work_certification_num']),
certificationTypeEnum::CAR => intval($cert_file['car_num']),
certificationTypeEnum::HOUSE => intval($cert_file['house_num']),
certificationTypeEnum::LAND => intval($cert_file['land_num']),
certificationTypeEnum::RESIDENT_BOOK => intval($cert_file['resident_book_num']),
certificationTypeEnum::MOTORBIKE => intval($cert_file['motorbike_num']),
);
$data = array(
'new_client' => intval($new_client_num),
'request_loan' => intval($request_loan),
'certification_file' => intval($cert_file['num']),
'certification_file_arr' => $cert_file_arr,
);
return new result(true, '', $data);
}
}
<file_sep>/framework/api_test/apis/entry/log.php
<?php
class logApiDocument extends apiDocument {
public function __construct()
{
$this->name = "log";
$this->description = "记录页面行为日志";
$this->url = C("entry_api_url") . "/log.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("cookieId", "用户Cookie ID", md5('test'), true);
$this->parameters[]= new apiParameter("url", "行为发生所在页面的url", "http://www.test.com/test.php?t=test", true);
$this->parameters[]= new apiParameter("refurl", "当前页面的来源url", "http://www.test.com/test2.php?t=test2");
$this->parameters[]= new apiParameter("ua", "请求头中的User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0");
$this->parameters[]= new apiParameter("screenX", "用户当前设备的屏幕宽度", "1280");
$this->parameters[]= new apiParameter("screenY", "用户当前设备的屏幕高度", "720");
$this->parameters[]= new apiParameter("os", "用户当前设备的操作系统", "Win32");
$this->parameters[]= new apiParameter("browser", "用户使用的浏览器", "Firefox");
$this->parameters[]= new apiParameter("browserLang", "用户使用的语言", "zh-CN");
$this->parameters[]= new apiParameter("title", "当前页面的标题", "Lucky Dig");
$this->parameters[]= new apiParameter("ch", "辅助字段,一般用来标记行为产生元素", "page");
$this->parameters[]= new apiParameter("ch1", "辅助字段1,一般用来记录行为类型", "init");
$this->parameters[]= new apiParameter("ch2", "辅助字段2,一般用来辅助标记行为产生元素或记录行为影响的值", "");
$this->parameters[]= new apiParameter("ch3", "辅助字段3,一般用来记录行为影响的值", "");
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.member.assets.evaluate.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 14:59
*/
class officerSubmitMemberAssetsEvaluateApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member asset evaluation submit";
$this->description = "客户资产估值确认";
$this->url = C("bank_api_url") . "/officer.submit.member.assets.evaluate.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("id", "资产ID", 1, true);
$this->parameters[]= new apiParameter("valuation", "估值", 500, true);
$this->parameters[]= new apiParameter("remark", "备注", '别墅', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array()
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/complaint.advice.list.php
<?php
$complaintAdviceStateLang = enum_langClass::getComplaintAdviceStateLang();
?>
<div class="content guarantor" style="padding: 0;border-bottom: 1px solid #D5D5D5;">
<table class="table table-bordered">
<thead>
<tr class="table-header">
<td>Type</td>
<td>Contact Name</td>
<td>Title</td>
<td>Contact Phone</td>
<td>Create Time</td>
<td>State</td>
<td>Function</td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach ($data['data'] as $row) {?>
<tr>
<td>
<?php echo $row['type'] ?>
</td>
<td>
<?php echo $row['contact_name'] ?>
</td>
<td>
<?php echo $row['title'] ?>
</td>
<td>
<?php echo $row['contact_phone'] ?>
</td>
<td>
<?php echo $row['create_time'] ?>
</td>
<td>
<?php echo $complaintAdviceStateLang[$row['state']]?>
</td>
<td>
<a class="btn btn-default" href="<?php echo getUrl('operator','details',array('uid'=>$row['uid']),false, BACK_OFFICE_SITE_URL)?>"><?php echo 'Details'?></a>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?><file_sep>/framework/api_test/apis/officer_app/officer.get.member.assets.evaluate.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 14:37
*/
class officerGetMemberAssetsEvaluateApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member asset list ";
$this->description = "会员资产列表";
$this->url = C("bank_api_url") . "/officer.get.member.assets.evaluate .php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_amount' => '',
'list' => array(
array(
'uid' => '资产ID',
'asset_type' => '资产类型',
'valuation' => '估值',
'remark' => '备注'
)
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/loan_approval.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/6
* Time: 17:53
*/
class loan_approvalModel extends tableModelBase
{
public function __construct()
{
parent::__construct('loan_approval');
}
public function getCreditApprovalInfo($p){
$row = $this->getRow($p);
if ($row) {
return new result(true, 'Edit successful!');
} else {
return new result(false, 'Edit failed--');
}
}
public function creditGrantConfirm($param){
$uid = intval($param['uid']);
$before_credit = $param['before_credit'];
$credit = $param['current_credit'];
$repayment_ability = $param['repayment_ability'];
$obj_guid = $param['obj_guid'];
$operator_id = intval($param['operator_id']);
$operator_name = $param['operator_name'];
$state = $param['state'];
$remark = $param['remark'];
if (!$credit) {
return new result(false, 'Credit cannot be empty!');
}
$m_loan_account = M('loan_account');
$m_loan_credit_release = M('loan_credit_release');
$row = $this->getRow(array('uid' => $uid));
if (empty($row)) {
return new result(false, 'Invalid Id!');
}
if($state == 1){
$m_member = new memberModel();
$member = $m_member->getRow(array(
'obj_guid' => $obj_guid
));
if( !$member ){
return new result(false,'No member!');
}
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$row->operator_id = $operator_id;
$row->operator_name = $operator_name;
$row->operate_time = Now();
$row->state = $state;
$rt_1 = $row->update();
if (!$rt_1->STS) {
$conn->rollback();
return new result(false, 'Edit failed--' . $rt_1->MSG);
}
$row_release = $m_loan_credit_release->newRow();
$row_release->obj_guid = $obj_guid;
$row_release->before_credit = $before_credit;
$row_release->current_credit = $credit;
$row_release->repayment_ability = $repayment_ability;
$row_release->remark = $remark;
$row_release->operator_id = $operator_id;
$row_release->operator_name = $operator_name;
$row_release->operate_time = Now();
$rt_2 = $row_release->insert();
if (!$rt_2->STS) {
$conn->rollback();
return new result(false, 'Edit failed--' . $rt_2->MSG);
}
$row_account = $m_loan_account->getRow(array('obj_guid' => $obj_guid));
$row_account->repayment_ability = $repayment_ability;
$row_account->update_time = Now();
$rt_3 = $row_account->update();
if (!$rt_3->STS) {
$conn->rollback();
return new result(false, 'Edit failed--' . $rt_3->MSG);
}
// 更新信用
$valid_time = intval($param['valid_time']);
$time = strtotime("+$valid_time year"); // todo 处理其他单位,默认年
$expire_time = date('Y-m-d H:i:s',$time);
$re = member_creditClass::grantCredit($member->uid,$credit,$expire_time);
if( !$re->STS ){
$conn->rollback();
return $re;
}
$conn->submitTransaction();
// 向用户发送消息
$title = 'Credit granting success';
$body = 'Your credit approval has been passed,new credit is '.$credit.',new monthly repayment ability is '.$row_account->repayment_ability.'! ';
member_messageClass::sendSystemMessage($member['uid'],$title,$body);
return new result(true, 'Edit Successful');
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
}else{
$row->operator_id = $operator_id;
$row->operator_name = $operator_name;
$row->operate_time = Now();
$row->state = $state;
$rt_1 = $row->update();
if (!$rt_1->STS) {
return new result(false, 'Edit failed--' . $rt_1->MSG);
}
return new result(true, 'Edit Successful');
}
}
}
<file_sep>/framework/weixin_baike/backoffice/templates/default/report/client.list.php
<div class="important-info clearfix">
<div class="item">
<p>Client Quantity</p>
<div class="c"><?php echo $data['statistics']['client_quantity']?:0?></div>
</div>
<div class="item">
<p>Credit Line(AVG)</p>
<div class="c"><?php echo ncAmountFormat($data['statistics']['avg_credit'])?></div>
</div>
<div class="item">
<p>Loan Number(AVG)</p>
<div class="c"><?php echo $data['statistics']['avg_loan_number']?:0?></div>
</div>
<div class="item">
<p>Loan Amount(AVG)</p>
<div class="c"><?php echo ncAmountFormat($data['statistics']['avg_loan_amount'])?></div>
</div>
<div class="item">
<p>New Client</p>
<div class="c"><?php echo $data['statistics']['new_client'] ?: 0?></div>
</div>
</div>
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Cid'; ?></td>
<td><?php echo 'Name'; ?></td>
<td><?php echo 'Credit Line(Used)'; ?></td>
<td><?php echo 'Loan Number'; ?></td>
<td><?php echo 'Loan Amount'; ?></td>
<td><?php echo 'Interest Amount'; ?></td>
<td><?php echo 'Admin Fee Amount'; ?></td>
<td><?php echo 'Unpaid Amount'; ?></td>
<td><?php echo 'Create Time'; ?></td>
<td><?php echo 'Function'; ?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<?php echo $row['obj_guid'] ?><br/>
</td>
<td>
<?php echo $row['display_name'] ?><br/>
</td>
<td>
<?php echo ncAmountFormat($row['credit']) . '(' . ncAmountFormat($row['credit'] - $row['receivable_principal']) . ')' ?>
<br/>
</td>
<td>
<?php echo $row['loan_number']?:0 ?><br/>
</td>
<td>
<?php echo ncAmountFormat($row['loan_amount']) ?><br/>
</td>
<td>
<?php echo ncAmountFormat($row['total_interest']) ?><br/>
</td>
<td>
<?php echo ncAmountFormat($row['total_admin_fee']) ?><br/>
</td>
<td>
<?php echo ncAmountFormat($row['unpaid_amount']) ?><br/>
</td>
<td>
<?php echo timeFormat($row['create_time']) ?><br/>
</td>
<td>
<div class="custom-btn-group">
<a class="custom-btn custom-btn-secondary" href="<?php echo getUrl('report', 'clientDetail', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL)?>">
<span><i class="fa fa-vcard-o"></i>Detail</span>
</a>
</div>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<?php include_once(template("widget/inc_content_pager"));?>
<file_sep>/framework/weixin_baike/mobile/templates/default/home/information.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/home.css?v=2">
<?php include_once(template('widget/inc_header'));?>
<div class="wrap information-wrap">
<?php $data = $output['data'];$work_info = $output['work_info'];?>
<div>
<ul class="aui-list request-detail-ul">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Khmer Name
</div>
<div class="aui-list-item-input label-on">
<?php $name = json_decode($data['id_kh_name_json'], true);echo $name['family_name'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Family Name
</div>
<div class="aui-list-item-input label-on">
<?php $name = json_decode($data['id_en_name_json'], true);echo $name['family_name'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Given Name
</div>
<div class="aui-list-item-input label-on">
<?php $name = json_decode($data['id_en_name_json'], true);echo $name['given_name'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Second Name
</div>
<div class="aui-list-item-input label-on">
<?php $name = json_decode($data['id_en_name_json'], true);echo $name['given_name'];?>
</div>
</div>
</li>
</ul>
</div>
<div class="aui-margin-t-10">
<ul class="aui-list info-list aui-margin-b-10">
<li class="aui-list-item operator-item" onclick="<?php if($data['id_sn']){?>javascript:location.href='<?php echo getUrl('home', 'idCardInfomation', array('cid'=>$_GET['cid']), false, WAP_OPERATOR_SITE_URL)?>'<?php }?>">
<div class="aui-list-item-inner content <?php if($data['id_sn']){?>aui-list-item-arrow<?php }?>">
<?php echo 'ID Card';?>
<?php if(!$data['id_sn']){?>
<span class="tip">No Verify</span>
<?php }?>
</div>
</li>
<li class="aui-list-item info-item" onclick="<?php if($work_info){?>javascript:location.href='<?php echo getUrl('home', 'occupationInfomation', array('id'=>$_GET['id']), false, WAP_OPERATOR_SITE_URL)?>'<?php }?>">
<div class="aui-list-item-inner content <?php if($work_info){?>aui-list-item-arrow<?php }?>">
<?php echo 'Occupation';?>
<?php if(!$work_info){?>
<span class="tip">No Verify</span>
<?php }?>
</div>
</li>
<li class="aui-list-item info-item" onclick="editAddress();">
<div class="aui-list-item-inner content aui-list-item-arrow">
<?php echo 'Place of residence';?>
</div>
</li>
</ul>
</div>
</div>
<script type="text/javascript">
function editAddress(){
if(window.operator){
window.operator.memberPlaceOfResidence('<?php echo $_GET['id'];?>');
return;
}
}
</script>
<file_sep>/framework/weixin_baike/api/control/phone.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 14:07
*/
class phoneControl extends bank_apiControl
{
/**
* 获取发送短信验证码的冷却时间
* @return result 时间是s
*/
public function verifyCoolTimeOp()
{
$params = array_merge(array(),$_GET,$_POST);
if( !$params['country_code'] || !$params['phone'] ){
return new result(false,'Phone number error',null,errorCodesEnum::INVALID_PARAM);
}
$format_phone = tools::getFormatPhone($params['country_code'],$params['phone']);
$contact_phone = $format_phone['contact_phone'];
$m = new phone_verify_codeModel();
$row = $m->orderBy('uid desc')->getRow(array(
'phone_id' => $contact_phone
));
if( !$row ){
return new result(true,'success',0); // 不在冷却中
}
$send_time = strtotime($row->create_time);
$end_time = $send_time+phoneCodeCDEnum::CD;
$c_time = time();
if( $end_time > $c_time ){
$cd = $end_time-$c_time;
return new result(true,'success',$cd);
}
return new result(true,'success',0);
}
/**
* 发送短信验证码,不处理验证问题,正常号码都可以发送,是否验证过在具体的业务处理
* @return result
*/
public function sendCodeOp()
{
// 做安全处理
/* $rt = $this->checkAppSign();
if( !$rt->STS ){
return $rt;
}*/
$params = array_merge(array(),$_GET,$_POST);
$country_code = $params['country_code'];
$phone_number = $params['phone'];
$format_phone = tools::getFormatPhone($country_code,$phone_number);
$contact_phone = $format_phone['contact_phone'];
// 检查合理性
if( !isPhoneNumber($contact_phone) ){
return new result(false,'Invalid phone',null,errorCodesEnum::INVALID_PHONE_NUMBER);
}
$m_phone_verify_code = M('phone_verify_code');
// 是否在冷却时间内
// todo 增加发送账户的冷却
$verify_row = $m_phone_verify_code->orderBy('uid desc')->find(array(
'phone_id' => $contact_phone,
));
$last_time = 0;
if( $verify_row && $verify_row['create_time'] ){
$last_time = strtotime($verify_row['create_time']);
}
if( (time()-$last_time) < phoneCodeCDEnum::CD ){
return new result(false,'Wrong time',null,errorCodesEnum::UNDER_COOL_TIME);
}
// 发送短信验证码
$verify_code = mt_rand(100001,999999);
$smsHandler = new smsHandler();
$rt = $smsHandler->sendVerifyCode($contact_phone,$verify_code);
if( !$rt->STS ){
return new result(false,'Send code fail: '.$rt->MSG,null,errorCodesEnum::SMS_CODE_SEND_FAIL);
}
$sms_row = $rt->DATA;
$new_row = $m_phone_verify_code->newRow();
$new_row->phone_country = $country_code;
$new_row->phone_id = $contact_phone;
$new_row->verify_code = $verify_code;
$new_row->create_time = Now();
$new_row->sms_id = $sms_row->uid;
$insert = $new_row->insert();
if( !$insert->STS ){
return new result(false,'Insert verify code fail',null,errorCodesEnum::DB_ERROR);
}
$verify_id = $insert->AUTO_ID;
return new result(true,'success',array(
'verify_id' => $verify_id,
'phone_id' => $contact_phone
));
}
/**
* 验证短信验证码
* @return result
*/
public function verifyCodeOp()
{
$params = array_merge(array(),$_GET,$_POST);
$verify_id = $params['verify_id'];
$verify_code = $params['verify_code'];
if( !$verify_id || !$verify_code ){
return new result(false,'Invalid param',null,errorCodesEnum::DATA_LACK);
}
$m_phone_verify_code = new phone_verify_codeModel();
$row = $m_phone_verify_code->getRow($verify_id);
if( !$row ){
return new result(false,'No data',null,errorCodesEnum::UNEXPECTED_DATA);
}
if( $row->verify_code != $verify_code ){
return new result(false,'Verify fail',null,errorCodesEnum::UNEXPECTED_DATA);
}
$create_time = strtotime($row->create_time);
if( ($create_time+60*30) < time() ){ // 有效时间30分钟
return new result(false,'Code expired',null,errorCodesEnum::DATA_EXPIRED);
}
$row->state = 1;
$up = $row->update();
if( !$up->STS ){
return new result(false,'Update data fail',null,errorCodesEnum::DB_ERROR);
}
// 会员电话认证
if( isset($params['is_certificate']) && $params['is_certificate'] == 1 ){
$m_member = new memberModel();
$member = $m_member->getRow(array(
'phone_id' => $row->phone_id,
'is_verify_phone' => 0
));
if( $member ){
$member->is_verify_phone = 1;
$member->verify_phone_time = date('Y-m-d H:i:s');
$update = $member->update();
if( !$update->STS ){
return new result(false,'Certificate fail',null,errorCodesEnum::DB_ERROR);
}
}
}
return new result(true,'Verify success');
}
public function phoneIsRegisteredOp()
{
$params = array_merge(array(),$_GET,$_POST);
$country_code = $params['country_code'];
$phone_number = $params['phone'];
$format_phone = tools::getFormatPhone($country_code,$phone_number);
$contact_phone = $format_phone['contact_phone'];
// 检查合理性
if( !isPhoneNumber($contact_phone) ){
return new result(false,'Invalid phone',null,errorCodesEnum::INVALID_PARAM);
}
// 判断是否被其他member注册过
$is_registered = 0;
$m_member = new memberModel();
$row = $m_member->getRow(array(
'phone_id' => $contact_phone,
));
if( $row ){
$is_registered = 1;
}
return new result(true,'success',array(
'is_registered' => $is_registered
));
}
}<file_sep>/framework/weixin_baike/data/model/member_verify_cert.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/6
* Time: 17:53
*/
class member_verify_certModel extends tableModelBase
{
public function __construct()
{
parent::__construct('member_verify_cert');
}
/**
* 获取role信息
* @param $param
* @return result
*/
public function updateState($param)
{
$uid = intval($param['uid']);
$insert = $param['insert'];
$auditor_id = $param['auditor_id'];
$auditor_name = $param['auditor_name'];
$cert_name = $param['cert_name'];
$cert_sn = $param['cert_sn'];
$cert_addr = $param['cert_addr_detail'];
$cert_expire_time = $param['cert_expire_time'];
$remark = $param['remark'];
$row = $this->getRow(array('uid' => $uid));
if (empty($row)) {
return new result(false, 'Invalid Id!');
}
if ($insert) {
$row->cert_name = $cert_name;
$row->cert_sn = $cert_sn;
$row->cert_addr = $cert_addr;
$row->cert_expire_time = $cert_expire_time;
}
if (isset($param['verify_state'])) {
$row->verify_state = $param['verify_state'];
}
$row->auditor_id = $auditor_id;
$row->auditor_name = $auditor_name;
$row->auditor_time = Now();
$row->verify_remark = $remark;
$ret = $row->update();
if (!$ret->STS) {
return new result(false, 'Edit failed--' . $ret->MSG);
}
// 给用户发送消息
$member_id = $row['member_id'];
switch ($param['verify_state']) {
case certStateEnum::PASS:
$title = 'Certification Pass';
$body = 'Your submitted certificate has been passed!';
member_messageClass::sendSystemMessage($member_id, $title, $body);
break;
case certStateEnum::NOT_PASS :
$title = 'Certification Un-pass';
$body = 'Your submitted certificate authentication did not pass, please resubmit the information!';
member_messageClass::sendSystemMessage($member_id, $title, $body);
break;
default:
break;
}
return new result(true, 'Edit Successful');
}
}
<file_sep>/framework/api_test/apis/microbank/loan.product.lists.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/9
* Time: 11:10
*/
class loanProductListsApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Product Lists";
$this->description = "贷款产品列表";
$this->url = C("bank_api_url") . "/loan.product.list.php";
$this->parameters = array();
//$this->parameters[]= new apiParameter("token", "登陆令牌", '<KEY>', true);
//$this->parameters[]= new apiParameter("pageNum", "页码", 1);
//$this->parameters[]= new apiParameter("pageSize", "每页条数", 10);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '产品详情',
array(
'uid' => '产品ID',
'product_code' => '产品Code',
'product_name' => '产品名',
'product_description' => '产品描述,富文本',
'product_qualification' => '贷款条件,富文本',
'product_feature' => '产品特色,富文本',
'product_required' => '贷款必须资料,富文本',
'product_notice' => '产品公告,富文本',
//'state' => '状态',
//'create_time' => '创建时间',
//'creator_id' => '创建者Id',
//'creator_name' => '创建者Name',
'update_time' => '更新时间',
'penalty_divisor_days' => '罚款利率除以多少天',
'penalty_on' => '罚款基数',
'penalty_rate' => '罚款利率',
'is_multi_contract' => '允许多合同标志',
'is_advance_interest' => '罚款利率',
'is_editable_penalty' => '是否允许合同修改罚款利率',
'is_editable_interest' => '是否允许修改利息',
'is_editable_grace_days' => '是否允许修改宽限天数',
'product_key' => '产品系列key',
'is_credit_loan' => '是否信用贷',
'min_rate_desc' => '最低利率',
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.phone.register.new.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/22
* Time: 15:41
*/
// member.phone.register.new
class memberPhoneRegisterNewApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Phone Register";
$this->description = "电话注册";
$this->url = C("bank_api_url") . "/member.phone.register.new.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("country_code", "电话国际区号", '855', true);
$this->parameters[]= new apiParameter("phone", "手机号码", '326587451', true);
$this->parameters[]= new apiParameter("sms_id", "短信id", '1', true);
$this->parameters[]= new apiParameter("sms_code", "短信验证码", '888888', true);
$this->parameters[]= new apiParameter("login_code", "登陆账号", 'test', true);
$this->parameters[]= new apiParameter("password", "密码", '<PASSWORD>', true);
$this->parameters[]= new apiParameter("civil_status", "婚姻状况", 'married', true);
$this->parameters[]= new apiParameter("photo", "头像图片,文件流", '', true);
$this->parameters[]= new apiParameter("is_bind_officer", "是否绑定会员的officer", 0);
$this->parameters[]= new apiParameter("officer_id", "officer ID", 1);
$this->parameters[]= new apiParameter("officer_name", "officer 名字", 'officer');
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => 'API返回数据',
'uid' => 'Member ID',
'obj_guid' => '全局编号',
'login_code' => '登录账号',
'family_name' => '姓',
'given_name' => '名',
'initials' => '首字母',
'display_name' => '全名',
'alias_name' => 'json多语言名字',
'is_staff' => '是否内部员工',
'gender' => '性别',
'civil_status' => '婚姻状况',
'birthday' => '生日',
'phone_contry' => '电话国际区号',
'phone_id' => '格式化联系电话,如+85562548715',
'is_verify_phone' => '是否验证电话',
'verify_phone_time' => '电话验证时间',
'email' => '邮箱',
'is_verify_email' => '是否验证邮件',
'verify_email_time' => '邮件验证时间',
'member_property' => 'json保存扩展属性,如职业收入等',
'member_verification' => 'json字符串,计算项',
'member_grade' => '会员等级',
'member_officer' => '会员的officer',
'member_image' => '头像原图',
'member_icon' => '头像剪切图',
'open_source' => '开户来源',
'open_org' => '开户机构',
'open_addr' => '开户地址',
'member_state' => '会员状态',
'create_time' => '创建时间',
'creator_id' => '创建人ID',
'creator_name' => '创建人名字',
'update_time' => '更新时间',
'last_login_time' => '最后登录时间',
'last_login_ip' => '最后登录ip',
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.apply.app.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/16
* Time: 11:06
*/
class loanApplyAppApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "App loan apply";
$this->description = "APP贷款申请";
$this->url = C("bank_api_url") . "/loan.apply.app.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id,没登陆传 0", 0, true);
$this->parameters[]= new apiParameter("amount", "贷款金额", 1000, true);
$this->parameters[]= new apiParameter("loan_propose", "贷款目的", 'Business', true);
$this->parameters[]= new apiParameter("loan_time", "贷款时间", 1, true);
$this->parameters[]= new apiParameter("loan_time_unit", "贷款时间单位 year month day", 'year', true);
$this->parameters[]= new apiParameter("name", "非登陆必传参数->贷款人名字 ", 'test');
$this->parameters[]= new apiParameter("address", "非登陆必传参数->地址 ", 'street 208');
$this->parameters[]= new apiParameter("country_code", "非登陆必传参数->电话国家码", '855');
$this->parameters[]= new apiParameter("phone", "非登陆必传参数->电话号码", '85625415');
$this->parameters[]= new apiParameter("sms_id", "非登陆必传参数->短信ID", 1);
$this->parameters[]= new apiParameter("sms_code", "非登陆必传参数->验证码", '888888');
$this->parameters[]= new apiParameter("mortgage", "抵押物,多个用,隔开", null);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => ''
);
}
}<file_sep>/framework/api_test/apis/microbank/member.forgot.password.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/18
* Time: 16:41
*/
class memberForgotPasswordApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member forgot password";
$this->description = "忘记密码";
$this->url = C("bank_api_url") . "/member.resetpwd.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("type", "找回方式 sms 短信", 'sms', true);
$this->parameters[]= new apiParameter("country_code", "国家码", '', true);
$this->parameters[]= new apiParameter("phone", "手机号码", '', true);
$this->parameters[]= new apiParameter("sms_id", "验证id", '', true);
$this->parameters[]= new apiParameter("sms_code", "验证码", '', true); // password
$this->parameters[]= new apiParameter("password", "新密码", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.search.member.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 16:34
*/
// officer.search.member
class officerSearchMemberApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Officer search member";
$this->description = "搜索会员";
$this->url = C("bank_api_url") . "/officer.search.member.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("type", "类型, 1 GUID 2 电话号码", 1, true);
$this->parameters[]= new apiParameter("guid", "会员GUID,type为1传", '10000001');
$this->parameters[]= new apiParameter("country_code", "国家码,type为2传", '86');
$this->parameters[]= new apiParameter("phone_number", "电话号码,type为2传", '18902461905');
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '用户信息'
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/request_loan.audit.php
<link href="<?php echo BACK_OFFICE_SITE_URL ?>/resource/css/loan.css?v=9" rel="stylesheet" type="text/css"/>
<style>
.audit-table tr td:first-child {
width: 200px;
}
.audit-table textarea {
width: 300px;
height: 80px;
float: left;
}
.custom-btn-group {
float: inherit;
}
.btn {
min-width: 80px;
border-radius: 0;
}
#coModal .modal-dialog {
margin-top: 10px !important;
}
#coModal .easyui-panel {
border: 1px solid #DDD;
}
</style>
<?php
$loanApplySourceLang = enum_langClass::getLoanApplySourceLang();
$unit_lang = enum_langClass::getLoanTimeUnitLang();
?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Request To Loan</h3>
<ul class="tab-base">
<li>
<a href="<?php echo getUrl('operator', 'requestLoan', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a>
</li>
<li><a class="current"><span>Handle</span></a></li>
</ul>
</div>
</div>
<div class="container">
<form class="form-horizontal">
<table class="table audit-table">
<tbody class="table-body">
<tr>
<td><label class="control-label">Name</label></td>
<td><?php echo $output['apply_info']['applicant_name'] ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Product</label></td>
<td><?php echo $output['apply_info']['product_name']?:'Null'; ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Amount</label></td>
<td><?php echo ncPriceFormat($output['apply_info']['apply_amount']).$output['apply_info']['currency']; ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Time</label></td>
<td><?php echo $output['apply_info']['loan_time'].' '.$unit_lang[$output['apply_info']['loan_time_unit']]; ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Purpose</label></td>
<td><?php echo $output['apply_info']['loan_purpose'] ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Mortgage</label></td>
<td><?php echo $output['apply_info']['mortgage'] ?></td>
</tr>
<tr>
<td><label class="control-label">Contact Phone</label></td>
<td><?php echo $output['apply_info']['contact_phone'] ?></td>
</tr>
<tr>
<td><label class="control-label">Address</label></td>
<td><?php echo $output['apply_info']['applicant_address'] ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Time</label></td>
<td><?php echo timeFormat($output['apply_info']['apply_time']) ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Source</label></td>
<td><?php echo $loanApplySourceLang[$output['apply_info']['request_source']]; ?></td>
</tr>
<tr>
<td><label class="control-label">Verify State</label></td>
<td>
<label class="radio-inline">
<input type="radio" name="verify_state" value="allot" checked/> Allot To Oc
</label>
<label class="radio-inline">
<input type="radio" name="verify_state" value="close"/> Reject
</label>
</td>
</tr>
<tr id="credit_officer">
<td><label class="control-label">Credit Officer</label></td>
<td>
<span class="credit_officer_name"></span>
<input type="hidden" name="credit_officer_id" value=""/>
<button type="button" class="btn btn-primary" style="padding: 4px 10px" onclick="showSelectOc();"><i class="fa fa-arrow-right"></i><?php echo 'Select' ?></button>
<div class="error_msg"></div>
</td>
</tr>
<tr>
<td><label class="control-label">Audit Remark</label></td>
<td>
<textarea class="form-control" name="remark"></textarea>
<div class="error_msg"></div>
</td>
</tr>
<tr>
<td><label class="control-label"></label></td>
<td>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" onclick="checkSubmit();"><i class="fa fa-check"></i><?php echo 'Submit' ?></button>
<button type="button" class="btn btn-info" onclick="checkAbandon();"><i class="fa fa-arrow-right"></i><?php echo 'Abandon' ?></button>
<button type="button" class="btn btn-default" onclick="javascript:history.go(-1);"><i class="fa fa-reply"></i><?php echo 'Back' ?></button>
</div>
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="uid" value="<?php echo $output['apply_info']['uid']; ?>">
</form>
</div>
</div>
<div class="modal" id="coModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" style="width: 700px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?php echo 'Credit Officer'?></h4>
</div>
<div class="modal-body" style="margin-bottom: 20px">
<div class="business-condition">
<form class="form-inline" id="frm_search_condition">
<table class="search-table">
<tr>
<td>
<div class="input-group">
<input type="text" class="form-control" id="search_text" name="search_text" placeholder="Search for co" style="min-width: 150px">
<span class="input-group-btn">
<button type="button" class="btn btn-default" id="btn_search_list" onclick="btn_search_onclick();">
<i class="fa fa-search"></i>
<?php echo 'Search'; ?>
</button>
</span>
</div>
</td>
<td>
<select class="form-control" name="branch_id">
<option value="0">Select Branch</option>
<?php foreach ($output['branch_list'] as $branch) { ?>
<option value="<?php echo $branch['uid'];?>"><?php echo $branch['branch_name'];?></option>
<?php } ?>
</select>
</td>
</tr>
</table>
</form>
</div>
<div class="modal-table">
<div>
<table class="table table-bordered">
<thead>
<tr class="table-header" style="background-color: #EEE">
<td>Branch</td>
<td>Co Name</td>
<td>Tasks(Client)</td>
<td>Tasks(Request Loan)</td>
<td>Function</td>
</tr>
</thead>
<tbody class="table-body">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/validform/jquery.validate.min.js?v=2"></script>
<script>
$(function () {
$('input[name="verify_state"]').click(function () {
var verify_state = $(this).val();
if (verify_state == 'allot') {
$('#credit_officer').show();
} else {
$('#credit_officer').hide();
}
})
})
function showSelectOc() {
btn_search_onclick();
$('#coModal').modal('show');
}
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 20;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var _search_text = $('#search_text').val();
var _branch_id = $('select[name="branch_id"]').val();
yo.dynamicTpl({
tpl: "operator/co.list",
dynamic: {
api: "operator",
method: "getCoList",
param: {
pageNumber: _pageNumber,
pageSize: _pageSize,
search_text: _search_text,
branch_id: _branch_id
}
},
callback: function (_tpl) {
$("#coModal .modal-table").html(_tpl);
}
});
}
function selectOc(co_id, co_name) {
$('#credit_officer .credit_officer_name').text(co_name);
$('#credit_officer input[name="credit_officer_id"]').val(co_id);
$('#coModal').modal('hide');
}
function checkSubmit(){
if (!$(".form-horizontal").valid()) {
return;
}
var values = $(".form-horizontal").getValues();
submitHandle(values);
}
function checkAbandon() {
var values = $(".form-horizontal").getValues();
values.verify_state = 'abandon';
submitHandle(values);
}
function submitHandle(values){
yo.loadData({
_c: 'operator',
_m: 'submitRequestLoan',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
window.location.href = '<?php echo getUrl('operator', 'requestLoan', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL) ?>';
} else {
alert(_o.MSG);
}
}
});
}
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
error.appendTo(element.closest('td').find('.error_msg'));
},
rules: {
remark: {
required: true
},
credit_officer_id: {
checkRequired: true
}
},
messages: {
remark: {
required: '<?php echo 'Required'?>'
},
credit_officer_id: {
checkRequired: '<?php echo 'Required'?>'
}
}
});
jQuery.validator.addMethod("checkRequired", function (value, element) {
var verify_state = $('input[name="verify_state"]:checked').val();
if (verify_state == 'allot' && !value) {
return false;
} else {
return true;
}
});
</script>
<file_sep>/framework/api_test/apis/microbank/client.member.set.fingerprint.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/24
* Time: 10:27
*/
// client.member.set.fingerprint
class clientMemberSetFingerprintApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Set client member fingerprint";
$this->description = "设置会员指纹库";
$this->url = C("bank_api_url") . "/client.member.set.fingerprint.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员GUID", 10000001, true);
$this->parameters[]= new apiParameter("finger_index", "序号", 1, true);
$this->parameters[]= new apiParameter("feature_img", "指纹图片", 'test', true);
$this->parameters[]= new apiParameter("feature_data", "指纹特征数据", 'test', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '保险列表'
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/financial/receive.account.list.php
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Receive Account</h3>
<ul class="tab-base">
<li><a class="current"><span>List</span></a></li>
<li><a href="<?php echo getUrl('financial', 'addReceiveAccount', array(), false, BACK_OFFICE_SITE_URL)?>"><span>Add</span></a></li>
</ul>
</div>
</div>
<div class="container">
<div class="business-content">
<div class="business-list">
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'No.';?></td>
<td><?php echo 'Bank Name';?></td>
<td><?php echo 'Account No';?></td>
<td><?php echo 'Account Name';?></td>
<td><?php echo 'Account Phone';?></td>
<td><?php echo 'Currency';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Function';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php $i = 0;foreach ($output['account_list'] as $key => $row) { ++$i;?>
<tr>
<td>
<?php echo $i; ?><br/>
</td>
<td>
<?php echo $row['bank_name']; ?>
</td>
<td>
<?php echo $row['bank_account_no']; ?>
</td>
<td>
<?php echo $row['bank_account_name']; ?>
</td>
<td>
<?php echo $row['bank_account_phone']; ?>
</td>
<td>
<?php echo $row['currency']; ?>
</td>
<td>
<?php echo $row['account_state'] == 1 ? 'Valid' : 'Invalid'; ?>
</td>
<td>
<a title="<?php echo $lang['common_edit'] ;?>" href="<?php echo getUrl('financial', 'editReceiveAccount', array('uid'=>$row['uid']), false, BACK_OFFICE_SITE_URL); ?>" style="margin-right: 5px" >
<i class="fa fa-edit"></i>
Edit
</a>
<a title="<?php echo $lang['common_delete'];?>" href="<?php echo getUrl('financial', 'deleteReceiveAccount', array('uid'=>$row['uid']), false, BACK_OFFICE_SITE_URL); ?>">
<i class="fa fa-trash"></i>
Delete
</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div><file_sep>/framework/weixin_baike/class/wechat.callback.class.php
<?php
/**
* Created by PhpStorm.
* User: hh
* Date: 2018/3/18
* Time: 下午 4:17
*/
class wechatCallbackClass
{
public static function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if( !$postStr ){
$postStr = file_get_contents('php://input');
}
if( $postStr ){
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
$MsgType = $postObj->MsgType;
switch( $MsgType ){
case 'text':
self::responseTextMsg($postObj);
break;
case 'image':
self::responseImageMsg($postObj);
break;
case 'event':
$Event = $postObj->Event;
if( $Event == 'subscribe'){
self::responseSubscribeMsg($postObj);
}
break;
default:
echo 'Hello';
die;
}
}else{
echo 'OK';die;
}
}
public static function responseTextMsg($msg_obj)
{
$MsgType = $msg_obj->MsgType;
$from_username = $msg_obj->FromUserName;
$to_username = $msg_obj->ToUserName;
$CreateTime = $msg_obj->CreateTime;
$Content = $msg_obj->Content;
$MsgId = $msg_obj->MsgId;
$textTpl = "<xml> <ToUserName>< ![CDATA[%s] ]></ToUserName> <FromUserName>< ![CDATA[%s] ]></FromUserName> <CreateTime>%s</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[%s] ]></Content> </xml>";
$res = sprintf($textTpl,$from_username,$to_username,time(),$Content);
echo $res;
die;
}
public static function responseImageMsg($msg_obj)
{
$MsgType = $msg_obj->MsgType;
$from_username = $msg_obj->FromUserName;
$MsgType = $msg_obj->MsgType;
$to_username = $msg_obj->ToUserName;
$CreateTime = $msg_obj->CreateTime;
$MsgId = $msg_obj->MsgId;
$MediaId = $msg_obj->MediaId;
$PicUrl = $msg_obj->PicUrl;
$tpl = "<xml><ToUserName>< ![CDATA[%s] ]></ToUserName><FromUserName>< ![CDATA[%s] ]></FromUserName><CreateTime>%s</CreateTime><MsgType>< ![CDATA[image] ]></MsgType><Image><MediaId>< ![CDATA[%s] ]></MediaId></Image></xml>";
$res = sprintf($tpl,$from_username,$to_username,time(),$MediaId);
echo $res;
die;
}
public static function responseSubscribeMsg($msg_obj)
{
$MsgType = $msg_obj->MsgType;
$from_username = $msg_obj->FromUserName;
$to_username = $msg_obj->ToUserName;
$CreateTime = $msg_obj->CreateTime;
$event = $msg_obj->Event;
$textTpl = "<xml> <ToUserName>< ![CDATA[%s] ]></ToUserName> <FromUserName>< ![CDATA[%s] ]></FromUserName> <CreateTime>%s</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[%s] ]></Content> </xml>";
$res = sprintf($textTpl,$from_username,$to_username,time(),'欢迎您!');
echo $res;
die;
}
}
<file_sep>/framework/api_test/apis/microbank/member.add.guarantee.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/18
* Time: 16:54
*/
// member.add.guarantee
class memberAddGuaranteeApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Add guarantee";
$this->description = "客户添加担保人";
$this->url = C("bank_api_url") . "/member.add.guarantee.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("country_code", "国家码", '855', true);
$this->parameters[]= new apiParameter("phone", "电话", '325481', true);
$this->parameters[]= new apiParameter("guarantee_member_account", "担保人会员账号", 'test', true);
$this->parameters[]= new apiParameter("relation_type", "关系类型", 'son', true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/weixin_baike/data/model/loan_prepayment_apply.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/23
* Time: 14:38
*/
class loan_prepayment_applyModel extends tableModelBase
{
function __construct()
{
parent::__construct('loan_prepayment_apply');
}
}<file_sep>/framework/weixin_baike/mobile/templates/default/home/assets.evaluate.edit.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/home.css?v=2">
<?php include_once(template('widget/inc_header'));?>
<div class="wrap assets-evalute-wrap">
<?php $data = $output['data']['asset_detail']; ?>
<form id="" method="post">
<div class="cerification-input aui-margin-b-10">
<div class="loan-form">
<ul class="aui-list aui-form-list loan-item">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Valuation
</div>
<div class="aui-list-item-input">
<input type="text" name="valuation" id="valuation" value="<?php echo $data['valuation'];?>" placeholder="Enter" />
<span class="p-unit">USD</span>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Remark
</div>
<div class="aui-list-item-input">
<input type="text" name="remark" id="remark" value="<?php echo $data['remark'];?>" placeholder="Enter" />
</div>
</div>
</li>
</ul>
</div>
</div>
<div style="padding: 0 .8rem;">
<div class="aui-btn aui-btn-danger aui-btn-block custom-btn custom-btn-purple aui-margin-t-15" id="submit">Submit</div>
</div>
</form>
</div>
<script type="text/javascript">
$('#submit').on('click', function(){
var id = '<?php echo $_GET['uid'];?>';
valuation = $.trim($('#valuation').val()),
remark = $.trim($('#remark').val());
if(!valuation){
verifyFail('<?php echo 'Please input valuation.';?>');
return;
}
if(!remark){
verifyFail('<?php echo 'Please input remark.';?>');
return;
}
toast.loading({
title: '<?php echo $lang['label_loading'];?>'
});
$.ajax({
type: 'get',
url: '<?php echo WAP_OPERATOR_SITE_URL;?>/index.php?act=home&op=ajaxEditEvalute',
data: {id: id,valuation: valuation, currency: 'USD',remark: remark},
dataType: 'json',
success: function(data){
toast.hide();
if(data.STS){
window.location.href="<?php echo WAP_OPERATOR_SITE_URL;?>/index.php?act=home&op=assetsEvaluate&cid=<?php $_GET['cid'];?>&id=<?php echo $_GET['mid']?>&back=search";
}else{
verifyFail(data.MSG);
}
},
error: function(xhr, type){
toast.hide();
verifyFail('<?php echo $lang['tip_get_data_error'];?>');
}
});
});
</script>
<file_sep>/framework/api_test/apis/microbank/system.define.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 13:05
*/
class systemDefineListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System define ";
$this->description = "系统定义项目";
$this->url = C("bank_api_url") . "/system.define.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("type", "类型 1 性别 2 职业 3 家庭关系 4 贷款用途", 1, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
array(
'uid' => 'ID',
'category' => '分类',
'category_name' => '分类名称',
'category_name_json' => '分类名称多语言',
'item_name' => '项目名称',
'item_name_json' => '项目名称多语言 en 英语 kh 柬语 zh_cn 中文',
'item_code' => '项目简码',
'item_desc' => '项目描述',
'item_value' => '项目计算值',
'is_system' => '是否系统内置'
)
)
);
}
}<file_sep>/framework/weixin_baike/data/model/member_work.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 17:36
*/
class member_workModel extends tableModelBase
{
function __construct()
{
parent::__construct('member_work');
}
}<file_sep>/framework/api_test/apis/officer_app/co.get.member.guarantee.list.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/8
* Time: 17:35
*/
class coGetMemberGuaranteeListApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member A guarantee list ";
$this->description = "客户担保人列表 ";
$this->url = C("bank_api_url") . "/co.get.member.guarantee.list.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'guarantee_list' => array(
'@description' => '自己的担保人列表',
'uid' => '关系id',
'relation_type' => '关系类型',
'relation_type_name_json' => array(
'@description' => '关系类型多语言',
'en' => '',
'kh' => '',
'zh_cn' => '',
),
'relation_state' => '0 创建, 11 拒绝 100 接受',
'display_name' => '英文名字',
'kh_display_name' => '柬文名字',
'member_icon' => '头像',
'phone_id' => '电话',
),
'as_guarantee_list' => array(
'@description' => '为别人担保的列表,同上',
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.set.fingerprint.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/10
* Time: 13:34
*/
class memberSetFingerprintApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Set Fingerprint";
$this->description = "会员设置指纹";
$this->url = C("bank_api_url") . "/member.set.fingerprint.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("fingerprint", "指纹,URL编码参数", '', true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'fingerprint' => '指纹'
)
);
}
}<file_sep>/framework/weixin_baike/data/model/um_user_track.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/28
* Time: 13:36
*/
class um_user_trackModel extends tableModelBase
{
function __construct()
{
parent::__construct('um_user_track');
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.get.pay.off.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/16
* Time: 16:09
*/
// loan.contract.get.pay.off.detail
class loanContractGetPayOffDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Pay Off Detail";
$this->description = "合同提前还款全额应还详细";
$this->url = C("bank_api_url") . "/loan.contract.get.pay.off.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", "合同id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
/*'contract_info' => '合同信息',
'pay_off_total' => array(
'pay_off_principal' => '应还本金',
'pay_off_interest' => '应还利息',
'pay_off_penalty' => '应还罚金',
'pay_off_commission' => '提前还款手续费',
'pay_off_total_amount' => '合计应还'
)*/
'total_prepayment_amount' => '合计提前偿还总额',
'currency' => '应还利息',
'total_paid_principal' => '合计本金',
'total_paid_interest' => '合计利息',
'total_paid_penalty' => '合计罚金',
'total_paid_commission' => '合计手续费',
)
);
}
}<file_sep>/framework/api_test/apis/microbank/system.country.code.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 13:19
*/
class systemCountryCodeApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System country code";
$this->description = "系统国家编码";
$this->url = C("bank_api_url") . "/system.country.code.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'855','86','66','84'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.loan.summary.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/18
* Time: 11:15
*/
// member.loan.summary
class memberLoanSummaryApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Loan Summary";
$this->description = "会员贷款统计";
$this->url = C("bank_api_url") . "/member.loan.summary.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'own_loan_summary' => array(
'@description'=> '自己贷款的',
'contract_num_summary' => array(
'total_contracts' => '合计合同(审批通过的)',
'processing_contracts' => '正常进行的合同(含逾期的)',
'delinquent_contracts' => '延期合同',
'normal_processing_contracts' => '正常进行无逾期',
'complete_contracts' => '还款完成合同',
'rejected_contracts' => '被拒绝的合同',
'pending_approval_contracts' => '待审核的合同',
'write_off_contracts' => '核销合同'
),
'contract_amount_summary' => array(
'total_principal' => '总共贷款本金',
'total_liabilities' => '合同总共应还金额',
'total_write_off_amount' => '核销合同的额度',
'total_Outstanding_Write_off_balance' => '坏账损失金额'
),
'next_schema' => array(
'@description' => '没有为null',
'repayment_time' => '下期还款时间',
'repayment_amount' => '金额',
'currency' => '币种'
)
),
'as_guarantee_loan_summary' => array(
'@description' => '作为担保人贷款的,格式同自己贷款的',
),
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/apply.audit.php
<link href="<?php echo BACK_OFFICE_SITE_URL ?>/resource/css/loan.css?v=9" rel="stylesheet" type="text/css"/>
<style>
.audit-table tr td:first-child {
width: 200px;
}
.audit-table textarea {
width: 300px;
height: 80px;
float: left;
}
.custom-btn-group {
float: inherit;
}
</style>
<?php
$loanApplySourceLang = enum_langClass::getLoanApplySourceLang();
$unit_lang = enum_langClass::getLoanTimeUnitLang();
?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Request To Loan</h3>
<ul class="tab-base">
<li>
<a href="<?php echo getUrl('loan', 'apply', array('type' => 'unprocessed'), false, BACK_OFFICE_SITE_URL) ?>"><span>Unprocessed</span></a>
</li>
<li>
<a href="<?php echo getUrl('loan', 'apply', array('type' => 'processed'), false, BACK_OFFICE_SITE_URL) ?>"><span>Processed</span></a>
</li>
<li><a class="current"><span>Handle</span></a></li>
</ul>
</div>
</div>
<div class="container">
<form class="form-horizontal cerification-form" id="validForm" method="post">
<table class="table audit-table">
<tbody class="table-body">
<tr>
<td><label class="control-label">Name</label></td>
<td><?php echo $output['apply_info']['applicant_name'] ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Product</label></td>
<td><?php echo $output['apply_info']['product_name']?:'No'; ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Amount</label></td>
<td><?php echo ncPriceFormat($output['apply_info']['apply_amount']).$output['apply_info']['currency']; ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Time</label></td>
<td><?php echo $output['apply_info']['loan_time'].' '.$unit_lang[$output['apply_info']['loan_time_unit']]; ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Purpose</label></td>
<td><?php echo $output['apply_info']['loan_purpose'] ?></td>
</tr>
<tr>
<td><label class="control-label">Loan Mortgage</label></td>
<td><?php echo $output['apply_info']['mortgage'] ?></td>
</tr>
<tr>
<td><label class="control-label">Contact Phone</label></td>
<td><?php echo $output['apply_info']['contact_phone'] ?></td>
</tr>
<tr>
<td><label class="control-label">Address</label></td>
<td><?php echo $output['apply_info']['applicant_address'] ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Time</label></td>
<td><?php echo timeFormat($output['apply_info']['apply_time']) ?></td>
</tr>
<tr>
<td><label class="control-label">Apply Source</label></td>
<td><?php echo $loanApplySourceLang[$output['apply_info']['request_source']]; ?></td>
</tr>
<tr>
<td><label class="control-label">Allot Credit Officer</label></td>
<td>
<?php if( !empty($output['bound_credit_officer']) ){ ?>
<?php echo $output['bound_credit_officer']['user_name']; ?>
<?php }else{ ?>
<select name="credit_officer_id" class="form-control" style="width: 300px" <?php echo $output['lock']?"disabled":"" ?>>
<option value="0" selected="selected"><?php echo $lang['common_select']?></option>
<?php foreach($output['credit_officer_list'] as $val){?>
<option value="<?php echo $val['uid'] ?>"><?php echo $val['user_name'] ?: $val['user_code'] ?></option>
<?php }?>
</select>
<?php } ?>
</td>
</tr>
<tr>
<td><label class="control-label">Audit Remark</label></td>
<td>
<?php if ($output['lock']) {
echo '<span class="color28B779">Auditing...</span>';
} else { ?>
<textarea class="form-control" name="remark"></textarea><span
class="validate-checktip"></span>
<?php } ?>
</td>
</tr>
<?php if ($output['lock']) { ?>
<tr>
<td><label class="control-label">Handler</label></td>
<td><span class="color28B779"><?php echo $output['apply_info']['handler_name']; ?></span></td>
</tr>
<?php } ?>
<tr>
<td><label class="control-label"></label></td>
<td>
<?php if ($output['lock']) { ?>
<span class="color28B779">Auditing...</span>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" onclick="javascript:history.go(-1);"><i
class="fa fa-vcard-o"></i>Back
</button>
</div>
<?php } else { ?>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" style="min-width:80px;"
onclick="applyApproved();"><i class="fa fa-check"></i><?php echo 'Approve' ?>
</button>
<button type="button" class="btn btn-default" style="min-width:80px;"
onclick="applyReject();"><i class="fa fa-close"></i><?php echo 'Reject' ?>
</button>
<button type="button" class="btn btn-info" onclick="javascript:history.go(-1);"
style="min-width:80px"><i class="fa fa-vcard-o"></i><?php echo 'Back' ?>
</button>
</div>
<?php } ?>
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="form_submit" value="ok">
<input type="hidden" name="approve_state" value="0">
<input type="hidden" name="uid" value="<?php echo $output['apply_info']['uid']; ?>">
</form>
</div>
</div>
<script type="text/javascript"
src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/validform/jquery.validate.min.js?v=1"></script>
<script type="text/javascript" src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/js/common.js?v=20"></script>
<script>
$(function () {
/*window.onbeforeunload = function(){
var uid = $('input[name="uid"]').val();
if(!uid){
return false;
}
yo.loadData({
_c: 'loan',
_m: 'unlockedApply',
param: {uid: uid},
callback: function (_o) {
if (!_o.STS) {
return false;
}
}
})
}*/
});
function applyApproved()
{
$('input[name="approve_state"]').val(1);
submitForm();
}
function applyReject()
{
$('input[name="approve_state"]').val(0);
submitForm();
}
function submitForm() {
$('#validForm').submit();
}
var validParam = {
ele: '#validForm', //表单id
params: [{
field: 'remark',
rules: {
required: true
},
messages: {
required: 'Please input the remark.'
}
}]
};
validform(validParam);
</script>
<file_sep>/framework/weixin_baike/api/control/asiaweiluly.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/31
* Time: 10:05
*/
class asiaweilulyControl extends bank_apiControl
{
function testOp()
{
$ace_api = new asiaweiluyApi();
return $ace_api->test();
}
function verifyClientMemberOp()
{
$params = array_merge(array(),$_GET,$_POST);
$aceAccount = trim($params['account']);
if( !$aceAccount ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$re = asiaweiluyClass::verifyAceAccount($aceAccount);
return $re;
}
function bindAceAccountStartOp()
{
$params = array_merge(array(),$_GET,$_POST);
$country_code = $params['country_code'];
$phone = $params['phone'];
if( !$country_code || !$phone ){
return new result(false,'Invalid param',null,errorCodesEnum::INVALID_PARAM);
}
$aceAccount = '+'.trim($country_code).'-'.trim($phone);
$chk = asiaweiluyClass::verifyAceAccount($aceAccount);
if( !$chk->STS ){
return $chk;
}
$is = $chk->DATA;
if( !$is ){
return new result(false,'Not ace member',null,errorCodesEnum::ACE_ACCOUNT_NOT_EXIST);
}
$re = asiaweiluyClass::bindAccountSendVerifyCode($aceAccount);
return $re;
}
}<file_sep>/framework/weixin_baike/counter/control/counter_base.php
<?php
class counter_baseControl extends control
{
public $user_id;
public $user_name;
public $user_info;
public $auth_list;
public $user_position;
function __construct()
{
Language::read('auth');
$this->checkLogin();
$user = userBase::Current('counter_info');
$user_info = $user->property->toArray();
$user_info['user_position'] = my_json_decode($user_info['user_position']);
$this->user_info = $user_info;
$this->user_id = $user_info['uid'];
$this->user_name = $user_info['user_code'];
$this->user_position = $user_info['user_position'];
$auth_arr = $user->getAuthList();
$this->auth_list = $auth_arr['counter'];
}
private function checkLogin()
{
if (!getSessionVar("is_login") || !getSessionVar("counter_info")) {
$ref_url = request_uri();
$login_url = getUrl("login", "login", array("ref_url" => urlencode($ref_url)), false, ENTRY_COUNTER_SITE_URL);
@header('Location:' . $login_url);
die();
} else {
return operator::getUserInfo();
}
}
protected function outputSubMenu($key)
{
$reset_menu = $this->getResetMenu();
$sub_menu = $reset_menu[$key]['child'];
Tpl::output('sub_menu', $sub_menu);
}
/**
* 根据权限获取menu
* @return array
*/
protected function getResetMenu()
{
$index_menu = $this->getIndexMenu();
foreach ($index_menu as $key => $menu) {
foreach ($menu['child'] as $k => $child) {
$argc = explode(',', $child['args']);//分割args字符串
$auth = $argc[1] . '_' . $argc[2];//取control和function连接
if (!in_array($auth, $this->auth_list)) { //判断是否存在权限
unset($index_menu[$key]['child'][$k]);//没有权限就删除
}
}
if (empty($index_menu[$key]['child'])) {//如果整个child都为空,及二级菜单都为空,不展示一级菜单
unset($index_menu[$key]);
}
if ($key == 'cash_in_vault' && !in_array(userPositionEnum::CHIEF_TELLER, $this->user_position)) {
unset($index_menu[$key]);
}
}
return $index_menu;
}
/**
* 定义menu
* @return array
*/
private function getIndexMenu()
{
$indexMenu = array(
'member' => array(
"title" => 'Member',
'child' => array(
array('args' => 'microbank/counter,member,register', 'title' => 'Register'),
array('args' => 'microbank/counter,member,documentCollection', 'title' => 'Document collection'),
array('args' => 'microbank/counter,member,fingerprintCollection', 'title' => 'Fingerprint Collection'),
array('args' => 'microbank/counter,member,loan', 'title' => 'Loan'),
array('args' => 'microbank/counter,member,deposit', 'title' => 'Deposit'),
array('args' => 'microbank/counter,member,withdrawal', 'title' => 'Withdrawal'),
array('args' => 'microbank/counter,member,profile', 'title' => 'Profile'),
)
),
'company' => array(
"title" => 'Company',
'child' => array(
array('args' => 'microbank/counter,company,index', 'title' => 'Index'),
)
),
'service' => array(
"title" => 'Service',
'child' => array(
array('args' => 'microbank/counter,service,requestLoan', 'title' => 'Request Loan'),
array('args' => 'microbank/counter,service,currencyExchange', 'title' => 'Currency Exchange'),
)
),
'mortgage' => array(
"title" => 'Mortgage',
'child' => array(
array('args' => 'microbank/counter,mortgage,index', 'title' => 'Index'),
)
),
'cash_on_hand' => array(
"title" => 'Cash On Hand',
'child' => array(
array('args' => 'microbank/counter,cash,cashOnHand', 'title' => 'Cash On Hand'),
)
),
'cash_in_vault' => array(
"title" => 'Cash In Vault',
'child' => array(
array('args' => 'microbank/counter,cash,cashInVault', 'title' => 'Cash In Vault'),
)
),
);
return $indexMenu;
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/new_client.check.php
<style>
.btn {
min-width: 80px;
border-radius: 0;
}
#coModal .modal-dialog {
margin-top: 10px!important;
}
#coModal .easyui-panel {
border: 1px solid #DDD;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>New Client</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('operator', 'newClient', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a></li>
<li><a class="current"><span>Audit</span></a></li>
</ul>
</div>
</div>
<?php $client_info = $output['client_info']?>
<div class="container">
<form class="form-horizontal">
<table class="table audit-table">
<tbody class="table-body">
<tr>
<td><label class="control-label">Member Icon</label></td>
<td>
<a target="_blank" href="<?php echo $client_info['member_icon'] ?>">
<img style="max-height: 200px;max-width: 100%" src="<?php echo $client_info['member_icon'] ?>">
</a>
</td>
</tr>
<tr>
<td><label class="control-label">CID</label></td>
<td><?php echo $client_info['obj_guid'];?></td>
</tr>
<tr>
<td><label class="control-label">Login Account</label></td>
<td><?php echo $client_info['login_code'];?></td>
</tr>
<tr>
<td><label class="control-label">Display Name</label></td>
<td><?php echo $client_info['display_name'];?></td>
</tr>
<tr>
<td><label class="control-label">Phone</label></td>
<td><?php echo $client_info['phone_id'];?></td>
</tr>
<tr>
<td><label class="control-label">Email</label></td>
<td><?php echo $client_info['email'];?></td>
</tr>
<tr>
<td><label class="control-label">Member Grade</label></td>
<td><?php echo $client_info['grade_code'];?></td>
</tr>
<tr>
<td><label class="control-label">Member State</label></td>
<td><?php echo $lang['client_member_state_' . $client_info['member_state']];?></td>
</tr>
<tr>
<td><label class="control-label">Check State</label></td>
<td><?php echo $lang['operator_task_state_' .$client_info['operate_state']];?></td>
</tr>
<tr>
<td><label class="control-label">Register Time</label></td>
<td><?php echo timeFormat($client_info['create_time']);?></td>
</tr>
<tr>
<td><label class="control-label">Verify State</label></td>
<td>
<label class="radio-inline">
<input type="radio" name="verify_state" value="pass" checked/> Pass
</label>
<label class="radio-inline">
<input type="radio" name="verify_state" value="close"/> Close
</label>
<label class="radio-inline">
<input type="radio" name="verify_state" value="allot"/> Allot To Oc
</label>
</td>
</tr>
<tr id="credit_officer" style="display: none">
<td><label class="control-label">Credit Officer</label></td>
<td>
<span class="credit_officer_name"></span>
<input type="hidden" name="credit_officer_id" value=""/>
<button type="button" class="btn btn-primary" style="padding: 4px 10px" onclick="showSelectOc();"><i class="fa fa-arrow-right"></i><?php echo 'Select' ?></button>
<div class="error_msg"></div>
</td>
</tr>
<tr>
<td><label class="control-label">Check Remark</label></td>
<td>
<textarea class="form-control" name="remark" style="width: 300px"></textarea>
<div class="error_msg"></div>
</td>
</tr>
<tr>
<td><label class="control-label"></label></td>
<td>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" onclick="checkSubmit();"><i class="fa fa-check"></i><?php echo 'Submit' ?></button>
<button type="button" class="btn btn-info" onclick="checkAbandon();"><i class="fa fa-arrow-right"></i><?php echo 'Abandon' ?></button>
<button type="button" class="btn btn-default" onclick="javascript:history.go(-1);"><i class="fa fa-reply"></i><?php echo 'Back' ?></button>
</div>
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="uid" value="<?php echo $client_info['uid']; ?>">
</form>
</div>
</div>
<div class="modal" id="coModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" style="width: 700px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?php echo 'Credit Officer'?></h4>
</div>
<div class="modal-body" style="margin-bottom: 20px">
<div class="business-condition">
<form class="form-inline" id="frm_search_condition">
<table class="search-table">
<tr>
<td>
<div class="input-group">
<input type="text" class="form-control" id="search_text" name="search_text" placeholder="Search for co" style="min-width: 150px">
<span class="input-group-btn">
<button type="button" class="btn btn-default" id="btn_search_list" onclick="btn_search_onclick();">
<i class="fa fa-search"></i>
<?php echo 'Search'; ?>
</button>
</span>
</div>
</td>
<td>
<select class="form-control" name="branch_id">
<option value="0">Select Branch</option>
<?php foreach ($output['branch_list'] as $branch) { ?>
<option value="<?php echo $branch['uid'];?>"><?php echo $branch['branch_name'];?></option>
<?php } ?>
</select>
</td>
</tr>
</table>
</form>
</div>
<div class="modal-table">
<div>
<table class="table table-bordered">
<thead>
<tr class="table-header" style="background-color: #EEE">
<td>Branch</td>
<td>Co Name</td>
<td>Tasks(Client)</td>
<td>Tasks(Request Loan)</td>
<td>Function</td>
</tr>
</thead>
<tbody class="table-body">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/validform/jquery.validate.min.js?v=2"></script>
<script>
$(function () {
$('input[name="verify_state"]').click(function () {
var verify_state = $(this).val();
if (verify_state == 'allot') {
$('#credit_officer').show();
} else {
$('#credit_officer').hide();
}
})
})
function showSelectOc() {
btn_search_onclick();
$('#coModal').modal('show');
}
function btn_search_onclick(_pageNumber, _pageSize) {
if (!_pageNumber) _pageNumber = $(".business-content").data('pageNumber');
if (!_pageSize) _pageSize = $(".business-content").data('pageSize');
if (!_pageNumber) _pageNumber = 1;
if (!_pageSize) _pageSize = 20;
$(".business-content").data("pageNumber", _pageNumber);
$(".business-content").data("pageSize", _pageSize);
var _search_text = $('#search_text').val();
var _branch_id = $('select[name="branch_id"]').val();
yo.dynamicTpl({
tpl: "operator/co.list",
dynamic: {
api: "operator",
method: "getCoList",
param: {
pageNumber: _pageNumber,
pageSize: _pageSize,
search_text: _search_text,
branch_id: _branch_id
}
},
callback: function (_tpl) {
$("#coModal .modal-table").html(_tpl);
}
});
}
function selectOc(co_id, co_name) {
$('#credit_officer .credit_officer_name').text(co_name);
$('#credit_officer input[name="credit_officer_id"]').val(co_id);
$('#coModal').modal('hide');
}
function checkSubmit(){
if (!$(".form-horizontal").valid()) {
return;
}
var values = $(".form-horizontal").getValues();
submitCheck(values);
}
function checkAbandon() {
var values = $(".form-horizontal").getValues();
values.verify_state = 'abandon';
submitCheck(values);
}
function submitCheck(values){
yo.loadData({
_c: 'operator',
_m: 'submitCheckClient',
param: values,
callback: function (_o) {
if (_o.STS) {
alert(_o.MSG);
window.location.href = '<?php echo getUrl('operator', 'newClient', array(), false, BACK_OFFICE_SITE_URL);?>';
} else {
alert(_o.MSG);
}
}
});
}
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
error.appendTo(element.closest('td').find('.error_msg'));
},
rules: {
remark: {
required: true
},
credit_officer_id: {
checkRequired: true
}
},
messages: {
remark: {
required: '<?php echo 'Required'?>'
},
credit_officer_id: {
checkRequired: '<?php echo 'Required'?>'
}
}
});
jQuery.validator.addMethod("checkRequired", function (value, element) {
var verify_state = $('input[name="verify_state"]:checked').val();
if (verify_state == 'allot' && !value) {
return false;
} else {
return true;
}
});
</script>
<file_sep>/framework/weixin_baike/data/model/phone_verify_code.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/1
* Time: 15:18
*/
class phone_verify_codeModel extends tableModelBase
{
public function __construct()
{
parent::__construct('common_verify_code');
}
}<file_sep>/framework/api_test/apis/officer_app/officer.base.info.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/6
* Time: 16:32
*/
// officer.base.info
class officerBaseInfoApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Officer base info";
$this->description = "业务员信息";
$this->url = C("bank_api_url") . "/officer.base.info.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("officer_id", "业务员 id", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'user_info' => array(
'@description' => '用户信息',
),
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.cert.asset.land.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/5
* Time: 13:32
*/
class memberCertAssetLandApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member asset land cert";
$this->description = "土地认证";
$this->url = C("bank_api_url") . "/member.cert.asset.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("type", "认证类型,固定值 land", 'land', true);
$this->parameters[]= new apiParameter("property_card", "产权证照片,文件流", null, true);
$this->parameters[]= new apiParameter("trading_record", "交易记录,文件流", null, true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_result' => '基本信息',
'extend_info' => '扩展信息'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/phone.code.verify.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/8
* Time: 13:28
*/
class phoneCodeVerifyApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Phone Code Verify";
$this->description = "短信验证码验证";
$this->url = C("bank_api_url") . "/phone.code.verify.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("verify_id", "验证ID", '1', true);
$this->parameters[]= new apiParameter("verify_code", "验证码", '236541', true);
$this->parameters[] = new apiParameter('is_certificate','是否会员手机号认证,是 1,否 0',0);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/email.cooltime.php
<?php
class emailCooltimeApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Email Cool Time";
$this->description = "获取邮件发送冷却时间";
$this->url = C("bank_api_url") . "/email.cooltime.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("email", "邮箱", '<EMAIL>', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => '0 不在冷却中 >0 剩余时间(秒)'
);
}
}<file_sep>/framework/api_test/apis/microbank/member.bind.bank.delete.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/7
* Time: 10:21
*/
// member.bind.bank.delete
class memberBindBankDeleteApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member bind bank delete";
$this->description = "会员删除绑定的银行卡";
$this->url = C("bank_api_url") . "/member.bind.bank.delete.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员ID", 1, true);
$this->parameters[]= new apiParameter("bind_id", "绑定的handler ID", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => null
);
}
}<file_sep>/framework/api_test/apis/microbank/member.cert.family.relationship.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/14
* Time: 17:38
*/
class memberCertFamilyRelationshipApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Family relationship";
$this->description = "家庭关系证明";
$this->url = C("bank_api_url") . "/member.cert.family.relationship.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("relation_type", "关系类型", '', true);
$this->parameters[]= new apiParameter("relation_name", "关系人名字", '', true);
$this->parameters[]= new apiParameter("relation_cert_type", "关系人证件类型", '', true);
$this->parameters[]= new apiParameter("relation_cert_photo", "关系人证件照片,文件流", '', true);
$this->parameters[]= new apiParameter("country_code", "电话国际号", '', true);
$this->parameters[]= new apiParameter("relation_phone", "电话", '', true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
)
);
}
}<file_sep>/framework/api_test/apis/microbank/member.query.credit.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/31
* Time: 11:13
*/
// member.query.credit
class memberQueryCreditApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member query credit";
$this->description = "会员信用信息";
$this->url = C("bank_api_url") . "/member.query.credit.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("token", "登陆令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'credit' => '信用值',
'balance' => '可用信用',
'evaluate_time' => '最后授信时间',
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/user/branch.edit.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL;?>/js/jquery.validation.min.js"></script>
<style>
#select_area .col-sm-6:nth-child(2n+1) {
padding-left: 0;
padding-right: 3px;
margin-bottom: 10px;
}
#select_area .col-sm-6:nth-child(2n) {
padding-right: 0;
padding-left: 3px;
margin-bottom: 10px;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Branch</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('user', 'branch', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a></li>
<li><a href="<?php echo getUrl('user', 'addBranch', array(), false, BACK_OFFICE_SITE_URL)?>"><span>Add</span></a></li>
<li><a class="current"><span>Edit</span></a></li>
</ul>
</div>
</div>
<div class="container" style="width: 600px;">
<form class="form-horizontal" method="post">
<input type="hidden" name="form_submit" value="ok">
<input type="hidden" name="uid" value="<?php echo $output['branch_info']['uid']?>">
<input type="hidden" name="address_id" value="<?php echo $output['branch_info']['address_id']?>">
<input type="hidden" name="address_region" value="<?php echo $output['branch_info']['address_region']?>">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Branch Code'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="branch_code" placeholder="" value="<?php echo $output['branch_info']['branch_code']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><span class="required-options-xing">*</span><?php echo 'Branch Name'?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="branch_name" placeholder="" value="<?php echo $output['branch_info']['branch_name']?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Contact phone' ?></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="contact_phone" value="<?php echo $output['branch_info']['contact_phone'] ?>" placeholder="">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Manager' ?></label>
<div class="col-sm-9">
<select class="form-control" name="manager">
<option value="0">Please Select</option>
<?php foreach($output['user_list'] as $user){?>
<option value="<?php echo $user['uid']?>" <?php echo $user['uid'] == $output['branch_info']['manager']?'selected':''?>><?php echo $user['user_code']?></option>
<?php }?>
</select>
</div>
</div>
<?php $limit_arr = $output['branch_info']['limit_arr'];?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Limit Loan' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="limit_loan[max_per_time]" value="<?php echo $limit_arr['limit_loan']['max_per_time']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0;border-right: 0">$ Per Time</span>
<input type="number" class="form-control" name="limit_loan[max_per_day]" value="<?php echo $limit_arr['limit_loan']['max_per_day']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0">$ Per Day</span>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Limit Deposit' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="limit_deposit[max_per_time]" value="<?php echo $limit_arr['limit_deposit']['max_per_time']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0;border-right: 0">$ Per Time</span>
<input type="number" class="form-control" name="limit_deposit[max_per_day]" value="<?php echo $limit_arr['limit_deposit']['max_per_day']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0">$ Per Day</span>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Limit Exchange' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="limit_exchange[max_per_time]" value="<?php echo $limit_arr['limit_exchange']['max_per_time']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0;border-right: 0">$ Per Time</span>
<input type="number" class="form-control" name="limit_exchange[max_per_day]" value="<?php echo $limit_arr['limit_exchange']['max_per_day']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0">$ Per Day</span>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Limit Withdraw' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="limit_withdraw[max_per_time]" value="<?php echo $limit_arr['limit_withdraw']['max_per_time']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0;border-right: 0">$ Per Time</span>
<input type="number" class="form-control" name="limit_withdraw[max_per_day]" value="<?php echo $limit_arr['limit_withdraw']['max_per_day']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0">$ Per Day</span>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Limit Transfer' ?></label>
<div class="col-sm-9">
<div class="input-group">
<input type="number" class="form-control" name="limit_transfer[max_per_time]" value="<?php echo $limit_arr['limit_transfer']['max_per_time']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0;border-right: 0">$ Per Time</span>
<input type="number" class="form-control" name="limit_transfer[max_per_day]" value="<?php echo $limit_arr['limit_transfer']['max_per_day']?>">
<span class="input-group-addon" style="min-width: 80px;border-left: 0">$ Per Day</span>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Bank' ?></label>
<div class="col-sm-9">
<select class="form-control" name="bank_id">
<option value="0">Please Select</option>
<?php foreach($output['bank_list'] as $bank){?>
<option value="<?php echo $bank['uid']?>" <?php echo $output['branch_info']['bank_id'] == $bank['uid'] ? 'selected' : ''?>><?php echo $bank['bank_code']?></option>
<?php }?>
</select>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label"><?php echo 'Location' ?></label>
<div class="col-sm-9" id="select_area">
<?php if (!empty($output['region_list'])) { ?>
<?php foreach ($output['region_list'] as $area) { ?>
<div class="col-sm-6">
<select class="form-control">
<option value="0">Please Select</option>
<?php foreach ($area as $val) { ?>
<option value="<?php echo $val['uid'] ?>" is-leaf="<?php echo $val['is_leaf'] ?>" <?php echo $val['selected']?'selected':''?>><?php echo $val['node_text'] ?></option>
<?php } ?>
</select>
</div>
<?php }?>
<?php }?>
</div>
<div class="col-sm-9 col-sm-offset-3">
<input type="text" class="form-control" name="address_detail" placeholder="Detailed Address" value="<?php echo $output['branch_info']['address_detail']?>">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Map</label>
<div class="col-sm-9">
<div id="map" style="width: 500px;height: 300px;border: 1px solid #9e9e9e"></div>
<input type="hidden" id="coord_x" name="coord_x" value="<?php echo $output['branch_info']['coord_x']?>">
<input type="hidden" id="coord_y" name="coord_y" value="<?php echo $output['branch_info']['coord_y']?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo 'Status';?></label>
<div class="col-sm-9" style="margin-top: 7px">
<label><input type="radio" value="1" name="status" <?php echo $output['branch_info']['status'] == 1?'checked':''?>><?php echo 'Valid'?></label>
<label style="margin-left: 10px"><input type="radio" value="0" name="status" <?php echo $output['branch_info']['status'] == 0?'checked':''?>><?php echo 'Invalid'?></label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-col-sm-9" style="padding-left: 20px">
<button type="button" class="btn btn-danger"><i class="fa fa-check"></i><?php echo 'Save' ?></button>
<button type="button" class="btn btn-default" onclick="javascript:history.go(-1);"><i class="fa fa-reply"></i><?php echo 'Back' ?></button>
</div>
</div>
</form>
</div>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap"></script>
<script type="text/javascript">
//Google map start
var geocoder;
var map;
var marker;
function initMap() {
if($('#map').length==0){
return;
}
//地图初始化
var coord_x = $('#coord_x').val() ? $('#coord_x').val() : '11.54461675917885';
var coord_y = $('#coord_y').val() ? $('#coord_y').val() : '104.89746106250004';
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(coord_x, coord_y);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
//引入marker
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable:true,
title:"Drag me!"
});
// 获取坐标
google.maps.event.addListener(marker, "dragend", function () {
$('#coord_x').val(marker.getPosition().lat());
$('#coord_y').val(marker.getPosition().lng());
});
}
//根据地址获取经纬度
function codeAddress(address,zoom) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(zoom);
marker.setPosition(results[0].geometry.location);
$('#coord_x').val(marker.getPosition().lat());
$('#coord_y').val(marker.getPosition().lng());
}
});
}
//google map end
</script>
<script>
var _address_region;
$(function () {
if(!'<?php echo $output['branch_info']['address_id']?>'){
getArea(0);
}
$('#select_area').delegate('select', 'change', function () {
var _value = $(this).val();
$('input[name="address_id"]').val(_value);
$(this).closest('div').nextAll().remove();
_address_region = '';
$('#select_area select').each(function () {
if ($(this).val() != 0) {
_address_region += $(this).find('option:selected').text() + ' ';
}
})
var _address = _address_region + ' ' + $('input[name="address_detail"]').val();
codeAddress(_address, 14);
if (_value != 0 && $(this).find('option[value="' + _value + '"]').attr('is-leaf') != 1) {
getArea(_value);
}
})
$('input[name="address_detail"]').change(function () {
var _address = _address_region + ' ' + $('input[name="address_detail"]').val();
codeAddress(_address, 14);
})
$('.btn-danger').click(function () {
if (!$(".form-horizontal").valid()) {
return;
}
if (_address_region) {
$('input[name="address_region"]').val(_address_region);
}
$('.form-horizontal').submit();
})
})
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
error.appendTo(element.next());
},
rules: {
branch_code: {
required: true,
checkNumAndStr:true
},
branch_name: {
required: true
}
},
messages: {
branch_code: {
required: '<?php echo 'Required!'?>',
checkNumAndStr: '<?php echo 'It can only be Numbers or letters!'?>'
},
branch_name: {
required: '<?php echo 'Required!'?>'
}
}
});
function getArea(uid) {
yo.dynamicTpl({
tpl: "setting/area.list",
dynamic: {
api: "setting",
method: "getAreaList",
param: {uid: uid}
},
callback: function (_tpl) {
$("#select_area").append(_tpl);
}
})
}
jQuery.validator.addMethod("checkNumAndStr", function (value, element) {
value = $.trim(value);
if (!/^[A-Za-z0-9]+$/.test(value)) {
return false;
} else {
return true;
}
});
</script><file_sep>/framework/weixin_baike/backoffice/templates/default/loan/approval.edit.php
<style>
.approval-btn-group {
float: inherit;
}
.custom-btn-pass {
color: #28B779;
}
.color28B779 {
color: #28B779;
}
.colorcc0000 {
color: #cc0000;
}
.custom-btn-refuse {
margin: 0 10px!important;
color: #cc0000;
}
.approval-base-info {
width: 100%;
}
.approval-history {
width: 100%;
background-color: #fff;
margin-top: 20px;
}
.approval-history .ibox-content {
padding: 0;
}
</style>
<?php $info = $output['info'];?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Approval</h3>
<ul class="tab-base">
<li><a href="<?php echo getUrl('loan', 'credit', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a></li>
<li><a class="current"><span>Edit</span></a></li>
</ul>
</div>
</div>
<div class="container clearfix">
<div class="approval-base-info">
<table class="table">
<tbody class="table-body">
<tr>
<td><label class="control-label">GUID</label></td><td><?php echo $info['obj_guid'];?></td>
<td><label class="control-label">Name</label></td><td><?php echo $info['display_name'];?></td>
</tr>
<tr>
<td><label class="control-label">Before Credit</label></td><td><?php echo $info['before_credit'];?></td>
<td><label class="control-label">Apply Credit</label></td><td><?php echo $info['current_credit'];?></td>
</tr>
<tr>
<td><label class="control-label">Credit Valid Time</label></td><td><?php echo $info['valid_time'].' '.$info['valid_time_unit'];?></td>
<td><label class="control-label">Monthly Repayment Ability</label></td><td>$<?php echo $info['repayment_ability'];?></td>
</tr>
<tr>
<td><label class="control-label">Creator</label></td><td><?php echo $info['creator_name'];?></td>
<td><label class="control-label">Create Time</label></td><td><?php echo timeFormat($info['create_time']);?></td>
</tr>
<!-- <tr>
<td><label class="control-label">Phone</label></td><td><?php /*echo $info['phone_id'];*/?></td>
<td><label class="control-label">Email</label></td><td><?php /*echo $info['email'];*/?></td>
</tr>-->
<tr>
<td><label class="control-label">Apply Type</label></td><td><?php if($info['type'] == 0){echo 'First Credit';}elseif($info['type'] == 1){echo 'Raise';}else{echo 'Down';} ?></td>
<td><label class="control-label">State</label></td><td><?php if($info['state'] == 0){echo 'Auditing';}elseif($info['state']==1){echo 'Passed';}else{echo 'Refuse';} ?></td>
</tr>
<tr>
<td><label class="control-label">Remark</label></td><td><?php echo $info['remark'];?></td>
<td colspan="2"></td>
</tr>
<tr>
<td colspan="4" style="text-align: center;">
<?php if($info['state']==1){?>
<span class="color28B779">Passed</span>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" onclick="javascript:history.go(-1);"><i class="fa fa-vcard-o"></i>Back</button>
<button type="button" class="btn btn-success" onclick="javascript:window.location.href='<?php echo getUrl('client', 'clientDetail', array('uid'=>$info['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>'"><i class="fa fa-vcard-o"></i>Member Detail</button>
</div>
<?php }elseif($info['state']==-1){?>
<span class="colorcc0000">Refuse</span>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-danger" onclick="javascript:history.go(-1);"><i class="fa fa-vcard-o"></i>Back</button>
<button type="button" class="btn btn-success" onclick="javascript:window.location.href='<?php echo getUrl('client', 'clientDetail', array('uid'=>$info['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>'"><i class="fa fa-vcard-o"></i>Member Detail</button>
</div>
<?php }else{?>
<div class="custom-btn-group approval-btn-group">
<button type="button" class="btn btn-info" onclick="javascript:window.location.href='<?php echo getUrl('loan', 'approvalConfirm', array('uid'=>$info['uid'],'state'=>1), false, BACK_OFFICE_SITE_URL)?>'"><i class="fa fa-check"></i>Pass</button>
<button type="button" class="btn btn-warning" onclick="javascript:window.location.href='<?php echo getUrl('loan', 'approvalConfirm', array('uid'=>$info['uid'],'state'=>'-1'), false, BACK_OFFICE_SITE_URL)?>'"><i class="fa fa-times"></i>Refuse</button>
<button type="button" class="btn btn-danger" onclick="javascript:history.go(-1);"><i class="fa fa-vcard-o"></i>Back</button>
<button type="button" class="btn btn-success" onclick="javascript:window.location.href='<?php echo getUrl('client', 'clientDetail', array('uid'=>$info['member_id'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>'"><i class="fa fa-vcard-o"></i>Member Detail</button>
</div>
<?php } ?>
</td>
</tr>
</tbody>
</table>
</div>
<div class="approval-history">
<div class="ibox-title">
<h5>Approval History</h5>
</div>
<div class="ibox-content">
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'Before Credit';?></td>
<td><?php echo 'Current Credit';?></td>
<td><?php echo 'Create Time';?></td>
<td><?php echo 'Operate ID';?></td>
<td><?php echo 'Operate Time';?></td>
<td><?php echo 'Type';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Remark';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php $list = $output['list'];?>
<?php foreach($list as $row){?>
<tr>
<td><?php echo $row['before_credit'];?></td>
<td><?php echo $row['current_credit'];?></td>
<td><?php echo timeFormat($row['create_time']);?></td>
<td><?php echo $row['operator_id'];?></td>
<td><?php echo timeFormat($row['operator_time']);?></td>
<td><?php if($row['type'] == 0){echo 'First Credit';}elseif($row['type'] == 1){echo 'Raise';}else{echo 'Down';} ?></td>
<td><?php if($row['state'] == 0){echo 'Auditing';}elseif($row['state']==1){echo 'Passed';}else{echo 'Refuse';} ?></td>
<td><?php echo $row['remark'];?></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
$(function () {
})
</script>
<file_sep>/framework/weixin_baike/api/control/apiLogin.php
<?php
/**
* Created by PhpStorm.
* User: Seven
* Date: 2017/10/31
* Time: 09:30
*/
class apiLoginControl
{
function __construct()
{
Language::read('entry_index,common');
}
/**
* 登录api
* @return result
*/
function loginOp()
{
$p = array_merge(array(), $_GET, $_POST);
$user_code = trim($p['user_code']);
$user_password = trim($p['user_password']);
if (empty($user_code)) {
return new result(false, 'The account cannot be empty!');
}
if (empty($user_password)) {
return new result(false, 'The password cannot be empty!');
}
$m_um_user = M('um_user');
$user = $m_um_user->getRow(array(
"user_code" => $user_code,
));
if (empty($user)) {
return new result(false, 'Account error!');
}
if ($user->user_status == 0) {
return new result(false, 'Deactivated account!');
}
if (empty($user) || $user->password != md5($<PASSWORD>)) {
return new result(false, 'Password error!');
}
$position_arr = array(
userPositionEnum::CREDIT_OFFICER,
userPositionEnum::TELLER,
userPositionEnum::CHIEF_TELLER,
userPositionEnum::BRANCH_MANAGER,
);
$user_position = my_json_decode($user['user_position']);
foreach ($user_position as $position) {
if (in_array($position, $position_arr)) {
return new result(false, 'No access to the system.!');
}
}
$data_update = array(
'uid' => $user->uid,
'last_login_time' => Now(),
'last_login_ip' => getIp()
);
$m_um_user->update($data_update);
$user_arr = $user->toArray();
setSessionVar("user_info", $user_arr);
setSessionVar("is_login", "ok");
$m_um_user_log = M('um_user_log');
$m_um_user_log->recordLogin($user->uid, 'web');
if ($p["remember_me"] == 1) {
setcookie("user_code", $p["user_code"], time() + 3600 * 24 * 7);
} else {
setcookie("user_code", "", time() - 3600);
}
return new result(true, '', array('new_url' => ENTRY_DESKTOP_SITE_URL . DS . 'index.php'));
}
/**
* counter登录
* @return result
*/
public function counterLoginOp()
{
$p = array_merge(array(), $_GET, $_POST);
$user_code = trim($p['user_code']);
$user_password = trim($p['user_password']);
if (empty($user_code)) {
return new result(false, 'The account cannot be empty!');
}
if (empty($user_password)) {
return new result(false, 'The password cannot be empty!');
}
$m_um_user = M('um_user');
$user = $m_um_user->getRow(array(
"user_code" => $user_code,
));
if (empty($user)) {
return new result(false, 'Account error!');
}
if ($user->is_credit_officer) {
return new result(false, 'Not a teller!');
}
if ($user->user_status == 0) {
return new result(false, 'Deactivated account!');
}
if (empty($user) || $user->password != md5($user_password)) {
return new result(false, 'Password error!');
}
//postion判断能否登陆
$position_arr = array(
userPositionEnum::TELLER,
userPositionEnum::CHIEF_TELLER,
userPositionEnum::BRANCH_MANAGER,
);
$user_position = my_json_decode($user['user_position']);
$is_access = false;
foreach ($user_position as $position) {
if (in_array($position, $position_arr)) {
$is_access = true;
break;
}
}
if(!$is_access){
return new result(false, 'No access to the system!');
}
$data_update = array(
'uid' => $user->uid,
'last_login_time' => Now(),
'last_login_ip' => getIp()
);
$m_um_user->update($data_update);
$user_arr = $user->toArray();
setSessionVar("counter_info", $user_arr);
setSessionVar("is_login", "ok");
$m_um_user_log = M('um_user_log');
$m_um_user_log->recordLogin($user->uid, 'counter');
if ($p["remember_me"] == 1) {
setcookie("user_code", $p["user_code"], time() + 3600 * 24 * 7);
} else {
setcookie("user_code", "", time() - 3600);
}
return new result(true, '', array('new_url' => ENTRY_COUNTER_SITE_URL . DS . 'index.php'));
}
}
<file_sep>/framework/api_test/apis/microbank/system.company.info.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/27
* Time: 17:18
*/
class systemCompanyInfoApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System Company Info";
$this->description = "公司信息";
$this->url = C("bank_api_url") . "/system.company.info.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'address_region' => '地址区域',
'address_detail' => '详细地址',
'company_name' => '公司名称',
'hotline' => array(
'8552365478',
'966854123'
),
'email' => '公司邮箱',
'file' => '',
'company_icon' => '公司icon',
'coord_x' => 'X坐标',
'coord_y' => 'Y坐标',
'description' => '公司介绍',
'branch_list' => '分支列表'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.contract.prepayment.apply.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/16
* Time: 16:25
*/
// loan.contract.prepayment.apply
class loanContractPrepaymentApplyApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Contract Prepayment Apply";
$this->description = "贷款合同欠款信息";
$this->url = C("bank_api_url") . "/loan.contract.prepayment.apply.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("contract_id", "合同id", 1, true);
$this->parameters[]= new apiParameter("prepayment_type", "提前还款类型 0 部分还款 1 全额还款 2 固定期数", 0, true);
$this->parameters[]= new apiParameter("repay_period", "固定期数参数,偿还期数 ", 2);
$this->parameters[]= new apiParameter("amount", "部分还款参数,本金金额", '100');
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '申请信息'
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/co.loan.request.bind.member.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/9
* Time: 14:21
*/
// co.loan.request.bind.member
class coLoanRequestBindMemberApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan request bind member";
$this->description = "CO 为贷款申请绑定会员";
$this->url = C("bank_api_url") . "/co.loan.request.bind.member.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("request_id", "申请 id", 1, true);
$this->parameters[]= new apiParameter("member_id", "会员 id", 1, true);
$this->parameters[]= new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'request_detail' => array(
'uid' => 'id',
'member_id' => '会员id,没有为null或0',
'applicant_name' => '申请人名字',
'apply_amount' => '申请金额',
'currency' => '货币',
'contact_phone' => '联系电话',
'apply_time' => '申请时间',
'state' => '状态 0-100'
)
)
);
}
}<file_sep>/framework/api_test/apis/microbank/system.company.hotline.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/12/28
* Time: 9:55
*/
class systemCompanyHotlineApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "System Company Hotline";
$this->description = "公司热线电话";
$this->url = C("bank_api_url") . "/system.company.hotline.php";
$this->parameters = array();
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'8552365478',
'966854123'
)
);
}
}<file_sep>/framework/weixin_baike/wap/templates/default/credit/credit_loan.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_SITE_URL;?>/resource/css/credit.css?v=4">
<link rel="stylesheet" type="text/css" href="<?php echo WAP_SITE_URL;?>/resource/css/inc_header.css?v=4">
<header class="top-header" id="header">
<span class="back" onclick="javascript:history.back(-1);"><i class="aui-iconfont aui-icon-left"></i></span>
<h2 class="title"><?php echo $output['header_title'];?></h2>
<span class="right-btn" onclick="javascript:location.href='<?php echo getUrl('member', 'loanContract', array(), false, WAP_SITE_URL)?>'"><i class="aui-iconfont aui-icon-menu"></i></span>
</header>
<div class="wrap credit-loan-wrap">
<?php $credit_info = $output['credit_info'];$ace_info = $output['ace_info']; $insurance_info = $output['insurance_info'];?>
<?php $purpose = $output['purpose'];?>
<div class="credit-loan-balance">
<div class="b"><?php echo $credit_info['balance'];?></div>
<div class="l"><?php echo $lang['label_credit_balance'];?></div>
</div>
<div class="credit-loan-form">
<ul class="aui-list aui-form-list credit-loan-item">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_withdrawal_amount'];?>
</div>
<div class="aui-list-item-input">
<input type="number" name="amount" id="amount" placeholder="<?php echo $lang['label_enter'];?>">
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_loan_period'];?>
</div>
<div class="aui-list-item-input input-period">
<input type="number" name="loan_period" id="loan_period" placeholder="<?php echo $lang['label_enter'];?>">
<select class="" name="loan_period_unit" id="loan_period_unit">
<option value="year"><?php echo $lang['label_year'];?></option>
<option value="month" selected><?php echo $lang['label_month'];?></option>
<option value="day"><?php echo $lang['label_day'];?></option>
</select>
<i class="aui-iconfont aui-icon-down"></i>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_loan_purpose'];?>
</div>
<div class="aui-list-item-input input-select">
<select class="" name="propose" id="propose">
<option value="0"><?php echo $lang['label_select'];?></option>
<?php foreach ($purpose as $key => $value) { ?>
<option value="<?php echo $value['item_code'];?>"><?php echo $value['item_name'];?></option>
<?php } ?>
</select>
<i class="aui-iconfont aui-icon-down"></i>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_repayment_method'];?>
</div>
<div class="aui-list-item-input input-select">
<select class="" name="repayment_type" id="repayment_type">
<option value="0"><?php echo $lang['label_select'];?></option>
<option value="single_repayment"><?php echo 'Single';?></option>
<option value="annuity_scheme"><?php echo 'Installment';?></option>
</select>
<i class="aui-iconfont aui-icon-down"></i>
</div>
</div>
</li>
<li class="aui-list-item" id="repaymentFrequency">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_repayment_frequency'];?>
</div>
<div class="aui-list-item-input input-select">
<select name="repayment_period" id="repayment_period">
<option value="0"><?php echo $lang['label_select'];?></option>
<option value="monthly"><?php echo $lang['label_once_a_month'];?></option>
<option value="weekly"><?php echo $lang['label_once_a_week'];?></option>
</select>
<i class="aui-iconfont aui-icon-down"></i>
</div>
</div>
</li>
<li class="aui-list-item select-insurance">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
<?php echo $lang['label_select_insurance'];?>
</div>
<div class="aui-list-item-input input-select">
<input type="hidden" name="insurance_item_id" id="insurance_item_id" value="">
<input type="text" name="select_insurance" id="select_insurance" readonly placeholder="<?php echo $lang['label_select'];?>">
<i class="aui-iconfont aui-icon-down"></i>
</div>
</div>
</li>
</ul>
<div style="padding: .8rem 0;">
<div class="aui-btn aui-btn-danger aui-btn-block custom-btn custom-btn-purple" id="withdraw"><?php echo $lang['label_withdraw'];?></div>
</div>
</div>
<div class="insurance-list-wrap" style="display: none;">
<div class="content">
<div class="title">
<?php echo $lang['label_select_insurance'];?>
<span class="cancel" id="iCancel"><?php echo $lang['act_cancel'];?></span>
<span class="confirm" id="iConfirm"><?php echo $lang['act_confirm'];?></span>
</div>
<div class="list">
<ul class="aui-list aui-media-list insurance-ul">
<?php foreach ($insurance_info as $key => $value) { ?>
<li class="aui-list-item">
<div class="aui-list-item-label-icon insurance-icon">
<span class="item-ck" data-uid="<?php echo $value['uid'];?>" data-name="<?php echo $value['item_name'];?>"></span>
</div>
<div class="aui-list-item-inner insurance-text">
<div class="name"><?php echo $value['item_name'];?></div>
<div class="info"><?php echo $lang['label_coverage'].$lang['label_colon'];?> <?php echo $value['fixed_amount'];?><span><?php echo $lang['label_price'].$lang['label_colon'];?> <?php echo $value['fixed_price'];?></span></div>
</div>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#select_insurance').on('click', function(){
$('.insurance-list-wrap').show();
});
$('#iCancel').on('click', function(){
$('.insurance-list-wrap').hide();
});
$('#iConfirm').on('click', function(){
$('.insurance-list-wrap').hide();
var ck = document.getElementsByClassName('item-ck'), i = 0, len = ck.length, uids = [], names = [];
for (i; i < len; i++) {
var flag = $(ck[i]).hasClass('active');
if(flag){
var uid = $(ck[i]).attr('data-uid'), name = $(ck[i]).attr('data-name');
uids.push(uid);
names.push(name);
}
}
uids = uids.join(',');
names = names.join(',');
$('#insurance_item_id').val(uids);
$('#select_insurance').val(names);
});
$('.insurance-icon').on('click', function(e){
$(this).find('.item-ck').hasClass('active') ? $(this).find('.item-ck').removeClass('active') : $(this).find('.item-ck').addClass('active');
});
$('#repayment_type').on('change', function(){
var repayment_type = $.trim($('#repayment_type').val());
if(repayment_type == 'single_repayment'){
$('#repaymentFrequency').hide();
}else{
$('#repaymentFrequency').show();
}
});
$('#withdraw').on('click', function(){
//amount loan_period loan_period_unit propose repayment_type repayment_period insurance_item_id
var amount = $.trim($('#amount').val()), loan_period = $.trim($('#loan_period').val()),
loan_period_unit = $.trim($('#loan_period_unit').val()), propose = $.trim($('#propose').val()),
repayment_type = $.trim($('#repayment_type').val()), repayment_period = $.trim($('#repayment_period').val()),
insurance_item_id = $.trim($('#insurance_item_id').val()), param = {};
if(!amount){
verifyFail('<?php echo $lang['tip_please_input_withdrawal_amount'];?>');
return;
}
param.amount = amount;
if(!loan_period){
verifyFail('<?php echo $lang['tip_please_input_withdrawal_amount'];?>');
return;
}
param.loan_period = loan_period;
param.loan_period_unit = loan_period_unit;
if(!repayment_type){
verifyFail('<?php echo $lang['tip_please_input_repayment_method'];?>');
return;
}
param.repayment_type = repayment_type;
if(repayment_type != 'single_repayment'){
if(repayment_period == 0) {
verifyFail('<?php echo $lang['tip_please_input_repayment_method'];?>');
return;
}
param.repayment_period = repayment_period;
}
if(propose){
param.propose = propose;
}
if(insurance_item_id){
param.insurance_item_id = insurance_item_id;
}
toast.loading({
title: '<?php echo $lang['label_loading'];?>'
});
$.ajax({
type: 'POST',
url: '<?php echo WAP_SITE_URL;?>/index.php?act=credit&op=submitWithdraw',
data: param,
dataType: 'json',
success: function(data){
toast.hide();
if(data.STS){
window.location.href = '<?php echo WAP_SITE_URL;?>/index.php?act=credit&op=withdrawConfirm&contract_id='+data.DATA.contract_id;
}else{
verifyFail(data.MSG);
}
},
error: function(xhr, type){
toast.hide();
verifyFail('<?php echo $lang['tip_get_data_error'];?>');
}
});
});
</script>
<file_sep>/framework/api_test/apis/microbank/phone.code.send.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/8
* Time: 11:59
*/
class phoneCodeSendApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Phone Code Send";
$this->description = "发送短信验证码";
$this->url = C("bank_api_url") . "/phone.code.send.php";
$sign = md5('country_code=86&phone=18902461905'.'6bc944bd-8886-11e7-81e6-ccb0daf5504e');
$this->parameters = array();
$this->parameters[]= new apiParameter("country_code", "电话国际区号", '86', true);
$this->parameters[]= new apiParameter("phone", "电话", '18902461905', true);
//$this->parameters[]= new apiParameter("sign", "参数签名,计算方式:md5(所有参数按字母顺序排列的k=v使用&连接后字符串 . sign_key)",$sign, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'verify_id' => '短信验证ID',
'phone_id' => '发送电话'
)
);
}
}<file_sep>/framework/api_test/apis/microbank/loan.calculator.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/28
* Time: 13:50
*/
class loanCalculatorApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan Calculator";
$this->description = "贷款计算器";
$this->url = C("bank_api_url") . "/loan.calculator.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("amount", "贷款金额", 50000, true);
$this->parameters[]= new apiParameter("loan_period", "贷款周期,单位月", 24, true);
$this->parameters[]= new apiParameter("interest", "贷款年利率,百分比,如6%,填6", 6, true);
$this->parameters[]= new apiParameter("repayment_type", "还款方式,等额本息 annuity_scheme,等额本金 fixed_principal,一次偿还(每月计算一次利息) single_repayment,固定利息 flat_interest,先利息后本金 balloon_interest", 'annuity_scheme', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_summation' => array(
'payment_period' => '平均每期还款金额',
'total_interest' => '合计偿还利息',
'payment_total' => '合计偿还本息'
),
'payment_schema' => array(
'scheme_index' => '还款计划序号',
'receivable_principal' => '应还本金',
'receivable_interest' => '应还利息',
'receivable_operation_fee' => '运营费',
'amount' => '当期应还总额',
'remaining_principal' => '剩余应还本金',
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.submit.cert.residentbook.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 11:02
*/
class officerSubmitCertResidentbookApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Resident book cert";
$this->description = "居住证认证";
$this->url = C("bank_api_url") . "/officer.submit.cert.residentbook.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("member_id", "会员id", 1, true);
$this->parameters[]= new apiParameter("front_photo", "正面照,文件流", '', true);
$this->parameters[]= new apiParameter("back_photo", "背面照,文件流", '', true);
$this->parameters[]= new apiParameter("cert_id", "如果是编辑,需要传记录id", null);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'cert_result' => '基本信息',
'extend_info' => '扩展信息'
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/operator/grant.credit.edit.php
<script src="<?php echo GLOBAL_RESOURCE_SITE_URL; ?>/js/jquery.validation.min.js"></script>
<style>
#auth-list .list-group-item {
border-radius: 0px;
font-size: 14px;
padding: 7px 15px;
}
#auth-list .auth_group {
margin-bottom: 10px;
}
.form-filter {
width: 49%;
float: left;
}
.client-info {
width: 49%;
float: right;
}
.client-info .ibox-content {
padding: 0;
}
.client-info .verification-info .ibox-content .item {
padding: 15px 15px;
width: 50%;
float: left;
}
.client-info .verification-info .item span {
font-size: 12px;
margin-left: 5px;
float: right;
}
.client-info .verification-info .item span.checked {
color: #32BC61;
}
.client-info .verification-info .item span.checking {
color: red;
}
.client-info .base-info {
margin-top: 20px;
}
.activity-list .item {
margin-top: 0;
border-right: 1px solid #e7eaec;
}
.activity-list .item:nth-child(2n) {
border-right: 0;
}
.row-active-list .item {
padding: 10px;
border-bottom: 1px solid #e7eaec;
}
.base-info .ibox-content tbody tr td label {
padding-left: 10px;
}
.loan-exp {
float: left;
margin-left: 10px;
position: relative;
margin-top: 3px;
}
.loan-exp > span {
color: #5b9fe2;
}
.loan-exp > span:hover {
color: #ea544a;
}
.loan-exp-wrap {
filter: alpha(Opacity=0);
opacity: 0;
-moz-transition: top .2s ease-in-out, opacity .2s ease-in-out;
-o-transition: top .2s ease-in-out, opacity .2s ease-in-out;
-webkit-transition: top .2s ease-in-out, opacity .2s ease-in-out;
transition: top .2s ease-in-out, opacity .2s ease-in-out;
visibility: hidden;
position: absolute;
top: 24px;
right: 10px;
padding: 7px 10px;
border: 1px solid #ddd;
background-color: #f6fcff;
color: #5b9fe2;
font-size: 12px;
font-family: Arial, "Hiragino Sans GB", simsun;
}
.loan-exp-hover .loan-exp-wrap {
filter: alpha(enabled=false);
opacity: 1;
visibility: visible;
}
.loan-exp-wrap .pos {
position: relative;
}
.loan-exp-table .t {
color: #a5a5a5;
font-size: 12px;
font-weight: 400;
text-align: left;
}
.loan-exp-table .a {
color: #000;
font-size: 18px;
font-weight: 400;
text-align: left;
}
.loan-exp-table .a .y {
color: #ea544a;
}
.triangle-up {
left: auto!important;
right: 30px;
}
.loan-exp-table .t {
height: 20px;
}
.loan-exp-table .a {
font-size: 14px;
height: 30px;
}
</style>
<?php
$approval_info = $output['approval_info'];
$reference_value = $output['credit_reference_value'];
$credit_info = $output['credit_info'];
$info = $output['info'];
$certificationTypeEnumLangLang = enum_langClass::getCertificationTypeEnumLang();
?>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Credit</h3>
<ul class="tab-base">
<li>
<a href="<?php echo getUrl('operator', 'grantCredit', array(), false, BACK_OFFICE_SITE_URL) ?>"><span>List</span></a>
</li>
<li><a class="current"><span>Edit</span></a></li>
</ul>
</div>
</div>
<div class="container clearfix">
<div class="form-filter">
<div class="form-wrap">
<form class="form-horizontal" method="post" action="<?php echo getUrl('operator', 'editCredit', array(), false, BACK_OFFICE_SITE_URL) ?>">
<input type="hidden" name="form_submit" value="ok">
<input type="hidden" name="obj_guid" value="<?php echo $output['loan_info']['obj_guid'] ?>">
<div class="form-group">
<label class="col-sm-2 control-label">CID</label>
<div class="col-sm-8" style="line-height: 30px;">
<?php echo $info['obj_guid']; ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-8" style="line-height: 30px;">
<?php echo $info['display_name']; ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
<?php echo 'Credit Limit' ?>
</label>
<div class="col-sm-8">
<input type="number" class="form-control" name="credit" value="<?php echo $approval_info['uid'] ? $approval_info['current_credit'] : $credit_info['credit'] ?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
<?php echo 'Valid Time'; ?>
</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="valid_time" value="<?php echo $approval_info['uid'] ? $approval_info['valid_time'] : '';?>">
<span class="input-group-addon" style="min-width: 70px">Year</span>
</div>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
<?php echo 'Monthly Repayment Ability' ?>
</label>
<div class="col-sm-8">
<input type="number" class="form-control" name="repayment_ability" value="<?php echo $approval_info['uid'] ? $approval_info['repayment_ability'] : $output['loan_info']['repayment_ability'];?>">
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
<?php echo 'Remark' ?>
</label>
<div class="col-sm-8">
<textarea class="form-control" name="remark" rows="8" cols="80"><?php echo $approval_info['uid'] ? $approval_info['remark'] : '';?></textarea>
<div class="error_msg"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-col-sm-8" style="padding-left: 15px">
<button type="button" style="min-width: 80px" class="btn btn-danger <?php echo $approval_info['uid'] ? 'disabled' : ""?>"><i class="fa fa-check"></i><?php echo 'Save' ?></button>
<?php if ($approval_info['uid']) { ?><span style="color: red;">Auditing...</span><?php } ?>
</div>
</div>
</form>
</div>
<!--建议授信金额-->
<div class="credit-reference-value" style="margin-top: 20px;">
<div>
<div class="ibox-title">
<h4>Credit Level</h4>
</div>
<div class="ibox-content">
<div class="row-active-list clearfix">
<div class="item row" style="font-weight: 600">
<div class="col-sm-4">
Credit Amount
</div>
<div class="col-sm-8">
Certification List
</div>
</div>
<?php if (!empty($reference_value)) {
foreach ($reference_value as $reference) { ?>
<div class="item row">
<div class="col-sm-4">
<?php echo $reference['min_amount'] . ' - ' . $reference['max_amount']; ?>
</div>
<div class="col-sm-8">
<?php echo join(',', $reference['cert_list']);?>
</div>
</div>
<?php }
} ?>
</div>
</div>
</div>
</div>
</div>
<div class="client-info">
<div class="base-info" style="margin-top: 0">
<div class="ibox-title">
<h4>Check Result</h4>
</div>
<div class="ibox-content">
<div class="activity-list clearfix">
<table class="table">
<tbody class="table-body">
<tr>
<td><label class="control-label">Credit Officer</label></td>
<td><?php echo $info['co_name']; ?></td>
</tr>
<!-- <tr>-->
<!-- <td><label class="control-label">Is Check</label></td>-->
<!-- <td>--><?php //echo $info['co_state'] > 0 ? "YES" : "NO"; ?><!--</td>-->
<!-- </tr>-->
<tr>
<td><label class="control-label">Assets Valuation</label></td>
<td>
<div style="float: left"><em style="font-weight: 600;font-size: 18px;color: red"><?php echo ncAmountFormat($output['assets_valuation']); ?></em></div>
<?php if ($output['assets_valuation_type']){ ?>
<div class="loan-exp">
<span class="loan-plan-detail">Detail</span>
<div class="loan-exp-wrap">
<div class="pos">
<em class="triangle-up"></em>
<table class="loan-exp-table" style="width:300px;">
<tr class="t">
<td>Asset Type</td>
<td>Valuation</td>
</tr>
<?php foreach($output['assets_valuation_type'] as $assets_valuation){?>
<tr class="a">
<td><?php echo $certificationTypeEnumLangLang[$assets_valuation['asset_type']]; ?></td>
<td><?php echo ncAmountFormat($assets_valuation['assets_valuation']); ?></td>
</tr>
<?php }?>
</table>
</div>
</div>
</div>
<?php }?>
</td>
</tr>
<tr>
<td><label class="control-label">Evaluate Time</label></td>
<td><?php echo $output['credit_suggest']['create_time']; ?></td>
</tr>
<tr>
<td><label class="control-label">Suggest Credit </label></td>
<td><em style="font-weight: 600;font-size: 16px"><?php echo ncAmountFormat($output['credit_suggest']['suggest_credit']); ?></em></td>
</tr>
<tr>
<td><label class="control-label">Repayment Ability(Monthly)</label></td>
<td><em style="font-weight: 600;font-size: 16px"><?php echo ncAmountFormat($output['credit_suggest']['monthly_repayment_ability']); ?></em></td>
</tr>
<tr>
<td><label class="control-label">Business Profitability</label></td>
<td><span style="font-weight: 600;font-size: 16px"><?php echo 'None'; ?></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="verification-info">
<div class="ibox-title" style="margin-top: 20px">
<h4>Check List</h4>
</div>
<div class="ibox-content">
<div class="activity-list clearfix">
<?php $verify_field = $output['verify_field']; $verifys = $output['verifys']; ?>
<?php foreach ($verify_field as $key => $value) { ?>
<div class="item">
<div>
<?php echo $value; ?>
<span>
<?php if ($verifys[$key] == 1) { ?>
<i class="fa fa-check" aria-hidden="true" style="font-size: 18px;color:green;"></i>
<?php } else { ?>
<i class="fa fa-question" aria-hidden="true" style="font-size: 18px;color:red;"></i>
<?php } ?>
<i></i>
</span>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="base-info">
<div class="ibox-title">
<h4>Client Info</h4>
</div>
<div class="ibox-content">
<div class="activity-list clearfix">
<table class="table">
<tbody class="table-body">
<tr>
<td><label class="control-label">CID</label></td>
<td><?php echo $info['obj_guid']; ?></td>
</tr>
<tr>
<td><label class="control-label">Name</label></td>
<td><?php echo $info['display_name']; ?></td>
</tr>
<tr>
<td><label class="control-label">Credit</label></td>
<td><?php echo $info['credit']; ?></td>
</tr>
<tr>
<td><label class="control-label">Account Type</label></td>
<td><?php echo 'Member'; ?></td>
</tr>
<tr>
<td><label class="control-label">Phone</label></td>
<td><?php echo $info['phone_id']; ?></td>
</tr>
<tr>
<td><label class="control-label">Email</label></td>
<td><?php echo $info['email']; ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('.loan-exp').hover(function () {
$(this).addClass('loan-exp-hover');
}, function () {
$(this).removeClass('loan-exp-hover');
});
});
$('.btn-danger').click(function () {
if (!$(".form-horizontal").valid()) {
return;
}
$('.form-horizontal').submit();
});
$('.form-horizontal').validate({
errorPlacement: function (error, element) {
var ele = $(element).closest('.form-group').find('.error_msg');
error.appendTo(ele);
},
rules: {
credit: {
required: true
},
valid_time: {
required: true
},
repayment_ability: {
required: true
},
remark: {
required: true
}
},
messages: {
credit: {
required: '<?php echo 'Required';?>'
},
valid_time: {
required: '<?php echo 'Required';?>'
},
repayment_ability: {
required: '<?php echo 'Required';?>'
},
remark: {
required: '<?php echo 'Required';?>'
}
}
});
</script>
<file_sep>/framework/weixin_baike/data/model/member_verify_cert_image.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/1/4
* Time: 10:05
*/
class member_verify_cert_imageModel extends tableModelBase
{
public function __construct()
{
parent::__construct('member_verify_cert_image');
}
}<file_sep>/framework/api_test/apis/microbank/loan.apply.preview.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/5
* Time: 13:14
*/
// loan.apply.preview
class loanApplyPreviewApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Loan apply preview";
$this->description = "贷款申请预览";
$this->url = C("bank_api_url") . "/loan.apply.preview.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("amount", "贷款金额", 1000, true);
$this->parameters[]= new apiParameter("loan_time", "贷款时间,单位是月", 1, true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'total_interest_rate' => '合计利率信息',
'total_repayment_amount' => '合计还款总额'
)
);
}
}<file_sep>/index.php
<?php
echo 'Hello,my git project!';
<file_sep>/framework/weixin_baike/mobile/templates/default/home/information.occupation.php
<link rel="stylesheet" type="text/css" href="<?php echo WAP_OPERATOR_SITE_URL;?>/resource/css/home.css?v=2">
<?php include_once(template('widget/inc_header'));?>
<div class="wrap information-wrap">
<?php $work_info = $output['work_info'];?>
<div>
<ul class="aui-list request-detail-ul">
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Company Name
</div>
<div class="aui-list-item-input label-on">
<?php echo $work_info['company_name'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Company Address
</div>
<div class="aui-list-item-input label-on">
<?php echo $work_info['company_addr'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Position
</div>
<div class="aui-list-item-input label-on">
<?php echo $work_info['position'];?>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label label">
Government Staff
</div>
<div class="aui-list-item-input label-on">
<?php echo ['is_government']?'Yes':'No';?>
</div>
</div>
</li>
</ul>
</div>
</div>
<script type="text/javascript">
</script>
<file_sep>/framework/api_test/apis/microbank/member.savings.bill.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/17
* Time: 11:27
*/
class memberSavingsBillDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member bill detail";
$this->description = "客户账单详情";
$this->url = C("bank_api_url") . "/member.savings.bill.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("bill_id", "账单ID", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'bill_detail' => array(
'uid' => '流水ID',
'category' => '分类',
'trading_type' => '交易类型',
'subject' => '标题',
'credit' => '收入',
'debit' => '支出',
'create_time' => '创建时间',
'state' => '状态 0 新建 90 在途 100 成功 '
),
'account_info' => array(
'uid' => '',
'currency' => '',
'balance' => '',
'credit' => '',
'outstanding' => '',
)
)
);
}
}<file_sep>/framework/api_test/apis/officer_app/officer.get.member.cert.result.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/7
* Time: 16:40
*/
// officer.get.member.cert.result
class officerGetMemberCertResultApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member Cert List";
$this->description = "会员认证列表";
$this->url = C("bank_api_url") . "/officer.get.member.cert.result.php";
$this->parameters = array();
$this->parameters[] = new apiParameter("member_id", "会员id", 1, true);
$this->parameters[] = new apiParameter("token", "token令牌", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'@description' => '认证列表,各类型含义 1 身份证 2 户口本 3 护照 4 房产 5 汽车资产 6 工作证明 7 公务员(合在工作)8 家庭关系证明 9 土地 10 居住证 11 摩托车',
1 => '-10 未认证 -1 资料审核中 0 待审核 10 认证通过 11 已过期 100 认证失败',
2 => '资产认证(如摩托车,房屋,汽车,土地等)返回的是已认证数量,如0,1,2',
3 => '',
4 => '',
5 => '',
6 => '',
7=> '',
8=> '',
9=> ''
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/templates/default/home/monitor.php
<div>
<audio src="resources/voice/alert.mp3" id="ad_default"></audio>
</div>
<style>
.monitor-flash{
background-color: #801010;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Monitor</h3>
</div>
</div>
<div class="container">
<div class="col-sm-10">
<?php $groups=$output['monitor_items'];?>
<div id="div_monitor">
<ul class="list-inline">
<?php foreach($groups as $group){?>
<li>
<ul class="list-group">
<li class="list-group-item list-group-item-info" style="font-size: 18px;font-weight: bold">
<?php echo $group['title']?>
</li>
<?php foreach($group['items'] as $item){?>
<li class="list-group-item" style="height: 150px">
<div id="div_monitor_item_<?php echo $item['key']?>" class="popover top" style="position: relative;display: block;float: left;width: 200px;margin: 20px;z-index: 500">
<div class="popover-title">
<a href="<?php echo $item['url'] ?>" my_title="<?php echo $item['title'];?>">
<?php echo $item['title']?>
<span class="badge <?php echo $item['key']?>_badge_monitor" style="float: right">0</span>
</a>
</div>
<div id="div_monitor_content_<?php echo $item['key']?>" class="popover-content"><?php echo $item['desc']?:'Null<br/> '?></div>
</div>
</li>
<?php }?>
</ul>
</li>
<?php }?>
</ul>
</div>
</div>
<div class="col-sm-2">
<div style="top: 0;border: 0;right: 0;">
<ul class="list-group" id="ul_msg">
<li class="list-group-item list-group-item-info">
Message
</li>
</ul>
</div>
</div>
</div>
</div>
<script>
var _ad_playing=false;//是否正在播放
$(document).ready(function(){
$("#ad_default").bind("ended",function(){
_ad_playing=false;
});
$("#ad_default").bind("play",function(){
_ad_playing=true;
});
monitor.start();
});
</script>
<!------******************Monitor**************************-->
<script>
var monitor={};
monitor.clear=function(){
monitor.div.html();
};
monitor.start=function(){
monitor.getData();
};
monitor.stop=function(){
if(monitor.timer_id){
clearTimeout(monitor.timer_id);
}
};
monitor.play_voice=true;
monitor.show_alert=true;
monitor.timer_id=null;
monitor.last_time=null;
monitor.getData=function(){
var _url = '<?php echo ENTRY_API_SITE_URL . DS . 'monitor.get.php'?>';
$.post(_url, {last_time:monitor.last_time}, function (_o) {
_o = $.parseJSON(_o);
if(!_o.STS) return false;
monitor.last_time=_o.last_time;
var _monitor_items=_o.data;
var _new_task=0;
for(var _monitor_key in _monitor_items){
$("."+_monitor_key+"_badge_monitor").text(_monitor_items[_monitor_key].count);
var _div_monitor_item=$("#div_monitor_item_"+_monitor_key);
if(_monitor_items[_monitor_key].count>0){
_div_monitor_item.addClass('monitor-alert');
}else{
_div_monitor_item.removeClass('monitor-alert');
}
$("#div_monitor_content_"+_monitor_key).html(_monitor_items[_monitor_key].content);
if(_monitor_items[_monitor_key].new>0){
_new_task+=_monitor_items[_monitor_key].new;
var _li='<li class="list-group-item" style="font-size: 10px">'+'<p>'+_monitor_items[_monitor_key]['title']+' <code>'+_o.last_time+'</code></p>'+'</li>';
if($("#ul_msg").find("li").length>=10){
$("#ul_msg li:last-child").remove();
}
$("#ul_msg li:first-child").after(_li);
_div_monitor_item.data("flash_time",0);
//闪动效果
_flashItem(_div_monitor_item);
}
}
//计算新的task
if(_new_task>0){
if(monitor.play_voice==true){
if(_ad_playing==false){
$("#ad_default").trigger("play");
}
}
}
monitor.timer_id=setTimeout(function(){
monitor.getData();
},1000*30);//30秒请求一次
});
}
function _flashItem(_div_fi){
if(parseInt(_div_fi.data("flash_time"))%2==0){
_div_fi.addClass("monitor-flash");
}else{
_div_fi.removeClass("monitor-flash");
}
_div_fi.data("flash_time",parseInt(_div_fi.data('flash_time'))+1);
if(parseInt(_div_fi.data("flash_time"))<10){
setTimeout(function(){
_flashItem(_div_fi);
},500);
}
}
</script>
<file_sep>/framework/weixin_baike/backoffice/templates/default/financial/exchange_rate.list.php
<style>
.fa.fa-exchange, .fa.fa-angle-double-right, .fa.fa-angle-double-left {
color: #32BC61;
}
</style>
<div class="page">
<div class="fixed-bar">
<div class="item-title">
<h3>Currency</h3>
<ul class="tab-base">
<li><a class="current"><span>List</span></a></li>
<li><a href="<?php echo getUrl('financial', 'setExchangeRate', array(), false, BACK_OFFICE_SITE_URL)?>"><span>Setting</span></a></li>
</ul>
</div>
</div>
<div class="container">
<div class="business-content">
<div class="business-list">
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'No.';?></td>
<td><?php echo 'Currency';?></td>
<td><?php echo 'Buy Rate';?></td>
<td><?php echo 'Sell Rate';?></td>
<td><?php echo 'Update Name';?></td>
<td><?php echo 'Update Time';?></td>
<td>Function</td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($output['exchange_rate_list'] as $key => $row){ ?>
<tr>
<td>
<?php echo $row['uid']; ?><br/>
</td>
<td>
<?php echo $row['first_currency']; ?>
<i class="fa fa-exchange"></i>
<?php echo $row['second_currency']; ?>
</td>
<td>
<?php echo ncPriceFormat($row['buy_rate_unit']); ?>
<i class="fa fa-angle-double-right"></i>
<?php echo ncPriceFormat($row['buy_rate']); ?>
</td>
<td>
<?php echo ncPriceFormat($row['sell_rate']); ?>
<i class="fa fa-angle-double-left"></i>
<?php echo ncPriceFormat($row['sell_rate_unit']); ?>
</td>
<td>
<?php echo $row['update_name']; ?>
</td>
<td>
<?php echo timeFormat($row['update_time']); ?>
</td>
<td>
<a title="<?php echo $lang['common_edit'] ;?>" href="<?php echo getUrl('financial', 'setExchangeRate', array('uid' => $row['uid']), false, BACK_OFFICE_SITE_URL)?>">
<i class="fa fa-edit"></i>
Edit
</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<file_sep>/framework/weixin_baike/data/model/um_user_token.model.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/2/1
* Time: 15:41
*/
class um_user_tokenModel extends tableModelBase
{
function __construct()
{
parent::__construct('um_user_token');
}
}<file_sep>/framework/api_test/apis/microbank/credit.loan.preview.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2017/11/28
* Time: 17:55
*/
class creditLoanPreviewApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Credit Loan Preview";
$this->description = "贷款预览";
$this->url = C("bank_api_url") . "/credit_loan.preview.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("product_id", "贷款产品id", 1, true);
$this->parameters[]= new apiParameter("amount", "贷款金额", 500, true);
$this->parameters[]= new apiParameter("loan_period", "贷款周期,单位月", 6, true);
$this->parameters[]= new apiParameter("repayment_type", "还款方式,等额本息 annuity_scheme,等额本金 fixed_principal,一次偿还(每月计算一次利息) single_repayment,固定利息 flat_interest,先利息后本金 balloon_interest", 'annuity_scheme', true);
$this->parameters[]= new apiParameter("repayment_period", "还款周期,一年一次 yearly,半年一次 semi_yearly,一季度一次 quarter,一月一次 monthly,一周一次 weekly,一天一次 daily", 'monthly', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'product_info' => '产品信息',
'loan_fee' => '贷款手续费',
'arrival_amount' => '实际到手贷款金额',
'interest_rate' => '利率值',
'interest_rate_type' => '利率类型 0 百分比 1 固定金额',
'period_repayment_amount' => '平均每期还款金额',
'total_repayment'=> '还款合计',
'repayment_schema' => array(
array(
'scheme_index' => '还款计划序号',
'receivable_principal' => '应还本金',
'receivable_interest' => '应还利息',
'receivable_operation_fee' => '运营费',
'amount' => '当期应还总额',
'remaining_principal' => '剩余应还本金',
)
)
)
);
}
}<file_sep>/framework/api_test/apis/test.ace.api/ace.verify.client.account.php
<?php
/**
* Created by PhpStorm.
* User: 43070
* Date: 2018/1/31
* Time: 17:19
*/
class aceVerifyClientAccountApiDocument extends apiDocument {
public function __construct()
{
$this->name = "Ace API - ace.member.verify";
$this->description = "Verify if the phone register is ACE member or not.";
$this->url = C("bank_api_url") . "/test.ace.api.php?op=verify_client_account";
$this->parameters = array();
$this->parameters[]= new apiParameter("ace_account", "Member Phone Number", "+86-15928677642", true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'flag_ace_member' => '1: 是ace的会员,2: 不是'
)
);
}
}<file_sep>/framework/weixin_baike/data/model/um_user.model.php
<?php
/**
* Created by PhpStorm.
* User: tim
* Date: 5/31/2015
* Time: 1:15 AM
*/
class um_userModel extends tableModelBase
{
// public $schema = array(
// array("Field" => "user_code", "Type" => "varchar", "Null" => "NO", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "first_name", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "last_name", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "password", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "user_image", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "user_icon", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "email", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "mobile_phone", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "user_type", "Type" => "int(4)", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "user_status", "Type" => "int(4)", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "creator_id", "Type" => "int", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "insert_time", "Type" => "timestamp", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "remark", "Type" => "varchar(200)", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "last_login_time", "Type" => "datetime", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "last_login_ip", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "last_login_area", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "role_code", "Type" => "varchar", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// array("Field" => "profile", "Type" => "text", "Null" => "", "Key" => "", "Default" => "", "Extra" => ""),
// );
public function __construct()
{
parent::__construct('um_user');
}
}
<file_sep>/framework/weixin_baike/counter/templates/default/member/guarantee.list.php
<div>
<table class="table table-bordered">
<thead>
<tr class="table-header">
<td><?php echo '<NAME>';?></td>
<td><?php echo 'Phone';?></td>
<td><?php echo 'Relationship';?></td>
<td><?php echo 'State';?></td>
<td><?php echo 'Create Time';?></td>
<td><?php echo 'Update Time';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php if($data['data']) {?>
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<?php echo $row['display_name'] ?><br/>
</td>
<td>
<?php echo $row['phone_id'] ?><br/>
</td>
<td>
<?php echo $row['relation_type'] ?><br/>
</td>
<td>
<?php echo $row['relation_state'] == 0 ? 'Create' : 'Pass'; ?><br/>
</td>
<td>
<?php echo timeFormat($row['create_time']) ?><br/>
</td>
<td>
<?php echo timeFormat($row['update_time']) ?><br/>
</td>
</tr>
<?php }?>
<?php } else { ?>
<tr>
<td colspan="6">Null</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<file_sep>/framework/api_test/apis/officer_app/officer.get.member.asset.detail.php
<?php
/**
* Created by PhpStorm.
* User: sahara
* Date: 2018/3/16
* Time: 14:31
*/
class officerGetMemberAssetDetailApiDocument extends apiDocument
{
public function __construct()
{
$this->name = "Member one asset detail";
$this->description = "会员某项资产明细";
$this->url = C("bank_api_url") . "/officer.get.member.asset.detail.php";
$this->parameters = array();
$this->parameters[]= new apiParameter("asset_id", "资产ID", 1, true);
$this->parameters[]= new apiParameter("token", "<PASSWORD>", '', true);
$this->return = array(
'STS' => 'API结果状态,true/false',
'CODE' => 'API结果代码',
'MSG' => '错误消息(调试情况下才会出现)',
'DATA' => array(
'asset_detail' => array(
'valuation' => '估值',
'remark' => '备注'
)
)
);
}
}<file_sep>/framework/weixin_baike/backoffice/control/tools.php
<?php
class toolsControl extends baseControl
{
public function __construct()
{
parent::__construct();
Language::read('tools');
Tpl::setLayout("empty_layout");
Tpl::output("html_title", "Home");
Tpl::setDir("tools");
}
/**
* 计算器
*/
public function calculatorOp()
{
$class_product = new product();
$valid_products = $class_product->getValidProductList();
Tpl::output("valid_products", $valid_products);
$m_core_definition = M('core_definition');
$define_arr = $m_core_definition->getDefineByCategory(array('mortgage_type', 'guarantee_type'));
Tpl::output("mortgage_type", $define_arr['mortgage_type']);
Tpl::output("guarantee_type", $define_arr['guarantee_type']);
$interest_payment = (new interestPaymentEnum())->Dictionary();
$interest_rate_period = (new interestRatePeriodEnum())->Dictionary();
Tpl::output("interest_payment", $interest_payment);
Tpl::output("interest_rate_period", $interest_rate_period);
Tpl::showPage("calculator");
}
/**
* 贷款计算
* @param $p
* @return result
*/
public function loanPreviewOp($p)
{
$creditLoan = new credit_loanClass();
$re = $creditLoan->loanPreview($p);
if (!$re->STS) {
return $re;
}
$data = $re->DATA;
$data_new = array();
$data_new['loan_amount'] = ncAmountFormat($data['total_repayment']['total_principal']);
$data_new['repayment_amount'] = ncAmountFormat($data['total_repayment']['total_payment']);
$data_new['arrival_amount'] = ncAmountFormat($data['arrival_amount']);
$data_new['service_charge'] = ncAmountFormat($data['loan_fee']);
$data_new['total_interest'] = ncAmountFormat($data['total_repayment']['total_interest']);
$data_new['period_repayment_amount'] = ncAmountFormat($data['period_repayment_amount']);
$data_new['interest_rate'] = $data['interest_rate_type'] == 0 ? ($data['interest_rate'] . '%') : ncAmountFormat($data['interest_rate']);
$data_new['interest_rate_unit'] = $data['interest_rate_unit'];
$data_new['repayment_number'] = count($data['repayment_schema']);
if ($data_new['repayment_number'] > 1) {
$first_repayment = array_shift($data['repayment_schema']);
$second_repayment = array_shift($data['repayment_schema']);
if ($first_repayment['amount'] == $second_repayment['amount']) {
$data_new['each_repayment'] = ncAmountFormat($first_repayment['amount']);
$data_new['single_repayment'] = 0;
$data_new['first_repayment'] = 0;
} else {
$data_new['first_repayment'] = ncAmountFormat($first_repayment['amount']);
$data_new['single_repayment'] = 0;
$data_new['each_repayment'] = 0;
}
} else {
$first_repayment = array_shift($data['repayment_schema']);
$data_new['single_repayment'] = ncAmountFormat($first_repayment['amount']);
$data_new['first_repayment'] = 0;
$data_new['each_repayment'] = 0;
}
$data_new['operation_fee'] = ncAmountFormat($first_repayment['receivable_operation_fee']);
$re->DATA = $data_new;
return $re;
}
/**
* sms
*/
public function smsOp()
{
$condition = array(
"date_start" => date("Y-m-d", strtotime(dateAdd(Now(), -30))),
"date_end" => date('Y-m-d')
);
Tpl::output("condition", $condition);
Tpl::showpage('sms');
}
/**
* @param $p
* @return array
*/
public function getSmsListOp($p)
{
$search_text = trim($p['search_text']);
$need_resend = intval($p['need_resend']);
$d1 = $p['date_start'];
$d2 = dateAdd($p['date_end'], 1);
$r = new ormReader();
$sql = "SELECT * FROM common_sms WHERE (create_time BETWEEN '" . $d1 . "' AND '" . $d2 . "') AND task_state != " . smsTaskState::CANCEL;
if ($search_text) {
$sql .= " AND phone_id like '%" . $search_text . "%'";
}
if ($need_resend) {
$sql .= " AND task_state = " . smsTaskState::SEND_FAILED;
}
$sql .= ' ORDER BY uid DESC';
$pageNumber = intval($p['pageNumber']) ?: 1;
$pageSize = intval($p['pageSize']) ?: 20;
$data = $r->getPage($sql, $pageNumber, $pageSize);
$rows = $data->rows;
$total = $data->count;
$pageTotal = $data->pageCount;
return array(
"sts" => true,
"data" => $rows,
"total" => $total,
"pageNumber" => $pageNumber,
"pageTotal" => $pageTotal,
"pageSize" => $pageSize
);
}
public function resendSmsOp($p)
{
$uid = intval($p['uid']);
$m_common_sms = M('common_sms');
$sms_row = $m_common_sms->getRow($uid);
if (!$sms_row) {
$data = array('state' => 'Resend Failed');
return new result(false, 'Invalid Id!', $data);
}
if ($sms_row->task_state != smsTaskState::SEND_FAILED) {
$data = array('state' => 'Resend Failed');
return new result(false, 'Sms state error!', $data);
}
$smsHandler = new smsHandler();
if ($sms_row->task_type == smsTaskType::VERIFICATION_CODE) {
// 发送短信验证码
$verify_code = mt_rand(100001, 999999);
$contact_phone = $sms_row->phone_id;
$rt = $smsHandler->sendVerifyCode($contact_phone, $verify_code);
if (!$rt->STS) {
$data = array('state' => 'Resend Failed');
return new result(false, 'Send code fail: ' . $rt->MSG, $data);
}
$data = $rt->DATA;
$content = $data->content;
$conn = ormYo::Conn();
$conn->startTransaction();
try {
$m_phone_verify_code = M('common_verify_code');
$new_row = $m_phone_verify_code->newRow();
$new_row->phone_country = $sms_row->phone_country;
$new_row->phone_id = $contact_phone;
$new_row->verify_code = $verify_code;
$new_row->create_time = Now();
$new_row->sms_id = $sms_row->uid;
$insert = $new_row->insert();
if (!$insert->STS) {
$conn->rollback();
return new result(false, 'Insert verify code fail');
}
$sms_row->task_state = smsTaskState::CANCEL;
$sms_row->update_time = Now();
$update = $sms_row->update();
if (!$update->STS) {
$conn->rollback();
$data = array('state' => 'Resend Failed');
return new result(false, 'Update sms fail', $data);
}
$conn->submitTransaction();
$data = array('content' => $content, 'state' => L('task_state_' . smsTaskState::SEND_SUCCESS));
return new result(true, 'Resend successful!', $data);
} catch (Exception $ex) {
$conn->rollback();
return new result(false, $ex->getMessage());
}
} else {
$rt = $smsHandler->resend($uid);
if ($rt->STS) {
$data = $rt->DATA;
$data = array('content' => $data->content, 'state' => L('task_state_' . smsTaskState::SEND_SUCCESS));
return new result(true, 'Resend successful!', $data);
} else {
$data = array('state' => 'Resend Failed');
return new result(true, 'Resend failed!', $data);
}
}
}
}
<file_sep>/framework/weixin_baike/backoffice/templates/default/loan/credit.list.php
<div>
<table class="table">
<thead>
<tr class="table-header">
<td><?php echo 'CID';?></td>
<td><?php echo 'Name';?></td>
<td><?php echo 'Credit';?></td>
<td><?php echo 'Multi Contract';?></td>
<td><?php echo 'Type';?></td>
<td><?php echo 'Update Time';?></td>
<td><?php echo 'Function';?></td>
</tr>
</thead>
<tbody class="table-body">
<?php foreach($data['data'] as $row){?>
<tr>
<td>
<a href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$row['uid'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>"><?php echo $row['obj_guid'] ?></a>
<br/>
</td>
<td>
<a href="<?php echo getUrl('client', 'clientDetail', array('uid'=>$row['uid'], 'show_menu'=>'client-client'), false, BACK_OFFICE_SITE_URL)?>"><?php echo $row['display_name'] ?></a>
</td>
<td>
<?php echo $row['credit']?:0; ?><br/>
</td>
<td>
<?php echo ($row['allow_multi_contract'] == 1)?'Yes':'No'; ?><br/>
</td>
<td>
<?php switch ($row['account_type']) {
case 0:
echo 'member';
break;
case 10:
echo 'partner';
break;
case 20:
echo 'dealer';
break;
case 30:
echo 'Legal person';
break;
default:
echo 'member';
break;
} ?><br/>
</td>
<td>
<?php echo timeFormat($row['update_time']) ?><br/>
</td>
<td>
<div class="custom-btn-group">
<a title="<?php echo $lang['common_delete'];?>" class="custom-btn custom-btn-primary" href="<?php echo getUrl('loan', 'editCredit', array('obj_guid'=>$row['obj_guid']), false, BACK_OFFICE_SITE_URL)?>" >
<span><i class="fa fa-send-o"></i>Credit</span>
</a>
</div>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<hr>
<?php include_once(template("widget/inc_content_pager"));?>
| 314c0e5b1afbb3bb2c34da5e776872e6f759985f | [
"Markdown",
"PHP"
] | 247 | PHP | yangruofeng/fri_community | f6b91d094bfc16b800f3c2bfb86ea09f737c6748 | 4e5b7b20cf7b3542c82818bbb631d47a3b3d7e6c |
refs/heads/master | <repo_name>roman-aguilera/romans_pybullet_gym_envs<file_sep>/octopus_env.py
import gym, gym.spaces, gym.utils, gym.utils.seeding
import numpy as np
import pybullet
import os
from pybullet_utils import bullet_client #for physics client (lets you run multiple clients in parallel)
from pkg_resources import parse_version
import einsteinpy.coordinates #used to convert between cartesian to spherical coordinates
import random #used for resetting goal target
import pybullet_data
try:
if os.environ["PYBULLET_EGL"]:
import pkgutil
except:
pass
#call this env with env_instance = gym.make("OctopusArm2DBulletEnv-v0", render=True)
class OctopusEnv(gym.Env):
"""
Base class for Bullet physics simulation loading MJCF (MuJoCo .xml) environments in a Scene.
These environments create single-player scenes and behave like normal Gym environments, if
you don't use multiplayer.
"""
metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 60}
def __init__(self, render=True, number_of_links_urdf=8, number_of_joints_urdf=8): #def __init__(self, render=False):
self.scene = None
self.physicsClientId = -1 #indicates that we have not started a pybullet simulation, this number is changed when we do start a simulation
self.ownsPhysicsClient = 0 #indicates that we have not started a pybullet simulation, this is changed to True when we do start a simulation (in the reset function)
self.camera = Camera()
#self.joints = Joint()
#self.joints_and_links = robotJointsandLinks(number_of_joints=None, number_of_links=None, bodyUniqueId=self.o)
self.isRender = render
#self.robot = robot
self.seed()
self._cam_dist = 3
self._cam_yaw = 0
self._cam_pitch = -30
self._render_width = 320
self._render_height = 240
self.number_of_links_urdf = number_of_links_urdf
self.number_of_joints_urdf = number_of_joints_urdf
self.number_of_torques_urdf = number_of_links_urdf
self.target_x = 0 # this is 0 in 2D case
self.target_y = 5 # ee y coordinate limits for 8 link arm are
self.target_z = 5 # ee z coordniate limits for 8 link arm are
[self.x_lower_limit, self.x_upper_limit] = [0.0, 0.0] # reachable x coordinates (double check for each arm)
[self.y_lower_limit, self.y_upper_limit] = [-15,15] # reachable y coordinates
[self.z_lower_limit, self.z_upper_limit] = [0,15] # reachable z coordinates
self.radius_to_goal_epsilon = 5 #10 #1e0 #9e-1 #1e-1 #1e-3
self.joint_states=np.zeros(shape=(2*self.number_of_links_urdf,))
self.time_stamp = 0 #time elapsed since last reset
self.time_step = 1./240 #this is the default timestep in pybullet, to set other tipestep use the following code and place it in the reset() method: self._p.setTimeStep(timeStep = self.time_step, physicsclientId=self.physicsClientId)
#################### create action and observation spaces (begin)
obs_dim = 22 # num_links (8) *2 + extra_states (self.radius_to_goal, self.theta_to_goal, self.phi_to_goal) + extra states ((self.end_effector_vx, self.end_effector_vy, self.end_effector_vz))
high = np.inf * np.ones([obs_dim]); self.observation_space = gym.spaces.Box(-high, high) #self.observation_space = robot.observation_space
action_dim = self.number_of_torques_urdf
high = np.ones([action_dim]); self.action_space = gym.spaces.Box(-high, high) #self.action_space = robot.action_space
#self.reset()
#################### create action spaces (end)
#def configure(self, args):
# self.robot.args = args
def seed(self, seed=None):
self.np_random, seed = gym.utils.seeding.np_random(seed)
# self.robot.np_random = self.np_random # use the same np_randomizer for robot as for env
return [seed]
#### RESET
def reset(self):
if (self.physicsClientId < 0): #if it is the first time we are loading the simulations
self.ownsPhysicsClient = True #this
if self.isRender:
self._p = bullet_client.BulletClient(connection_mode=pybullet.GUI) # connect to physics server, and render through Graphical User Interface (GUI)
else:
self._p = bullet_client.BulletClient() #connect to physics server, and DO NOT render through graphical user interface
self.physicsClientId = self._p._client # get the client ID from physics server, this makes self.physicsClientId become a value greater than 0
self._p.resetSimulation() # reset physics server and remove all objects (urdf files, or mjcf, or )
#self.number_of_links_urdf = number_of_links_urdf
self.model_urdf = "romans_urdf_files/octopus_files/python_scripts_edit_urdf/octopus_generated_"+str(self.number_of_links_urdf)+"_links.urdf"
self.octopusBodyUniqueId = self._p.loadURDF( fileName=os.path.join(pybullet_data.getDataPath(),self.model_urdf) , flags=pybullet.URDF_USE_SELF_COLLISION | pybullet.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS)
self._p.setJointMotorControlArray(bodyUniqueId=self.octopusBodyUniqueId, jointIndices=list(range(8)), controlMode = self._p.POSITION_CONTROL, positionGains=[0.1]*self.number_of_links_urdf, velocityGains=[0.1]*self.number_of_links_urdf, forces=[0]*self.number_of_links_urdf) #turns off motors so that robot joints are not stiff
self.goal_point_urdf = "sphere8cube.urdf"
self.goalPointUniqueId = self._p.loadURDF( fileName=os.path.join(pybullet_data.getDataPath(),self.goal_point_urdf) , basePosition=[self.target_x, self.target_y, self.target_z], useFixedBase=1 ) #flags=self._p.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS)
#self.goalPointUniqueId = self._p.createVisualShape(physicsClientId=self.physicsClientId, shapeType=self._p.GEOM_SPHERE, radius=4, specularColor=[0.5,0.5,0.5]) #secularcolor = [r,g,b]
#self._p.resetBasePositionAndOrientation(bodyUniqueId=self.goalPointUniqueId, physicsClientId=self.physicsClientId, posObj=[self.target_x, self.target_y, self.target_z], ornObj=[0,0,0,1])
#function usage example: 'bodyUniqueId = pybullet.loadURDF(fileName="path/to/file.urdf", basePosition=[0.,0.,0.], baseOrientation=[0.,0.,0.,1.], useMaximalCoordinates=0, useFixedBase=0, flags=0, globalScaling=1.0, physicsClientId=0)\nCreate a multibody by loading a URDF file.'
#optionally enable EGL for faster headless rendering
try:
if os.environ["PYBULLET_EGL"]:
con_mode = self._p.getConnectionInfo()['connectionMethod']
if con_mode==self._p.DIRECT:
egl = pkgutil.get_loader('eglRenderer')
if (egl):
self._p.loadPlugin(egl.get_filename(), "_eglRendererPlugin")
else:
self._p.loadPlugin("eglRendererPlugin")
except:
pass
self.physicsClientId = self._p._client #get physics client ID
# enable gravity
self._p.setGravity(gravX=0, gravY=0, gravZ=0, physicsClientId=self.physicsClientId)
self._p.configureDebugVisualizer(pybullet.COV_ENABLE_GUI, 0)
self.joints_and_links = robotJointsandLinks(number_of_joints=self.number_of_joints_urdf, number_of_links=self.number_of_links_urdf, bodyUniqueId=self.octopusBodyUniqueId, physicsClientId=self.physicsClientId) #make dictionaries of joints and links (refer to robotJointsandLinks() class)
#end of "if first loading pybullet client"
#reset goal target to random one
self.target_x = 0 # no x comoponent for 2D case
self.target_y = random.uniform(self.y_lower_limit, self.y_upper_limit) # choose y coordinates such that arm can reach
self.target_z = random.uniform(self.z_lower_limit, self.z_upper_limit) # choose z coordinates such that arm can reach
#correspondingly move visual representation of goal target
self._p.resetBasePositionAndOrientation( bodyUniqueId=self.goalPointUniqueId, posObj=[self.target_x, self.target_y, self.target_z], ornObj=[0,0,0,1], physicsClientId=self.physicsClientId )
#reset joint positions and velocities
for i in range(self.number_of_joints_urdf):
#ROLLOUT1: all positions=0, all velocities=0 #(initially stretched and static)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=0, targetVelocity=0 ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#ROLLOUT2: all positions=pi, all velocities=0 #(initially contracted and static)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=np.pi, targetVelocity=0 )
#ROLLOUT3: all positions=0, all velocities=(-pi*c, pi*c) # (initially stretched and dynamic)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=0, targetVelocity=random.uniform(-np.pi*0.5, np.pi*0.5) )
#ROLLOUT4: all positions = pi (IDEA: try uniform sampling around it?), all velocities=(-pi*c,*pi*c) (initially contracted and dynamic)
self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=np.pi, targetVelocity=random.uniform(-np.pi*2, np.pi*2) )
#TRAINING1: random initial positions=0, velocities=0 #essentialltially arm is reset to contracted and dynamic
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING2: random initial positions=(-pi, pi), velocities=0
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#LAST LEFT OFF HERE
#TRAINING3: random initial positions=(-pi, pi), velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi/4, np.pi/4) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING4: random initial positions=0, velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING5: random initial positions=(-pi*c, pi*c), velocities=0
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/4, np.pi/4), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING6: random initial positions=(-pi*c, pi*c), velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/4, np.pi/4), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING7: all initial positions=0, velocities=(pi*c,pi*c) #essentially arm is is reset to stretched and dynamic
#TRAINING8: all initial positions=pi, velocities=(pi*c,pi*c) #initiall arm is reset to contracted and dynamic
self.time_stamp=0
#make first link angle face downward
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=0, targetValue=random.uniform(np.pi/2*2, np.pi/2*2), targetVelocity=random.uniform(-np.pi*0, np.pi*0) ) #reset base link
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=0, targetValue=random.uniform(-np.pi/2*1, np.pi/2*1), targetVelocity=random.uniform(-np.pi*0, np.pi*0) ) #reset base link
#randomize joint positions and velocities
#for i in range(self.number_of_joints_urdf):
# pass
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/2,np.pi/2), targetVelocity=0 ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#if self.scene is None:
# self.scene = self.create_single_player_scene(self._p)
#if not self.scene.multiplayer and self.ownsPhysicsClient:
# self.scene.episode_restart(self._p)
#self.robot.scene = self.scene
self.frame = 0
self.done = 0
self.reward = 0
self.states = None
self.step_observations = self.states
dump = 0
#s = self.robot.reset(self._p)
#self.potential = self.robot.calc_potential()
self.states = self.get_states()
self.step_observations = self.states
return self.step_observations
#### GET STATES
def get_states(self):
#### get tuple of link states
self.link_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list( range(self.number_of_links_urdf) ), computeLinkVelocity=True, computeForwardKinematics=True ) # [self.number_of_links_urdf-1] )#linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., self.number_of_links_urdf-1]
### indexing tuple: link_states[index of link, index of state_variable tuple, index of state variable sub-variable]
#linkWorldPosition = np.zeros(shape=(number_of_links,3))
# get end effector x,y,z coordinates
#( linkWorldPosition, linkWorldOrientation, localInertialFramePosition, localInertialFrameOrientation, worldLinkFramePosition, worldLinkFrameOrientation, worldLinkLinearVelocity, worldLinkAngularVelocity) = self.link_states[self.number_of_links-1]
#linkWorldPosition == self.link_states[link_index][0]
(self.end_effector_x, self.end_effector_y, self.end_effector_z) = self.link_states[-1][0] #xyz position of end effector
(self.end_effector_vx, self.end_effector_vy, self.end_effector_vz) = self.link_states[-1][6] #xyz velocity of end effector
#get end effector x,y,z distances to goal
[self.x_to_goal, self.y_to_goal, self.z_to_goal] = [self.target_x-self.end_effector_x, self.target_y-self.end_effector_y, self.target_z-self.end_effector_z]
#get end effector distance and angles to goal
(self.radius_to_goal, self.theta_to_goal, self.phi_to_goal) = einsteinpy.coordinates.utils.cartesian_to_spherical_novel(self.x_to_goal, self.y_to_goal, self.z_to_goal)
self.polar_vector_to_goal_states = np.array((self.radius_to_goal, self.theta_to_goal, self.phi_to_goal)) #self.polar_vector_to_goal_states.shape==(3,)
####TODO: append angle to goal and distance to goal to state vector
#### observe jointstates (add jointstates to state vector)
self.all_joint_states = self._p.getJointStates(bodyUniqueId=self.octopusBodyUniqueId, jointIndices = list(range(self.number_of_joints_urdf))) # [self.number_of_joints_urdf] )#linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., slef.number_of_links_urdf-1]
#for i in range(self.number_of_joints_urdf):
# (joint_pos, joint_vel, (joint_reaction_forces), applied_joint_motor_torque) = self.all_joint_states[i]
######## TODO: joint_pos, joint_vel (append these to joint state vector)
#update_joint_states #self.joint_states.shape==(number_of_links_urdf, )
#import pdb; pdb.set_trace();
for i in range(self.number_of_joints_urdf):
self.joint_states[i] = self.all_joint_states[i][0] #angular position of joint i
self.joint_states[i+self.number_of_joints_urdf] = self.all_joint_states[i][1] #angular velocity of joint i
#concatenate states
states_as_list = list(self.joint_states) + list((self.radius_to_goal, self.theta_to_goal, self.phi_to_goal)) + list((self.end_effector_vx, self.end_effector_vy, self.end_effector_vz))
self.states = np.array(states_as_list)
self.step_observations = self.states
#get speed of end effector (used to reward low end effector speeds when goal is near)
self.ee_speed = np.sqrt( sum( np.square([self.end_effector_vx, self.end_effector_vy, self.end_effector_vz]) ) ) # speed = 2-norm of the xyz velocity vector
return self.step_observations
#### STEP
def step(self, actions):
#self.link_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., slef.number_of_links_urdf-1]
#self.joint_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list(range(self.number_of_links_urdf)))
#set torques
self.torques = 100*actions #1000*actions
#self.torques[7] = 240 #set last link's torque to zero
self.torques[7] = self.torques[7]/10 #self.torques[7] = 0
#self.torques = np.clip(a=self.torques, a_min=np.array([-3000, -450, -400, -400, -400, -300, -300, -241]), a_max=np.array([3000, 450, 400, 400, 400, 300, 300, 241])) #min and max were determined with eye test
#note #clips for lower minimun torque to move joint a_min=np.array([240, 242, 242, 242, 242, 242, 240, 240])
#self.torques[7] = 240.2
#
self._p.setJointMotorControlArray(physicsClientId=self.physicsClientId, bodyUniqueId=self.octopusBodyUniqueId, jointIndices= list(range(self.number_of_torques_urdf)) , controlMode=self._p.TORQUE_CONTROL, forces=list( self.torques ) )
self._p.stepSimulation(physicsClientId=self.physicsClientId)
self.time_stamp += self.time_step
self.step_observations = self.get_states()
self.ee_link_index = 7
self.reward_for_being_close_to_goal = 0 # 1/(abs(0.05*self.radius_to_goal)**2) #+ 1/(abs(np.clip(a=self.joint_states[self.ee_link_index+self.number_of_joints_urdf], a_min=1e-1, a_max=None) )) # + 1/abs(actions[self.ee_link_index]) # 1/abs(self.joint_states[self.ee_link_index+self.number_of_joints_urdf])) #reward low ee angular velocity #- (1/500)*sum(abs(self.torques)) # - (self.time_stamp)**2 #-electricity_cost #+1/(fractal_dimensionality_number)
#self.reward += self.step_reward
#print("radius to goal : ", self.radius_to_goal) #debugging
#rewards
self.reward_for_reaching_goal = 1 if self.radius_to_goal <= self.radius_to_goal_epsilon else 0 # 1/abs(self.radius_to_goal**4) if self.radius_to_goal <= 2*self.radius_to_goal_epsilon else 0 #reward for reaching goal
self.reward_for_being_close_to_goal = 0# 1/(abs(0.05*self.radius_to_goal)**2) #+ 1/(abs(np.clip(a=self.joint_states[self.ee_link_index+self.number_of_joints_urdf], a_min=1e-1, a_max=None) )) # + 1/abs(actions[self.ee_link_index]) # 1/abs(self.joint_states[self.ee_link_index+self.number_of_joints_urdf])) #reward low ee angular velocity #- (1/500)*sum(abs(self.torques)) # - (self.time_stamp)**2 #-electricity_cost #+1/(fractal_dimensionality_number)
#costs
self.num_joints_at_limit = 0
#self.joints_at_limit_array = np.logical_or(self.joints_and_links.joints_above_upper_limit_array, self.joints_and_links.joints_below_lower_limit_array) #MAKE THIS OBJECT IN JOINTS AND LINKS CLASS
#self.num_joints_at_limit = np.count_nonzero(self.joints_at_limit_array)
#self.joints_at_limit_cost = self.num_joints_at_limit * self.num_joints_at_limit
#add reward that slows down the end effector near goal
#self.reward_for_low_ee_speed = 1000*1/(abs(self.ee_speed))
#self.step_reward += self.reward_for_low_ee_speed
#self.reward += self.reward_for_low_ee_speed
#else:
#self.step_reward += self.reward_for_reaching_goal
#self.reward += self.reward_for_reaching_goal
self.step_reward = self.reward_for_being_close_to_goal + self.reward_for_reaching_goal #+ self.joints_at_limit_cost
self.reward += self.step_reward
#stopping criteria
self.done = True if self.radius_to_goal <= self.radius_to_goal_epsilon else self.done # update done criteria if ee is in epsilon ball
if self.time_stamp >= 8: #originally >=20
self.done=True
if self.radius_to_goal <= self.radius_to_goal_epsilon: #within epsilon ball
self.done=True
return self.step_observations, self.step_reward, self.done, {}
#### RENDER
def render(self, mode='human', close=False):
if mode == "human":
self.isRender = True
if mode != "rgb_array":
return np.array([])
base_pos = [0, 0, 0]
if (hasattr(self, 'robot')):
if (hasattr(self.robot, 'body_xyz')):
base_pos = self.robot.body_xyz
if (self.physicsClientId>=0):
view_matrix = self._p.computeViewMatrixFromYawPitchRoll(cameraTargetPosition=base_pos,
distance=self._cam_dist,
yaw=self._cam_yaw,
pitch=self._cam_pitch,
roll=0,
upAxisIndex=2)
proj_matrix = self._p.computeProjectionMatrixFOV(fov=60,
aspect=float(self._render_width) /
self._render_height,
nearVal=0.1,
farVal=100.0)
(_, _, px, _, _) = self._p.getCameraImage(width=self._render_width,
height=self._render_height,
viewMatrix=view_matrix,
projectionMatrix=proj_matrix,
renderer=pybullet.ER_BULLET_HARDWARE_OPENGL)
try:
# Keep the previous orientation of the camera set by the user.
con_mode = self._p.getConnectionInfo()['connectionMethod']
if con_mode==self._p.SHARED_MEMORY or con_mode == self._p.GUI:
[yaw, pitch, dist] = self._p.getDebugVisualizerCamera()[8:11]
self._p.resetDebugVisualizerCamera(dist, yaw, pitch, base_pos)
except:
pass
else:
px = np.array([[[255,255,255,255]]*self._render_width]*self._render_height, dtype=np.uint8)
rgb_array = np.array(px, dtype=np.uint8)
rgb_array = np.reshape(np.array(px), (self._render_height, self._render_width, -1))
rgb_array = rgb_array[:, :, :3]
return rgb_array
def close(self):
if (self.ownsPhysicsClient):
if (self.physicsClientId >= 0):
self._p.disconnect()
self.physicsClientId = -1
def HUD(self, state, a, done):
pass
# def step(self, *args, **kwargs):
# if self.isRender:
# base_pos=[0,0,0]
# if (hasattr(self,'robot')):
# if (hasattr(self.robot,'body_xyz')):
# base_pos = self.robot.body_xyz
# # Keep the previous orientation of the camera set by the user.
# #[yaw, pitch, dist] = self._p.getDebugVisualizerCamera()[8:11]
# self._p.resetDebugVisualizerCamera(3,0,0, base_pos)
#
#
# return self.step(*args, **kwargs)
if parse_version(gym.__version__) < parse_version('0.9.6'):
_render = render
_reset = reset
_seed = seed
class Camera:
def __init__(self):
pass
def move_and_look_at(self, i, j, k, x, y, z):
lookat = [x, y, z]
distance = 10
yaw = 10
self._p.resetDebugVisualizerCamera(distance, yaw, -20, lookat)
class robotJointsandLinks:
def __init__(self, number_of_joints=None, number_of_links=None, bodyUniqueId=None, physicsClientId=None):
self.joint_dictionary = dict() #create empty dictionary
self.link_dictionary = dict()
for index in range(number_of_joints):
self.joint_dictionary["joint_" + str(index)] = Joint( bodyUniqueId=bodyUniqueId, physicsClientId=physicsClientId, joint_index=index ) # add joint to a dictionary
for index in range(number_of_links):
self.link_dictionary["link_" + str(index)] = Link( bodyUniqueId=bodyUniqueId , link_index=index ) #add link to a dictionary
#np.logical_or(self.joints_and_links.joints_above_upper_limit_array, self.joints_and_links.joints_below_lower_limit_array) #MAKE THIS OBJECT IN JOINTS AND LINKS CLASS
class Joint:
def __init__(self, bodyUniqueId=None, physicsClientId=None, joint_index=None, jointLowerLimit=-np.pi/2, jointUpperLimit=+np.pi/2 ):
self.bodyUniqueId = bodyUniqueId
self.jointIndex = joint_index
self.JointLimitLow = jointLowerLimit
self.JointLimitUpper = jointUpperLimit
def check_if_at_limit(self):
pass #self._p.get
def joint_limit_reached(self):
pass
def update_upper_joint_limit(self, new_joint_lower_limit):
pass
def update_lower_joint_limit(self, new_joint_upper_limit):
pass
def get_joint_info(self):
pass
def get_maximal_joint_state(self, index):
pass
class Link:
def __init__(self, bodyUniqueId=None, physicsCLientId=None, link_index=None ):
self.bodyUniqueId = bodyUniqueId
self.linkIndex = link_index
def get_link_length(self):
#return selflink_mass
pass
def get_link_mass(self):
pass
def getLinkPosition(self):
pass
def getLinkAngularVelocity(self):
pass
#TODO: line 238 cost comment, add joints_at_limit_reward, mess with urdf joint parameters in order to change torque needed to move arm link
<file_sep>/octopus_lockedjoints_1stUnlockedJoint_env.py
####DEBUGGING CODE (START)
#call this envrionment from the python interpreter by using these commands
#import gym; import pybullet_envs;
#env_instance = gym.make("OctopusArmLockedJoints2DBulletEnv-v0", render=True, number_of_free_joints=3)
#env_instance.reset();
#optional #env_instance.env._p.setRealTimeSimulation(1) #optional
#joint_test=7; action_sample_test=env_instance.env.action_space.sample()*1; action_sample_test[0:joint_test]=0; action_sample_test[joint_test]=10; action_sample_test[joint_test+1:8]=0; env_instance.step(action_sample_test); #input torque at single joint for one timestep
#### DEBUGGING CODE (END)
###TODO: so far i have the last 3 joints unlocked, and they implement the torques
'''
###TESTER
import gym; import pybullet_envs; env_instance = gym.make('OctopusArmLockedJoints1stUnlockedJoints2DBulletEnv-v0', render=True, number_of_links_urdf=8, number_of_joints_urdf=8, number_of_free_joints=3);env_instance.reset();env_instance.env._p.setRealTimeSimulation(1);
import gym; import pybullet_envs; env_instance = gym.make('OctopusArmLockedJoints1stUnlockedJoints2DBulletEnv-v0', render=True, number_of_links_urdf=8, number_of_joints_urdf=8, number_of_free_joints=3);env_instance.reset(); env_instance.step(env_instance.action_space.sample()); env_instance.env._p.setRealTimeSimulation(1);
'''
import gym, gym.spaces, gym.utils, gym.utils.seeding
import numpy as np
import pybullet
import os
from pybullet_utils import bullet_client #for physics client (lets you run multiple clients in parallel)
from pkg_resources import parse_version
import einsteinpy.coordinates #used to convert between cartesian to spherical coordinates
import random #used for resetting goal target
import pybullet_data
try:
if os.environ["PYBULLET_EGL"]:
import pkgutil
except:
pass
#import gym; import pybullet_envs;
#env_instance = gym.make('OctopusArmLockedJointsNUnlockedJoints2DBulletEnv-v0', renders=True, number_of_links_urdf=8, number_of_joints_urdf=8, number_of_free_joints=3)
#env_instance.reset(); #optional #env_instance.env._p.setRealTimeSimulation(1)
#joint_test=7; action_sample_test=env_instance.env.action_space.sample()*1; action_sample_test[0:joint_test]=0; action_sample_test[joint_test]=10; action_sample_test[joint_test+1:8]=0; env_instance.step(action_sample_test);
class OctopusEnv(gym.Env):
"""
Base class for Bullet physics simulation loading MJCF (MuJoCo .xml) environments in a Scene.
These environments create single-player scenes and behave like normal Gym environments, if
you don't use multiplayer.
"""
metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 60}
def __init__(self, render=True, number_of_links_urdf=8, number_of_joints_urdf=8, number_of_free_joints=3): #def __init__(self, render=False):
self.scene = None
self.physicsClientId = -1 #indicates that we have not started a pybullet simulation, this number is changed when we do start a simulation
self.ownsPhysicsClient = 0 #indicates that we have not started a pybullet simulation, this is changed to True when we do start a simulation (in the reset function)
self.camera = Camera()
#self.joints = Joint()
#self.joints_and_links = robotJointsandLinks(number_of_joints=None, number_of_links=None, bodyUniqueId=self.o)
self.isRender = render
#self.robot = robot
self.seed()
self._cam_dist = 3
self._cam_yaw = 0
self._cam_pitch = -30
self._render_width = 320
self._render_height = 240
self.number_of_links_urdf = number_of_links_urdf
self.number_of_joints_urdf = number_of_joints_urdf
self.number_of_torques_urdf = number_of_links_urdf
self.number_of_free_joints = number_of_free_joints
#### LOCK/UNLOCK MEACHANISM (begin)
#creates a list of constraints to use and update (needed to lock and unlock joints)
print("creating joint lock/unlock mechanism... ")
self.constraintUniqueIdsList = [None]*self.number_of_joints_urdf
#creates list of masks for chossing which joints to unlock #modified from https://stackoverflow.com/a/1851138/14024439
import itertools
def kbits(n, k):
result = []
for bits in itertools.combinations(range(n), k):
s = ['0'] * n
for bit in bits:
s[bit] = '1'
result.append(''.join(s))
return result
#list of masks (locked vs unlocked) in string format
self.masks_unlock_as_list_of_strings=kbits(self.number_of_joints_urdf, self.number_of_free_joints) #each element is a binary string
#convert masks (locked vs unlocked) from string format to np array format
self.masks_unlock_as_list_of_nparrays=[None]*len(self.masks_unlock_as_list_of_strings) #empty list where size = (total number of permutations)
for i in range( len(self.masks_unlock_as_list_of_nparrays) ):
self.masks_unlock_as_list_of_nparrays[i] = np.array([int(x) for x in self.masks_unlock_as_list_of_strings[i]]) #now we have masks as a 2D nparray indexing=(masks_unlock_as_list_of_nparrays[mask_number][joint_number])
self.number_of_combinations_unlock=len(self.masks_unlock_as_list_of_nparrays)
#### LOCK/UNLOCK MEACHANISM (end)
#### ACTUATE/UNACTUATE MECHANISHM (begin)
print("creating joint actuate/unactuate mechnism...")
#creates list of masks for choosing whether unlocked joint is actuated or underactuated (torque 0)
#modified from https://code.activestate.com/recipes/425303-generating-all-strings-of-some-length-of-a-given-a/
def allstrings2(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
c = [ ]
for i in range(length):
c = [[x]+y for x in alphabet for y in c or [[]]]
return c
#list of masks (actuated vs unactuated) (0 = unactuate, 1 = actuate)
masks_unactuated_as_np_array = []
masks_unactuated_as_list_of_list_of_ints = []
for i in range(self.number_of_joints_urdf+1): #between 0 unlocked joints to all joints unlocked
masks_unactuated_as_list_of_list_of_ints.append(allstrings2([0,1], i) )
masks_unactuated_as_np_array = np.array(masks_unactuated_as_list_of_list_of_ints)
#for masks_unactuated_as_np_array: first index corresponds to number of unlockedjoints, second index corresponds to decision of unactuation for whole arm, third index corresponds to joint index
#masks_unactuated_as_list_of_np_array = np.array(allstrings2([0,1], self.number_of_unlocked_joints)) # first index corresponds to decision of unactuation for whole arm, second index corresponds to joint index
self.number_of_combinations_unactuate=len(masks_unactuated_as_np_array[self.number_of_free_joints]) #length of masks for (self.number_of_free_joints) number of uncatuated joints
#### ACTUATE/UNACTUATE MECHANISM (end)
self.target_x = 0 # this is 0 in 2D case
self.target_y = 5 # ee y coordinate limits for 8 link arm are
self.target_z = 5 # ee z coordniate limits for 8 link arm are
[self.x_lower_limit, self.x_upper_limit] = [0.0, 0.0] # reachable x coordinates (double check for each arm)
[self.y_lower_limit, self.y_upper_limit] = [-15,15] # reachable y coordinates
[self.z_lower_limit, self.z_upper_limit] = [0,15] # reachable z coordinates
self.radius_to_goal_epsilon = 5 #10 #1e0 #9e-1 #1e-1 #1e-3
self.joint_states=np.zeros(shape=(2*self.number_of_links_urdf,))
self.time_stamp = 0 #time elapsed since last reset
self.time_step = 1./240 #this is the default timestep in pybullet, to set other tipestep use the following code and place it in the reset() method: self._p.setTimeStep(timeStep = self.time_step, physicsclientId=self.physicsClientId)
##### CREATE ACTION AND OBSERVATION SPACES (begin)
#observation space (formats the types of inputs to NN)
obs_dim = 22 # num_links (8) *2 + extra_states (self.radius_to_goal, self.theta_to_goal, self.phi_to_goal) + extra states ((self.end_effector_vx, self.end_effector_vy, self.end_effector_vz))
high = np.inf * np.ones([obs_dim]);
self.observation_space = gym.spaces.Box(-high, high) #self.observation_space = robot.observation_space
#action space(formats the types of outputs of NN)
action_dim = self.number_of_torques_urdf
high = np.ones([action_dim]);
self.action_space = gym.spaces.Dict({
'torques' : gym.spaces.Box(-high, high) ,
'unlocked_joints_combination' : gym.spaces.Discrete(self.number_of_free_joints),
'unactuated_joints_combination' : gym.spaces.Discrete(self.number_of_combinations_unactuate) }) #self.number_of_free_joints??? insteaf
#self.action_space = robot.action_space
#self.reset()
#### CREATE ACTION AND OBSERVATION SPACES (end)
#def configure(self, args):
# self.robot.args = args
def seed(self, seed=None):
self.np_random, seed = gym.utils.seeding.np_random(seed)
# self.robot.np_random = self.np_random # use the same np_randomizer for robot as for env
return [seed]
#### RESET
def reset(self):
if (self.physicsClientId < 0): #if it is the first time we are loading the simulations
self.ownsPhysicsClient = True #this
if self.isRender:
self._p = bullet_client.BulletClient(connection_mode=pybullet.GUI) # connect to physics server, and render through Graphical User Interface (GUI)
else:
self._p = bullet_client.BulletClient() #connect to physics server, and DO NOT render through graphical user interface
self.physicsClientId = self._p._client # get the client ID from physics server, this makes self.physicsClientId become a value greater than 0 (this value indicates the server that this environement instance is connected to)
self._p.resetSimulation() # reset physics server and remove all objects (urdf files, or mjcf, or )
#self.number_of_links_urdf = number_of_links_urdf
self.model_urdf = "romans_urdf_files/octopus_files/python_scripts_edit_urdf/octopus_generated_"+str(self.number_of_links_urdf)+"_links.urdf"
#load URDF into pybullet physics simulator
self.octopusBodyUniqueId = self._p.loadURDF( fileName=os.path.join(pybullet_data.getDataPath(), self.model_urdf), flags=self._p.URDF_USE_SELF_COLLISION | self._p.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS)
#turn off all motors so that joints are not stiff for the rest of the simulation
self._p.setJointMotorControlArray(bodyUniqueId=self.octopusBodyUniqueId, jointIndices=list(range(8)), controlMode = self._p.POSITION_CONTROL, positionGains=[0.1]*self.number_of_links_urdf, velocityGains=[0.1]*self.number_of_links_urdf, forces=[0]*self.number_of_links_urdf)
#### CHOOSE COMBINATION OF JOINTS (RESET) (begin)
#this loop unlocks all of the arm's joints
for i in range(self.number_of_joints_urdf):
if self.constraintUniqueIdsList[i] is not None:
self._p.removeConstraint(self.constraintUniqueIdsList[i])
self.constraintUniqueIdsList[i]=None
#this loop locks all of the arm's joints
for i in range(self.number_of_joints_urdf):
#lock single joint
self.constraintUniqueIdsList[i] = self._p.createConstraint( parentBodyUniqueId=self.octopusBodyUniqueId, parentLinkIndex=i-1, childBodyUniqueId=self.octopusBodyUniqueId, childLinkIndex=i, jointType=self._p.JOINT_FIXED, jointAxis=[1,0,0], parentFramePosition= [0,0,1], childFramePosition=[0,0,-1], parentFrameOrientation=self._p.getJointInfo(bodyUniqueId=self.octopusBodyUniqueId, jointIndex=i, physicsClientId=self.physicsClientId)[15], childFrameOrientation=self._p.getQuaternionFromEuler(eulerAngles=[-self._p.getJointState(bodyUniqueId=self.octopusBodyUniqueId, jointIndex=i, physicsClientId=self.physicsClientId)[0],-0,-0]), physicsClientId=self.physicsClientId )
#unlock first joints
print("hello",self.masks_unlock_as_list_of_nparrays[3][-1])
for i in range(self.number_of_joints_urdf-1, self.number_of_joints_urdf):
if self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i] is not None:
self._p.removeConstraint( userConstraintUniqueId=self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i] , physicsClientId=self.physicsClientId )
self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i]=None
#### CHOOSE COMBINATION OF JOINTS (RESET) (end)
#indicate urdf file for visualizing goal point and load it
self.goal_point_urdf = "sphere8cube.urdf"
self.goalPointUniqueId = self._p.loadURDF( fileName=os.path.join(pybullet_data.getDataPath(),self.goal_point_urdf) , basePosition=[self.target_x, self.target_y, self.target_z], useFixedBase=1 ) #flags=self._p.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS)
#self.goalPointUniqueId = self._p.createVisualShape(physicsClientId=self.physicsClientId, shapeType=self._p.GEOM_SPHERE, radius=4, specularColor=[0.5,0.5,0.5]) #secularcolor = [r,g,b]
#self._p.resetBasePositionAndOrientation(bodyUniqueId=self.goalPointUniqueId, physicsClientId=self.physicsClientId, posObj=[self.target_x, self.target_y, self.target_z], ornObj=[0,0,0,1])
#function usage example: 'bodyUniqueId = pybullet.loadURDF(fileName="path/to/file.urdf", basePosition=[0.,0.,0.], baseOrientation=[0.,0.,0.,1.], useMaximalCoordinates=0, useFixedBase=0, flags=0, globalScaling=1.0, physicsClientId=0)\nCreate a multibody by loading a URDF file.'
#optionally enable EGL for faster headless rendering
try:
if os.environ["PYBULLET_EGL"]:
con_mode = self._p.getConnectionInfo()['connectionMethod']
if con_mode==self._p.DIRECT:
egl = pkgutil.get_loader('eglRenderer')
if (egl):
self._p.loadPlugin(egl.get_filename(), "_eglRendererPlugin")
else:
self._p.loadPlugin("eglRendererPlugin")
except:
pass
# get Physics Client Id
self.physicsClientId = self._p._client
# enable gravity
self._p.setGravity(gravX=0, gravY=0, gravZ=0, physicsClientId=self.physicsClientId)
self._p.configureDebugVisualizer(pybullet.COV_ENABLE_GUI, 0)
self.joints_and_links = robotJointsandLinks(number_of_joints=self.number_of_joints_urdf, number_of_links=self.number_of_links_urdf, bodyUniqueId=self.octopusBodyUniqueId, physicsClientId=self.physicsClientId) #make dictionaries of joints and links (refer to robotJointsandLinks() class)
#end of "if first loading pybullet client"
#reset goal target to random one
self.target_x = 0 # no x comoponent for 2D case
self.target_y = random.uniform(self.y_lower_limit, self.y_upper_limit) # choose y coordinates such that arm can reach
self.target_z = random.uniform(self.z_lower_limit, self.z_upper_limit) # choose z coordinates such that arm can reach
#correspondingly move visual representation of goal target
self._p.resetBasePositionAndOrientation( bodyUniqueId=self.goalPointUniqueId, posObj=[self.target_x, self.target_y, self.target_z], ornObj=[0,0,0,1], physicsClientId=self.physicsClientId )
#reset joint positions and velocities
for i in range(self.number_of_joints_urdf):
#ROLLOUT1: all positions=0, all velocities=0 #(initially stretched and static)
self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=0, targetVelocity=0 ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#ROLLOUT2: all positions=pi, all velocities=0 #(initially contracted and static)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=np.pi, targetVelocity=0 )
#ROLLOUT3: all positions=0, all velocities=(-pi*c, pi*c) # (initially stretched and dynamic)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=0, targetVelocity=random.uniform(-np.pi*0.5, np.pi*0.5) )
#ROLLOUT4: all positions = pi (IDEA: try uniform sampling around it?), all velocities=(-pi*c,*pi*c) (initially contracted and dynamic)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=np.pi, targetVelocity=random.uniform(-np.pi*2, np.pi*2) )
#TRAINING1: random initial positions=0, velocities=0 #essentialltially arm is reset to contracted and dynamic
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING2: random initial positions=(-pi, pi), velocities=0
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#LAST LEFT OFF HERE
#TRAINING3: random initial positions=(-pi, pi), velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi/4, np.pi/4) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING4: random initial positions=0, velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi, np.pi), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING5: random initial positions=(-pi*c, pi*c), velocities=0
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/4, np.pi/4), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING6: random initial positions=(-pi*c, pi*c), velocities=(-pi*c, pi*c)
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/4, np.pi/4), targetVelocity=random.uniform(-np.pi*0.5*0, np.pi*0.5*0) ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#TRAINING7: all initial positions=0, velocities=(pi*c,pi*c) #essentially arm is is reset to stretched and dynamic
#TRAINING8: all initial positions=pi, velocities=(pi*c,pi*c) #initiall arm is reset to contracted and dynamic
self.time_stamp=0
#make first link angle face downward
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=0, targetValue=random.uniform(np.pi/2*2, np.pi/2*2), targetVelocity=random.uniform(-np.pi*0, np.pi*0) ) #reset base link
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=0, targetValue=random.uniform(-np.pi/2*1, np.pi/2*1), targetVelocity=random.uniform(-np.pi*0, np.pi*0) ) #reset base link
#randomize joint positions and velocities
#for i in range(self.number_of_joints_urdf):
# pass
#self._p.resetJointState(bodyUniqueId = self.octopusBodyUniqueId, physicsClientId=self.physicsClientId , jointIndex=i, targetValue=random.uniform(-np.pi/2,np.pi/2), targetVelocity=0 ) #tagetValue is angular (or xyz) position #targetvelocity is angular (or xyz) veloity
#if self.scene is None:
# self.scene = self.create_single_player_scene(self._p)
#if not self.scene.multiplayer and self.ownsPhysicsClient:
# self.scene.episode_restart(self._p)
#self.robot.scene = self.scene
self.frame = 0
self.done = 0
self.reward = 0
self.states = None
self.step_observations = self.states
dump = 0
#s = self.robot.reset(self._p)
#self.potential = self.robot.calc_potential()
self.states = self.get_states()
self.step_observations = self.states
return self.step_observations
#### GET STATES
def get_states(self):
#### get tuple of link states
self.link_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list( range(self.number_of_links_urdf) ), computeLinkVelocity=True, computeForwardKinematics=True ) # [self.number_of_links_urdf-1] )#linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., self.number_of_links_urdf-1]
### indexing tuple: link_states[index of link, index of state_variable tuple, index of state variable sub-variable]
#linkWorldPosition = np.zeros(shape=(number_of_links,3))
# get end effector x,y,z coordinates
#( linkWorldPosition, linkWorldOrientation, localInertialFramePosition, localInertialFrameOrientation, worldLinkFramePosition, worldLinkFrameOrientation, worldLinkLinearVelocity, worldLinkAngularVelocity) = self.link_states[self.number_of_links-1]
#linkWorldPosition == self.link_states[link_index][0]
(self.end_effector_x, self.end_effector_y, self.end_effector_z) = self.link_states[-1][0] #xyz position of end effector
(self.end_effector_vx, self.end_effector_vy, self.end_effector_vz) = self.link_states[-1][6] #xyz velocity of end effector
#get end effector x,y,z distances to goal
[self.x_to_goal, self.y_to_goal, self.z_to_goal] = [self.target_x-self.end_effector_x, self.target_y-self.end_effector_y, self.target_z-self.end_effector_z]
#get end effector distance and angles to goal
(self.radius_to_goal, self.theta_to_goal, self.phi_to_goal) = einsteinpy.coordinates.utils.cartesian_to_spherical_novel(self.x_to_goal, self.y_to_goal, self.z_to_goal)
self.polar_vector_to_goal_states = np.array((self.radius_to_goal, self.theta_to_goal, self.phi_to_goal)) #self.polar_vector_to_goal_states.shape==(3,)
####TODO: append angle to goal and distance to goal to state vector
#### observe jointstates (add jointstates to state vector)
self.all_joint_states = self._p.getJointStates(bodyUniqueId=self.octopusBodyUniqueId, jointIndices = list(range(self.number_of_joints_urdf))) # [self.number_of_joints_urdf] )#linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., slef.number_of_links_urdf-1]
#for i in range(self.number_of_joints_urdf):
# (joint_pos, joint_vel, (joint_reaction_forces), applied_joint_motor_torque) = self.all_joint_states[i]
######## TODO: joint_pos, joint_vel (append these to joint state vector)
#update_joint_states #self.joint_states.shape==(number_of_links_urdf, )
#import pdb; pdb.set_trace();
for i in range(self.number_of_joints_urdf):
self.joint_states[i] = self.all_joint_states[i][0] #angular position of joint i
self.joint_states[i+self.number_of_joints_urdf] = self.all_joint_states[i][1] #angular velocity of joint i
#concatenate states
states_as_list = list(self.joint_states) + list((self.radius_to_goal, self.theta_to_goal, self.phi_to_goal)) + list((self.end_effector_vx, self.end_effector_vy, self.end_effector_vz))
self.states = np.array(states_as_list)
self.step_observations = self.states
#get speed of end effector (used to reward low end effector speeds when goal is near)
self.ee_speed = np.sqrt( sum( np.square([self.end_effector_vx, self.end_effector_vy, self.end_effector_vz]) ) ) # speed = 2-norm of the xyz velocity vector
return self.step_observations
#### STEP
def step(self, actions):
#self.link_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list(range(self.number_of_links_urdf))) #linkIndices=[0,..., slef.number_of_links_urdf-1]
#self.joint_states = self._p.getLinkStates(bodyUniqueId=self.octopusBodyUniqueId, linkIndices = list(range(self.number_of_links_urdf)))
#set torques
self.torques = actions['torques']*10 #100*actions #1000*actions
#self.torques[7] = 240 #set last link's torque to zero
#self.torques[7] = self.torques[7]/10 #self.torques[7] = 0
#self.torques = np.clip(a=self.torques, a_min=np.array([-3000, -450, -400, -400, -400, -300, -300, -241]), a_max=np.array([3000, 450, 400, 400, 400, 300, 300, 241])) #min and max were determined with eye test
#note #clips for lower minimun torque to move joint a_min=np.array([240, 242, 242, 242, 242, 242, 240, 240])
#self.torques[7] = 240.2
#TODO: lock joints
#for i in range(self.number_of_joints_urdf-1):
#this doesnt work #self._p.createConstraint(parentBodyUniqueId=self.octopusBodyUniqueId , parentLinkIndex=i childBodyUniqueId=self.octopusBodyUniqueId , childLinkIndex=i+1 , jointType=JOINT_FIXED , jointAxis=[0,0,1], parentFramePosition= [0,0,1], childFramePosition=[0,0,1], parentFrameOrientation=[0,0,1], childFrameOrientation=[0,0,1], physicsClientId=self.physicsClientId )
#TODO: unlock joints
#### CHOOSE COMBINATION OF UNLOCKED JOINTS (STEP) (begin)
#this loop unlocks all of the arm's joints
for i in range(self.number_of_joints_urdf):
if self.constraintUniqueIdsList[i] is not None:
self._p.removeConstraint(self.constraintUniqueIdsList[i])
self.constraintUniqueIdsList[i]=None
#this loop locks all of the arm's joints
for i in range(self.number_of_joints_urdf):
#lock single joint
self.constraintUniqueIdsList[i] = self._p.createConstraint( parentBodyUniqueId=self.octopusBodyUniqueId, parentLinkIndex=i-1, childBodyUniqueId=self.octopusBodyUniqueId, childLinkIndex=i, jointType=self._p.JOINT_FIXED, jointAxis=[1,0,0], parentFramePosition= [0,0,1], childFramePosition=[0,0,-1], parentFrameOrientation=self._p.getJointInfo(bodyUniqueId=self.octopusBodyUniqueId, jointIndex=i, physicsClientId=self.physicsClientId)[15], childFrameOrientation=self._p.getQuaternionFromEuler(eulerAngles=[-self._p.getJointState(bodyUniqueId=self.octopusBodyUniqueId, jointIndex=i, physicsClientId=self.physicsClientId)[0],-0,-0]), physicsClientId=self.physicsClientId )
#unlock desired joints
unlock_decision = actions['unlocked_joints_combination'] #is this an int
print(self.masks_unlock_as_list_of_nparrays[1][-1])
self.masks_unlock_as_list_of_nparrays[self.number_of_free_joints][-1] #three unlocked joints #last 3 unlocked
unlock_decision = actions['unlocked_joints_combination']
for i in range(self.number_of_joints_urdf-1, self.number_of_joints_urdf): #for i in range(3):
if self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i] is not None:
self._p.removeConstraint( userConstraintUniqueId=self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i] , physicsClientId=self.physicsClientId )
self.constraintUniqueIdsList[self.number_of_joints_urdf-1-i]=None
#### CHOOSE COMBINATION OF UNLOCKED JOINTS (STEP) (end)
unactuate_decision = actions['unactuated_joints_combination']
self.torques = actions['torques']
#set torques
self._p.setJointMotorControlArray(physicsClientId=self.physicsClientId, bodyUniqueId=self.octopusBodyUniqueId, jointIndices= list(range(self.number_of_torques_urdf)) , controlMode=self._p.TORQUE_CONTROL, forces=list( self.torques ) )
#step simulation TODO: step 3 times?
self._p.stepSimulation(physicsClientId=self.physicsClientId)
self.time_stamp += self.time_step
self.step_observations = self.get_states()
self.ee_link_index = 7
self.reward_for_being_close_to_goal = 0 # 1/(abs(0.05*self.radius_to_goal)**2) #+ 1/(abs(np.clip(a=self.joint_states[self.ee_link_index+self.number_of_joints_urdf], a_min=1e-1, a_max=None) )) # + 1/abs(actions[self.ee_link_index]) # 1/abs(self.joint_states[self.ee_link_index+self.number_of_joints_urdf])) #reward low ee angular velocity #- (1/500)*sum(abs(self.torques)) # - (self.time_stamp)**2 #-electricity_cost #+1/(fractal_dimensionality_number)
#self.reward += self.step_reward
#print("radius to goal : ", self.radius_to_goal) #debugging
#rewards
self.reward_for_reaching_goal = 1 if self.radius_to_goal <= self.radius_to_goal_epsilon else 0 # 1/abs(self.radius_to_goal**4) if self.radius_to_goal <= 2*self.radius_to_goal_epsilon else 0 #reward for reaching goal
self.reward_for_being_close_to_goal = 0# 1/(abs(0.05*self.radius_to_goal)**2) #+ 1/(abs(np.clip(a=self.joint_states[self.ee_link_index+self.number_of_joints_urdf], a_min=1e-1, a_max=None) )) # + 1/abs(actions[self.ee_link_index]) # 1/abs(self.joint_states[self.ee_link_index+self.number_of_joints_urdf])) #reward low ee angular velocity #- (1/500)*sum(abs(self.torques)) # - (self.time_stamp)**2 #-electricity_cost #+1/(fractal_dimensionality_number)
#costs
self.num_joints_at_limit = 0
#self.joints_at_limit_array = np.logical_or(self.joints_and_links.joints_above_upper_limit_array, self.joints_and_links.joints_below_lower_limit_array) #MAKE THIS OBJECT IN JOINTS AND LINKS CLASS
#self.num_joints_at_limit = np.count_nonzero(self.joints_at_limit_array)
#self.joints_at_limit_cost = self.num_joints_at_limit * self.num_joints_at_limit
#add reward that slows down the end effector near goal
#self.reward_for_low_ee_speed = 1000*1/(abs(self.ee_speed))
#self.step_reward += self.reward_for_low_ee_speed
#self.reward += self.reward_for_low_ee_speed
#else:
#self.step_reward += self.reward_for_reaching_goal
#self.reward += self.reward_for_reaching_goal
self.step_reward = self.reward_for_being_close_to_goal + self.reward_for_reaching_goal #+ self.joints_at_limit_cost
self.reward += self.step_reward
#stopping criteria
self.done = True if self.radius_to_goal <= self.radius_to_goal_epsilon else self.done # update done criteria if ee is in epsilon ball
if self.time_stamp >= 8: #originally >=20
self.done=True
if self.radius_to_goal <= self.radius_to_goal_epsilon: #within epsilon ball
self.done=True
return self.step_observations, self.step_reward, self.done, {}
#### RENDER
def render(self, mode='human', close=False):
if mode == "human":
self.isRender = True
if mode != "rgb_array":
return np.array([])
base_pos = [0, 0, 0]
if (hasattr(self, 'robot')):
if (hasattr(self.robot, 'body_xyz')):
base_pos = self.robot.body_xyz
if (self.physicsClientId>=0):
view_matrix = self._p.computeViewMatrixFromYawPitchRoll(cameraTargetPosition=base_pos,
distance=self._cam_dist,
yaw=self._cam_yaw,
pitch=self._cam_pitch,
roll=0,
upAxisIndex=2)
proj_matrix = self._p.computeProjectionMatrixFOV(fov=60,
aspect=float(self._render_width) /
self._render_height,
nearVal=0.1,
farVal=100.0)
(_, _, px, _, _) = self._p.getCameraImage(width=self._render_width,
height=self._render_height,
viewMatrix=view_matrix,
projectionMatrix=proj_matrix,
renderer=pybullet.ER_BULLET_HARDWARE_OPENGL)
try:
# Keep the previous orientation of the camera set by the user.
con_mode = self._p.getConnectionInfo()['connectionMethod']
if con_mode==self._p.SHARED_MEMORY or con_mode == self._p.GUI:
[yaw, pitch, dist] = self._p.getDebugVisualizerCamera()[8:11]
self._p.resetDebugVisualizerCamera(dist, yaw, pitch, base_pos)
except:
pass
else:
px = np.array([[[255,255,255,255]]*self._render_width]*self._render_height, dtype=np.uint8)
rgb_array = np.array(px, dtype=np.uint8)
rgb_array = np.reshape(np.array(px), (self._render_height, self._render_width, -1))
rgb_array = rgb_array[:, :, :3]
return rgb_array
def close(self):
if (self.ownsPhysicsClient):
if (self.physicsClientId >= 0):
self._p.disconnect()
self.physicsClientId = -1
def HUD(self, state, a, done):
pass
# def step(self, *args, **kwargs):
# if self.isRender:
# base_pos=[0,0,0]
# if (hasattr(self,'robot')):
# if (hasattr(self.robot,'body_xyz')):
# base_pos = self.robot.body_xyz
# # Keep the previous orientation of the camera set by the user.
# #[yaw, pitch, dist] = self._p.getDebugVisualizerCamera()[8:11]
# self._p.resetDebugVisualizerCamera(3,0,0, base_pos)
#
#
# return self.step(*args, **kwargs)
if parse_version(gym.__version__) < parse_version('0.9.6'):
_render = render
_reset = reset
_seed = seed
class Camera:
def __init__(self):
pass
def move_and_look_at(self, i, j, k, x, y, z):
lookat = [x, y, z]
distance = 10
yaw = 10
self._p.resetDebugVisualizerCamera(distance, yaw, -20, lookat)
class robotJointsandLinks:
def __init__(self, number_of_joints=None, number_of_links=None, bodyUniqueId=None, physicsClientId=None):
self.joint_dictionary = dict() #create empty dictionary
self.link_dictionary = dict()
for index in range(number_of_joints):
self.joint_dictionary["joint_" + str(index)] = Joint( bodyUniqueId=bodyUniqueId, physicsClientId=physicsClientId, joint_index=index ) # add joint to a dictionary
for index in range(number_of_links):
self.link_dictionary["link_" + str(index)] = Link( bodyUniqueId=bodyUniqueId , link_index=index ) #add link to a dictionary
#np.logical_or(self.joints_and_links.joints_above_upper_limit_array, self.joints_and_links.joints_below_lower_limit_array) #MAKE THIS OBJECT IN JOINTS AND LINKS CLASS
class Joint:
def __init__(self, bodyUniqueId=None, physicsClientId=None, joint_index=None, jointLowerLimit=-np.pi/2, jointUpperLimit=+np.pi/2 ):
self.bodyUniqueId = bodyUniqueId
self.jointIndex = joint_index
self.JointLimitLow = jointLowerLimit
self.JointLimitUpper = jointUpperLimit
def check_if_at_limit(self):
pass #self._p.get
def joint_limit_reached(self):
pass
def update_upper_joint_limit(self, new_joint_lower_limit):
pass
def update_lower_joint_limit(self, new_joint_upper_limit):
pass
def get_joint_info(self):
pass
def get_maximal_joint_state(self, index):
pass
class Link:
def __init__(self, bodyUniqueId=None, physicsCLientId=None, link_index=None ):
self.bodyUniqueId = bodyUniqueId
self.linkIndex = link_index
def get_link_length(self):
#return selflink_mass
pass
def get_link_mass(self):
pass
def getLinkPosition(self):
pass
def getLinkAngularVelocity(self):
pass
#TODO: line 238 cost comment, add joints_at_limit_reward, mess with urdf joint parameters in order to change torque needed to move arm link
<file_sep>/helper_scripts_for_gym_env_creation/least_common_denominator_for_links.py
#trying to figure out how many links to create so that we can evenly divide the links into subsets such that a N-link arm can be turned into a (n<N)-link arm
#idea: find optimal locking so that energy is minimized for a reaching task / walking task
from math import gcd # Python versions 3.5 and above
#from fractions import gcd # Python versions below 3.5
from functools import reduce # Python version 3.x
def lcm(denominators):
return reduce(lambda a,b: a*b // gcd(a,b), denominators)
'''
Example:
>>> lcm([100, 200, 300])
>>> lcm(list(range(1,9)))
'''
#find number of links necessary to have arm be able to be decomposed between 1-link to 7-links
lcm(list(range(1,7)))
<file_sep>/octopus_testing.py
#this python scrpt is inteded to help with streamlining the creation of the octopus gym environments development
#it (1) loads the octopus urdf and (2) allows for for testing of different pybullet APIs
#refer to the pybullet quickstart guide found in "Pybullet Quickstart Guide.pdf" withinin this repository or the online one found in https://pybullet.org/wordpress/ . The online doc is usually very slow due to heavy online traffic
import pybullet as p
physicsClientId = p.connect(p.GUI)# connect to a physics simulation server
p.setRealTimesimulation(1)
import os
import pybullet_data
number_of_joints_urdf=8
number_of_links_urdf=8
#load URDF
octopusBodyUniqueId = p.loadURDF( fileName=os.path.join(pybullet_data.getDataPath(), "romans_urdf_files/octopus_files/python_scripts_edit_urdf/octopus_generated_8_links.urdf") , flags=p.URDF_USE_SELF_COLLISION | p.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS)
#turn off all motorrs so that joints are not stiff for the rest of the simulation
p.setJointMotorControlArray(bodyUniqueId=octopusBodyUniqueId, jointIndices=list(range(8)), controlMode=p.POSITION_CONTROL, positionGains=[0.1]*number_of_links_urdf, velocityGains=[0.1]*number_of_links_urdf, forces=[0]*number_of_links_urdf)
#query the joint info
p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=0, physicsClientId=physicsClientId) #query all joint info
p.getJointInfo(bodyUniqueId=octopusBodyUniqueId,jointIndex=0)[12] # joint's child link name (helps with debugging)
#p.getJointInfos() doesnt exist !
#query the joint state(s)
p.getJointState(bodyUniqueId=octopusBodyUniqueId, jointIndex=0, physicsClientId=physicsClientId)
p.getJointStates(bodyUniqueId=octopusBodyUniqueId, jointIndices=list(range(number_of_links_urdf)), physicsClientId=physicsClientId)
#query the link info
#p.getLinkInfo() doesnt exist !
#p.getLinkInfos() doesnt exist !
#query the link state
(linkWorldPosition, linkWorldOrientation, localInertialFramePosition, localInertialFrameOrientation, worldLinkFramePosition, worldLinkFrameOrientation, worldLinkLinearVelocity, worldLinkAngularVelocity) = p.getLinkState(bodyUniqueId=octopusBodyUniqueId, linkIndex=0, computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=physicsClientId) #list items 0,1 are same as list items 4,5 for octopus 8-link case #CoM frame position = inertial Frame position and orientation # for 8-link octopusarms list items [2,3] are localInertialFramePosition=[0,0,0] and localInertialFrameOrientation=[0,0,0,1]
= p.getLinkStates( ) #list items 0,1 are same as list items 4,5 for octopus 8-link case #CoM frame position = inertial Frame position and orientation, localInertianFramePosition=[0,0,0], localInertialFrameOrientation=[0,0,0,0]
#LOCK A JOINT
#get joint's child link name (for sanity check to ensure that we are indexing correct values from the list)
jointChildLinkName=jointParentFramePosition=p.getJointInfo(self.octopusBodyUniqueId, jointIndex=0, physicsClientId=self.physicsClientId)[12]
#get joint frame position, relative to parent link frame
jointFramePosition_WRT_ParentLinkFrame=p.getJointInfo(octopusBodyUniqueId, jointIndex=0, physicsClientId=physicsClientId)[14]
#get joint frame orientation, relative to parent CoM link frame
jointFrameOrientation_WRT_ParentLinkFrame=p.getJointInfo(octopusBodyUniqueId, jointIndex=0, physicsClientId=physicsClientId)[15]
#get position of the joint frame, relative to a given child CoM Coordidinate Frame, (other posibility: get world origin (0,0,0) if no child specified for this joint)
jointsChildLinkFramePosition_WRT_WorldFramePosition = p.getJointState()
jointsFramePosition_WRT_WorldFramePosition =
jointsFramePosition_WRT_jointsChildLinkFramePosition =
#get position of the joint frame, relative to a given child center of mass coordinate frame, (or get the world origin if no child is specified for this joint)
jointsChildLinkFrameOrientation_WRT_WorldOrientation=p.getLinkState()
jointFrameOrientation_WRT_WorldFrameOrientation=
jointFrameOrientation_WRT_jointsChildFrameOrientation=
#add constraint (lockjoint)
constraintId = p.createConstraint(
parentBodyUniqueId=octopusBodyUniqueId ,
parentLinkIndex=6,
childBodyUniqueId=octopusBodyUniqueId ,
childLinkIndex=6+1 ,
jointType=p.JOINT_FIXED ,
jointAxis=[1,0,0],
parentFramePosition=[0,0,1],
childFramePosition=[0,0,-1],
parentFrameOrientation= [0,0,0,1] , #orientation of joint frame, relative to parent center of mass frame #parentFrameOrientation=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15]
childFrameOrientation=[0,0,0,1], #orientation of joint frame, relative to child center of mass frame # childFrameOrientation=
physicsClientId=physicsClientId )
constraintId = p.createConstraint(
parentBodyUniqueId=octopusBodyUniqueId,
parentLinkIndex=6,
childBodyUniqueId=octopusBodyUniqueId,
childLinkIndex=6+1,
jointType=p.JOINT_FIXED,
jointAxis=[1,0,0],
parentFramePosition=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[14], #jointFramePosition_WRT_ParentCoMFramePosition
childFramePosition=[0,0,-1], #jointFramePosition_WRT_ChildCoMFramePosition
parentFrameOrientation=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15], #jointFrameOrientation_WRT_ParentCoMOrientation
childFrameOrientation=p.getLinkState(bodyUniqueId=octopusBodyUniqueId, linkIndex=7, computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=physicsClientId)[4], physicsClientId=physicsClientId )
constraintId = p.createConstraint(
parentBodyUniqueId=octopusBodyUniqueId,
parentLinkIndex=6,
childBodyUniqueId=octopusBodyUniqueId,
childLinkIndex=6+1,
jointType=p.JOINT_FIXED,
jointAxis=[1,0,0],
parentFramePosition= [0,0,1], #THIS WORKS
childFramePosition=[0,0,-1], #THIS WORKS
parentFrameOrientation=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15], #jointFrameOrientation_WRT_ParentCoMOrientation #THIS WORKS
childFrameOrientation= p.getQuaternionFromEuler(eulerAngles=[np.pi,0,0]), #p.getLinkState(bodyUniqueId=octopusBodyUniqueId, linkIndex=7, computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=physicsClientId)[4], #
physicsClientId=physicsClientId )
# went from euler angles [angle,0,0] to quaternion [a,b,c,d] to set constraint
constraintId = p.createConstraint( parentBodyUniqueId=octopusBodyUniqueId, parentLinkIndex=6, childBodyUniqueId=octopusBodyUniqueId, childLinkIndex=6+1, jointType=p.JOINT_FIXED, jointAxis=[1,0,0], parentFramePosition= [0,0,1], childFramePosition=[0,0,-1], parentFrameOrientation=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15], childFrameOrientation= p.getQuaternionFromEuler(eulerAngles=[np.pi,0,0]), physicsClientId=physicsClientId )
constraintId = p.createConstraint( parentBodyUniqueId=octopusBodyUniqueId, parentLinkIndex=6, childBodyUniqueId=octopusBodyUniqueId, childLinkIndex=6+1, jointType=p.JOINT_FIXED, jointAxis=[1,0,0], parentFramePosition= [0,0,1], childFramePosition=[0,0,-1], parentFrameOrientation=p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15], childFrameOrientation= p.getQuaternionFromEuler(eulerAngles=-[p.getJointState(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[0],0,0]), physicsClientId=physicsClientId )
while(1):
print("running...")
#remove constraint
p.removeConstraint(constraintId)
#position of the joint frame relative to parent center of mass frame.
p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[14]
#position of the joint frame relative to a given child center of mass frame (or world origin if no child specified)
#joint position wrt to child = joint position wrt world - child position wrt to world = (joint position wrt to parent + parent position wrt world) - (child wrt world)
p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[14]) #joint position wrt to parent
p.getLinkState(bodyUniqueId=octopusBodyUniqueId, linkIndex=7, computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=physicsClientId)[0?][?] #parent position wrt to world
p.getLinkInfo() #child position wrt world
# joint wrt child =
#joint frame orientation wrt world frame
p.getJointInfo(bodyUniqueId=octopusBodyUniqueId, jointIndex=7, physicsClientId=physicsClientId)[15])
#orientation
p.getLinkState(bodyUniqueId=octopusBodyUniqueId, linkIndex=7, computeLinkVelocity=1, computeForwardKinematics=1, physicsClientId=physicsClientId)[4] #link frame orientation, offset to local inertial frame
<file_sep>/helper_scripts_for_gym_env_creation/combination.py
def kbits(n, k):
result = []
for bits in itertools.combinations(range(n), k):
s = ['0'] * n
for bit in bits:
s[bit] = '1'
result.append(''.join(s))
return result
def kbits2(n, k):
result = []
for bits in itertools.combinations(range(n), k):
s = [0] * n
for bit in bits:
s[bit] = 1
result.append([].join(s))
return result
#https://code.activestate.com/recipes/425303-generating-all-strings-of-some-length-of-a-given-a/
def allstrings(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
if length == 0: return []
c = [[a] for a in alphabet[:]]
if length == 1: return c
c = [[x,y] for x in alphabet for y in alphabet]
if length == 2: return c
for l in range(2, length):
c = [[x]+y for x in alphabet for y in c]
return c
def allstrings2(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
c = []
for i in range(length):
c = [[x]+y for x in alphabet for y in c or [[]]]
return c
if __name__ == "__main__":
for p in allstrings([0,1,2],4):
print p
number_of_joints_urdf=8
number_of_free_joints=3
masks=kbits(number_of_joints_urdf, number_of_free_joints) #list of masks
print(masks)
<file_sep>/README.md
# Roman's Pybullet Gym Environments
This is where I keep my custom OpenAI Gym environments. To use them, enter the following commands from the terminal:
```
cd <path/to/where/you/want/to/store/these/files>
git clone https://github.com/roman-aguilera/romans_pybullet_gym_envs.git
cd romans_pybullet_gym_envs
pip install -e .
```
##URDF Files
* URDF Files can be found here (make sure to add them to your pybullet datapath):
https://github.com/roman-aguilera/romans_urdf_files/tree/master/octopus_files/python_scripts_edit_urdf
## Environments
The exact environments that I created myself are:
* The 8-link octopus environment:
https://github.com/roman-aguilera/romans_pybullet_envs/blob/master/octopus_env.py
* The 8-link octopus environment, with joint locking (work in rogress):
https://github.com/roman-aguilera/romans_pybullet_envs/blob/master/octopus_lockedjoints_env.py
## Requirements
PyKDL (used for locked env). Docs and references included here:
https://anaconda.org/conda-forge/python-orocos-kdl
https://answers.ros.org/question/10124/relative-rotation-between-two-quaternions/
http://docs.ros.org/diamondback/api/kdl/html/python/index.html
http://wiki.ros.org/python_orocos_kdl
http://docs.ros.org/indigo/api/orocos_kdl/html/classKDL_1_1Rotation.html
https://github.com/orocos/orocos_kinematics_dynamics
ArgParse
https://docs.python.org/3.3/library/argparse.html
## Links for cleaning up later:
adding a gitignore file for swp files
* https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
* https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
## Credits:
This repository is a modified version of pybullet_envs: https://github.com/bulletphysics/bullet3/tree/master/examples/pybullet/gym/pybullet_envs
The Pybullet Gymperium code was a helpful reference when designing these environments: https://github.com/benelot/pybullet-gym
| 605d0d8d6f4afd4b611c9f62b076669ea0e829a7 | [
"Markdown",
"Python"
] | 6 | Python | roman-aguilera/romans_pybullet_gym_envs | 8856a5853098d676dadb5bdae256a825ff501dea | 697d89933fdbdc456177eece87010f263c5f8540 |
refs/heads/master | <repo_name>saidaml/scikit-learn<file_sep>/sklearn/_build_utils/__init__.py
"""
Utilities useful during the build.
"""
# author: <NAME>, <NAME>
# license: BSD
import os
from distutils.version import LooseVersion
import contextlib
from .openmp_helpers import check_openmp_support
DEFAULT_ROOT = 'sklearn'
# The following places need to be in sync with regard to Cython version:
# - .circleci config file
# - sklearn/_build_utils/__init__.py
# - advanced installation guide
CYTHON_MIN_VERSION = '0.28.5'
def _check_cython_version():
message = ('Please install Cython with a version >= {0} in order '
'to build a scikit-learn from source.').format(
CYTHON_MIN_VERSION)
try:
import Cython
except ModuleNotFoundError:
# Re-raise with more informative error message instead:
raise ModuleNotFoundError(message)
if LooseVersion(Cython.__version__) < CYTHON_MIN_VERSION:
message += (' The current version of Cython is {} installed in {}.'
.format(Cython.__version__, Cython.__path__))
raise ValueError(message)
def cythonize_extensions(top_path, config):
"""Check that a recent Cython is available and cythonize extensions"""
_check_cython_version()
from Cython.Build import cythonize
with_openmp = check_openmp_support()
n_jobs = 1
with contextlib.suppress(ImportError):
import joblib
if LooseVersion(joblib.__version__) > LooseVersion("0.13.0"):
# earlier joblib versions don't account for CPU affinity
# constraints, and may over-estimate the number of available
# CPU particularly in CI (cf loky#114)
n_jobs = joblib.cpu_count()
config.ext_modules = cythonize(
config.ext_modules,
nthreads=n_jobs,
compile_time_env={'SKLEARN_OPENMP_SUPPORTED': with_openmp},
compiler_directives={'language_level': 3})
def gen_from_templates(templates, top_path):
"""Generate cython files from a list of templates"""
# Lazy import because cython is not a runtime dependency.
from Cython import Tempita
for template in templates:
outfile = template.replace('.tp', '')
# if the template is not updated, no need to output the cython file
if not (os.path.exists(outfile) and
os.stat(template).st_mtime < os.stat(outfile).st_mtime):
with open(template, "r") as f:
tmpl = f.read()
tmpl_ = Tempita.sub(tmpl)
with open(outfile, "w") as f:
f.write(tmpl_)
| 508fc0f918d50988a01dec7c644ced6b92dfef3b | [
"Python"
] | 1 | Python | saidaml/scikit-learn | ac7081c510fc2c27b1bef002dfefc9f3854e2c9a | 63fc7134eaf3ef2c28ce882bd329aca75eb47e47 |
refs/heads/main | <repo_name>mjohnson518/ECDSA-Exchange<file_sep>/server/index.js
const express = require('express');
const app = express();
const cors = require('cors');
const port = 3042;
const SHA256 = require('crypto-js/sha256');
// localhost can have cross origin errors
// depending on the browser you use!
app.use(cors());
app.use(express.json());
/* replaced #1
const balances = {
"1": 100,
"2": 50,
"3": 75,
}*/
const START_ACCOUNTS = 3;
const balances = {}; //replaces #1
const Ledger = require('./ledger');
const ledger = new Ledger();
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
console.log('==================');
console.log('AVAILABLE ACCOUNTS');
for (let i = 0; i < START_ACCOUNTS; i++) {
const key = ec.genKeyPair();
const privateKey = key.getPrivate().toString(16);
const publicKey = key.getPublic().encode('hex');
const address = '0x'+publicKey.slice(-40);
console.log(`(${i})`);
console.log(`Address : ${address}`);
console.log(`Private Key : ${privateKey}`);
// sets a random balance between 50 & 100
const balance = Math.floor((Math.random() * 50) + 50);
balances[address] = balance;
console.log(`Balance : ${balance}`);
//// Ledger class not needed for my challenge 1 solution
//const newAccount = ledger.addAccount(publicKey, balance);
}
console.log('==================');
console.log('');
app.get('/balance/:address', (req, res) => {
const {address} = req.params;
const balance = balances[address] || 0;
res.send({ balance });
});
app.post('/send', (req, res) => {
const {sender, signature, recipient, amount, recid} = req.body
const message = {amount: amount}
const msgHash = SHA256(message).words;
const publicKey = ec.recoverPubKey(msgHash, signature, recid);
const key1 = ec.keyFromPublic(publicKey);
if (('0x' + publicKey.encode("hex").slice(-40)) === sender) {
balances[sender] -= amount;
balances[recipient] = (balances[recipient] || 0) + +amount;
}
res.send({ balance: balances[sender] });
});
app.listen(port, () => {
console.log(`Listening on port ${port}!`);
});
<file_sep>/README.md
# ECDSA-Exchange
| 8976dadb527fe434213a1d49e0a7808b6b7df278 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mjohnson518/ECDSA-Exchange | c985007f8574faa62a09eeb353d646ecc3404b70 | bf89beb59a8e8cb82856cece58a816af3feaee37 |
refs/heads/master | <repo_name>liartes/ng2MavenWar<file_sep>/angular/src/app/authors.service.ts
export class AuthorsService {
findAuthors() : string[] {
return ['Lovecraft', 'Orwell', 'Hobbs'];
}
}
<file_sep>/README.md
# ng2MavenWar
Maven configuration building ng2 app, serving it within the producted war
| 545889a3cd6f883b839999895e6453afb18e6966 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | liartes/ng2MavenWar | d922486733e494267574bd87192c527e6a69b364 | d7cd192858e366a9f3f34e90dec2bd41ee4b3844 |
refs/heads/master | <file_sep>import config as cfg
import sqlite3
from jinja2 import Environment, FileSystemLoader
from itertools import zip_longest
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
def format_date(st):
if not st:
return ''
return '/'.join([st[8:10], st[5:7], st[:4]])
# load template
env = Environment(loader=FileSystemLoader(cfg.template_root))
temp = env.get_template("template.html")
# connect db
con = sqlite3.connect('movies.db')
cur = con.cursor()
# custom query
cur.execute(
"""
select
id, release_date, title, original_title, genres, vote_average, my_rating, poster_path, overview
from movies
where
--genres like '%Thriller%'
--and
my_rating is null
order by vote_average desc
"""
)
res = cur.fetchall()
data_b = list()
for id, release_date, title, original_title, genres, vote_average, my_rating, poster_path, overview in res:
data_b.append(
dict(
id=id,
release_date=format_date(release_date),
title=title,
original_title=original_title,
genres=genres.split(';'),
vote_average=vote_average,
my_rating=my_rating ,
poster_path=poster_path,
overview=overview
)
)
data = grouper(6, data_b)
html_content = temp.render(movies=data)
with open('results.html', 'w', encoding='utf8') as f:
f.write(html_content)
<file_sep>import requests
import sqlite3
import config as cfg
root = "https://api.themoviedb.org/3"
root2 = "https://api.themoviedb.org/4"
genres = "/genre/movie/list"
mylist = f"/list/{cfg.mylist}"
rated_movie = f"/account/{cfg.account_id}/movie/rated"
# connect db
con = sqlite3.connect('movies.db')
cur = con.cursor()
# reset table
cur.execute("DROP TABLE IF EXISTS movies")
cur.execute(
"""
CREATE TABLE movies (
id, release_date, title, original_title, genres, vote_average, my_rating, poster_path, overview
)
"""
)
# create session
s = requests.Session()
# get genres
r = s.get(root+genres, params=dict(
api_key=cfg.api_key,
language=cfg.locale
))
gen = r.json()
gen_dict = dict()
for g in gen.get("genres"):
gen_dict[g['id']] = g['name']
# get rated movies
ratings = dict()
page = 1
while True:
r = s.get(
root2+rated_movie,
headers={
"Content-Type": "application/json;charset=utf-8",
"Authorization": f"Bearer {cfg.read_access_token}"
},
params={
'page': page
}
)
data = r.json()
for res in data.get('results'):
ratings[res['id']] = res['account_rating']['value']
page += 1
if page > data.get('total_pages', 0):
break
# get movie list
page = 1
while True:
r = s.get(
root2+mylist,
params=dict(
api_key=cfg.api_key,
sort_by="primary_release_date.desc",
language=cfg.locale,
page=page
),
headers={
"Content-Type": "application/json;charset=utf-8",
"Authorization": f"Bearer {cfg.read_access_token}"
},
)
data = r.json()
for x in data.get('results'):
id = x.get('id')
media_type = x.get('media_type')
if media_type != 'movie':
continue
release_date = x.get('release_date')
title = x.get('title')
original_title = x.get('original_title')
genre_ids = x.get('genre_ids')
genres = ";".join([gen_dict.get(y) for y in genre_ids])
vote_average = x.get('vote_average')
poster_path = x.get('poster_path')
overview = x.get('overview')
my_rating = ratings.get(id)
cur.execute("insert into movies values (?,?,?,?,?,?,?,?,?)", (id, release_date, title, original_title, genres, vote_average, my_rating, poster_path, overview))
page += 1
if page > data.get('total_pages', 0):
break
con.commit()
con.close()<file_sep># test_tmdb
Run main to fetch movie infos for all the movies in the list, saves it to a sqlite db
Edit the sql query and run fill_template to query the db and generate html page with the results
## install
Create a config.py file with:
api_key, read_access_token -> https://www.themoviedb.org/settings/api
account_id -> your account id
mylist -> id of the list to fetch
locale -> fr-FR, en-GB ...
template_root -> path to template folder
| 17fbad434f3e653e2d9c534a7a289abb2103c4b6 | [
"Markdown",
"Python"
] | 3 | Python | romainvigneres/test_tmdb | a4b78315eb281ee42e552da05f55e2ee53308da5 | d40566018ff9bf24385875fa509d6ed4009f3379 |
refs/heads/master | <file_sep>
var a =0;
var text = " ";
var puppies = ["https://thehappypuppysite.com/wp-content/uploads/2015/09/The-Siberian-Husky-HP-long.jpg", "https://i.pinimg.com/originals/cd/a5/1b/cda51b70758b5302de57225b7c52a202.jpg", "https://www.insidedogsworld.com/wp-content/uploads/2016/12/husky10.jpg", "https://emborapets.com/wp-content/uploads/2019/02/71379863_m-1024x683.jpg"];
console.log(a);
var toAdd = document.createDocumentFragment();
function upDogs() {
a++;
console.log(a);
if(a == puppies.length){
a = 0;
}
document.getElementById("myImg").src = puppies[a];
}
function downDogs() {
if(a == 0){
a = puppies.length -1;
}else{
a--;
}
console.log(a);
document.getElementById("myImg").src = puppies[a];
}
function randomDog() {
a = Math.floor(Math.random() * puppies.length);
document.getElementById("myImg").src = puppies[a];
console.log(a);
}
<file_sep>window.onload = function() {
var video = document.querySelector(".video");
var juice = document.querySelector(".blue-juice");
var btn = document.getElementById("play-pause");
var fullScreenButton = document.getElementById("full-screen");
var volumeBar = document.getElementById("volume-bar");
function togglePlayPause() {
if(video.paused) {
btn.className = "pause";
video.play();
} else {
btn.className = "play";
video.pause();
}
}
btn.onclick = function() {
togglePlayPause();
};
video.addEventListener('timeupdate', function(){
var juicePos = video.currentTime / video.duration;
juice.style.width = juicePos * 100 + "%";
if (video.ended){
btn.className = "play";
}
});
//Event listener for volume bar
volumeBar.addEventListener("change", function(){
//Update the video volume
video.volume=volumeBar.value;
});
//Event listener for fullscreen button
fullScreenButton.addEventListener("click", function() {
if(video.requestFullscreen){
video.requestFullscreen();
}else if(video.mozRequestFullScreen){
video.mozRequestFullScreen();// Firefox
}else if(video.webkitRequestFullscreen){
video.webkitRequestFullscreen();//Chrome & Safari
}
});
}
<file_sep>//Choose a random color
const button = document.querySelector('button')
const body = document.querySelector('body')
const colors = ['rgb(255, 77, 77)', 'rgb(230, 255, 255)', 'rgb(26, 136, 255)', 'rgb(255, 255, 204)', 'rgb(255, 230, 255)', 'rgb(204, 204, 255)']
body.style.backgroundColor = 'rgb(204, 229, 255)'
button.addEventListener('click', changeBackground)
function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length)
body.style.backgroundColor = colors[colorIndex]
}
| 2d42c253773fb61c90315c42186cb5507f10e6e3 | [
"JavaScript"
] | 3 | JavaScript | jennycao30/jennycao30.github.io | c6dc10230f4ae0650798fe42f907e316a444f039 | 10a07f0d6c10c91b13bd7fc018aae50dbfbc7405 |
refs/heads/master | <file_sep>package com.properties.examples.examples.method_with_default_propertie_value;
import org.springframework.stereotype.Component;
@Component
public class PhoneValidation implements ValidationRule {
@Override
public void doValidation() {
System.out.println("validate phone");
}
}
<file_sep>package com.properties.examples.examples.convertors_example.client.convertor_by_properties_sheme;
import com.properties.examples.examples.convertors_example.client.convertor_by_dto_sheme.VehicleSystemBDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/system_b_prop")
@RequiredArgsConstructor
public class VehiclePropSystemBController {
private final VehiclePropertiesSchemeConverter schemeConverter;
@GetMapping("/get")
public List<VehicleSystemBDto> getData() {
return schemeConverter.getData();
}
}
<file_sep>package com.properties.examples.examples.convertors_example.client.convertor_by_dto_sheme;
import com.properties.examples.examples.convertors_example.RestTemplateService;
import com.properties.examples.examples.convertors_example.client.VehicleDtoList;
import com.properties.examples.examples.convertors_example.server.VehicleDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@Component
@RequiredArgsConstructor
public class VehicleDtoSchemeConverter {
private final RestTemplateService restTemplateService;
public List<VehicleSystemBDto> getData() {
return systemBDtoListConverter(restTemplateService.getData());
}
public List<VehicleSystemBDto> getDataV2() {
return systemBDtoListConverterV2(restTemplateService.getData());
}
private List<VehicleSystemBDto> systemBDtoListConverter(VehicleDtoList vehicleDtoList) {
List<VehicleSystemBDto> vehicleSystemBDtos = new ArrayList<>();
for (VehicleDto vehicleDto : vehicleDtoList.getVehicleDtoList()) {
VehicleSystemBDto vehicleSystemBDto = new VehicleSystemBDto();
vehicleSystemBDto.setColor(vehicleDto.getColor());
if ("A".equals(vehicleDto.getType())) {
vehicleSystemBDto.setType("MOTO");
vehicleSystemBDtos.add(vehicleSystemBDto);
continue;
}
if ("B".equals(vehicleDto.getType())) {
vehicleSystemBDto.setType("CAR");
vehicleSystemBDtos.add(vehicleSystemBDto);
continue;
}
}
return vehicleSystemBDtos;
}
private static final List<String> TYPE_LIST = Arrays.asList("A", "B");
private List<VehicleSystemBDto> systemBDtoListConverterV2(VehicleDtoList vehicleDtoList) {
List<VehicleSystemBDto> vehicleSystemBDtos = new ArrayList<>();
for (VehicleDto vehicleDto : vehicleDtoList.getVehicleDtoList()) {
VehicleSystemBDto vehicleSystemBDto = new VehicleSystemBDto();
vehicleSystemBDto.setColor(vehicleDto.getColor());
if (TYPE_LIST.contains(vehicleDto.getType())) {
vehicleSystemBDto.setType(Objects.requireNonNull(VehicleTypeConstant.find(vehicleDto.getType())).name());
vehicleSystemBDtos.add(vehicleSystemBDto);
continue;
}
}
return vehicleSystemBDtos;
}
}
<file_sep> # Варианты работы с разными структурами данных(колекциями) из .properties файлов
``1.`` В application.properties имеем слудующую конфигурацю:
- driverDocType2Category.MOTO=A
- driverDocType2Category.CAR=B
- driverDocType2Category.TRUCK=C
- driverDocType2Category.BUS=D
Задача - получить карту **Map<String, String>**, где ключом будет название категории, а значением его обозначениее.
- создаем класс CollectionsPropertyUtils, который будет бином, + сканировать наши проперти и название наших строк.
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
public final Map<String, String> driverDocType2Category = new HashMap<>();
}
```
С помощью аннотации @ConfigurationProperties() мы можем срузу инициадизировать нужную карту, обращаясь к блоку конфигураций
по имени driverDocType2Category. Имя карты должно совпадать с названием проперти из файла. в данном случае :
driverDocType2Category.MOTO=A
**Для работы данной анотации спринг бут попросит вас добавить зависимость**
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
```
Теперь сделаем сервис куда мы будем инжектить наш бин в котором будем работать с нашей структурой данных, получив
карту с помощью гетера
```
@Component
public class PropertiesService {
private final CollectionsPropertyUtils collectionsPropertyUtils;
@Autowired
public PropertiesService(CollectionsPropertyUtils collectionsPropertyUtils) {
this.collectionsPropertyUtils = collectionsPropertyUtils;
}
void mapFromProperties() {
Map<String, String> driverDocType2CategoryMap = collectionsPropertyUtils.getDriverDocType2Category();
driverDocType2CategoryMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
}
```
Результатом выполнения будет:
- MOTO ->A
- TRUCK ->C
- BUS ->D
- CAR ->B
Аналогичным способом получаяем из .properties файла, карту - где значениеми будет выступать уже список параметров.
``2.`` В application.properties имеем слудующую конфигурацю:
- driverDocType2Categories.MOTO=A,A1,A2
- driverDocType2Categories.CAR=B,B1,B2
- driverDocType2Categories.TRUCK=C.C1,C2
- driverDocType2Categories.BUS=D,D1,D2
После равно, видим список значений
Задача - получить карту **Map<String, List<String>>**, где ключом будет название категории, а значением - набор значений.
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
private final Map<String, List<String>> driverDocType2Categories = new HashMap<>();
}
```
```
@Component
public class PropertiesService {
private final CollectionsPropertyUtils collectionsPropertyUtils;
@Autowired
public PropertiesService(CollectionsPropertyUtils collectionsPropertyUtils) {
this.collectionsPropertyUtils = collectionsPropertyUtils;
}
void mapFromPropertiesWithListValues() {
Map<String, List<String>> driverDocType2CategoriesMap = collectionsPropertyUtils.getDriverDocType2Categories();
driverDocType2CategoriesMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
}
```
Результатом выполнения будет:
- MOTO ->[A, A1, A2]
- TRUCK ->[C.C1, C2]
- BUS ->[D, D1, D2]
- CAR ->[B, B1, B2]
Теперь давайте получим, теже структуры данных. Но уже другим способом.
``3.`` В application.properties имеем слудующую конфигурацю:
- test.map={\
- "key1":"value1",\
- 'key2':'value2',\
- key3:'value3'\
- }
**СИНТАКСИС** Все три ключа со значением, имеют разный синтаксис. Вы можете использовать любой вариант.
Что бы получить карту, нам всего лиш необходимо воспользоватся аннотацией **@Value**
```
@Value("#{${test.map}}")
private Map<String, String> testMap;
```
и метод который выводит содержимое карты(работаем все в том же сервисе)
```
void mapFromPropertiesSecondOption() {
testMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
```
Результат выполнения:
- key1 ->value1
- key2 ->value2
- key3 ->value3
``4.``В application.properties имеем слудующую конфигурацю:
- test.map.list.value={\
- 'KEY1': {'value1','value2'}, \
- 'KEY2': {'value3','value4'}, \
- 'KEY3': {'value5'} \
- }
```
@Value("#{'${numberStringList}'.split(',')}")
private List<String> numberStringList;
```
метод который выводит содержимое карты(работаем все в том же сервисе)
```
void mapFromPropertiesWithListValuesSecondOption() {
testMapListValue.forEach((k, v) -> System.out.println(k + " ->" + v));
}
```
Результат выполнения:
KEY1 ->[value1, value2]
KEY2 ->[value3, value4]
KEY3 ->[value5]
Задача - пулчить с помощью @Value лиш одно поле из карты
``5.1`` Если в файле .properties мы храним карту, при необходимости можем получить от туда только
одно значение по ключю.
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
@Value("#{${test.map}.key3}")
private String fieldFomMap;
}
```
Метод для вывода
```
void valueFromMapByField() {
System.out.println(fieldFomMap);
}
```
Результат выполнения:
value3
Задача - получить из .properties карту отсортированную по ключю либо по значению.
``5.2`` Теперь возьмем нашу карту и выведм ее, указав что не хотим в результате опирировать одним из ключей.
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
@Value("#{${test.map}.?[key!='key3']}")
private Map<String, String> filteredTestMap;
}
```
Метод для вывода
```
void filteredMap() {
System.out.println(filteredTestMap);
}
```
Результат выполнения:
{key1=value1, key2=value2}
``5.`` В application.properties имеем слудующую конфигурацю:
- number.array=1,2,3,
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
@Value("${number.array}")
private int [] numberArray;
}
```
Задача - получить массив чисел.
``5.`` В application.properties имеем слудующую конфигурацю:
- stringList=one,two,three
Метод для вывода
```
void arrayFromPropFile(){
for (int i=0; i<numberArray.length;i++){
System.out.println(numberArray[i]);
}
}
```
Результат выполнения:
-1
-2
-3
-4
Задача - получить список **List<String>**.
``5.1`` . Получаем список, с помощью класса анотированого @ConfigurationProperties(), присвоив колекции имя
которое совпадает с именем свойства в .properties файле.
```
@Getter
@Component
@ConfigurationProperties()
public class CollectionsPropertyUtils {
private final List<String> numberStringList = new ArrayList<>();
}
```
Метод для вывода
```
void listFromProperties() {
collectionsPropertyUtils.getNumberStringList().forEach(System.out::println);
}
```
Результат выполнения:
- one
- two
- three
``5.2`` С помощью аннотации **@Value и spell** выражения
```
@Value("#{'${numberStringList}'.split(',')}")
private List<String> numberStringList;
```
Метод для проверки
```
void listFromPropertiesSecondOption() {
numberStringList.forEach(System.out::println);
}
```
Результат выполнения:
- one
- two
- three
``6.`` В application.properties имеем слудующую конфигурацю:
- random.number=${random.int}
- random.long=${random.long}
- random.uuid=${random.uuid}
Задача - получить объект с полями number,long,uuid .
В данном примере, использованна генереция значений к полях значений.
Создаем ObjectPropertyConfigurator сласс
```
@Component
@ConfigurationProperties(prefix = "random")
@Getter
@Setter
@ToString
public class ObjectPropertyConfigurator {
String url;
String username;
String password;
}
```
Который является компонетом, имеет гетеры и сетеры. B основная аннотация:
@ConfigurationProperties(prefix = "random") - которая говорит, что будет из всего списка пропертей
вычитывать только с префиксом "random", а через точку будет название поля объекта
в сервисе просто инжектим наш ObjectPropertyConfigurator
```
@Component
public class PropertiesService {
private final ObjectPropertyConfigurator objectPropertyConfigurator;
@Autowired
public PropertiesService(ObjectPropertyConfigurator objectPropertyConfigurator) {
this.objectPropertyConfigurator = objectPropertyConfigurator;
}
void objectFromProperties() {
System.out.println(objectPropertyConfigurator.toString());
}
}
```
Результат выполнения:
ObjectPropertyConfigurator(url=<PASSWORD>, username=aa2aace70946a0ceee6c0456432330f4, password=<PASSWORD>)
Пример конвертора который берет данные в одном формате и возврщает в другом.
С гибкой возможностью выбора что конвертировать, а что нет. AddressTestService
Исходный формат
```json
[{"country":"Ukraine","city":"Dnipro","street":"Dniprova","house":"22","type":"1"},{"country":"Ukraine","city":"Dnipro","street":"Dniprova","house":"22","type":"2"},{"country":"Ukraine","city":"Dnipro","street":"Dniprova","house":"22","type":"3"},{"country":"Ukraine","city":"Dnipro","street":"Dniprova","house":"22","type":"4"}]
```
выдаваемый формат:
address_local_country - Ukraine
address_local_city - Dnipro
address_local_street - Dniprova
address_local_house - 22
address_foreign_country - Ukraine
address_foreign_city - Dnipro
address_foreign_street - Dniprova
address_foreign_house - 22
address_temporary_country - Ukraine
address_temporary_city - Dnipro
address_temporary_street - Dniprova
address_temporary_house - 22
address_former_country - Ukraine
address_former_city - Dnipro
address_former_street - Dniprova
address_former_house - 22
Исчерпывающая документация:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding
<file_sep>package com.properties.examples.examples.method_with_default_propertie_value;
import org.springframework.stereotype.Component;
@Component
public class EmailValidation implements ValidationRule {
@Override
public void doValidation() {
System.out.println("validate email");
}
}
<file_sep>package com.properties.possible.structures.example.possibleStructures;
import com.properties.possible.structures.example.possibleStructures.propertiesUtils.CollectionsPropertyUtils;
import com.properties.possible.structures.example.possibleStructures.propertiesUtils.ObjectPropertyConfigurator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@RequiredArgsConstructor
public class PropertiesService {
// private final ObjectPropertyConfigurator objectPropertyConfigurator;
private final CollectionsPropertyUtils collectionsPropertyUtils;
@Value("#{${test.map}}")
private Map<String, String> testMap2;
@Value("#{${test.map.list.value}}")
Map<String, List<String>> testMapListValue2;
@Value("${number.array}")
private int [] numberArray;
@Value("#{'${stringList}'.split(',')}")
private List<String> stringList2;
@Value("#{${test.map}.key3}")
private String fieldFomMap2;
@Value("#{${test.map}.?[key!='key3']}")
private Map<String, String> filteredTestMap2;
void mapFromProperties() {
Map<String, String> driverDocType2CategoryMap = collectionsPropertyUtils.getDriverDocType2Category();
driverDocType2CategoryMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
void mapFromPropertiesWithListValues() {
Map<String, List<String>> driverDocType2CategoriesMap = collectionsPropertyUtils.getDriverDocType2Categories();
//Todo можем переложить, но зачем?
//Map<String, List<String>> testPropMapList = new HashMap<>();
//testPropMap.forEach((k, v) -> testPropMapList.put(k, Arrays.asList(v.split(","))));
driverDocType2CategoriesMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
void mapFromPropertiesSecondOption() {
testMap.forEach((k, v) -> System.out.println(k + " ->" + v));
}
void mapFromPropertiesWithListValuesSecondOption() {
testMapListValue.forEach((k, v) -> System.out.println(k + " ->" + v));
}
// void objectFromProperties() {
// System.out.println(objectPropertyConfigurator.toString());
// }
void arrayFromPropFile(){
for (int i=0; i<numberArray.length;i++){
System.out.println(numberArray[i]);
}
}
void listFromProperties() {
collectionsPropertyUtils.getStringList().forEach(System.out::println);
}
void listFromPropertiesSecondOption() {
System.out.println(stringList);
}
void valueFromMapByField() {
System.out.println(fieldFomMap);
}
void filteredMap() {
System.out.println(filteredTestMap);
}
@Value("#{${test.map}}")
private Map<String, String> testMap;
@Value("#{${test.map.list.value}}")
Map<String, List<String>> testMapListValue;
@Value("#{'${stringList}'.split(',')}")
private List<String> stringList;
@Value("#{${test.map}.key3}")
private String fieldFomMap;
@Value("#{${test.map}.?[key!='key3']}")
private Map<String, String> filteredTestMap;
@Value("#{new java.text.SimpleDateFormat('${start.check.date_format}').parse('${start.check.date}')}")
Date myDate;
}
<file_sep>package com.properties.examples.examples.method_with_default_propertie_value;
public interface ValidationRule {
void doValidation();
}
<file_sep>package com.properties.examples.examples.strategy_example;
public interface MessageSender {
String doSomeCase();
}
<file_sep>package com.properties.examples.examples.convertors_example.client.convertor_by_dto_sheme;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class VehicleSystemBDto {
private String type;
private String color;
}
| 476f3b47d5eb2f9b89924b3eb876a79057a2adf5 | [
"Markdown",
"Java"
] | 9 | Java | ArtyrGetman/powerOfProperties | 5730fd533a32dc1f92e1898d9ab468f5030bd4e1 | b490395ecb02c64b271d1d51e0f0fa2e966e6ae1 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for plate management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public class Assiette : MonoBehaviour
{
private IEnumerable<string> _thinConsumables = null;
/// <summary>
/// Start event method
/// </summary>
public void Start()
{
_thinConsumables = new[] { "Steack", "TrancheDeChedar" };
}
/// <summary>
/// OnTriggerStay event method
/// </summary>
/// <param name="other">gameObject collided</param>
public void OnTriggerStay(Collider other)
{
GameObject collidedGameObject = other.gameObject;
OVRGrabbable grabbable = collidedGameObject.GetComponent<OVRGrabbable>();
if (collidedGameObject.tag == "Consumable" && !grabbable.isGrabbed)
{
collidedGameObject.GetComponent<Rigidbody>().useGravity = false;
// instantiate new consumable
collidedGameObject.gameObject.GetComponent<Consumable>().Instantiate();
// set Quarternion
collidedGameObject.transform.rotation = collidedGameObject.GetComponent<Consumable>().InitialQuarternion;
// set as child of assiette
collidedGameObject.transform.parent = this.transform;
// set position
int nbChildren = this.transform.childCount;
// set thickness depending if it's thick or not
float consumableThickness = 0.005f;
if (_thinConsumables.Contains(collidedGameObject.gameObject.name)) consumableThickness = 0.002f;
collidedGameObject.transform.localPosition = new Vector3(0f, 0.025f + consumableThickness * nbChildren, 0f);
// disable collider to not interact with again
collidedGameObject.gameObject.GetComponent<MeshCollider>().enabled = false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for consumable management
/// </summary>
public class Consumable : MonoBehaviour
{
private UnityEngine.Object _consumablePrefab;
private OVRGrabbable _currentGrabbableObject;
private OVRGrabber _grabber;
private Vector3 _initialPosition;
private Quaternion _initialQuarternion;
private Transform _initialParent;
private bool _isInstantiate;
/// <summary>
/// Get method for consumable initial rotation (quarternion)
/// </summary>
public Quaternion InitialQuarternion
{
get
{
return _initialQuarternion;
}
}
/// <summary>
/// Start event method
/// </summary>
public void Start()
{
_consumablePrefab = Resources.Load<UnityEngine.Object>($"Prefabs/Consumables/{gameObject.name.Split('(')[0]}");
_currentGrabbableObject = GetComponent<OVRGrabbable>();
_initialPosition = this.transform.position;
_initialQuarternion = this.transform.rotation;
_initialParent = this.transform.parent;
_isInstantiate = false;
}
/// <summary>
/// Method to initiate consumable prefab
/// </summary>
/// <param name="prefab">Prefab to set</param>
public void SetPrefab(UnityEngine.Object prefab)
{
_consumablePrefab = prefab;
}
/// <summary>
/// Instantiate a consumable
/// </summary>
public void Instantiate()
{
if(!_isInstantiate) //can instantiate only one time
{
var instantiatedConsumable = (GameObject) Instantiate(_consumablePrefab, _initialPosition, _initialQuarternion);
_isInstantiate = true;
instantiatedConsumable.transform.parent = GameObject.Find($"Consumables").transform;
instantiatedConsumable.tag = "Consumable";
// avoid the possibility to get the same instantiated consumable
string tempStr = instantiatedConsumable.name;
tempStr.Remove(tempStr.Length - 7);
instantiatedConsumable.name = instantiatedConsumable.name.Remove(tempStr.Length - 7);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for stored recipes management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public static class RecipeManager
{
private const string _recipesPath = "recipesBdd.json";
private const string _recipesToPlayPath = "recipesToPlay.json";
/// <summary>
/// Set the recipes to play with (called in menu scene)
/// </summary>
/// <param name="gameMode">chosen game mode</param>
/// <param name="recipes">chosen recipes</param>
public static void SetRecipesToPlay(GameMode gameMode, Recipes recipes)
{
string filePath = Path.Combine(Application.streamingAssetsPath, _recipesToPlayPath);
if (File.Exists(filePath))
{
// Convert the data to a JSon string and save it to a JSon file
File.WriteAllText(filePath, JsonUtility.ToJson(recipes));
if(gameMode.HasFlag(GameMode.Arcade | GameMode.Training)) //TODO change it when we have more scenes
SceneManager.LoadScene("Game", LoadSceneMode.Single);
}
else
{
Debug.LogError("Cannot load recipes!");
}
}
/// <summary>
/// Get the recipes to play with (called in game scene)
/// </summary>
/// <returns>recipes to play</returns>
public static Recipes GetRecipesToPlay()
{
Recipes loadedData = null;
string filePath = Path.Combine(Application.streamingAssetsPath, _recipesToPlayPath);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a GameData object from it
loadedData = JsonUtility.FromJson<Recipes>(dataAsJson);
}
else
{
Debug.LogError("Cannot load recipes!");
}
return loadedData;
}
/// <summary>
/// Get all available recipes (called in menu scene)
/// </summary>
/// <returns>available recipes</returns>
public static Recipes GetAllRecipes()
{
Recipes loadedData = null;
string filePath = Path.Combine(Application.streamingAssetsPath, _recipesPath);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a GameData object from it
loadedData = JsonUtility.FromJson<Recipes>(dataAsJson);
}
else
{
Debug.LogError("Cannot load recipes!");
}
return loadedData;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using Assets.Scripts.Game;
using System.Linq;
using UnityEngine.SceneManagement;
namespace Assets.Scripts.Menu
{
public class TrainingModeCaller : MonoBehaviour
{
private Recipes _bddRecipes;
private Recipes _recipes;
public GameObject _spawnPoint;
public GameObject _popup;
private void Start()
{
_bddRecipes = RecipeManager.GetAllRecipes();
_recipes = new Recipes();
_recipes.recipes = new List<Recipe>();
}
public void PlayGame()
{
Transform[] childrenList = _spawnPoint.transform.Cast<Transform>().ToArray();
string tempString = String.Empty;
foreach (Transform child in childrenList)
{
if (child.gameObject.GetComponent<Toggle>().isOn)
{
tempString = child.GetChild(0).GetComponent<Text>().text;
Recipe tempRecipe = _bddRecipes.recipes.FirstOrDefault(r => r.recipeName == tempString);
if (tempRecipe != null) _recipes.recipes.Add(tempRecipe);
}
}
RecipeManager.SetRecipesToPlay(GameMode.Training, _recipes);
if (_recipes.recipes.Count > 0)
{
SceneManager.LoadScene("Game", LoadSceneMode.Single);
}
else
{
_popup.transform.GetChild(0).GetChild(0).GetComponent<Text>().text = "Erreur";
_popup.transform.GetChild(0).GetChild(1).GetComponent<Text>().text = "Veuillez sélectionner au moins une recette.";
_popup.SetActive(true);
}
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for recipe management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
[Serializable]
public class Recipe
{
public string recipeName;
public List<string> ingredients;
/// <summary>
/// Check a recipe
/// </summary>
/// <param name="sendIngredients">recipe ingredients to test</param>
/// <returns>OK / KO</returns>
public bool IsRecipeOk(List<string> sendIngredients)
{
if (ingredients.Count != sendIngredients.Count) return false;
int length = ingredients.Count;
bool check = true;
for (int i = 0; i < length; i++)
{
if (ingredients[i] != sendIngredients[i])
{
check = false;
break;
}
}
return check;
}
/// <summary>
/// Recipe ToString method
/// </summary>
/// <returns>recipe description</returns>
public override string ToString()
{
string str = $"*****\nRecette {recipeName} : \n";
foreach (string s in ingredients)
{
str += $" - {s}";
}
return str += "\n\n****";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
using UnityEngine.SceneManagement;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for game management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public class GameManager : MonoBehaviour
{
public SoundManager _soundManager;
public BurgerModelBuilder _burgerModelBuilder;
private Recipes _recipesToPlay;
private Recipe _currentRecipe;
/// <summary>
/// Awake event method
/// </summary>
public void Awake()
{
_recipesToPlay = null;
}
/// <summary>
/// Start event method
/// </summary>
public void Start()
{
// recup dans fichier json (recipe.json) les recettes à jouer
_recipesToPlay = RecipeManager.GetRecipesToPlay();
_currentRecipe = _recipesToPlay.Get(0);
_burgerModelBuilder.BuildBurgerModel(_currentRecipe);
}
/// <summary>
/// Check recipe put in the plate
/// </summary>
public void CheckRecipe()
{
// Get ingredients
List<string> ingredients = new List<string>();
foreach(Transform child in transform)
{
ingredients.Add(child.name);
// destroy ingredient
Destroy(child.gameObject);
}
// Check recipe
if (_currentRecipe.IsRecipeOk(ingredients))
{
_soundManager.PlayRecipeSound(true);
ChangeRecipe();
Debug.Log("Current Recipe Changed");
}
else { _soundManager.PlayRecipeSound(false); Debug.Log("Wrong recipe"); }
}
/// <summary>
/// Change recipe on game start or when previous one has been checked
/// </summary>
private void ChangeRecipe()
{
_recipesToPlay.Remove(_currentRecipe);
_burgerModelBuilder.CleanModel();
if (_recipesToPlay.Count() == 0) Win();
else
{
_currentRecipe = _recipesToPlay.Get(0);
Debug.Log(_currentRecipe);
_burgerModelBuilder.BuildBurgerModel(_currentRecipe);
}
}
/// <summary>
/// Win a game
/// </summary>
private void Win()
{
_soundManager.PlayVictorySound();
SceneManager.LoadScene("Menu", LoadSceneMode.Single);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for sound management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public class SoundManager : MonoBehaviour
{
public AudioClip _rightRecipe;
public AudioClip _wrongRecipe;
public AudioClip _winSound;
private AudioSource _audioSource;
/// <summary>
/// Start event method
/// </summary>
public void Start()
{
_audioSource = gameObject.GetComponent<AudioSource>();
}
/// <summary>
/// Play sound depending on recipe check
/// </summary>
/// <param name="recipeOk">recipe check</param>
public void PlayRecipeSound(bool recipeOk)
{
if (recipeOk) _audioSource.PlayOneShot(_rightRecipe);
else _audioSource.PlayOneShot(_wrongRecipe);
}
/// <summary>
/// Play end game sound
/// </summary>
public void PlayVictorySound()
{
_audioSource.PlayOneShot(_winSound);
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for recipes data management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
[Serializable]
public class Recipes
{
public List<Recipe> recipes;
/// <summary>
/// Get a specified recipe
/// </summary>
/// <param name="i">specified recipe index</param>
/// <returns></returns>
public Recipe Get(int i) => recipes[i];
/// <summary>
/// Remove a specified recipe
/// </summary>
/// <param name="r">specified recipe</param>
public void Remove(Recipe r) => recipes.Remove(r);
/// <summary>
/// Count the recipe's number
/// </summary>
/// <returns>recipe's number</returns>
public int Count() => recipes.Count;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Assets.Scripts.Game;
using System.Linq;
namespace Assets.Scripts.Menu
{
public class Spawn : MonoBehaviour
{
private Recipes _bddRecipes;
public GameObject _spawnPoint;
public GameObject _prefab;
private GameObject _spawnedObject;
private GameObject _popup;
// Use this for initialization
void Start()
{
_bddRecipes = RecipeManager.GetAllRecipes();
_popup = GameObject.Find("popup");
_popup.SetActive(false);
foreach (Recipe currentRecipe in _bddRecipes.recipes)
{
SpawnEntities(currentRecipe.recipeName);
}
}
// Update is called once per frame
void Update()
{
}
private void SpawnEntities(string currentName)
{
_spawnedObject = Instantiate(_prefab, _spawnPoint.transform.position, _spawnPoint.transform.rotation);
_spawnedObject.transform.parent = _spawnPoint.transform;
_spawnedObject.transform.GetChild(0).GetComponent<Text>().text = currentName;
_spawnedObject.transform.GetChild(1).GetComponent<PopRecipe>().SetPopup(_popup);
}
}
}
<file_sep>using Assets.Scripts.Game;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace Assets.Scripts.Menu
{
class ArcadeModeCaller : MonoBehaviour
{
private Recipes _bddRecipes;
private Recipes _recipes;
public GameObject _spawnPoint;
public GameObject _popup;
private void Start()
{
_bddRecipes = RecipeManager.GetAllRecipes();
_recipes = new Recipes();
_recipes.recipes = new List<Recipe>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
Transform[] childrenList = _spawnPoint.transform.Cast<Transform>().ToArray();
string tempString = String.Empty;
foreach (Transform child in childrenList)
{
//Debug.Log(child.gameObject.GetComponent<Toggle>().isOn);
if (child.gameObject.GetComponent<Toggle>().isOn)
{
tempString = child.GetChild(0).GetComponent<Text>().text;
//Debug.Log(tempString);
Recipe tempRecipe = _bddRecipes.recipes.FirstOrDefault(r => r.recipeName == tempString);
//Debug.Log(tempRecipe.recipeName);
if (tempRecipe != null) _recipes.recipes.Add(tempRecipe);
}
}
RecipeManager.SetRecipesToPlay(GameMode.Arcade, _recipes);
if (_recipes.recipes.Count > 0)
{
SceneManager.LoadScene("Game", LoadSceneMode.Single);
}
else
{
_popup.transform.GetChild(0).GetChild(0).GetComponent<Text>().text = "Erreur";
_popup.transform.GetChild(0).GetChild(1).GetComponent<Text>().text = "Veuillez sélectionner au moins une recette.";
_popup.SetActive(true);
}
}
}
}
}
<file_sep># Tommy's Project
Project of a burger maker simulation for apprentice cook.
## Functions
- 1 game mode : " Training "
- 5 ingredients : (top bun, bottom bun, salad, cheese, steack)
- Multiple choices of recipes to make the game vary (based on the available ingredients)
- Haptic rendering when grab ingredients
- Sound on recipe serving
## Developpers
[<NAME>](https://github.com/jraillard) -
[<NAME>](https://github.com/MickaMx) -
[<NAME>](https://github.com/florentyvon) -
[<NAME>](https://github.com/kilo-graham)
## Bugs
Interaction bugs with plate are known and due to OVR Scripts management.
## Evolutions
1. Set up a background sound
2. Add some new ingredients (tomato, onions, sauces, bacon and some others...)
3. Add recipes
4. Make a timed mode
5. Be able to make several recipes in parallel
6. Design restaurant's vibe by adding AI to make the simulation mode realistic
7. Make a "real mode" : customers come in front of the user and ask for a random recipe
## Demo







## Installation
No need, just play the executable available in the "Release" folder.
### Prerequesites
[Unity 3D (2018.2.1 version)](https://unity3d.com/fr/get-unity/download/archive) -
[Oculus Rift](https://www.oculus.com/rift/setup/)
<file_sep>using Assets.Scripts.Game;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for bell management
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public class BellService : MonoBehaviour
{
public GameManager _gameManager;
/// <summary>
/// OnTriggerEnter event method
/// </summary>
/// <param name="collider">gameObject collided</param>
public void OnTriggerEnter(Collider collider)
{
if (collider.tag == "Player")
{
// if collided by player, check recipe made in the plate
_gameManager.CheckRecipe();
}
}
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scripts.Game
{
/// <summary>
/// Class for model burger maker
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
public class BurgerModelBuilder : MonoBehaviour
{
public Vector3 _initialPosition;
public Text _recipeName;
private Vector3 _incrementedPosition;
/// <summary>
/// Constructor method
/// </summary>
/// <param name="recipe">burger recipe to make</param>
public void BuildBurgerModel(Recipe recipe)
{
UnityEngine.Object tempIngredient = null;
GameObject tempInstantiatedIngredient = null;
_incrementedPosition = _initialPosition;
foreach (string str in recipe.ingredients)
{
Debug.Log(str);
tempIngredient = Resources.Load<UnityEngine.Object>($"Prefabs/Recipe_Models/{str}");
tempInstantiatedIngredient = (GameObject) Instantiate(tempIngredient, _incrementedPosition, ((GameObject)tempIngredient).gameObject.transform.rotation);
tempInstantiatedIngredient.name = $"{tempInstantiatedIngredient.name}-Model";
tempInstantiatedIngredient.transform.parent = this.transform;
tempInstantiatedIngredient.GetComponent<Rigidbody>().useGravity = false;
_incrementedPosition += new Vector3(0, 0.025f, 0);
}
_recipeName.text = recipe.recipeName;
}
/// <summary>
/// Clear the model before creating the new one
/// </summary>
public void CleanModel()
{
_incrementedPosition = _initialPosition;
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
}
}
}<file_sep>using Assets.Scripts.Game;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class PopRecipe : MonoBehaviour {
private GameObject _popup;
public void SetPopup(GameObject popup)
{
_popup = popup;
}
public void Popup()
{
string tempString = transform.GetComponent<Button>().transform.parent.GetChild(0).GetComponent<Text>().text;
Debug.Log(tempString);
Recipes _bddRecipes = RecipeManager.GetAllRecipes(); ;
Recipe tempRecipe = _bddRecipes.recipes.FirstOrDefault(r => r.recipeName == tempString);
_popup.transform.GetChild(0).GetChild(0).GetComponent<Text>().text = tempString;
_popup.transform.GetChild(0).GetChild(1).GetComponent<Text>().text = tempRecipe.ToString();
_popup.SetActive(true);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.Game
{
/// <summary>
/// Enumeration for Game modes
/// <author><NAME>, <NAME>, <NAME>, <NAME></author>
/// </summary>
[Flags]
public enum GameMode
{
Training = 0x1,
Arcade = 0x2
}
} | f3dfd910f6f3a5b2cf60032069f3c3fda46483bd | [
"Markdown",
"C#"
] | 15 | C# | jraillard/Tommys_Project | 9774ee7003db4a7a267aaa4852717f6916b5b8b2 | b59353674162cfd53dbd0530cae1d03ff77b753e |
refs/heads/master | <repo_name>rijumanandhar/ExerciseTimer<file_sep>/app/src/main/java/com/example/exercise/MainActivity.java
package com.example.exercise;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public final String EXERCISE = "Exercise (seconds) : ";
public final String BREAK = "Break (seconds) : ";
int exerciseTime = 45;
int breakTime = 15;
long timeLeftMillSecond = 0;
CountDownTimer countDownTimer;
boolean isExercise = true;
boolean isTicking = false;
private Button startbtn, stopbtn, changebtn;
private TextView exercisetv, breaktv;
private TextView timertv;
private Dialog dialogWithMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timertv = findViewById(R.id.countdown_tv);
exercisetv = findViewById(R.id.exercise_tv);
breaktv = findViewById(R.id.break_tv);
startbtn = findViewById(R.id.start_button);
stopbtn = findViewById(R.id.stop_button);
changebtn = findViewById(R.id.change_button);
setupView();
}
public void setupView(){
updateView();
releaseMediaPlayer();
mediaPlayer= MediaPlayer.create(this, R.raw.sound_file_1); // file name should not include space or capital letters
startbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTimer();
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopTimer();
}
});
changebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
change();
}
});
}
public void startTimer(){
if (!isTicking){
isTicking = true;
if (isExercise){
timeLeftMillSecond = exerciseTime*1000;
isExercise = false;
}else{
timeLeftMillSecond = breakTime*1000;
isExercise = true;
}
countDownTimer = new CountDownTimer(timeLeftMillSecond,1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeftMillSecond = millisUntilFinished;
updateTimerView();
}
@Override
public void onFinish() {
mediaPlayer.start();
isTicking = false;
startTimer();
}
}.start();
}
}
public void stopTimer(){
if (isTicking){
countDownTimer.cancel();
isTicking = false;
isExercise = true;
timeLeftMillSecond = 0;
updateTimerView();
}
}
public void updateTimerView(){
int minute = (int)timeLeftMillSecond/60000;
int second = (int)timeLeftMillSecond%60000/1000;
String timeLeftText="";
if (minute<10) timeLeftText = "0";
timeLeftText +=minute+"";
timeLeftText += " : ";
if (second<10) timeLeftText += "0";
timeLeftText += second+"";
timertv.setText(timeLeftText);
}
public void change(){
dialogWithMessage = new Dialog(this);
dialogWithMessage.setContentView(R.layout.floating_dialog);
final EditText exerciseEt, breakEt;
Button doneBtn;
exerciseEt = dialogWithMessage.findViewById(R.id.exercise_et);
breakEt = dialogWithMessage.findViewById(R.id.break_et);
doneBtn = dialogWithMessage.findViewById(R.id.done_btn);
exerciseEt.setText(exerciseTime+"");
breakEt.setText(breakTime+"");
doneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String exerciseString = exerciseEt.getText().toString();
String breakString = breakEt.getText().toString();
if (exerciseString.length()!=0 && breakString.length() != 0){
try{
exerciseTime = Integer.parseInt(exerciseString);
breakTime = Integer.parseInt(breakString);
updateView();
dialogWithMessage.dismiss();
}catch (NumberFormatException e){
}
}
}
});
dialogWithMessage.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogWithMessage.show();
}
public void updateView(){
exercisetv.setText(EXERCISE+exerciseTime);
breaktv.setText(BREAK+breakTime);
}
//what does this do, idk
public void releaseMediaPlayer(){
if (mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
}
<file_sep>/settings.gradle
rootProject.name='Exercise'
include ':app'
| 58d8a43c58020140be705b3c765558f8a372e01f | [
"Java",
"Gradle"
] | 2 | Java | rijumanandhar/ExerciseTimer | 1e34e8d2344e2f8c6c0234a9ee591a6b6dab1288 | 524cc859398e012d064819b8659862af19c95695 |
refs/heads/main | <repo_name>BrettMarkland-Sanchez/employee-management-system<file_sep>/server.js
const mysql = require('mysql');
const inquirer = require('inquirer');
const cTable = require('console.table');
const queries = require('./queries');
const art = require('ascii-art');
// creates the connection information for the sql database
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'employees_DB',
});
// function for querying the database using a given query string
const query = (string) => {
connection.query(string, function(error, results, fields) {
if (error) throw error;
console.log('\n');
console.table(results);
start();
});
}
// function for adding new employees with Inquirer
const employee = () => {
inquirer.prompt([
{
name: 'first_name',
type: 'input',
message: `What is the new employee's first name?`
},
{
name: 'last_name',
type: 'input',
message: `What is the new employee's last name?`
},
{
name: 'role_id',
type: 'input',
message: `What is the new employee's role id?`
},
{
name: 'manager_id',
type: 'input',
message: `What is the new employee's manager id?`,
default: null
}
])
.then((answers) => {
let string = `
insert into employee (first_name, last_name, role_id, manager_id)
values ('${answers.first_name}', '${answers.last_name}', ${answers.role_id}, ${answers.manager_id});
`;
query(string);
})
}
// function for updating employee roles with Inquirer
const employeeRole = () => {
inquirer.prompt([
{
name: 'employee_id',
type: 'input',
message: `What is the id of the employee being updated?`
},
{
name: 'role_id',
type: 'input',
message: `What is the new role_id for the employee?`
}
])
.then((answers) => {
let string = `
update employee
set role_id = ${answers.role_id}
where id = ${answers.employee_id}
`;
query(string);
})
}
// function for updating employee manager with Inquirer
const employeeManager = () => {
inquirer.prompt([
{
name: 'employee_id',
type: 'input',
message: `What is the id of the employee being updated?`
},
{
name: 'manager_id',
type: 'input',
message: `What is the new manager_id for the employee?`
}
])
.then((answers) => {
let string = `
update employee
set manager_id = ${answers.manager_id}
where id = ${answers.employee_id}
`;
query(string);
})
}
// function for adding new roles with Inquirer
const role = () => {
inquirer.prompt([
{
name: 'title',
type: 'input',
message: `What is the title for the new role?`
},
{
name: 'salary',
type: 'input',
message: `What is the salary for the new role?`
},
{
name: 'department_id',
type: 'input',
message: `What is the department_id for the new role?`
}
])
.then((answers) => {
let string = `
insert into role (title, salary, department_id)
values ('${answers.title}', '${answers.salary}', ${answers.department_id});
`;
query(string);
})
}
// function for adding new departments with Inquirer
const department = () => {
inquirer.prompt({
name: 'name',
type: 'input',
message: `What is the name for the new department?`
})
.then((answers) => {
let string = `
insert into department (name)
values ('${answers.name}');
`;
query(string);
})
}
// function which prompts the user for what action they should take
const start = () => {
inquirer
.prompt({
name: 'home',
type: 'list',
message: 'What would you like to do?',
choices: [
'View All Employees',
'View All Employees by Department',
'View All Employees by Manager',
'Add Employee',
//'Remove Employee',
'Update Employee Role',
'Update Employee Manager',
'View All Roles',
'Add Role',
//'Remove Role',
'Add Department',
//'Remove Department'
'Exit'
]})
.then((answers) => {
// based on their answer, perform basic CRUD operations using CLI
switch(answers.home){
case 'View All Employees': {
query(queries.a);
} break;
case 'View All Employees by Department': {
query(queries.b);
} break;
case 'View All Employees by Manager': {
query(queries.c);
} break;
case 'Add Employee': {
employee();
} break;
//case 'Remove Employee': {} break;
case 'Update Employee Role': {
employeeRole();
} break;
case 'Update Employee Manager': {
employeeManager();
} break;
case 'View All Roles': {
query(queries.d);
} break;
case 'Add Role': {
role();
} break;
//case 'Remove Role': {} break;
case 'Add Department': {
department();
} break;
//case 'Remove Department': {} break;
case 'Exit': {
return;
}
default: start();
}
return;
});
};
// creates ascii text art on startup
setTimeout(function() {
art.font("Employee", 'doom', (error, data) => console.log(data))
}, 0);
setTimeout(function() {
art.font("Management", 'doom', (error, data) => console.log(data))
}, 300);
setTimeout(function() {
art.font("System", 'doom', (error, data) => console.log(data))
}, 600);
setTimeout(function(){start()}, 900);<file_sep>/sql/seed.sql
insert into department (name)
values
("Operations"),
("Human Resources"),
("Finance"),
("Technology"),
("Marketing")
;
insert into role (title, salary, department_id)
values
("CEO", 500000, 1),
("CPO", 250000, 2),
("CFO", 250000, 3),
("CTO", 250000, 4),
("CMO", 250000, 5),
("Senior Executive", 200000, 1),
("HR Officer", 80000, 2),
("Accounting Specialist", 80000, 3),
("Support Specialist", 80000, 4),
("Ad Campaign Manager", 100000, 5)
;
insert into employee (first_name, last_name, role_id, manager_id)
values
("Karyn", "Workman", 1, null),
("Gretchen", "Skinner", 2, 1),
("Hop", "Thompson", 3, 1),
("Thor", "Bowers", 4, 1),
("Yetta", "Craft", 5, 1),
("Samson", "Golden", 6, 1),
("Macey", "Carter", 7, 2),
("Carl", "Salinas", 8, 3),
("Fay", "Lewis", 9, 4),
("Craig", "Shaffer", 10, 5),
("Astra", "Houston", 6, 1),
("Flynn", "Lawson", 7, 2),
("Lila", "Hyde", 8, 3),
("Alma", "Tillman", 8, 3),
("Akeem", "George", 8, 3),
("Sigourney", "Hampton", 9, 4),
("Amber", "Ortiz", 9, 4),
("Tyrone", "Acevedo", 9, 4),
("Elvis", "Munoz", 10, 5)
;<file_sep>/README.md
# Employee Management System
[](https://opensource.org/licenses/MIT)
## Description
Utilizes MySQL to manage employee data with the CLI.
## Demo Video
[](https://vimeo.com/577431628 "EMS Demonstration Video")
## Database Schema

## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Contributions](#contributions)
- [Testing](#testing)
- [License](#license)
## Installation
Requires Node, Inquirer, and MySQL in order to run.
## Usage
Allows simplified employee data management with inquirer-based menus in the CLI.
## Contributions
To suggest changes, please submit all requests by email.
### <EMAIL>
### https://github.com/BrettMarkland-Sanchez
## Testing
There are currently no predefined tests for this project.
## License
Copyright © <NAME>. All rights reserved.
Licensed under the MIT license.
Find a copy of this license here:
https://opensource.org/licenses/MIT
| 582e9cf864b881f8a0d6e14a6067d7127afa0c98 | [
"JavaScript",
"SQL",
"Markdown"
] | 3 | JavaScript | BrettMarkland-Sanchez/employee-management-system | b4634dca8c90ff1aa1076c3f4e9d3e6f67a14de4 | c5d372a56c09bd7ab87469ff0e8925de266dc96b |
refs/heads/master | <repo_name>kad15/SYSTEMES_REPARTIS<file_sep>/2018/bck/Correction TP DéploiementMobilité/AgentPiCorrection/AgentTourisk.java
import org.javact.util.ActorProfile;
public interface AgentTourisk extends ActorProfile, Recherche, Superviseur, Afficheur {
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/SelectAllAction.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;
import org.javact.plugin.debug.ActorDebug;
/**
* This class represents the action "SelectAll"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class SelectAllAction extends Action {
//~ Instance fields --------------------------------------------------------
private TableViewer tableViewer;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new SelectAllAction object.
*
* @param _tableViewer the TableViewer of the selection
*/
public SelectAllAction(TableViewer _tableViewer) {
tableViewer = _tableViewer;
setText("Select All");
}
//~ Methods ----------------------------------------------------------------
/**
* @see Action#run()
*/
public void run() {
TableItem[] items = tableViewer.getTable().getItems();
for (int i = 0; i < items.length; i++) {
items[i].setChecked(true);
((ActorDebug) items[i].getData()).setIsChecked(true);
}
}
}
<file_sep>/2019/TP/javact2019/.metadata/version.ini
#Wed Jan 23 13:36:24 CET 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.1.v20160907-1200
<file_sep>/BCK/JavAct/workspace_javact/.metadata/version.ini
#Tue Jan 09 14:21:57 CET 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.1.v20160907-1200
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/tools/JavActUtilities.java
package org.javact.plugin.tools;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JarPackageFragmentRoot;
import org.eclipse.jdt.internal.ui.packageview.ClassPathContainer;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.javact.plugin.JavActPlugin;
import org.javact.plugin.views.JVMView;
import org.osgi.framework.Bundle;
/**
* Usefull static methods for the plugin
*
* @author <NAME>, <NAME>, <NAME>
* @version $Revision: 1.1 $
*/
public class JavActUtilities {
//~ Static fields/initializers ---------------------------------------------
// the selected javact project (null if no selection or if the selected project is not a javactproject)
public static IJavaProject javaProject;
// currently running JVM
public static HashMap processJVM = new HashMap();
public static IJavaProject javaProjectDebug;
//~ Methods ----------------------------------------------------------------
/**
* Finds a file within a plugin.
*
* @param pluginId the id of the plugin
* @param fileName the name of the file
* @return the path to the file of null, if not found
* @throws IOException will be raised in problem accessing ressource
*/
public static IPath findFileInPlugin(String pluginId, String fileName) {
// get the bundle and its location
Bundle theBundle = Platform.getBundle(pluginId);
if (theBundle == null) {
warning("Find in Plugin", "Could not find " + pluginId + " plugin");
return null;
}
// get an entry in bundle as URL, will return bundleentry://nnn/...
// resolve the entry as an URL, typically file://...
URL theFileAsEntry = theBundle.getEntry(fileName);
if (theFileAsEntry == null) {
return null;
}
try {
URL resEntry = Platform.resolve(theFileAsEntry);
if (resEntry == null) {
warning("Find in Plugin",
"Could not find the file " + fileName + " in " + pluginId);
return null;
}
// convert from URL to an IPath
IPath thePath = new Path(new File(resEntry.getFile()).getAbsolutePath());
return thePath;
} catch (IOException ex) {
warning("Find in Plugin",
"Unable to find the file " + fileName + " in the plugin " +
pluginId, ex);
return null;
}
}
/**
* Shows an error popup message and write the exception stack trace in the .log file
*
* @param title the title of the popup
* @param texte the text of the error
* @param ex the exception causing the error
*/
public static void error(String title, String texte, Exception ex) {
// create the popup
MessageDialog.openError(new Shell(), title,
texte + " :\n\n" + ex.toString() +
"\n (detailed information in .log file)");
// write the error in the log
editLog(title, texte, ex);
}
/**
* Writes an error in the .log file
*
* @param title the title of the error
* @param texte the content of the error
* @param ex the exception which caused the error
*/
public static void editLog(String title, String texte, Exception ex) {
// the .metadata folder
String metadataFolder = ResourcesPlugin.getWorkspace().getRoot()
.getLocation().toOSString() +
File.separator + ".metadata" + File.separator;
try {
// write the stack trace of the exception at the end of the .log file
FileOutputStream fos = new FileOutputStream(metadataFolder +
".log", true);
OutputStreamWriter writer = new OutputStreamWriter(fos);
writer.write(title + "\n" + texte + " :\n" + ex.getMessage());
writer.close();
} catch (FileNotFoundException e) {
error("Creating error .log file",
"Unable to open the .log file in " + metadataFolder + " : " +
e.toString());
} catch (IOException e) {
error("Writing error in .log file",
"Unable to write in the .log file :\n" + e.toString());
}
}
/**
* Shows an error popup message
*
* @param title the title of the popup
* @param text the text of the error
*/
public static void error(String title, String text) {
MessageDialog.openError(new Shell(), title, text);
}
/**
* Shows a warning popup message with an exception
*
* @param title the title of the popup
* @param text the text of the error
* @param ex the exception causing the error
*/
public static void warning(String title, String text, Exception ex) {
MessageDialog.openWarning(new Shell(), title,
text + " :\n\n" + ex.toString());
}
/**
* Shows a warning popup message
*
* @param title the title of the popup
* @param text the text of the warning
*/
public static void warning(String title, String text) {
MessageDialog.openWarning(new Shell(), title, text);
}
/**
* Show an information popup message
*
* @param title the title of the popup
* @param text the text of the information
*/
public static void notify(String title, String text) {
MessageDialog.openInformation(new Shell(), title, text);
}
/**
* Find all the .java files in the project
*
* @param project Project in which we must find .java files
*
* @return Array of .java file names
*
* @throws CoreException when the project isn't open or doesn't exist
*/
public static String[] getJavaFiles(IProject project)
throws CoreException {
Vector javaFiles = new Vector();
String[] arrayJavaFiles = null;
findJavaFiles(project.members(), javaFiles);
arrayJavaFiles = new String[javaFiles.size()];
for (int i = 0; i < arrayJavaFiles.length; i++) {
arrayJavaFiles[i] = (String) javaFiles.elementAt(i);
}
return arrayJavaFiles;
}
/**
* Recursive method to find .java files in the array of IResource
*
* If the IResource is an IFile, we add its path in the vector.
* If the IResource is an IFolder, we get the IResource[] from this IFolder
* and we relaunch the method on this new array and the vector.
* At the end, all the .java files path are stored in the vector.
*
* @param resources Array of resources (IFile and IFolder)
* @param javaFiles Vector in which were stored found .java files
*
* @throws CoreException when the resources don't exist
*/
private static void findJavaFiles(IResource[] resources, Vector javaFiles)
throws CoreException {
for (int i = 0; i < resources.length; i++) {
if (resources[i].getType() == IResource.FOLDER) {
findJavaFiles(((IFolder) resources[i]).members(), javaFiles);
} else if (resources[i].getType() == IResource.FILE) {
String fileExt = ((IFile) resources[i]).getFileExtension();
if (fileExt != null) {
if (fileExt.equals("java")) {
javaFiles.add(resources[i].getLocation().toOSString());
}
}
} else {
throw new CoreException(new Status(IStatus.ERROR, "JavAct", 0,
"Wrong ressource", null));
}
}
}
/**
* Creates the file places.txt at the root of the project with a default content
*
* @param aProject the project in which the file must be created
*/
public static void createDefaultPlaces(IProject aProject) {
final IFile placesFile = aProject.getFile(new Path("places.txt"));
InputStream placesStream;
// the file containing the default content of places.txt
String placesDefault = JavActUtilities.findFileInPlugin("JavAct",
JavActPlugin.pathPlaces).toOSString();
try {
placesStream = new FileInputStream(placesDefault);
} catch (FileNotFoundException e) {
JavActUtilities.error("places.txt creation",
"Default configuration file places.txt was not found in " +
placesDefault + " an empty file will be created", e);
// the file will be empty
placesStream = new ByteArrayInputStream("".getBytes());
}
try {
if (placesFile.exists()) {
placesFile.setContents(placesStream, true, true, null);
} else {
placesFile.create(placesStream, true, null);
}
placesStream.close();
} catch (CoreException e) {
JavActUtilities.error("places.txt creation",
"Can't write the file places.txt, please create it in the workspace and add places where JVM are to be launched",
e);
} catch (IOException e) {
JavActUtilities.error("places.txt creation",
"Can't close the file places.txt, please create it in the workspace and add places where JVM are to be launched",
e);
}
}
/**
* Creates the file awfullpolicy at the root of the project with a default content
*
* @param aProject the project in which the file must be created
*/
public static void createDefaultPolicy(IProject aProject) {
final IFile policyFile = aProject.getFile(new Path("awfullPolicy"));
InputStream policyStream;
// the file containing the default content of awfullPolicy
String policyDefault = JavActUtilities.findFileInPlugin("JavAct",
JavActPlugin.pathAwfullpolicy).toOSString();
try {
policyStream = new FileInputStream(policyDefault);
} catch (FileNotFoundException e) {
JavActUtilities.error("awfullPolicy creation",
"Default configuration file awfullPolicy was not found in " +
policyDefault + " an empty file will be created", e);
// the file will be empty
policyStream = new ByteArrayInputStream("".getBytes());
}
try {
if (policyFile.exists()) {
policyFile.setContents(policyStream, true, true, null);
} else {
policyFile.create(policyStream, true, null);
}
policyStream.close();
} catch (CoreException e) {
JavActUtilities.error("awfullPolicy creation",
"Can't write the file awfullPolicy", e);
} catch (IOException e) {
JavActUtilities.error("awfullPolicy creation",
"Can't close the file awfullPolicy", e);
}
}
/**
* Parses the places.txt file and launch a JVM on each local place specified in this file
*
* @param project the project for which the JVM are launched
*/
public static final void launchLocalJVM(IProject project) {
Cursor cursor = new Cursor(null, SWT.CURSOR_WAIT);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
.setCursor(cursor);
String projectPath = project.getLocation().toOSString();
String projectName = project.getName();
String awfullPolicyPath = projectPath + File.separator +
"awfullPolicy";
// Verifying if awfullPolicy exists for the project
try {
BufferedReader test = new BufferedReader(new FileReader(
awfullPolicyPath));
// Test passed, closing the buffer
test.close();
} catch (FileNotFoundException e) {
error("Launch local JVM",
"File " + awfullPolicyPath +
" not found, a new awfullPolicy file will be created with the default policy",
e);
createDefaultPolicy(project);
return;
} catch (IOException e) {
error("Launch local JVM",
"IO exception while accessing the file " + awfullPolicyPath, e);
return;
}
// researching local places in places.txt
Vector foundPlaces = null;
try {
foundPlaces = parsePlacesLocal(project);
} catch (FileNotFoundException e) {
error("Places.txt parsing",
"File places.txt not found, a new file places.txt with default content will be created",
e);
createDefaultPlaces(project);
return;
} catch (IOException e) {
error("Places.txt parsing", "Error while reading places.txt", e);
return;
}
Iterator iter = foundPlaces.iterator();
/*System.out.println("Searching not JVM launched local places in places.txt ...");
while (iter.hasNext()) {
System.out.println(iter.next().toString() +
" found in places.txt");
}
System.out.println("Testing if the ports are free ...");
*/
iter = foundPlaces.iterator();
String error = "";
Place place;
TestPlace testPlace;
Vector testPlaces = new Vector();
// Launching threads that will test is the ports are free
while (iter.hasNext()) {
place = (Place) iter.next();
testPlace = new TestPlace(place);
testPlaces.add(testPlace);
testPlace.start();
}
// create the view for the JVM
JVMView jvmView = null;
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
if (window != null) {
try {
jvmView = (JVMView) window.getActivePage()
.showView(JVMView.ID,
project.getName(), IWorkbenchPage.VIEW_VISIBLE);
} catch (PartInitException e) {
error("Launch Local JVM", "Error while creating JVMView", e);
return;
}
} else {
error("Launch Local JVM", "Can't find the active workbench window",
null);
}
// Retrieving the results of the threads launched above
iter = testPlaces.iterator();
JVMLauncher jvml;
while (iter.hasNext()){
testPlace = (TestPlace) iter.next();
try {
// wait for the thread to finish
testPlace.join();
} catch (InterruptedException e) {
error += e.getMessage();
}
if (!testPlace.isFree()) {
error += ("Port " + testPlace.getPlace().getPort() +
" is not free on localhost\n");
} else {
// The port is free : launching the JVM
jvml = new JVMLauncher(project, testPlace.getPlace(), jvmView);
jvml.run();
processJVM.put(projectName + ":" + testPlace.getPlace().getPort(), jvml);
}
}
if (!error.equalsIgnoreCase("")) {
error("Port free test", error);
}
cursor.dispose();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
.getShell().setCursor(null);
}
/**
* Test if the JVM specified in places.txt (local and distant) are launched.
* return a string which contains the list of the errors.
* Changes the cursor while processing.
*
* @param jProject the project for which the test is done
*
* @return the string containing errors
*/
public static String testJVMButton(IJavaProject jProject) {
return testJVM(jProject, true);
}
/**
* Test if the JVM specified in places.txt (local and distant) are launched.
* return a string which contains the list of the errors.
* Changes the cursor while processing.
*
* @param jProject the project for which the test is done
*
* @return the string containing the errors
*/
public static String testJVMLaunch(IJavaProject jProject) {
return testJVM(jProject, false);
}
/**
* Test if the JVM specified in places.txt (local and distant) are launched.
* return a string which contains the list of the errors.
* Changes the cursor while processing is hourGlass is true.
*
* @param jProject the project for which the test is done
*
* @return the string containing the errors
*/
public static String testJVM(IJavaProject jProject, boolean hourGlass) {
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
// get the current cursor
final Cursor[] cursor = new Cursor[1];
Cursor oldCursor = cursor[0];
if (hourGlass) {
// change the cursor during the test
// no available before the launch (window.getShell() == null)
cursor[0] = new Cursor(null, SWT.CURSOR_WAIT);
window.getShell().setCursor(cursor[0]);
}
IProject project = jProject.getProject();
Vector foundPlaces = null;
String error = "";
try {
// parse places.txt to get a vector of all places
foundPlaces = parsePlacesAll(project, !hourGlass);
} catch (FileNotFoundException e) {
createDefaultPlaces(project);
error += "File places.txt not found, a new file places.txt with default content will be created\n";
} catch (IOException e) {
error += "Error while parsing places.txt\n";
}
Iterator iter = foundPlaces.iterator();
Vector launchedPlaces = new Vector();
TestPlace testPlace;
while (iter.hasNext()) {
// create and run a thread which will test if the place is used or not
testPlace = new TestPlace((Place) iter.next());
testPlace.start();
launchedPlaces.add(testPlace);
}
iter = launchedPlaces.iterator();
while (iter.hasNext()) {
testPlace = (TestPlace) iter.next();
try {
// wait for the thread to finish
testPlace.join();
} catch (InterruptedException e) {
error += e.getMessage();
}
if (testPlace.isFree()) {
error += ("There is no JVM launched on " + testPlace.getPlace().getHost() +
":" + testPlace.getPlace().getPort() + "\n");
}
}
// put the old cursor back
if (hourGlass) {
cursor[0].dispose();
window.getShell().setCursor(oldCursor);
}
return error;
}
/**
* Called when closing eclipse to kill all the JVM launched wherever the current project
*/
public static final void killAllLocalJVM() {
int numberJVMLaunched = processJVM.size();
int numberJVMKilled = 0;
String port;
Iterator keyIterator = processJVM.keySet().iterator();
System.out.println("\nKilling all JVM on local places ...");
if (numberJVMLaunched > 1) {
System.out.println(numberJVMLaunched +
" JVM launched by JavAct Plugin are still alive");
} else {
System.out.println(numberJVMLaunched +
" JVM launched by JavAct Plugin is still alive");
}
while (keyIterator.hasNext()) {
port = (String) keyIterator.next();
((JVMLauncher) processJVM.get(port)).destroy();
numberJVMKilled++;
}
if (numberJVMLaunched > 0) {
System.out.println("Result : " + numberJVMKilled + " JVM killed\n");
}
processJVM.clear();
}
/**
* Returns all the entries of the hashmap that correspond to the project
*
* @param projectName the project for which the the entries are selected
*
* @return the hashmap with only the selected entries
*/
public static final Vector getKeys(String projectName) {
Vector keys = new Vector();
String key;
Iterator keyIterator = processJVM.keySet().iterator();
while (keyIterator.hasNext()) {
key = (String) keyIterator.next();
if (key.startsWith(projectName + ":")) {
keys.add(key);
}
}
return keys;
}
/**
* Kill all the JVM lauched for the project when closing the project's JVMView
*
* @param projectName the projet for which the JVM will be closed
*/
public static final void killLocalProjectJVM(String projectName) {
String key;
System.out.println("\nKilling " + projectName +
" JVM on local places ...");
// get the key for the current project
Vector keyToRemove = getKeys(projectName);
Iterator keyToRemoveIterator = keyToRemove.iterator();
Vector vecWellKilled = new Vector();
while (keyToRemoveIterator.hasNext()) {
key = (String) keyToRemoveIterator.next();
removeLocalJVM(key);
// to check if the port is free
vecWellKilled.add(new TestWellKilled(Integer.parseInt(
key.split(":")[1])));
}
String warning = "";
// we must assure that the port are free when the method finishes
for (int i = 0; i < vecWellKilled.size(); i++) {
try {
((TestWellKilled) vecWellKilled.elementAt(i)).join();
} catch (InterruptedException e) {
// if the thread is interrupted we can't assure that the port is free
warning = "The thread was interrupted please wait 5 seconds please before closing this dialog";
}
}
if (warning != "") {
warning("Killing JVM", warning);
}
}
/**
* Kill all the JVM lauched for the project when clicking Kill JVM
*
* @param projectName the projet for which the JVM will be closed
*/
public static final void killLocalProjectJVMfromButton(String projectName) {
Cursor cursor = new Cursor(null, SWT.CURSOR_WAIT);
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
window.getShell().setCursor(cursor);
JVMView jvmView = null;
// get the running jvm for this project
Vector keyToRemove = getKeys(projectName);
String key;
if (window != null) {
try {
// hide the JVm vue of this project
jvmView = (JVMView) window.getActivePage()
.showView(JVMView.ID, projectName,
IWorkbenchPage.VIEW_CREATE);
window.getActivePage().hideView(jvmView);
} catch (PartInitException e) {
error("", "Error while hiding JVMView", e);
}
Iterator keyToRemoveIterator = keyToRemove.iterator();
Vector vecWellKilled = new Vector();
TestWellKilled t;
while (keyToRemoveIterator.hasNext()) {
key = (String) keyToRemoveIterator.next();
t = new TestWellKilled(Integer.parseInt(key.split(":")[1]));
vecWellKilled.add(t);
t.start();
}
String warning = "";
for (int i = 0; i < vecWellKilled.size(); i++) {
try {
((TestWellKilled) vecWellKilled.elementAt(i)).join();
} catch (InterruptedException e) {
// if the thread is interrupted we can't assure that the port is free
warning = "The thread was interrupted please wait 5 seconds please before closing this dialog";
}
}
if (warning != "") {
warning("Killing JVM", warning);
}
} else {
error("", "Can't find the active workbench window", null);
}
cursor.dispose();
window.getShell().getShell().setCursor(null);
}
/**
* Kills only one JVM
*
* @param key the key in the Hashmap of the JVM to kill
*/
public static final void removeLocalJVM(String key) {
((JVMLauncher) processJVM.get(key)).destroy();
processJVM.remove(key);
}
/**
* Gets the selected java project
*
* @param sel the selection
*
* @return the selected java project
*/
public static IJavaProject getIJavaProjectFromSelection(ISelection sel) {
IJavaProject javaProject = null;
if (sel instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) sel;
Object object = structuredSelection.getFirstElement();
if ((object != null) && (object instanceof ClassPathContainer)) {
javaProject = ((ClassPathContainer) object).getJavaProject();
} else if ((object != null) &&
(object instanceof JarPackageFragmentRoot)) {
javaProject = ((JarPackageFragmentRoot) object).getJavaProject();
} else if ((object != null) && (object instanceof IAdaptable)) {
IResource resource = (IResource) ((IAdaptable) object).getAdapter(IResource.class);
javaProject = getIJavaProjectContaining(resource);
}
if (!isJavActProject(javaProject)) {
javaProject = null;
}
}
return javaProject;
}
/**
* Find the javAct project (a JavAct project is a java project containing a .genConfig file) containing the resource in parameter
* return null if it's not a JavAct project or if the resource can't be found
*
* @param res the ressource
*
* @return the found JavAct project or null
*/
public static IJavaProject getIJavaProjectContaining(IResource res) {
IJavaProject foundProject = null;
IJavaProject tmpProject = null;
String javaProjectPath;
IJavaProject[] javaProjects;
try {
javaProjects = JavaCore.create(ResourcesPlugin.getWorkspace()
.getRoot())
.getJavaProjects();
int i = 0;
while ((i < javaProjects.length) && (foundProject == null)) {
tmpProject = javaProjects[i];
javaProjectPath = tmpProject.getProject().getLocation()
.toOSString();
if (res.getLocation().toOSString().startsWith(javaProjectPath)) {
foundProject = tmpProject;
}
i++;
}
} catch (JavaModelException e) {
error("Internal eror",
"Unable to find the projects in the workspace", e);
}
return foundProject;
}
/**
* Return true if the project is a JavAct project
*
* @param aProject the project
*
* @return true if the project is a JavAct project
*/
private static boolean isJavActProject(IJavaProject aProject) {
if (aProject != null) {
return aProject.getProject().getFile(new Path(".genConfig")).exists();
} else {
return false;
}
}
/**
* Parse the file places.txt and return all the JVM
*
* @param aProject The project which JVM have to be tested
*
* @return All the machines of places.txt in a Vector of Place
*
* @throws FileNotFoundException
* @throws IOException
*/
public static Vector parsePlacesAll(IProject aProject, boolean isRun)
throws FileNotFoundException, IOException {
return parsePlaces(aProject, false, isRun);
}
/**
* Parse the file places.txt and return all the local JVM
*
* @param aProject The project which JVM have to be tested
*
* @return All the local machines of places.txt in a Vector of Place
*
* @throws FileNotFoundException
* @throws IOException
*/
public static Vector parsePlacesLocal(IProject aProject)
throws FileNotFoundException, IOException {
return parsePlaces(aProject, true, false);
}
/**
* Parse the file places.txt and return all the JVM or only the local JVM
* depending on the localParse value
*
* @param aProject The project which JVM have to be tested
* @param localParse true if only local JVM has to be returned
* @param isRun true is the method is called during the "run"
*
* @return All the machines of places.txt in a Vector of Place according to localParse
*
* @throws FileNotFoundException
* @throws IOException
*/
private static Vector parsePlaces(IProject aProject, boolean localParse, boolean isRun)
throws FileNotFoundException, IOException {
String projectPath = aProject.getLocation().toOSString();
String placesFile = projectPath + File.separator + "places.txt";
Vector places = new Vector();
BufferedReader in = new BufferedReader(new FileReader(placesFile));
String s;
String error = "";
int index;
boolean debug;
String host;
int port;
Place place = null;
int indexSpace;
int indexTab;
while ((s = in.readLine()) != null) {
debug = false;
s = s.trim();
if ((s.length() != 0) && (!s.startsWith("#"))) {
// skip blanklines and lines starting with #
indexSpace = s.indexOf(" ");
indexTab = s.indexOf("\t");
if (indexSpace == -1){
index = indexTab;
} else if (indexTab == -1) {
index = indexSpace;
} else {
index = Math.min(indexTab, indexSpace);
}
if (index != -1) { // index always != 0 because of the s.trim()
debug = s.substring(index).trim().equalsIgnoreCase("debug");
s = s.substring(0,index);
}
// if no port defined : defaut rmi port (1099)
int i = s.indexOf(":");
if (i == -1) {
place = new Place(s, 1099, debug);
} else {
host = s.substring(0,i);
try {
port = Integer.parseInt(s.substring(i+1));
if ((port < 1099) || (port > 65535)) {
error += "Error in " + s + " : port out of range\n";
} else {
place = new Place(host, port, debug);
}
} catch (NumberFormatException e) {
error += "Error in " + s + " : " + s.substring(i+1) + " is not a well typed port\n";
}
}
if (place != null) {
if (!places.contains(place)) {
if (!localParse) {
places.add(place);
} else if (place.getHost().equals("localhost") || place.getHost().equals("127.0.0.1")) {
places.add(place);
}
}
}
}
}
in.close();
if (!isRun && error != "") {
error("places.txt Parse", error);
}
return places;
}
}
<file_sep>/BCK/workspace_javact_Version_utilisee_sur_fedora/AgentPi/Recherche.java
import org.javact.util.ActorProfile;
import org.javact.util.BehaviorProfile;
import org.javact.util.StandAlone;
public interface Recherche extends BehaviorProfile, StandAlone {
public void become(Superviseur beh);
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/actions/ActionLaunchJVMLocal.java
package org.javact.plugin.actions;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
import org.eclipse.ui.PlatformUI;
import org.javact.plugin.JavActPlugin;
import org.javact.plugin.tools.JavActUtilities;
/**
* This class represents the action button "Launch JVM Local"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class ActionLaunchJVMLocal implements IWorkbenchWindowPulldownDelegate {
//~ Constructors -----------------------------------------------------------
/**
* The constructor.
*/
public ActionLaunchJVMLocal() {
super();
}
//~ Methods ----------------------------------------------------------------
/**
* @see org.eclipse.ui.IActionDelegate#run
*/
public void run(IAction action) {
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
Cursor cursor = new Cursor(null, SWT.CURSOR_WAIT);
window.getShell().setCursor(cursor);
// the SelectionChanged method from the ActionJavActGen class assure that JavActUtilities.javaProject is the selected project
IJavaProject javaProject = JavActUtilities.javaProject;
if (javaProject != null) {
JavActUtilities.killLocalProjectJVMfromButton(javaProject.getProject()
.getName());
JavActUtilities.launchLocalJVM(javaProject.getProject());
} else {
JavActUtilities.warning("Launch JVM",
"A JavAct project must be selected before launching JVM");
}
cursor.dispose();
window.getShell().getShell().setCursor(null);
}
/**
* @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
JavActUtilities.javaProject = JavActUtilities.getIJavaProjectFromSelection(selection);
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose
*/
public void dispose() {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init
*/
public void init(IWorkbenchWindow window) {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowPulldownDelegate#getMenu
*/
public Menu getMenu(Control parent) {
Menu m = new Menu(parent);
ActionContributionItem aci = new ActionContributionItem(new ActionKillJVMLocal());
aci.getAction().setText("Kill JVM on the localhost");
aci.getAction()
.setImageDescriptor(JavActPlugin.getImageDescriptor(
"icons/killjvm.gif"));
aci.fill(m, -1);
ActionContributionItem aci2 = new ActionContributionItem(new ActionTestAllJVM());
aci2.getAction().setText("Test the JVM of places.txt");
aci2.getAction()
.setImageDescriptor(JavActPlugin.getImageDescriptor(
"icons/testjvm.gif"));
aci2.fill(m, -2);
return m;
}
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/JavActPlugin.java
package org.javact.plugin;
import java.io.File;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.javact.plugin.tools.JavActUtilities;
import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class JavActPlugin extends AbstractUIPlugin {
//~ Static fields/initializers ---------------------------------------------
//The shared instance.
private static JavActPlugin plugin;
public final static String pathJAR = "lib" + File.separator + "javact.jar";
public final static String pathPlaces = "lib" + File.separator + "places.txt";
public final static String pathAwfullpolicy = "lib" + File.separator + "awfullPolicy";
//~ Constructors -----------------------------------------------------------
/**
* The constructor.
*/
public JavActPlugin() {
plugin = this;
}
//~ Methods ----------------------------------------------------------------
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
// kill all the launched JVM
JavActUtilities.killAllLocalJVM();
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static JavActPlugin getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given
* plug-in relative path.
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return AbstractUIPlugin.imageDescriptorFromPlugin("JavAct", path);
}
}
<file_sep>/2018/bck/javact_workspace/.metadata/version.ini
#Tue Jan 16 08:33:40 CET 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.1.v20160907-1200
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/tools/TestWellKilled.java
package org.javact.plugin.tools;
/**
* This class is used to test if a port is free on the localhost.
* When the JVM are killed, we create an instance of this class
* and we wait for the end of the execution of the run() method
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class TestWellKilled extends Thread {
//~ Instance fields --------------------------------------------------------
private int port;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new TestWellKilled object.
*
* @param _port the port to test
*/
public TestWellKilled(int _port) {
super();
port = _port;
}
//~ Methods ----------------------------------------------------------------
/**
* Launches the test
* If the test is false after 15 seconds, we return an error
*/
public void run() {
boolean correct = false;
TestPlace tp;
int timeout = 15000; //we configure a timeout of 15 seconds
int timeElapsed = 0;
while (!correct && timeElapsed<timeout) {
try {
Thread.sleep(50);
timeElapsed += 50;
tp = new TestPlace(new Place("localhost", port, false));
tp.start();
tp.join();
if (tp.isFree()) {
correct = true;
}
} catch (InterruptedException e) {
JavActUtilities.error("Kill JVM","A problem occurs when testing the JVM kill on localhost:"+port,e);
e.printStackTrace();
}
}
if(!correct)
JavActUtilities.error("Kill JVM","The JVM kill on localhost:" + port + " can't be killed after 15 seconds");
}
}
<file_sep>/2018/bck/JavAct/javactkillall.sh~
#!/bin/bash
CMD="~lerichse/stopJavActVM $1"
ROOM=d1-205
for ((i = 1; i < 10; i++))
do
echo "Fermeture de JavAct sur $ROOM-0$i..."
ssh $ROOM-0$i $CMD &
done
for ((i = 10; i <= 22; i++))
do
echo "Fermeture de JavAct sur $ROOM-1$i..."
ssh $ROOM-$i $CMD &
done
<file_sep>/BCK/javact_workspace/TP_JAVACT/Superviseur.java
import org.javact.util.BehaviorProfile;
public interface Superviseur extends BehaviorProfile {
public void become(Afficheur beh);
}
<file_sep>/2018/bck/Test/TouriskQuasiBehavior.java
import org.javact.lang.QuasiBehavior;
public abstract class TouriskQuasiBehavior extends QuasiBehavior implements Tourisk
{
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/tools/TestPlace.java
package org.javact.plugin.tools;
import java.io.IOException;
import java.net.Socket;
/**
* This class is used to test if a place is free or not
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class TestPlace extends Thread {
//~ Instance fields --------------------------------------------------------
/**
* DOCUMENT ME!
*/
private Place place;
/**
* DOCUMENT ME!
*/
private boolean isFree;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new TestPlace object.
*
* @param _place the hostname of the place to test
*/
public TestPlace(Place _place) {
super();
place = _place;
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*/
public void run() {
try {
Socket socket = new Socket(place.getHost(), place.getPort());
socket.close();
isFree = false;
} catch (IOException e) {
// There is nothing on this port
isFree = true;
}
}
/**
* Return true if the place is free after the test Have no sens if the test
* (run) isn't called before
*
* @return true if the place is free else false
*/
public boolean isFree() {
return isFree;
}
/**
* Gets the place where the JVM is launched
*
* @return the place
*/
public Place getPlace() {
return place;
}
}
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/MethodsToShowAction.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
import org.javact.plugin.JavActPlugin;
import org.javact.plugin.actions.ActionDebug;
import org.javact.plugin.debug.Debug;
/**
* This class represents the action button "Parameters"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class MethodsToShowAction implements IWorkbenchWindowPulldownDelegate {
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ParametersAction object.
*/
public MethodsToShowAction() {
super();
}
//~ Methods ----------------------------------------------------------------
/**
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose
*/
public void dispose() {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init
*/
public void init(IWorkbenchWindow window) {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowPulldownDelegate#getMenu(org.eclipse.swt.widgets.Control)
*/
public Menu getMenu(Control parent) {
Menu m = new Menu(parent);
Debug d = ActionDebug.debug;
ImageDescriptor image = JavActPlugin.getImageDescriptor(
"icons/debug/checked.gif");
ActionContributionItem aci1 = new ActionContributionItem(new MethodToShowEventItem(
Debug.createLocalDebugTxt));
aci1.getAction().setText(Debug.createLocalDebugTxt);
if (d.getMethod(Debug.createLocalDebugTxt)) {
aci1.getAction().setImageDescriptor(image);
} else {
aci1.getAction().setImageDescriptor(null);
}
aci1.fill(m, -1);
ActionContributionItem aci2 = new ActionContributionItem(new MethodToShowEventItem(
Debug.createLocalFromControlerDebugTxt));
aci2.getAction().setText(Debug.createLocalFromControlerDebugTxt);
if (d.getMethod(Debug.createLocalFromControlerDebugTxt)) {
aci2.getAction().setImageDescriptor(image);
} else {
aci2.getAction().setImageDescriptor(null);
}
aci2.fill(m, -2);
ActionContributionItem aci3 = new ActionContributionItem(new MethodToShowEventItem(
Debug.goToTxt));
aci3.getAction().setText(Debug.goToTxt);
if (d.getMethod(Debug.goToTxt)) {
aci3.getAction().setImageDescriptor(image);
} else {
aci3.getAction().setImageDescriptor(null);
}
aci3.fill(m, -3);
ActionContributionItem aci4 = new ActionContributionItem(new MethodToShowEventItem(
Debug.sendTxt));
aci4.getAction().setText(Debug.sendTxt);
if (d.getMethod(Debug.sendTxt)) {
aci4.getAction().setImageDescriptor(image);
} else {
aci4.getAction().setImageDescriptor(null);
}
aci4.fill(m, -4);
ActionContributionItem aci5 = new ActionContributionItem(new MethodToShowEventItem(
Debug.sendWithReplyTxt));
aci5.getAction().setText(Debug.sendWithReplyTxt);
if (d.getMethod(Debug.sendWithReplyTxt)) {
aci5.getAction().setImageDescriptor(image);
} else {
aci5.getAction().setImageDescriptor(null);
}
aci5.fill(m, -5);
ActionContributionItem aci6 = new ActionContributionItem(new MethodToShowEventItem(
Debug.mailBoxTxt));
aci6.getAction().setText(Debug.mailBoxTxt);
if (d.getMethod(Debug.mailBoxTxt)) {
aci6.getAction().setImageDescriptor(image);
} else {
aci6.getAction().setImageDescriptor(null);
}
aci6.fill(m, -6);
ActionContributionItem aci7 = new ActionContributionItem(new MethodToShowEventItem(
Debug.becomeTxt));
aci7.getAction().setText(Debug.becomeTxt);
if (d.getMethod(Debug.becomeTxt)) {
aci7.getAction().setImageDescriptor(image);
} else {
aci7.getAction().setImageDescriptor(null);
}
aci7.fill(m, -7);
ActionContributionItem aci8 = new ActionContributionItem(new MethodToShowEventItem(
Debug.suicideTxt));
aci8.getAction().setText(Debug.suicideTxt);
if (d.getMethod(Debug.suicideTxt)) {
aci8.getAction().setImageDescriptor(image);
} else {
aci8.getAction().setImageDescriptor(null);
}
aci8.fill(m, -8);
ActionContributionItem aci9 = new ActionContributionItem(new MethodToShowEventItem(
Debug.createDebug1Txt));
aci9.getAction().setText(Debug.createDebug1Txt);
if (d.getMethod(Debug.createDebug1Txt)) {
aci9.getAction().setImageDescriptor(image);
} else {
aci9.getAction().setImageDescriptor(null);
}
aci9.fill(m, -9);
ActionContributionItem aci10 = new ActionContributionItem(new MethodToShowEventItem(
Debug.createDebug2Txt));
aci10.getAction().setText(Debug.createDebug2Txt);
if (d.getMethod(Debug.createDebug2Txt)) {
aci10.getAction().setImageDescriptor(image);
} else {
aci10.getAction().setImageDescriptor(null);
}
aci10.fill(m, -10);
ActionContributionItem aci11 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withBoxTxt));
aci11.getAction().setText(Debug.withBoxTxt);
if (d.getMethod(Debug.withBoxTxt)) {
aci11.getAction().setImageDescriptor(image);
} else {
aci11.getAction().setImageDescriptor(null);
}
aci11.fill(m, -11);
ActionContributionItem aci12 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withBecTxt));
aci12.getAction().setText(Debug.withBecTxt);
if (d.getMethod(Debug.withBecTxt)) {
aci12.getAction().setImageDescriptor(image);
} else {
aci12.getAction().setImageDescriptor(null);
}
aci12.fill(m, -12);
ActionContributionItem aci13 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withCrtTxt));
aci13.getAction().setText(Debug.withCrtTxt);
if (d.getMethod(Debug.withCrtTxt)) {
aci13.getAction().setImageDescriptor(image);
} else {
aci13.getAction().setImageDescriptor(null);
}
aci13.fill(m, -13);
ActionContributionItem aci14 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withMveTxt));
aci14.getAction().setText(Debug.withMveTxt);
if (d.getMethod(Debug.withMveTxt)) {
aci14.getAction().setImageDescriptor(image);
} else {
aci14.getAction().setImageDescriptor(null);
}
aci14.fill(m, -14);
ActionContributionItem aci15 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withSndTxt));
aci15.getAction().setText(Debug.withSndTxt);
if (d.getMethod(Debug.withSndTxt)) {
aci15.getAction().setImageDescriptor(image);
} else {
aci15.getAction().setImageDescriptor(null);
}
aci15.fill(m, -15);
ActionContributionItem aci16 = new ActionContributionItem(new MethodToShowEventItem(
Debug.withLifTxt));
aci16.getAction().setText(Debug.withLifTxt);
if (d.getMethod(Debug.withLifTxt)) {
aci16.getAction().setImageDescriptor(image);
} else {
aci16.getAction().setImageDescriptor(null);
}
aci16.fill(m, -16);
return m;
}
}
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/actions/ActionJavActGen.java
package org.javact.plugin.actions;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
import org.javact.plugin.JavActPlugin;
import org.javact.plugin.properties.JavActGenConfiguration;
import org.javact.plugin.tools.ConsoleDisplayMgr;
import org.javact.plugin.tools.JavActUtilities;
import org.javact.plugin.tools.MessagePrinter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This class represents the action button "JavActGen..."
*
* @author <NAME>
* @version $Revision: 1.2 $
*/
public class ActionJavActGen implements IWorkbenchWindowPulldownDelegate {
//~ Methods ----------------------------------------------------------------
/**
* @see org.eclipse.ui.IActionDelegate#run
*/
public void run(IAction action) {
// We get the resource from the selection (SelectionChanged assure that JavActUtilities.javaProject is the selected project)
IJavaProject javaProject = JavActUtilities.javaProject;
if (javaProject != null) {
try {
// We get the project from the ressource
IProject project = javaProject.getProject();
new ConsoleDisplayMgr("JavActGen : " + project.getName());
if (project.isOpen()) {
// We get the project .java files
String[] arrayJavaFiles = JavActUtilities.getJavaFiles(project);
// We execute the generation
executeJavActGen(arrayJavaFiles, javaProject);
// We refresh the eclipse project path
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} else {
JavActUtilities.warning("JavActGen",
"The project is closed.\nYou must open it in order to launch JavActGen");
}
} catch (CoreException e) {
JavActUtilities.error("JavActGen",
"Unable to find .java files", e);
} catch (InterruptedException e) {
JavActUtilities.error("JavActGen",
"Error while generating files", e);
} catch (IOException e) {
JavActUtilities.error("JavActGen",
"Unable to run the javact generation", e);
}
} else {
JavActUtilities.warning("JavActGen",
"A JavAct project must be selected before launching JavActGen");
}
}
/**
* @see org.eclipse.ui.IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
JavActUtilities.javaProject = JavActUtilities.getIJavaProjectFromSelection(selection);
}
/**
* Execute the QuasiBehaviour, JAM and squeleton generation of the .java files
* in the specific directory
*
* @param javaFiles the String tab of java files in which find the actors
* @param javaProject the javact project linked with the generation
*/
private void executeJavActGen(String[] javaFiles, IJavaProject javaProject)
throws IOException, InterruptedException {
String projectPath = javaProject.getProject().getLocation().toOSString();
JavActGenConfiguration genConfig = JavActGenConfiguration.load(javaProject);
String[] options = new String[9];
options = genConfig.getOptions();
String[] cmdBegin = new String[14];
int indice;
// construct the command
if (System.getProperty("os.name").regionMatches(true, 0, "Windows", 0, 7)) {
// java -classpath projectPath;javactJarPath -v -generated-dir projectPath
cmdBegin[0] = "java";
cmdBegin[1] = "-classpath";
cmdBegin[2] = "\"" + projectPath + "\";\"" +
JavActUtilities.findFileInPlugin("JavAct", JavActPlugin.pathJAR)
.toOSString() + "\"";
cmdBegin[3] = "org.javact.compiler.Main";
indice = 0;
while (options[indice] != null) {
cmdBegin[4 + indice] = options[indice];
indice++;
}
cmdBegin[4 + indice] = null;
} else {
cmdBegin[0] = "java";
cmdBegin[1] = "-classpath";
cmdBegin[2] = projectPath + System.getProperty("path.separator") +
JavActUtilities.findFileInPlugin("JavAct", JavActPlugin.pathJAR)
.toOSString();
cmdBegin[3] = "org.javact.compiler.Main";
indice = 0;
while (options[indice] != null) {
cmdBegin[4 + indice] = options[indice];
indice++;
}
cmdBegin[4 + indice] = null;
}
// We create the cmd line by concataining cmdBegin and javaFiles
String[] cmd = new String[4 /* 4 is cmdBegin minimum length */ +
indice + javaFiles.length];
for (int i = 0; cmdBegin[i] != null; i++) {
cmd[i] = cmdBegin[i];
}
for (int i = 0; i < javaFiles.length; i++) {
cmd[i + 4 /* 4 is cmdBegin minimum length */ + indice] = javaFiles[i];
}
// We execute the command
Process p = Runtime.getRuntime().exec(cmd);
// We redirect the ErrorStream end the InputStream to the standard output with Threads
InputStreamReader errorStream = new InputStreamReader(p.getErrorStream());
BufferedReader bufError = new BufferedReader(errorStream);
InputStreamReader messageStream = new InputStreamReader(p.getInputStream());
BufferedReader bufMessage = new BufferedReader(messageStream);
new MessagePrinter(bufError, true).start();
new MessagePrinter(bufMessage, false).start();
// We wait for the end execution of the command
p.waitFor();
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose
*/
public void dispose() {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init
*/
public void init(IWorkbenchWindow window) {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.IWorkbenchWindowPulldownDelegate#getMenu
*/
public Menu getMenu(Control parent) {
Menu m = new Menu(parent);
ActionContributionItem aci = new ActionContributionItem(new ActionConfigureJavActGen());
aci.getAction().setText("Configure JavActGen...");
aci.getAction()
.setImageDescriptor(JavActPlugin.getImageDescriptor(
"icons/javactgenconf.gif"));
aci.fill(m, -1);
return m;
}
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/views/PlacesView.java
package org.javact.plugin.debug.views;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.javact.plugin.actions.ActionDebug;
import org.javact.plugin.debug.PlaceDebug;
import org.javact.plugin.debug.actions.ShowPlaceEventConsoleAction;
import java.util.Vector;
/**
* The Place View used to show the list of debug place
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class PlacesView extends ViewPart {
//~ Static fields/initializers ---------------------------------------------
public static String ID = PlacesView.class.getName();
//~ Instance fields --------------------------------------------------------
private TableViewer tableViewer;
//~ Methods ----------------------------------------------------------------
/**
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
// initialisation of the listViewer
tableViewer = new TableViewer(parent, SWT.CHECK);
tableViewer.setContentProvider(new PlaceContentProvider());
tableViewer.setLabelProvider(new PlaceLabelProvider());
tableViewer.setSorter(new ViewerSorter());
//the only one column of the table
Table table = tableViewer.getTable();
table.setLayoutData(new GridData(GridData.FILL_BOTH));
new TableColumn(table, SWT.LEFT);
table.getColumn(0).setWidth(200);
table.setHeaderVisible(false);
table.setLinesVisible(false);
// The contextMenu on the Table
final ShowPlaceEventConsoleAction showPlaceEventConsoleAction = new ShowPlaceEventConsoleAction(tableViewer);
MenuManager menu_manager = new MenuManager();
table.setMenu(menu_manager.createContextMenu(table));
menu_manager.add(showPlaceEventConsoleAction);
// The listener on the Table to listen when a element is doubleclicked
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
showPlaceEventConsoleAction.run();
}
});
// The listener on the Table to listen when a element is checked
tableViewer.getTable().addListener(SWT.Selection,
new Listener() {
public void handleEvent(Event event) {
if (event.detail == SWT.CHECK) {
((PlaceDebug) ((TableItem) event.item).getData()).changeIsChecked();
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage();
PrincipalView view = (PrincipalView) page.findView(PrincipalView.ID);
view.redraw();
}
}
});
if (ActionDebug.debug != null) {
tableViewer.setInput(ActionDebug.debug.getPlaces());
}
}
/**
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
}
/**
* Updates the TableViewer
*/
public void redraw() {
tableViewer.setInput(ActionDebug.debug.getPlaces());
}
//~ Inner Classes ----------------------------------------------------------
/**
* Ci-dessous des classes pour le listViewer
* class ProfilContentProvider implements IStructuredContentProvider
* class ProfilLabelProvider implements ILabelProvider
*/
/**
* This class provides the content for the profil table
*/
class PlaceContentProvider implements IStructuredContentProvider {
//~ Methods ------------------------------------------------------------
/**
* Returns the Profil objects
*/
public Object[] getElements(Object inputElement) {
return ((Vector) inputElement).toArray();
}
/**
* Disposes any created resources
*/
public void dispose() {
}
/**
* Called when the input changes
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
/**
* This class provides the labels for the profil table
*/
class PlaceLabelProvider implements ITableLabelProvider {
//~ Methods ------------------------------------------------------------
/**
* @see IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
/**
* @see IBaseLabelProvider#dispose()
*/
public void dispose() {
// TODO Auto-generated method stub
}
/**
* @see IBaseLabelProvider#isLabelProperty(java.lang.Object, java.lang.String)
*/
public boolean isLabelProperty(Object element, String property) {
return false;
}
/**
* @see IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
}
/**
* @see ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
/**
* @see ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
// We search the position of the element in the table
// to check the checkbutton if the element is checked
TableItem[] tabItem = tableViewer.getTable().getItems();
int pos = 0;
for (int i = 0; i < tabItem.length; i++) {
if (((PlaceDebug) tabItem[i].getData()) == element) {
pos = i;
}
}
if (element instanceof PlaceDebug) {
tabItem[pos].setChecked(((PlaceDebug) element).isChecked());
return ((PlaceDebug) element).getName();
} else {
return "";
}
}
}
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/views/JVMView.java
package org.javact.plugin.views;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
/**
* This class is the JVM View which is used to show the JVM and their message in the
* JavAct perspective
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class JVMView extends ViewPart {
//~ Static fields/initializers ---------------------------------------------
public static String ID = "org.javact.plugin.views.JVMView";
//~ Instance fields --------------------------------------------------------
private CTabFolder tabFolder;
//~ Methods ----------------------------------------------------------------
/**
* Get the CTabFolder containing the JVMTab
*
* @return the CTabFolder
*/
public CTabFolder getTabFolder() {
return tabFolder;
}
/**
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
/*
* Nothing to do
*/
}
/**
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
String projectName = this.getViewSite().getSecondaryId();
tabFolder = new CTabFolder(parent, 0);
this.setPartName(projectName + " JVM");
}
}
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/tools/JVMMessagePrinter.java
package org.javact.plugin.tools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.javact.plugin.views.JVMTab;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.IOException;
/**
* This class is used to print JVM messages in its tabItem
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class JVMMessagePrinter extends Thread {
//~ Instance fields --------------------------------------------------------
private JVMTab tabItem;
private BufferedReader bufferedReader;
private boolean error;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new JVMMessagePrinter object.
*
* @param _tabItem tabItem on which the messages must be printed
* @param _bufferedReader BufferedReader in which read the messages
* @param _error true if the messages are errors
*/
JVMMessagePrinter(JVMTab _tabItem, BufferedReader _bufferedReader,
boolean _error) {
tabItem = _tabItem;
bufferedReader = _bufferedReader;
error = _error;
}
//~ Methods ----------------------------------------------------------------
/**
* Prints the messages in the tabItem
*/
public void run() {
String message;
try {
if (error) {
while ((message = bufferedReader.readLine()) != null) {
// write the error in the tabItem
TextRunnable r = new TextRunnable(message, true);
Display.getDefault().asyncExec(r);
}
} else {
while ((message = bufferedReader.readLine()) != null) {
// write the message in the tabItem
TextRunnable r = new TextRunnable(message, false);
Display.getDefault().asyncExec(r);
}
}
} catch (IOException e) {
JavActUtilities.error("JVMMessagePrinter",
"An error occured when reading the messages for " +
tabItem.getPlace().getName(), e);
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* Runnable used to print a text
*
* @author $author$
* @version $Revision: 1.1 $
*/
private class TextRunnable implements Runnable {
//~ Instance fields ----------------------------------------------------
private String myMessage;
private boolean isError;
//~ Constructors -------------------------------------------------------
/**
* Creates a new TextRunnable object.
*
* @param _myMessage the message to print
* @param __isError true if the message is an error
*/
public TextRunnable(String _myMessage, boolean _isError) {
super();
myMessage = _myMessage;
isError = _isError;
}
//~ Methods ------------------------------------------------------------
/**
* Print the message
*/
public void run() {
if (isError) {
tabItem.appendText(myMessage, Color.RED, SWT.BOLD);
} else {
tabItem.appendText(myMessage, Color.BLUE, SWT.NORMAL);
}
}
}
}
<file_sep>/2018/bck/JavAct/stopJavActVM
#!/bin/sh
if [ -n "$1" ]
then
PSID=`ps -eo "%p %a" |grep javact.jar |grep $1 |grep -v grep | cut -c1-6`
else
PSID=`ps -eo "%p %a" |grep javact.jar |grep -v grep | cut -c1-6`
fi
if [ -n "$PSID" ]
then
echo "Fermeture de JavAct !"
kill $PSID
else
echo "Pas de JVM JavAct sur cette machine et sur le port $1 !"
fi
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/MethodToShowEventItem.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.Action;
import org.javact.plugin.actions.ActionDebug;
/**
* This class represents the item Parameter Event
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class MethodToShowEventItem extends Action {
//~ Instance fields --------------------------------------------------------
private String methodName;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ParameterEventItem object.
*
* @param _nbParameter the parameter number for this item
*/
public MethodToShowEventItem(String _methodName) {
super();
methodName = _methodName;
}
//~ Methods ----------------------------------------------------------------
/**
* @see Action#run()
*/
public void run() {
ActionDebug.debug.changeMethod(methodName);
}
}
<file_sep>/BCK/bck/TestJavAct/Plop.java
import org.javact.util.ActorProfile;
import org.javact.util.BehaviorProfile;
public interface Plop extends BehaviorProfile, ActorProfile {
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/tools/Place.java
package org.javact.plugin.tools;
// TODO comment
public class Place {
private String host;
private int port;
private boolean debug;
public boolean isDebug() {
return debug;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public Place(String host, int port, boolean debug) {
this.host = host;
this.port = port;
this.debug = debug;
}
public boolean equals(Place place) {
return host.equals(place.getHost()) && (port == place.getPort());
}
public String getName(){
return host + ":" + port;
}
public String toString() {
return host + ":" + port + (debug?" -d":"");
}
}
<file_sep>/BCK/workspace_javact_Version_utilisee_sur_fedora/.metadata/version.ini
#Tue Feb 06 19:18:19 CET 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.2.v20171130-0510
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/views/ActorEventView.java
package org.javact.plugin.debug.views;
import org.javact.plugin.debug.ActorDebug;
/**
* An ActorEventView used to show the actor's events in debug perspective
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class ActorEventView extends EventView {
//~ Static fields/initializers ---------------------------------------------
public final static String ID = ActorEventView.class.getName();
//~ Instance fields --------------------------------------------------------
private ActorDebug actor;
//~ Methods ----------------------------------------------------------------
/**
* Sets the actor linked to the view
*
* @param _actor an actor
*/
public void setActor(ActorDebug _actor) {
actor = _actor;
}
/**
* Gets the actor linked to the view
*
* @return the actor linked to the view
*/
public ActorDebug getActor() {
return actor;
}
/**
* When the view is disposed, if it's linked
* to an actor, we set the boolean isTraced of
* the actor at false
*/
public void dispose() {
if (actor != null) {
actor.setIsTraced(false);
}
super.dispose();
}
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/wizards/NewProjectWizard.java
package org.javact.plugin.wizards;
import java.io.File;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.wizards.JavaProjectWizard;
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
import org.eclipse.jface.wizard.IWizardPage;
import org.javact.plugin.JavActPlugin;
import org.javact.plugin.properties.JavActGenConfiguration;
import org.javact.plugin.tools.JavActUtilities;
/**
* Wizard which creat a new javact project. Add the javact library
* to the classpath and create two new files : "places.txt" and "awfullPolicy"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class NewProjectWizard extends JavaProjectWizard {
//~ Constructors -----------------------------------------------------------
// private JavaProjectWizardFirstPage fFirstPage;
// private JavaProjectWizardSecondPage fSecondPage;
// private IConfigurationElement fConfigElement;
/**
* Creates a new NewProjectWizard object.
*/
public NewProjectWizard() {
super();
setWindowTitle("New JavAct Project");
}
//~ Methods ----------------------------------------------------------------
/**
* @see JavaProjectWizard#addPages
*/
public void addPages() {
super.addPages();
// We give a new title and a new description for the pages of the wizard
IWizardPage[] pages = getPages();
if (pages.length == 2) {
pages[0].setTitle("Create a JavAct project");
pages[0].setDescription(
"Create a JavAct project in the workspace or in an external location.\n" +
"http://www.irit.fr/recherches/ISPR/IAM/JavAct.html");
pages[1].setTitle("Create a JavAct project");
pages[1].setDescription("Define the Java build settings.\n" +
"http://www.irit.fr/recherches/ISPR/IAM/JavAct.html");
}
}
/**
* This method is called when 'Finish' button is pressed in
* the wizard. We will create an operation and run it
* using wizard as execution context.
*
* @return true to close the wizard, false elsewhere
*/
public boolean performFinish() {
boolean res = super.performFinish();
// get project
JavaCapabilityConfigurationPage page = (JavaCapabilityConfigurationPage) getPage(
"JavaCapabilityConfigurationPage");
if (page == null) {
return res;
}
// update classpath
updateClasspath(page.getJavaProject());
// create environement files
createEnv(page.getJavaProject());
return res;
}
/**
* Updates the project's classpath with additional JavAct libraries.
*
* @param aProject a java project
*/
private void updateClasspath(IJavaProject aProject) {
try {
// get existing classpath
IClasspathEntry[] existingClasspath = aProject.getRawClasspath();
// get classpath entries for JavAct
IPath theJar = JavActUtilities.findFileInPlugin("JavAct",
JavActPlugin.pathJAR);
IClasspathEntry theJavActEntry = null;
if (theJar == null) {
JavActUtilities.error("JavAct project wizard",
"Could not create a classpath entry for javact.jar, please insert this library in your project");
return;
}
//theJavActEntry = JavaCore.newLibraryEntry(theJar, tools.EclipseUtilities.findFileInPlugin("JavAct", "src/javact-src.zip"),new Path("/"));
theJavActEntry = JavaCore.newLibraryEntry(theJar, null,
new Path(File.separator));
// complete classpath if necessary
if (theJavActEntry != null) {
// create new classpath with additional JavAct library last
IClasspathEntry[] newClasspath = new IClasspathEntry[existingClasspath.length +
1];
for (int i = 0; i < existingClasspath.length; i++) {
newClasspath[i] = existingClasspath[i];
}
newClasspath[existingClasspath.length] = theJavActEntry;
// set new classpath to project
aProject.setRawClasspath(newClasspath, null);
}
} catch (JavaModelException e) {
JavActUtilities.error("JavAct project wizard",
"Could not create a classpath entry for javact.jar, please insert this library in your project",
e);
}
}
/**
* Creates useful files in the project for javact compiler
*
* @param aProject a java project
*/
private void createEnv(IJavaProject aProject) {
// fill places.txt and create it
JavActUtilities.createDefaultPlaces(aProject.getProject());
// fill awfullPolicy and create it
JavActUtilities.createDefaultPolicy(aProject.getProject());
// create .genConfig which will save the code generation arguments
new JavActGenConfiguration(aProject.getProject().getLocation()
.toOSString()).save(aProject);
}
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/NumberEventItem.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.Action;
/**
* This class represents the item Number Events
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class NumberEventItem extends Action {
//~ Instance fields --------------------------------------------------------
private int nbEvent;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new NumberEventItem object.
*
* @param _nbEvent the number of events / step for this item
*/
public NumberEventItem(int _nbEvent) {
super();
nbEvent = _nbEvent;
}
//~ Methods ----------------------------------------------------------------
/**
* @see Action#run()
*/
public void run() {
NumberEventAction.actionChecked = nbEvent;
}
}
<file_sep>/2018/bck/JavAct/startJavActVM
#!/bin/sh
#for ((i = 1; i < 10; i++))
#do
# echo "Démarrage sur b313-0$i..."
# ssh b313-0$i "export DISPLAY=:0.0 ; cd DemoB313 ; java -jar lib/javact.jar &" &
#done
#echo "Démarrage sur b313-10..."
#ssh b313-10 "export DISPLAY=:0.0 ; cd DemoB313 ; java -jar lib/javact.jar &" &
#IP=`/sbin/ifconfig |grep "inet adr:"|grep -v "127.0.0.1"|grep -v "192." |cut -f2 -d':' |tr -d " Bcast"`
cd ~lerichse
java -Djava.rmi.server.useCodebaseOnly=false -Djava.rmi.server.hostname=`hostname -I` -jar javact.jar $1
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/launch/JavActArgumentsTab.java
package org.javact.plugin.launch;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.debug.ui.StringVariableSelectionDialog;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaArgumentsTab;
import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.JavaDebugImages;
import org.eclipse.jdt.internal.debug.ui.actions.ControlAccessibleListener;
import org.eclipse.jdt.internal.debug.ui.launcher.LauncherMessages;
import org.eclipse.jdt.internal.debug.ui.launcher.WorkingDirectoryBlock;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
/**
* This class implements the Arguments tab of the LaunchConfiguration
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class JavActArgumentsTab extends JavaArgumentsTab {
//~ Static fields/initializers ---------------------------------------------
protected static final String EMPTY_STRING = "";
//~ Instance fields --------------------------------------------------------
// Program arguments widgets
protected Label fPrgmArgumentsLabel;
protected Text fPrgmArgumentsText;
// VM arguments widgets
protected JavActVMArgumentsBlock fVMArgumentsBlock;
// Working directory
protected WorkingDirectoryBlock fWorkingDirectoryBlock;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new JavActArgumentsTab object.
*/
public JavActArgumentsTab() {
fVMArgumentsBlock = createJavActVMArgsBlock();
fWorkingDirectoryBlock = createWorkingDirBlock();
}
//~ Methods ----------------------------------------------------------------
/**
* Creation of the Block for the Virtual Machine Arguments
*
* @return the block for VM arguments
*/
protected JavActVMArgumentsBlock createJavActVMArgsBlock() {
return new JavActVMArgumentsBlock();
}
/**
* @see JavaArgumentsTab#createWorkingDirBlock()
*/
protected WorkingDirectoryBlock createWorkingDirBlock() {
return new WorkingDirectoryBlock();
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(Composite)
*/
public void createControl(Composite parent) {
Font font = parent.getFont();
Composite comp = new Composite(parent, parent.getStyle());
GridLayout layout = new GridLayout(1, true);
comp.setLayout(layout);
comp.setFont(font);
GridData gd = new GridData(GridData.FILL_BOTH);
comp.setLayoutData(gd);
setControl(comp);
setHelpContextId();
Group group = new Group(comp, SWT.NONE);
group.setFont(font);
layout = new GridLayout();
group.setLayout(layout);
group.setLayoutData(new GridData(GridData.FILL_BOTH));
String controlName = (LauncherMessages.JavaArgumentsTab__Program_arguments__5); //$NON-NLS-1$
group.setText(controlName);
fPrgmArgumentsText = new Text(group,
SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 40;
gd.widthHint = 100;
fPrgmArgumentsText.setLayoutData(gd);
fPrgmArgumentsText.setFont(font);
fPrgmArgumentsText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
updateLaunchConfigurationDialog();
}
});
ControlAccessibleListener.addListener(fPrgmArgumentsText,
group.getText());
String buttonLabel = LauncherMessages.JavaArgumentsTab_5; //$NON-NLS-1$
Button pgrmArgVariableButton = createPushButton(group, buttonLabel, null);
pgrmArgVariableButton.setLayoutData(new GridData(
GridData.HORIZONTAL_ALIGN_END));
pgrmArgVariableButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell());
dialog.open();
String variable = dialog.getVariableExpression();
if (variable != null) {
fPrgmArgumentsText.insert(variable);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fVMArgumentsBlock.createControl(comp);
fWorkingDirectoryBlock.createControl(comp);
}
/**
* Set the help context id for this launch config tab. Subclasses may
* override this method.
*/
protected void setHelpContextId() {
PlatformUI.getWorkbench().getHelpSystem()
.setHelp(getControl(),
IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_ARGUMENTS_TAB);
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#dispose()
*/
public void dispose() {
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(ILaunchConfiguration)
*/
public boolean isValid(ILaunchConfiguration config) {
return fWorkingDirectoryBlock.isValid(config);
}
/**
* Defaults are empty.
*
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy)
*/
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
(String) null);
fVMArgumentsBlock.setDefaults(config);
fWorkingDirectoryBlock.setDefaults(config);
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration)
*/
public void initializeFrom(ILaunchConfiguration configuration) {
try {
fPrgmArgumentsText.setText(configuration.getAttribute(
IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "")); //$NON-NLS-1$
fVMArgumentsBlock.initializeFrom(configuration);
fWorkingDirectoryBlock.initializeFrom(configuration);
} catch (CoreException e) {
setErrorMessage(LauncherMessages.JavaArgumentsTab_Exception_occurred_reading_configuration___15 +
e.getStatus().getMessage()); //$NON-NLS-1$
JDIDebugUIPlugin.log(e);
}
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy)
*/
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
getAttributeValueFrom(fPrgmArgumentsText));
fVMArgumentsBlock.performApply(configuration);
fWorkingDirectoryBlock.performApply(configuration);
}
/**
* Retuns the string in the text widget, or <code>null</code> if empty.
*
* @return text or <code>null</code>
*/
protected String getAttributeValueFrom(Text text) {
String content = text.getText().trim();
if (content.length() > 0) {
return content;
}
return null;
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
*/
public String getName() {
return LauncherMessages.JavaArgumentsTab__Arguments_16; //$NON-NLS-1$
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#setLaunchConfigurationDialog(ILaunchConfigurationDialog)
*/
public void setLaunchConfigurationDialog(ILaunchConfigurationDialog dialog) {
super.setLaunchConfigurationDialog(dialog);
fWorkingDirectoryBlock.setLaunchConfigurationDialog(dialog);
fVMArgumentsBlock.setLaunchConfigurationDialog(dialog);
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getErrorMessage()
*/
public String getErrorMessage() {
String m = super.getErrorMessage();
if (m == null) {
return fWorkingDirectoryBlock.getErrorMessage();
}
return m;
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getMessage()
*/
public String getMessage() {
String m = super.getMessage();
if (m == null) {
return fWorkingDirectoryBlock.getMessage();
}
return m;
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
*/
public Image getImage() {
return JavaDebugImages.get(JavaDebugImages.IMG_VIEW_ARGUMENTS_TAB);
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#activated(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
*/
public void activated(ILaunchConfigurationWorkingCopy workingCopy) {
// do nothing when activated
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#deactivated(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
*/
public void deactivated(ILaunchConfigurationWorkingCopy workingCopy) {
// do nothing when deactivated
}
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/DeselectAllAction.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;
import org.javact.plugin.debug.ActorDebug;
/**
* This class represents the action "DeselectAll"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class DeselectAllAction extends Action {
//~ Instance fields --------------------------------------------------------
private TableViewer tableViewer;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new DeselectAllAction object.
*
* @param _tableViewer the TableViewer of the selection
*/
public DeselectAllAction(TableViewer _tableViewer) {
tableViewer = _tableViewer;
setText("Deselect All");
}
//~ Methods ----------------------------------------------------------------
/**
* Run the DeselectAll Action
*
* @see Action#run()
*/
public void run() {
TableItem[] items = tableViewer.getTable().getItems();
for (int i = 0; i < items.length; i++) {
items[i].setChecked(false);
((ActorDebug) items[i].getData()).setIsChecked(false);
}
}
}
<file_sep>/2019/TP/javact2019/Pi/Recherche.java
import org.javact.util.ActorProfile;
import org.javact.util.BehaviorProfile;
import org.javact.util.StandAlone; // s'execute 1 fois créé
public interface Recherche extends BehaviorProfile {
public void become(Superviseur beh);
}
<file_sep>/BCK/JavAct/AgentPIEnac/Recherche.java
import org.javact.util.ActorProfile;
import org.javact.util.BehaviorProfile;
import org.javact.util.StandAlone;
public interface Recherche extends ActorProfile, BehaviorProfile {
}
<file_sep>/BCK/JavAct/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/views/PrincipalView.java
package org.javact.plugin.debug.views;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.part.ViewPart;
import org.javact.plugin.actions.ActionDebug;
import org.javact.plugin.debug.PlaceDebug;
import java.util.Vector;
/**
* The principal view used to show the PlaceComposite
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class PrincipalView extends ViewPart {
//~ Static fields/initializers ---------------------------------------------
public static String ID = PrincipalView.class.getName();
//~ Instance fields --------------------------------------------------------
private static int numColumns = 3;
private Composite parent;
private Shell invisibleShell;
private ScrolledComposite sc;
//~ Methods ----------------------------------------------------------------
/**
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
/*
* Nothing to do
*/
}
/**
* Redraw the view
*/
public void redraw() {
int j = 0;
Control[] childs = parent.getChildren();
for (int i = 0; i < childs.length; i++) {
PlaceComposite placecomposite = (PlaceComposite) childs[i];
if (!placecomposite.getPlaceDebug().isChecked()) {
placecomposite.setParent(invisibleShell);
} else {
j++;
}
}
childs = invisibleShell.getChildren();
for (int i = 0; i < childs.length; i++) {
PlaceComposite placecomposite = (PlaceComposite) childs[i];
if (placecomposite.getPlaceDebug().isChecked()) {
placecomposite.setParent(parent);
j++;
}
}
parent.layout();
if (j < numColumns) {
sc.setMinSize(new Double(-5 +
((j % numColumns) * (9 + PlaceComposite.width))).intValue(),
new Double(-5 +
(Math.ceil(new Double(j).doubleValue() / numColumns) * (9 +
PlaceComposite.heigth))).intValue());
} else {
sc.setMinSize(-5 + (numColumns * (9 + PlaceComposite.width)),
new Double(-5 +
(Math.ceil(new Double(j).doubleValue() / numColumns) * (9 +
PlaceComposite.heigth))).intValue());
}
}
/**
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite _parent) {
sc = new ScrolledComposite(_parent, SWT.H_SCROLL | SWT.V_SCROLL);
parent = new Composite(sc, SWT.NONE);
sc.setContent(parent);
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
GridLayout layout = new GridLayout();
layout.numColumns = numColumns;
parent.setLayout(layout);
invisibleShell = new Shell(getSite().getShell().getDisplay(), SWT.NULL);
update();
}
/**
* Update the placeComposite when the placeDebug change
*/
public void update() {
Control[] cIn = invisibleShell.getChildren();
Control[] cVi = parent.getChildren();
for (int i = 0; i < cIn.length; i++) {
cIn[i].dispose();
}
for (int i = 0; i < cVi.length; i++) {
cVi[i].dispose();
}
if (ActionDebug.debug != null) {
PlaceDebug place;
Vector places = ActionDebug.debug.getPlaces();
for (int i = 0; i < places.size(); i++) {
place = (PlaceDebug) places.elementAt(i);
place.setPlaceComposite(new PlaceComposite(invisibleShell,
SWT.BORDER, place));
}
}
redraw();
}
}
<file_sep>/2018/bck/workspace_javact_Version_utilisee_sur_fedora/AgentPi/Afficheur.java
import org.javact.util.BehaviorProfile;
import org.javact.util.StandAlone;
public interface Afficheur extends BehaviorProfile, StandAlone {
}
<file_sep>/2018/bck/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/views/PlaceEventView.java
package org.javact.plugin.debug.views;
import org.javact.plugin.debug.PlaceDebug;
/**
* An PlaceEventView used to show the place's events in debug perspective
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class PlaceEventView extends EventView {
//~ Static fields/initializers ---------------------------------------------
public final static String ID = PlaceEventView.class.getName();
//~ Instance fields --------------------------------------------------------
private PlaceDebug place;
//~ Methods ----------------------------------------------------------------
/**
* Sets the place linked to the view
*
* @param _place a place
*/
public void setPlace(PlaceDebug _place) {
place = _place;
}
/**
* Gets the place linked to the view
*
* @return the place linked to the view
*/
public PlaceDebug getPlace() {
return place;
}
}
<file_sep>/2018/bck/Test/JAMspeak.java
public class JAMspeak implements org.javact.lang.Message
{
private int signatureNumber ;
public JAMspeak()
{
signatureNumber = 0 ;
}
public final void handle(org.javact.lang.QuasiBehavior _behavior)
{
switch (signatureNumber)
{
case 0 :
if (_behavior instanceof Tourisk)
((Tourisk) _behavior).speak() ;
else
throw new org.javact.lang.MessageHandleException() ;
break ;
default :
throw new org.javact.lang.MessageHandleException() ;
}
}
}
<file_sep>/BCK/javact_workspace/TP_JAVACT/Recherche.java
import org.javact.util.BehaviorProfile;
public interface Recherche extends BehaviorProfile {
public void become(Superviseur beh);
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/views/JVMTab.java
package org.javact.plugin.views;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextContent;
import org.eclipse.swt.graphics.Color;
import org.javact.plugin.tools.JVMLauncher;
import org.javact.plugin.tools.JavActUtilities;
import org.javact.plugin.tools.Place;
/**
* This class is the JVM Tab which is used to show a JVM and its message in the
* JVM View
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class JVMTab extends CTabItem {
//~ Instance fields --------------------------------------------------------
private StyledText textArea;
private JVMLauncher jvmLauncher;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new JVMTab object.
*
* @param parent a CTabFolder which will be the parent of the new instance (cannot be null)
* @param style the style of control to construct
* @param launcher the JVMLauncher linked with this JVMTab
*
*/
public JVMTab(CTabFolder parent, int style, JVMLauncher launcher) {
super(parent, style);
jvmLauncher = launcher;
textArea = new StyledText(parent,
SWT.MULTI | SWT.READ_ONLY | SWT.V_SCROLL);
setControl(textArea);
}
//~ Methods ----------------------------------------------------------------
/**
* This method is used to append text in this JVMTab
*
* @param message the string to append
* @param color the color of the string
* @param fontStyle the font style of the string
*/
public void appendText(String message, java.awt.Color color, int fontStyle) {
textArea.append(message + "\n");
StyleRange styleRange = new StyleRange();
styleRange.start = textArea.getText().length() -
(message.length() + 1);
styleRange.length = message.length();
styleRange.fontStyle = fontStyle;
styleRange.foreground = new Color(textArea.getDisplay(),
color.getRed(), color.getGreen(), color.getBlue());
textArea.setStyleRange(styleRange);
revealEndOfDocument();
}
/**
* Disposes of the operating system resources associated with
* the receiver and all its descendents.
*/
public void dispose() {
super.dispose();
JavActUtilities.removeLocalJVM(jvmLauncher.getIdentifier());
}
/**
* Reveals the end of the text area
*/
private void revealEndOfDocument() {
StyledTextContent doc = textArea.getContent();
int docLength = doc.getCharCount();
if (docLength > 0) {
textArea.setCaretOffset(docLength);
textArea.showSelection();
}
}
/**
* Returns the placename of the JVM showed in the tab
*
* @return the placename
*/
public Place getPlace() {
return jvmLauncher.getPlace();
}
}
<file_sep>/BCK/eclipse_javact/plugins/JavAct_1.2.4/src/org/javact/plugin/debug/actions/ShowPlaceEventConsoleAction.java
package org.javact.plugin.debug.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.javact.plugin.debug.PlaceDebug;
import org.javact.plugin.debug.views.PlaceEventView;
import org.javact.plugin.tools.JavActUtilities;
/**
* This class represents the action "ShowActorEventConsole"
*
* @author <NAME>
* @version $Revision: 1.1 $
*/
public class ShowPlaceEventConsoleAction extends Action {
//~ Instance fields --------------------------------------------------------
private TableViewer tableViewer;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new ShowPlaceEventConsoleAction object.
*
* @param _tableViewer the TableViewer of the selection
*/
public ShowPlaceEventConsoleAction(TableViewer _tableViewer) {
tableViewer = _tableViewer;
setText("Show Place Event Console");
}
//~ Methods ----------------------------------------------------------------
/**
* @see Action#run()
*/
public void run() {
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection();
if (selection.size() == 1) {
PlaceDebug place = (PlaceDebug) selection.getFirstElement();
try {
// We split the placeName, because it contains ":"
// and that throws an exception java.lang.IllegalArgumentException: Illegal secondary id (cannot be empty or contain a colon)
String[] splitname = place.getName().split(":");
String ident = "";
for (int i = 0; i < splitname.length; i++) {
ident += splitname[i];
}
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getActivePage();
PlaceEventView view = (PlaceEventView) page.showView(PlaceEventView.class.getName(),
ident, IWorkbenchPage.VIEW_VISIBLE);
view.rename(place.getName());
} catch (PartInitException e) {
JavActUtilities.error("Show Place Event Console",
"Impossible to show the place event console", e);
}
}
}
}
| 4bc8e62434eef5c2c08bff4783f2f31e2dbd5977 | [
"Java",
"Shell",
"INI"
] | 39 | Java | kad15/SYSTEMES_REPARTIS | a0885d2c86844b480cc0c944d619d54f1530a07d | 47e7837c73e7d66e46ba6817aa098b4472b3a7b9 |
refs/heads/master | <repo_name>Sergred/k5-36-examples<file_sep>/lection1/src/ru/mephi/lections/lection1/inheritence/MyAbstractClass.java
package ru.mephi.lections.lection1.inheritence;
/**
* Created by Bazar on 05.09.14.
*/
public abstract class MyAbstractClass implements IMyInterfaceExample {
@Override
public String getText() {
return "Number:" + getInt();
}
public abstract int getInt();
}
<file_sep>/lection1/src/ru/mephi/lections/lection1/files/Reader.java
package ru.mephi.lections.lection1.files;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Reader {
private static File inFile;
private static File outFile;
private static FileInputStream fis;
private static FileOutputStream fos;
private static BufferedReader reader;
private static BufferedWriter writer;
private static Scanner scanner;
public static void main(String[] args) {
inFile = new File("group.csv");
try {
StdOutErrLog.tieSystemOutAndErrToLog();
System.out.println("Read via BufferedReader");
fis = new FileInputStream(inFile);
reader = new BufferedReader(new InputStreamReader(fis));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
System.out.println("-------");
System.out.println("Read via Scanner");
scanner = new Scanner(inFile);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
System.out.println("-------");
System.out.println("Read via Files utility");
List<String> list = Files.readAllLines(inFile.toPath(),
Charset.defaultCharset());
Map<Integer, String> students = new TreeMap<>();
for (String row : list) {
System.out.println(row);
String[] student = row.split(";");
students.put(Integer.valueOf(student[1]), student[0]);
}
System.out.println("write to file");
outFile = new File("out.txt");
fos = new FileOutputStream(outFile);
writer = new BufferedWriter(new OutputStreamWriter(fos));
for (Entry<Integer, String> entry : students.entrySet()) {
writer.append(entry.getKey().toString()).append("-")
.append(entry.getValue());
writer.newLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
} finally {
try {
reader.close();
writer.close();
scanner.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}<file_sep>/lection1/src/ru/mephi/lections/lection1/inheritence/IMyInterfaceExample.java
package ru.mephi.lections.lection1.inheritence;
/**
* Created by Bazar on 05.09.14.
*/
public interface IMyInterfaceExample {
public String getText();
}
<file_sep>/lection1/src/ru/mephi/lections/lection1/arrayscollections/ComparableClass.java
package ru.mephi.lections.lection1.arrayscollections;
/**
* Created by Bazar on 05.09.14.
*/
public class ComparableClass implements Comparable<ComparableClass> {
private Integer groupNumber;
private String name;
public ComparableClass(Integer groupNumber, String name) {
this.groupNumber = groupNumber;
this.name = name;
}
@Override
public int compareTo(ComparableClass o) {
int result = 0;
if (groupNumber == null) {
if (o.groupNumber != null) {
result = 1;
}
} else {
result = groupNumber.compareTo(o.groupNumber);
}
if (result == 0) {
if (name == null) {
if (o.name != null) {
result = 1;
}
} else {
result = name.compareTo(o.name);
}
}
return result;
}
@Override
public String toString() {
return "ComparableClass{" +
"groupNumber=" + groupNumber +
", name='" + name + '\'' +
'}';
}
}
<file_sep>/lection1/src/ru/mephi/lections/lection1/arrayscollections/SetExample.java
package ru.mephi.lections.lection1.arrayscollections;
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<Student> students = new HashSet<>();
Student.addStudents(students);
printSet(students);
students = new TreeSet<>(students);
printSet(students);
Set<Student> studentsSorted = new TreeSet<>(
new Student.StudentComparator());
studentsSorted.addAll(students);
printSet(studentsSorted);
Iterator<Student> iterator = studentsSorted.iterator();
int i = 0;
while (iterator.hasNext()) {
iterator.next().setId(i++);
}
printSet(studentsSorted);
printSet(students);
if (studentsSorted.containsAll(students)) {
System.out.println("Sets equals");
}
}
public static void printSet(Set set) {
System.out.println(Arrays.toString(set.toArray()));
}
}<file_sep>/lection1/src/ru/mephi/lections/lection1/files/StdOutErrLog.java
package ru.mephi.lections.lection1.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class StdOutErrLog {
private static PrintWriter writer;
private static PrintWriter err;
static {
try {
writer = new PrintWriter(new File("file.log"));
err = new PrintWriter(new File("error.log"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void tieSystemOutAndErrToLog() {
System.setOut(createLoggingProxy(System.out));
System.setErr(createLoggingProxyErr(System.err));
}
public static PrintStream createLoggingProxy(
final PrintStream realPrintStream) {
return new PrintStream(realPrintStream) {
public void print(final String string) {
realPrintStream.print(string);
writer.println(string);
writer.flush();
}
};
}
public static PrintStream createLoggingProxyErr(
final PrintStream realPrintStream) {
return new PrintStream(realPrintStream) {
public void print(final String string) {
realPrintStream.print(string);
err.println(string);
err.flush();
}
};
}
}<file_sep>/lection1/src/ru/mephi/lections/lection1/arrayscollections/CollectionsExample.java
package ru.mephi.lections.lection1.arrayscollections;
import java.util.List;
import java.util.Set;
/**
* Created by Bazar on 06.09.14.
*/
public class CollectionsExample {
private static final int[] numbers = new int[]{3, 5, 21, 1, 71, 54, 30};
public static void main(String[] args) {
List<Integer> myList;
Set<Integer> mySet;
}
}
| 04d63f866e632296acc287f98e1cf5812673e287 | [
"Java"
] | 7 | Java | Sergred/k5-36-examples | 73463b3ef94b5126fb497b838e2f6df2b9583e87 | 4269e2f9c4f3a75ab18c49bc980608fdbe99512f |
refs/heads/master | <repo_name>kenypsk/demo_test2<file_sep>/framework/base/testprint.py
print("hello git")
print("Á┌╚ř┤╬commit")
<file_sep>/testc.py
print("testc")
<file_sep>/git.py
print("git")
# ▓Ô╩ď╠߯╗github
<file_sep>/testb.py
print("testb")<file_sep>/testa.py
print("sdsd")
# zhushi
# sdfs
# ces
# 33232
# ×¢تح
| a25b6f9683ffdd2183d0e2ee8cbf2f540b25d4a9 | [
"Python"
] | 5 | Python | kenypsk/demo_test2 | 5bf516bccf76796e5c5222cccad6393ac00648ba | 49d46db01e45ccc35d3e46df8f584c362e079038 |
refs/heads/master | <file_sep># read the text files in the train folder.
# This should only be launched when the run_analysis.R
# file is in the UCI HAR Daataset folder
Xtrain<-read.table("train/X_train.txt")
# the previous command may take some time to run
# we can check for completness the dimension of the
# loaded table
dim(Xtrain)
ytrain<-read.table("train/y_train.txt")
subjectrain<-read.table("train/subject_train.txt")
# read the text files in the test folder.
# This should only be launched when the run_analysis.R
# file is in the UCI HAR Daataset folder
Xtest<-read.table("test/X_test.txt")
# the previous command may take some time to run
ytest<-read.table("test/y_test.txt")
subjectest<-read.table("test/subject_test.txt")
# merging the training and test features
# (using rbind is important, as merge may re-order the data)
mergetraintest<-rbind(Xtrain,Xtest)
# loading the names of the different variables
labels<-read.table("features.txt")
#labeling the merge variables (2nd column of labels)
names(mergetraintest)<-labels$V2
# selectionning only the variables mean and std
# We voluntarily exclude the variable names containing
# Mean, as they represent angles between mean variables, not means
mergetraintest<-mergetraintest[,grep("mean|std",labels$V2)]
# we now clean a little the variable names, using only lowercases,
# and no -,(,) characters
names(mergetraintest)<-gsub("-","",tolower(names(mergetraintest)))
names(mergetraintest)<-gsub("\\()","",names(mergetraintest))
# since t means time and f frequency, we make that explicit
names(mergetraintest)<-gsub("^f","frequency",names(mergetraintest))
names(mergetraintest)<-gsub("^t","time",names(mergetraintest))
# we can now add the subjects and activity to our merge table
subject<-rbind(subjectrain,subjectest)
activity<-rbind(ytrain,ytest)
# convert subject into a categorical variable
subject$V1<-factor(subject$V1)
names(subject)<-"subject"
# load the names of the activity, and convert them
# in lowercase and no _
labelsactivity<-read.table("activity_labels.txt")
labelsactivity$V2<-tolower(gsub("_","",labelsactivity$V2))
# replacing the numbers in activity by their corresponding activity names
activity$V1<-labelsactivity$V2[activity$V1]
names(activity)<-"activity"
# finally merging the features, activities and subjects
tidydata<-cbind(subject,activity,mergetraintest)
# average the different features for each activity and each subject
tidydataavg<-aggregate(tidydata[,3:81],by=list(tidydata$subject,tidydata$activity), mean)
#arrange by individuals, then by activity (alphabetic order)
names(tidydataavg)[1]<-"subject"
names(tidydataavg)[2]<-"activity"
library(dplyr)
tidydataavg<-arrange(tidydataavg,subject,activity)
# saving the tidy data set with the averages!
write.table(tidydataavg,file="tidyaverage.txt", row.name=FALSE)
<file_sep>---
title: "README"
output: html_document
---
This Readme file goes alongside with the run_analysis.R file, used to tidy the data for the project
of th Getting and Cleaning data MOOC. One should also consult the codebook to understand the variables
contained in the final text file.
First I read the text files in the train folder. This can only be done if
the run_analysis.R file is in the UCI HAR Daataset folder
(that can be downloaded here
https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip)
```{r}
Xtrain<-read.table("train/X_train.txt")
```
the previous command may take some time to run, as it is a large table.
One can convince himself that this is the case by inspecting the dimension of the loaded table
```{r}
dim(Xtrain)
```
We then load the remaining training files
```{r}
ytrain<-read.table("train/y_train.txt")
subjectrain<-read.table("train/subject_train.txt")
```
Then I read the text files in the test folder. This can only be done if
the run_analysis.R file is in the UCI HAR Daataset folder
```{r}
Xtest<-read.table("test/X_test.txt")
```
Again this may take some time to run. Loading the rest
```{r}
ytest<-read.table("test/y_test.txt")
subjectest<-read.table("test/subject_test.txt")
```
I then merge the training and test features. Using rbind is important, as merge may re-order the data
```{r}
mergetraintest<-rbind(Xtrain,Xtest)
```
I load the names of the different features
```{r}
labels<-read.table("features.txt")
```
and I label the merge features (2nd column of labels needed)
```{r}
names(mergetraintest)<-labels$V2
```
I then selection only the variables mean and std.
I voluntarily exclude the variable names containing Mean,
(with an uppercase) as they represent angles between mean variables, not real means.
Thus:
```{r}
mergetraintest<-mergetraintest[,grep("mean|std",labels$V2)]
```
I now clean a little the variable names, using only lowercases, and no -,(,) characters
```{r}
names(mergetraintest)<-gsub("-","",tolower(names(mergetraintest)))
names(mergetraintest)<-gsub("\\()","",names(mergetraintest))
```
Reading the README provided, t means time and f frequency, so I make that explicit
```{r}
names(mergetraintest)<-gsub("^f","frequency",names(mergetraintest))
names(mergetraintest)<-gsub("^t","time",names(mergetraintest))
```
I can now add the subjects and activity to my merge table.
First I merge the train and the test
```{r}
subject<-rbind(subjectrain,subjectest)
activity<-rbind(ytrain,ytest)
```
I then convert the subject into a categorical variable
```{r}
subject$V1<-factor(subject$V1)
names(subject)<-"subject"
```
I load the names of the activities, and convert them in lowercase
without special character
```{r}
labelsactivity<-read.table("activity_labels.txt")
labelsactivity$V2<-tolower(gsub("_","",labelsactivity$V2))
```
I replace the number in activity by their corresponding activity name
```{r}
activity$V1<-labelsactivity$V2[activity$V1]
names(activity)<-"activity"
```
I finally merge the features, activities and subjects
```{r}
tidydata<-cbind(subject,activity,mergetraintest)
```
I average the different features for each activity and each subject
```{r}
tidydataavg<-aggregate(tidydata[,3:81],by=list(tidydata$subject,tidydata$activity), mean)
```
I arrange by individuals, then by activity (alphabetic order)
```{r}
names(tidydataavg)[1]<-"subject"
names(tidydataavg)[2]<-"activity"
library(dplyr)
tidydataavg<-arrange(tidydataavg,subject,activity)
```
And I finally save the tidy data set with the averages
```{r}
write.table(tidydataavg,file="tidyaverage.txt", row.name=FALSE)
```
The final text file contains 81 variables(79 means and std as well as 2 columns for
the subjects and activities) for 180 rows(corresponding to 30 subjects * 6 activities) | a32747f35e87795c8bca63b69e419d1364d8d675 | [
"Markdown",
"R"
] | 2 | R | tomepel/Project_Getting_Cleaning | 09d37a54da1c4db481d72bfdd3279d185edfaab9 | 444176284ca054930f5f7fa92bdb14f509b3eba9 |
refs/heads/master | <file_sep>#Wed Aug 05 10:00:21 CST 2015
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140925-0400
<file_sep>package videoClub;
import java.io.IOException;
import javafx.application.Application;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
//CONTROLADORES
private VideoClubController videoClubController;
private Formulario1Controller formulario1Controller;
private Formulario2Controller formulario2Controller;
private FormularioContenedorController formularioContenedorController;
//FORMULARIOS
private Stage formularioContenedor;
private Stage formulario1;
private Stage formulario2;
private Stage formularioVideoClub;
@Override
public void start(Stage primaryStage) {
formularioContenedor = primaryStage;
try {
FXMLLoader load = new FXMLLoader();
load.setLocation(getClass().getResource("FormularioContenedor.fxml"));
AnchorPane root = (AnchorPane)load.load();
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("Video Club");
primaryStage.resizableProperty();
formularioContenedorController = load.getController();
formularioContenedorController.setMain(this);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void abrirFormularioVideoClub() {
}
public void abrirFormulario1() {
if(formulario1==null) {
formulario1 = new Stage();
formulario1.setTitle("Formulario1");
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Formulario1.fxml"));
AnchorPane root = (AnchorPane)loader.load();
Scene scene = new Scene(root);
formulario1.setScene(scene);
formulario1Controller = loader.getController();
formulario1Controller.setMain(this);
formulario1.initOwner(formularioContenedor);
formulario1.initModality(Modality.WINDOW_MODAL);
formulario1.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
formulario1.show();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("El formulario 1 ya esta abierto");
alert.setHeaderText("Formulario1");
alert.showAndWait();
}
}
public void abrirFormulario2() {
if(formulario2==null) {
formulario2 = new Stage();
formulario2.setTitle("Formulario2");
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Formulario2.fxml"));
AnchorPane root = (AnchorPane)loader.load();
Scene scene = new Scene(root);
formulario2.setScene(scene);
formulario2Controller = loader.getController();
formulario2Controller.setMain(this);
formulario2.initOwner(formularioContenedor);
formulario2.initModality(Modality.WINDOW_MODAL);
formulario2.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
launch(args);
}
public void cerrarFormulario1() {
formulario1.close();
}
}
<file_sep>package Formulario;
public class FormularioPrincipalController {
private Main main;
public FormularioPrincipalController(){
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public void abrirFormulario1() {
main.abrirFormulario1();
}
public void abrirFormulario2() {
main.abrirFormulario2();
}
public void Salir() {
System.exit(0);
}
}
<file_sep>package HolaMundo;
import javax.swing.JOptionPane;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class HolaMundoController {
@FXML private TextField txtnombre;
@FXML private Label lblMensaje;
@FXML
public void accionHolaMundo(){
}
@FXML
public void salir(){
System.exit(0);
}
}
<file_sep>package videoClub;
import java.net.URL;
import java.sql.Date;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import modelo.Cliente;
import modelo.Conexion;
import modelo.Moneda;
import modelo.Pelicula;
import modelo.Usuario;
import modelo.VideoClub;
public class VideoClubController implements Initializable{
@FXML private ComboBox<Pelicula> cboPelicula;
@FXML private ComboBox<Moneda> cboMoneda;
@FXML private Button btnAgregar;
@FXML private Button btnEliminar;
@FXML private Button btnModificar;
@FXML private TextField txtCodigo;
@FXML private TextField txtNombre;
@FXML private TextField txtDescripcion;
@FXML private TextField txtEstatus;
@FXML private TextField txtIdentidadCliente;
@FXML private TextField txtNombreCliente;
@FXML private TextField txtTelefono;
@FXML private TextField txtDemoraLempiras;
@FXML private TextField txtDemoraDolares;
@FXML private TextField txtCantidadPeliculas;
//Revisar el precio a alquiler y verificar si es estreno o no
@FXML private TextField txtPrecioAlquiler;
@FXML private TextField txtTotal;
@FXML private TableView<VideoClub> tblInformacion;
private Conexion conexion;
private ObservableList<Moneda> listaMoneda;
private ObservableList<Pelicula> listaPelicula;
private ObservableList<VideoClub> informacion;
@FXML private TableColumn<VideoClub,Number> clmnCodigoVenta;
@FXML private TableColumn<VideoClub,String> clmnCodigoCliente;
@FXML private TableColumn<VideoClub,String> clmnNombrePelicula;
@FXML private TableColumn<VideoClub,String> clmnNombreCliente;
@FXML private TableColumn<VideoClub,Date> clmnFechaDevolucion;
private Main main;
/*
@FXML private TableColumn<VideoClub,String> clmnDescripcionPelicula;
@FXML private TableColumn<VideoClub,String> clmnUsuario;
@FXML private TableColumn<VideoClub,String> clmnEstatusPelicula;
@FXML private TableColumn<VideoClub,Moneda> clmnMoneda;
@FXML private TableColumn<VideoClub,Date> clmnFechaRenta;
@FXML private TableColumn<VideoClub,Long> clmnIdentidad;
@FXML private TableColumn<VideoClub,Long> clmnTelefono;
@FXML private TableColumn<VideoClub,Number> clmnDemorasLempiras;
@FXML private TableColumn<VideoClub,Number> clmnDemorasDolares;
@FXML private TableColumn<VideoClub,Number> clmnCantidadPeliculas;
@FXML private TableColumn<VideoClub,Number> clmnPrecioAlquiler;
@FXML private TableColumn<VideoClub,Number> clmnTotal;
*/
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
/*
*
clmnCodigoVenta.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("codigoCliente"));
clmnDescripcionPelicula.setCellValueFactory(new PropertyValueFactory<VideoClub,String>("descripcionPelicula"));
clmnUsuario.setCellValueFactory(new PropertyValueFactory<VideoClub,String>("Usuario"));
clmnEstatusPelicula.setCellValueFactory(new PropertyValueFactory<VideoClub,String>("EstatusPelicula"));
clmnCategoria.setCellValueFactory(new PropertyValueFactory<VideoClub,Pelicula>("categoria"));
clmnMoneda.setCellValueFactory(new PropertyValueFactory<VideoClub,Moneda>("moneda"));
clmnFechaRenta.setCellValueFactory(new PropertyValueFactory<VideoClub,Date>("fechaRenta"));
clmnIdentidad.setCellValueFactory(new PropertyValueFactory<VideoClub,Long>("identidad"));
clmnTelefono.setCellValueFactory(new PropertyValueFactory<VideoClub,Long>("telefono"));
clmnDemorasLempiras.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("demorasLempiras"));
clmnDemorasDolares.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("demorasDolares"));
clmnCantidadPeliculas.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("cantidadPeliculas"));
clmnPrecioAlquiler.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("precioAlquiler"));
clmnTotal.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("total"));
*/
conexion = new Conexion();
conexion.establecerConexion();
//se enlistan
listaMoneda = FXCollections.observableArrayList();
listaPelicula = FXCollections.observableArrayList();
informacion = FXCollections.observableArrayList();
//llenar listas
Moneda.llenarInformacion(conexion.getConexion(), listaMoneda);
Pelicula.llenarInformacion(conexion.getConexion(), listaPelicula);
VideoClub.llenarTableView(conexion.getConexion(), informacion);
cboPelicula.setItems(listaPelicula);
cboMoneda.setItems(listaMoneda);
tblInformacion.setItems(informacion);
//ENLAZAR COLUMNAS CON ATRIBUTOS
clmnCodigoVenta.setCellValueFactory(new PropertyValueFactory<VideoClub,Number>("codigoVenta"));
/*clmnNombrePelicula.setCellValueFactory(new PropertyValueFactory<VideoClub,String>("plicula"));
clmnNombreCliente.setCellValueFactory(new PropertyValueFactory<VideoClub,String>("cliente"));
clmnFechaDevolucion.setCellValueFactory(new PropertyValueFactory<VideoClub,Date>("fechaDevolucion"));*/
tblInformacion.getSelectionModel().selectedItemProperty().
addListener(new ChangeListener<VideoClub>() {
@Override
public void changed(
ObservableValue<? extends VideoClub> arg0,
VideoClub valorNuevo, VideoClub valorAnterior) {
btnModificar.setDisable(false);
btnEliminar.setDisable(false);
if(valorNuevo != null) {
btnAgregar.setDisable(true);
llenarComponentes(valorNuevo);
}
}
}
);;
conexion.cerrarConexion();
}
//RECORDAR AQUI VAN TODOS LOS COMPONENTES QUE SE VAN A MODIFICAR EN UN DADO CASO
//QUE SE SELECCIONE DEL TABLEVIEW
public void llenarComponentes(VideoClub valorNuevo) {
this.txtCodigo.setText(String.valueOf(valorNuevo.getCodigoVenta()));
}
public void registroNoAgregado() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Registro no agregado");
alert.setTitle("Registro no agregado");
alert.setHeaderText("resultado");
alert.showAndWait();
}
//RECORDAR CORREGIR LOS DATOS FALTANTES EN LA BASE DE DATOS, CONSTRUCTORES ETC
@FXML
public void agregar() {
VideoClub vc = new VideoClub(
Integer.valueOf(txtCodigo.getText()),
Integer.valueOf(txtCantidadPeliculas.getText()),
Integer.valueOf(txtPrecioAlquiler.getText()),
//recordar crear funcion para calculo de total ( linea de abajo )
Integer.valueOf(txtTotal.getText()),
new Cliente(null , txtNombreCliente.getText(),Integer.valueOf( txtIdentidadCliente.getText()),Integer.valueOf(txtTelefono.getText()),Integer.valueOf(txtDemoraLempiras.getText())),
new Pelicula(null, this.txtNombre.getText(), null, this.txtDescripcion.getText(), null, this.txtEstatus.getText()),
null ,
null ,
null, new Usuario(null , null , null)
);
conexion.establecerConexion();
vc.guardarRegistro(conexion);
conexion.cerrarConexion();
}
@FXML
public void eliminar() {
VideoClub vc = new VideoClub(
Integer.valueOf(txtCodigo.getText()),
Integer.valueOf(txtCantidadPeliculas.getText()),
Integer.valueOf(txtPrecioAlquiler.getText()),
//recordar crear funcion para calculo de total ( linea de abajo )
Integer.valueOf(txtTotal.getText()),
new Cliente(null , txtNombreCliente.getText(),Integer.valueOf( txtIdentidadCliente.getText()),Integer.valueOf(txtTelefono.getText()),Integer.valueOf(txtDemoraLempiras.getText())),
new Pelicula(null, this.txtNombre.getText(), null, this.txtDescripcion.getText(), null, this.txtEstatus.getText()),
null ,
null ,
null, new Usuario(null , null , null)
);
conexion.establecerConexion();
int resultado = vc.eliminarRegistro(conexion);
conexion.cerrarConexion();
}
@FXML
public void modificar() {
VideoClub vc = new VideoClub(
Integer.valueOf(txtCodigo.getText()),
Integer.valueOf(txtCantidadPeliculas.getText()),
Integer.valueOf(txtPrecioAlquiler.getText()),
//recordar crear funcion para calculo de total ( linea de abajo )
Integer.valueOf(txtTotal.getText()),
new Cliente(null , txtNombreCliente.getText(),Integer.valueOf( txtIdentidadCliente.getText()),Integer.valueOf(txtTelefono.getText()),Integer.valueOf(txtDemoraLempiras.getText())),
new Pelicula(null, this.txtNombre.getText(), null, this.txtDescripcion.getText(), null, this.txtEstatus.getText()),
null ,
null ,
null, new Usuario(null , null , null)
);
conexion.establecerConexion();
int resultado = vc.modificarRegistro(conexion);
conexion.cerrarConexion();
}
public void abrirFormulario1() {
main.abrirFormulario1();
}
public void abrirFormulario2() {
main.abrirFormulario2();
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
@FXML
public void Salir() {
System.exit(0);
}
}
<file_sep>package clases;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Principal {
private ArrayList<Cliente> cliente;
private int op = 0;
private int op1 = 0;
private Cliente cliente1;
/*
* <NAME>
* 20131008925
* SECCION 1000
*/
public Principal(){
cliente = new ArrayList<Cliente>();
do{
op = Integer.valueOf(JOptionPane.showInputDialog(null, "Ingrese una opccion:\n1 - Agregar suscriptor.\n2 - Eliminar suscriptor."
+ "\n3 - Mostrar suscriptores.\n4 - Salir. "));
switch (op) {
case 1:
agregarSuscriptor();
break;
case 2:
eliminarSuscriptor();
break;
case 3:
mostrarDatos();
break;
case 4:
JOptionPane.showMessageDialog(null, " Bye Bye ¬¬");
System.exit(0);
break;
default:
JOptionPane.showMessageDialog(null, "Valor invalido");
break;
}
}while(op != 4 );
}
private void eliminarSuscriptor(){
op1 = Integer.valueOf(JOptionPane.showInputDialog("Que indice desea eliminar?"));
cliente.remove(op1);
}
private void agregarSuscriptor(){
cliente1 = new Cliente();
String errores= "";
do{
errores = "";
cliente1.solicitarDatos(new Cliente());
errores+= cliente1.validarDatos();
if(cliente1.validarDatos().isEmpty())
errores = "";
if(!errores.isEmpty())
JOptionPane.showMessageDialog(null, errores);
}while(!errores.isEmpty());
cliente.add(cliente1);
}
private void mostrarDatos(){
for(int i = 0; i < cliente.size(); i++){
System.out.println("Nombre" + "\t\t" + "Apellido" + "\t\t" + "Genero"+ "\t\t"
+ "Edad"+ "\t\t" + "---------------DATOS VARIOS-----------------------------------------------------------------------------------------" + "\n");
System.out.println(cliente.get(i).toString());
System.out.println("--------------------------------------------------------------------------------------------------------------------------------------\n");
}
}
public static void main(String[] args) {
new Principal();
}
}
<file_sep>package modelo;
public class Vendedor extends Usuario{
public Vendedor(Integer codigoUsuario, String cargo, String nombreUsuario) {
super(codigoUsuario, cargo, nombreUsuario);
// TODO Auto-generated constructor stub
}
}
<file_sep>package modelo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
public class Moneda {
private IntegerProperty codigoMoneda;
private StringProperty nombreMoneda;
public Moneda(Integer codigoMoneda, String nombreMoneda){
this.codigoMoneda = new SimpleIntegerProperty(codigoMoneda);
this.nombreMoneda = new SimpleStringProperty(nombreMoneda);
}
public Integer getCodigoMoneda(){
return codigoMoneda.get();
}
public void setCodigoMoneda(Integer codigoMoneda){
this.codigoMoneda = new SimpleIntegerProperty(codigoMoneda);
}
public String getNombreMoneda(){
return nombreMoneda.get();
}
public void setNombreMoneda(String nombreMoneda){
this.nombreMoneda = new SimpleStringProperty(nombreMoneda);
}
public IntegerProperty codigoMonedaProperty(){
return codigoMoneda;
}
public StringProperty nombreMonedaProperty(){
return nombreMoneda;
}
//RECORDAR MODIFICAR LA SENTENCIA SQL
public static void llenarInformacion(Connection connection, ObservableList<Moneda> lista) {
try {
Statement stament = connection.createStatement() ;
ResultSet resultado = stament.executeQuery(
"SELECT codigo_moneda, "
+"nombre_moneda "
+ "FROM tbl_moneda");
while(resultado.next()) {
lista.add(new Moneda( resultado.getInt("codigo_moneda"),
resultado.getString("nombre_moneda")
)
);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>package clases;
import java.util.Date;
import javax.swing.JOptionPane;
public class Mensajes extends Paquete{
private int CantidadSMS;
private int CantidadMMS;
private String errores = "";
public Mensajes(){
super();
}
public void IngresarDatos(Mensajes mensaje){
costo = Integer.valueOf(JOptionPane.showInputDialog("Costo del paquete"));
CantidadSMS = Integer.valueOf(JOptionPane.showInputDialog("Cantidad de mensajes de texto:",this.getCantidadSMS()));
CantidadMMS = Integer.valueOf(JOptionPane.showInputDialog("Cantidad de mensajes multimedia:",this.getCantidadMMS()));
}
public Mensajes(int costo, Date fechaAdquisicion, int cantidadSMS,
int cantidadMMS) {
super(costo, fechaAdquisicion);;
}
public String validarDatos(){
if(CantidadSMS==0)
errores+="Ingrese los mensajes de texto.\n";
if(CantidadMMS==0)
errores+="Ingrese los mensajes multimedia.\n";
return errores;
}
@Override
protected float Total() {
// TODO Auto-generated method stub
return 0;
}
public int getCantidadSMS() {
return CantidadSMS;
}
public void setCantidadSMS(int cantidadSMS) {
CantidadSMS = cantidadSMS;
}
public int getCantidadMMS() {
return CantidadMMS;
}
public void setCantidadMMS(int cantidadMMS) {
CantidadMMS = cantidadMMS;
}
@Override
public String toString() {
return "\t\t" + this.getCantidadMMS() + "\t\t"
+ this.CantidadSMS;
}
}
<file_sep>-- MySQL Script generated by MySQL Workbench
-- 07/19/15 13:18:46
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `mydb` ;
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
SHOW WARNINGS;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`pelicula`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`pelicula` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `mydb`.`pelicula` (
`pelicula_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`nombre` VARCHAR(20) NOT NULL COMMENT '',
`categoria` VARCHAR(45) NULL COMMENT '',
`descripcion` MEDIUMTEXT NULL COMMENT '',
`formato` VARCHAR(45) NOT NULL COMMENT '',
`status` VARCHAR(15) NULL COMMENT '',
`fecha_renta` DATE NULL COMMENT '',
`fecha_devolucion` DATE NULL COMMENT '')
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `mydb`.`cliente`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`cliente` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `mydb`.`cliente` (
`clinete_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`nombre` VARCHAR(45) NOT NULL COMMENT '',
`codigo` VARCHAR(45) NOT NULL COMMENT '',
`numero_id` VARCHAR(45) NOT NULL COMMENT '',
`telefono` VARCHAR(45) NOT NULL COMMENT '',
`status` VARCHAR(45) NOT NULL COMMENT '',
PRIMARY KEY (`clinete_id`) COMMENT '')
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `mydb`.`usuario`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`usuario` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `mydb`.`usuario` (
`usuario_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`codigo` VARCHAR(45) NOT NULL COMMENT '',
`nombre` VARCHAR(45) NOT NULL COMMENT '',
`cargo` VARCHAR(45) NOT NULL COMMENT '',
`cliente_clinete_id` INT NOT NULL COMMENT '',
PRIMARY KEY (`usuario_id`) COMMENT '',
CONSTRAINT `fk_usuario_cliente`
FOREIGN KEY (`cliente_clinete_id`)
REFERENCES `mydb`.`cliente` (`clinete_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
CREATE INDEX `fk_usuario_cliente_idx` ON `mydb`.`usuario` (`cliente_clinete_id` ASC) COMMENT '';
SHOW WARNINGS;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>package clases;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class LineaTelefonica {
private long numeroTelefonico;
private long imei;
private LineaTelefonica lineaTelefonica;
private ArrayList<Paquete> array;
private int op = 0;
private String errores = "";
Mensajes mensajes;
TiempoAire tiempoAire;
Internet internet;
//Como el constructor vacio ya esta asignado decidi ponerle uno boleano
public LineaTelefonica(boolean b){
}
public LineaTelefonica(){
array = new ArrayList<Paquete>();
}
public void solicitarDatos(LineaTelefonica lineaTelefonica){
numeroTelefonico = Long.valueOf(JOptionPane.showInputDialog("Ingrese el numero telefonico:", this.getNumeroTelefonico()));
imei = Long.valueOf(JOptionPane.showInputDialog("Imei:", this.getImei()));
do{
op = Integer.valueOf(JOptionPane.showInputDialog("Que desea agregar:\n1 - Paquete de mensajes.\n2 - Paquete de internet."+
"\n3 - Tiempo aire.\n4 - Continuar."));
switch (op) {
case 1:
mensajes = new Mensajes();
mensajes.IngresarDatos(new Mensajes());
errores += mensajes.validarDatos();
array.add(mensajes);
break;
case 2:
internet = new Internet();
internet.IngresarDatos(new Internet());
errores += internet.validarDatos();
array.add(internet);
break;
case 3:
tiempoAire = new TiempoAire();
tiempoAire.ingresarDatos(new TiempoAire());
errores += tiempoAire.validarDatos();
array.add(tiempoAire);
break;
case 4:
break;
default:
JOptionPane.showMessageDialog(null, "Ingrese una opcion.");
break;
}
}while(op != 4);
}
public String validarDatos(){
if(numeroTelefonico==0)
errores+="El campo numero de telefono esta vacio\n";
if(imei==0)
errores+="El campo imei esta vacio\n";
/*
errores+= mensajes.validarDatos();
errores+= internet.validarDatos();
errores+=tiempoAire.validarDatos();
*/
return errores;
}
public long getNumeroTelefonico() {
return numeroTelefonico;
}
public void setNumeroTelefonico(long numeroTelefonico) {
this.numeroTelefonico = numeroTelefonico;
}
public long getImei() {
return imei;
}
public void setImei(long imei) {
this.imei = imei;
}
public String getErrores() {
return errores;
}
public void setErrores(String errores) {
this.errores = errores;
}
@Override
public String toString() {
String s= "";
for(int i = 0;i<array.size();i++){
s += array.get(i).toString();
}
return "\t\t" + numeroTelefonico
+ "\t\t" + imei + "\t\t" + lineaTelefonica
+ "\t\t" + array + "\t\t"+ s ;
}
}
<file_sep>#Thu Jun 11 18:35:20 CST 2015
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140925-0400
<file_sep>package Inventario;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class InventarioController implements Initializable {
@FXML private ComboBox cboMarca;
@FXML private TextField txtCodigoProducto;
@FXML private TextField txtCodigoBarra;
@FXML private TextField txtNombreProducto;
@FXML private TextField txtPrecioVenta;
@FXML private TextField txtPrecioCompra;
@FXML private TextArea txtDescripcionProducto;
private ObservableList<String> listaMarcas;
//NOTIFICA A LA GUI CUANDO HAY CAMBIO EN LA INFORMACION
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// SE ESTA SEGYURO DE QUE LOS COMPONENTES D ELA GUI ESTAN INSTANCIADOS
listaMarcas = FXCollections.observableArrayList();
listaMarcas.add(null);
cboMarca.setItems(listaMarcas);
}
}
| 7288c4305bc16d6fd1656ccad6911bdd9b806e84 | [
"Java",
"SQL",
"INI"
] | 13 | INI | Marcocono/RepositorioMarco | 80fd49e3e18506a2761fdf351f921828cbceae5d | a22ba6951e2d9ca3e3e6b9bfa9583ab9330148c9 |
refs/heads/master | <repo_name>uniray7/SEO-profiler<file_sep>/README.md
# SEO-profiler
## Install
``` shell
$ npm install
```
## Get started
### Import the module
```javascript
const { scanHtml, Validator, rule1, rule2, rule3, rule4, rule5 } = require("./SEO-profiler.js");
```
### Input
##### File path as input
```javascript
const validator = new Validator([rule1]);
scanHtml('./example.html', validator, console);
```
##### Readstream as input
```javascript
const fs = require("fs");
const readStream = fs.createReadStream('example.html');
const validator = new Validator([rule1]);
scanHtml(readStream, validator, console);
```
### Output
##### File path as output
```javascript
const validator = new Validator([rule1]);
scanHtml('./example.html', validator, 'example.out');
```
##### Writestream as output
```javascript
const fs = require("fs");
const writeStream = fs.createWriteStream('example.out');
const validator = new Validator([rule1]);
scanHtml('./example.html', validator, writeStream);
```
##### Writestream as output
```javascript
const validator = new Validator([rule1]);
scanHtml('./example.html', validator, console);
```
### Self-defined rule
``` javascript
// Given rule 1:
// Detect if any <img /> tag without alt attribute
const myRule1 = new Rule().tag("img").notHasAttr("alt").gt(0);
// Given rule 3:
// In <head> tag
// i. Detect if header doesn’t have <title> tag
// ii. Detect if header doesn’t have <meta name=“descriptions” … /> tag
// iii. Detect if header doesn’t have <meta name=“keywords” … /> tag
const myRule3 = [
new Rule("head").tag("title").gt(0),
new Rule("head").tag("meta").hasAttr("name", "description").gt(0),
new Rule("head").tag("meta").hasAttr("name", "keywords").gt(0),
];
```
<file_sep>/src/Rule.js
class Rule{
constructor(scope) {
this._scope = scope;
this._tag = null;
this._attr = null;
this._cond = null;
this._thres = null;
}
tag(target) {
this._tag = target;
return this
}
notHasAttr(attr, value) {
this._attr = {};
this._attr.key = attr
if(value) {
this._attr.value = value;
}
this._attr.exist = false;
return this;
}
hasAttr(attr, value) {
this._attr = {};
this._attr.key = attr
if(value) {
this._attr.value = value;
}
this._attr.exist = true;
return this;
}
gt(num) {
this._cond = 'gt';
this._thres = num;
return this;
}
}
module.exports = Rule;
<file_sep>/src/Validator.js
const cheerio = require("cheerio");
const P = require("bluebird");
const { format } = require("util");
const { flatten, forEach } = require("lodash");
class Validator{
/**
* Construct a validator with given rules
* @param { [Rule,[Rule]] } rules - input source
*/
constructor(rules) {
this._rules = flatten(rules);
this._results;
}
scan(content) {
const $ = cheerio.load(content);
let results = new Array(this._rules.length);
// scan content with all rules
forEach(this._rules, function(rule, idx) {
let query = "";
if(rule._scope) {
query += rule._scope;
query += ">";
}
if(rule._tag) {
query += rule._tag;
}
if(rule._attr) {
if(rule._attr.exist) {
if(rule._attr.value) {
query += format("[%s='%s']", rule._attr.key, rule._attr.value);
} else {
query += format("[%s]", rule._attr.key);
}
} else {
query += ":not(";
if(rule._attr.value) {
query += format("[%s='%s']", rule._attr.key, rule._attr.value);
} else {
query += format("[%s]", rule._attr.key);
}
query += ")";
}
}
if(rule._cond && !isNaN(rule._thres)) {
if(rule._cond === "gt") {
results[idx] = ( $(query).length > rule._thres)
} else if(rule._cond === "lt") {
results[idx] = ( $(query).length < rule._thres)
}
}
});
this._results = results;
} // scan()
asyncGenReport() {
return new P.Promise((resolve, reject) => {
let report = "";
let results = this._results;
forEach(this._rules, function(rule, idx) {
report += "There is "
if(!results[idx]) {
report += "no "
}
if(rule._cond === "gt" && rule._thres>0) {
report += format("more than %d ", rule._thres);
} else if(rule._cond === "lt" && rule._thres>0) {
report += format("less than %d ", rule._thres);
}
report += format("<%s> tags ", rule._tag)
if(rule._attr) {
if(rule._attr.exist) {
report += format("with ")
} else {
report += format("without ")
}
report += format("attribute %s ", rule._attr.key);
if(rule._attr.value) {
report += format("= %s ", rule._attr.value);
}
}
if(rule._scope) {
report += format("in <%s> ", rule._scope);
}
report += ".\n";
}) //forEach
resolve(report);
}); //Promise
} // asyncGenReport
}
module.exports = Validator;
<file_sep>/SEO-profiler.js
const scanHtml = require("./src/scanHtml.js");
const Rule = require("./src/Rule.js");
const Validator = require("./src/Validator.js");
const rule1 = new Rule().tag("img").notHasAttr("alt").gt(0);
const rule2 = new Rule().tag("a").notHasAttr("rel").gt(0);
const rule3 = [
new Rule("head").tag("title").gt(0),
new Rule("head").tag("meta").hasAttr("name", "descriptions").gt(0),
new Rule("head").tag("meta").hasAttr("name", "keywords").gt(0),
];
const rule4 = new Rule().tag("strong").gt(15);
const rule5 = new Rule().tag("H1").gt(1);
module.exports = {
scanHtml,
Rule,
Validator,
rule1,
rule2,
rule3,
rule4,
rule5
};
<file_sep>/src/asyncFetchHtml.js
const fs = require("fs");
const P = require("bluebird");
const stream = require("stream");
/**
* Asynchronously fetch html file
* @param {string|ReadStream} target - the html file path or read stream
* @returns {string}
*/
function asyncFetchHtml(target) {
let readStream;
if (typeof target === "string") {
// TODO: error handling
readStream = fs.createReadStream(target);
}
// TODO: the "else if" statement may be not good,
// ref: https://stackoverflow.com/questions/23885095/nodejs-check-if-variable-is-readable-stream
else if(target instanceof stream.Readable) {
readStream = target;
}
else {
// TODO: throw error or return None
return;
}
let resultBuf = null;
return new P.Promise((resolve, reject) => {
readStream.on("data", (chunk) => {
if (resultBuf === null) {
resultBuf = chunk;
} else {
resultBuf = Buffer.concat([resultBuf, chunk]);
}
});
readStream.on("end", () => {
if(resultBuf) {
return resolve(resultBuf.toString());
} else {
return resolve("");
}
});
readStream.on("error", (err) => {
return reject(err);
});
});
}
module.exports = asyncFetchHtml;
// main for roughly testing
if (require.main === module) {
let testPath = "./test.html";
// asyncFetchHtml(path).then((result)=> {console.log(result); console.log("get!!!")})
const testStream = fs.createReadStream(testPath);
asyncFetchHtml(testStream).then((result)=> {console.log(result); console.log("get!!!")})
}
<file_sep>/example.js
const { scanHtml, Validator, rule1, rule2, rule3, rule4, rule5 } = require("./SEO-profiler.js");
const validator = new Validator([rule1, rule2, rule3, rule4, rule5]);
scanHtml('./example.html', validator, console);
<file_sep>/src/asyncOutput.js
const fs = require("fs");
const P = require("bluebird");
const stream = require("stream");
/**
* Asynchronously output to destination
* @params {string} content - contnt to output
* @params {console|string|WriteStream} dest - output destination
*/
function asyncOutput(content, dest) {
// TODO: need to check type of content?
if(dest instanceof console.Console) {
dest.log(content);
return P.resolve();
} else if(typeof(dest) === 'string'){
return new P.Promise((resolve, reject) => {
fs.writeFile(dest, content, (err) => {
if(err) {
reject(err);
} else {
resolve();
}
});
});
} else if(dest instanceof stream.Writable) {
// TODO: need slice content?
return new P.Promise((resolve, reject) => {
dest.write(content, 'utf-8', () => {
return resolve();
});
dest.on("error", (err) => {
return reject(err);
})
});
} else {
console.log("Wrong output type")
// TODO: error handling
}
}
module.exports = asyncOutput;
// main for roughly testing
if (require.main === module) {
let testPath = "./test.out";
const content = "asdfghjkl"
const testStream = fs.createWriteStream(testPath);
asyncOutput(content, testStream).then(()=> {console.log("finish write!!!")})
//asyncOutput(content, testPath).then(()=> {console.log("finish write!!!")})
//asyncOutput(content, console).then(()=> {console.log("finish write!!!")})
}
| 20cc1f21a7e921ce5d48f6ba0d96f13d0966aacf | [
"Markdown",
"JavaScript"
] | 7 | Markdown | uniray7/SEO-profiler | 839a18a9fa0f14e37cf2c5009e1dd6c3c40f641d | 69a99911c6f9fac7309da505cbb36f9dbf7ea9fb |
refs/heads/master | <repo_name>eduardomalikoski/QuickBuy<file_sep>/QuickBuy.Web/ClientApp/src/app/usuario/login/login.component.ts
import { Component, OnInit } from "@angular/core";
import { Usuario } from "../../model/usuario";
import { Router, ActivatedRoute } from "@angular/router";
import { UsuarioServico } from "../../servicos/usuario/usuario.servico";
@Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
public usuario;
public returnUrl: string;
public mensagem: string;
public ativar_spinner: boolean;
constructor(private router: Router, private activatedRouter: ActivatedRoute, private usuarioServico: UsuarioServico) {
}
ngOnInit(): void {
this.returnUrl = this.activatedRouter.snapshot.queryParams['returnUrl']
this.usuario = new Usuario();
}
entrar() {
this.ativar_spinner = true;
this.usuarioServico.verificarUsuario(this.usuario)
.subscribe(
usuario_json => {
this.usuarioServico.usuario = usuario_json;
if (this.returnUrl == null) {
this.router.navigate(['/']);
} else {
this.router.navigate([this.returnUrl]);
}
},
err => {
console.log(err.error);
this.mensagem = err.error;
this.ativar_spinner = false;
}
);
}
public img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAT4AAACfCAMAAABX0UX9AAAAzFBMVEX///+1LjHiMje0KCu0Ki2zISW6LzLcMja0LjG+SUvDXV/57u6yHiK0KSy8S02vBA39+PjEZWfSj5CxFxz25ufmxMTDWFvdoaL9+frhJiziLTLv09S3NDfWlpi7QkX64+PgFh6wDhTzsrPfrK3lu7zuz9DnWFzLdHb63N386+vmUFT1v8DlRUn30NHvmJrPfX/sgoTreXzhs7TRhYb<KEY>5ErkJggg==";
}
| 26522efdb5a39b0575333f5b221d3111a9eb47a1 | [
"TypeScript"
] | 1 | TypeScript | eduardomalikoski/QuickBuy | 074cd576c254c6d661ee7d651e20859a9eaa59f0 | 443dc8e180430145ef14c01af5a85e8e607720c8 |
refs/heads/master | <file_sep># encode:UTF-8
print "hellow world"
[ 0 for _ in range(10)]
| 762eccacb4fa39ab39829a72262bd883734d37ab | [
"Python"
] | 1 | Python | yhrfm/myfirstproject | 5fbeddc893ae743430a114713f8958ce43cb7839 | 0da3b206fdb88b4db50a00864e6624381ef2b210 |
refs/heads/master | <file_sep>global.self = global
// import createLogger from 'redux-logger'
import { identity } from 'ramda'
import { createStore, applyMiddleware, compose } from 'redux'
import red from '../reducers'
import createSagaMiddleware from 'redux-saga'
import { rootSaga } from '../sagas'
// import { helloSaga } from '../sagas'
// import persistState from 'redux-localstorage'
// import Immutable from 'immutable-ext'
// import { Socket } from 'dream-wallet/lib/network'
const network = require('dream-wallet/lib/network')
const middlewares = require('dream-wallet/lib/middleware')
import * as C from '../config'
import { persistStore, autoRehydrate } from 'redux-persist'
import { AsyncStorage } from 'react-native'
import { completeRehydration } from '../actions'
// persistStore(store, {storage: AsyncStorage})
import createEncryptor from 'redux-persist-transform-encrypt';
const configureStore = () => {
// const socket = new Socket()
// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__(
// { serialize: { immutable: Immutable } }) || compose
const api = network.createWalletApi({ rootUrl: C.ROOT_URL
, apiUrl: C.API_BLOCKCHAIN_INFO
, apiCode: C.API_CODE})
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
red({wpath: C.WALLET_IMMUTABLE_PATH, dpath: C.BLOCKCHAIN_DATA_PATH}),
compose(
// persistState('session'),
applyMiddleware(
middlewares.walletSyncMiddleware({ api: api, wpath: C.WALLET_IMMUTABLE_PATH}),
// walletSocketMiddleware({ socket }),
sagaMiddleware
// createLogger()
),
autoRehydrate()
)
)
// const encryptor = createEncryptor({
// secretKey: 'my-super-secret-key'
// });
persistStore(store,
{ storage: AsyncStorage,
whitelist: ['credentials'],
// transforms: [encryptor]
}
, () => { store.dispatch(completeRehydration()) }
// ).purge() // clean the stored state
)
sagaMiddleware.run(rootSaga({ api: api
, wpath: C.WALLET_IMMUTABLE_PATH
, dpath: C.BLOCKCHAIN_DATA_PATH}))
return {
...store
// runSaga: sagaMiddleware.run
}
}
export default configureStore
<file_sep>import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Button,
TextInput,
} from 'react-native'
import * as actions from '../actions'
import * as wActions from 'dream-wallet/lib/actions'
import * as C from '../config'
import { connect } from 'react-redux'
import LoggedIn from './LoggedIn'
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
}
})
class Login extends Component {
constructor (props) {
super(props)
this.state = {
email: '',
password: '',
pinSet: '',
// guid: 'f9df366a-3fc3-4826-827f-fb3c1e8ce616',
// sharedKey: '00efae13-985b-4858-81ad-71bd8b5ac863',
// logPass: '<PASSWORD>',
pin: ''
}
}
login () {
const credentials = {
// guid: this.state.guid,
// sharedKey: this.state.sharedKey,
// password: <PASSWORD>,
pin: this.state.pin
}
this.props.dispatch(actions.loginStart(credentials))
}
create () {
const credentials = {
email: this.state.email,
password: <PASSWORD>,
pin: this.state.pinSet
}
this.props.dispatch(wActions.newWallet(credentials))
}
renderLogin () {
return (
<View>
<View>
<Text>Login success: {this.props.loginState.success.toString()} </Text>
<Text>Login pending: {this.props.loginState.pending.toString()}</Text>
<Text>Login error: {this.props.loginState.error}</Text>
</View>
<View>
{/* <TextInput
style={{height: 40}}
autoCorrect={false}
value={this.state.guid}
keyboardType='default'
placeholder="guid"
autoCapitalize='none'
onChangeText={(guid) => this.setState({guid})}
/>
<TextInput
style={{height: 40}}
value={this.state.sharedKey}
autoCorrect={false}
keyboardType='default'
secureTextEntry={false}
placeholder="sharedKey"
autoCapitalize='none'
onChangeText={(sharedKey) => this.setState({sharedKey})}
/>
<TextInput
style={{height: 40}}
value={this.state.logPass}
autoCorrect={false}
keyboardType='default'
secureTextEntry={true}
placeholder="password"
autoCapitalize='none'
onChangeText={(logPass) => this.setState({logPass})}
/> */}
<TextInput
style={{height: 40}}
autoCorrect={false}
keyboardType='numeric'
secureTextEntry={true}
placeholder="pin"
autoCapitalize='none'
maxLength={4}
onChangeText={(pin) => this.setState({pin})}
/>
<Button onPress={this.login.bind(this)} title='Login' />
</View>
</View>
)
}
renderSignup () {
return (
<View>
<TextInput
style={{height: 40}}
autoCorrect={false}
keyboardType='email-address'
placeholder="email"
autoCapitalize='none'
onChangeText={(email) => this.setState({email})}
/>
<TextInput
style={{height: 40}}
autoCorrect={false}
keyboardType='default'
secureTextEntry={true}
placeholder="<PASSWORD>"
autoCapitalize='none'
onChangeText={(password) => this.setState({password})}
/>
<TextInput
style={{height: 40}}
autoCorrect={false}
keyboardType='numeric'
secureTextEntry={true}
placeholder="pin"
autoCapitalize='none'
maxLength={4}
onChangeText={(pinSet) => this.setState({pinSet})}
/>
<Button onPress={this.create.bind(this)} title='Sign up' />
</View>
)
}
render () {
if(!this.props.loginState.success) {
if(this.props.credentials.xpub) {
return this.renderLogin()
} else {
return this.renderSignup()
}
}
else {
return (
<View>
<LoggedIn />
</View>
)
}
}
}
const mapStateToProps = state => ({
loginState: state.loginState,
credentials: state.credentials
})
const mapDispatchToProps = dispatch => ({
dispatch
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Login)
<file_sep>const rate = 1018.78
export const btc = {
name: 'btc',
calc: (btc) => btc,
render: (amt) => `${amt} BTC`
}
export const fiat = {
name: 'fiat',
calc: (btc) => btc * rate,
render: (amt) => `$${amt.toFixed(2)}`
}
<file_sep>export const merchantXpub = state => state.credentials.xpub
<file_sep># Merchant App
1. `npm install`
2. `react-native run-ios`
<file_sep>import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'
import colors from './styles/colors'
const styles = StyleSheet.create({
nav: {
height: 72,
backgroundColor: colors.trueBlue,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
},
navText: {
color: 'white',
fontSize: 24,
marginTop: 16
}
})
class Header extends Component {
render () {
// let title = this.props.children
return (
<View style={styles.nav}>
{/* <IconButton name='bars' size={24} onPress={this.props.onMenu} /> */}
{/* {title ? <Text style={styles.navText}>{title}</Text> : null} */}
{/* <IconButton name='qrcode' size={24} /> */}
</View>
)
}
}
export default Header
<file_sep>import React from 'react'
import { StyleSheet, Text } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import colors from './styles/colors'
const styles = StyleSheet.create({
icon: {
marginTop: 16,
marginLeft: 8
},
verticalIcon: {
width: 120,
flexDirection: 'column'
}
})
const IconButton = ({ name, vertical, children, ...props }) => (
<Icon.Button
name={name}
style={vertical ? styles.verticalIcon : styles.icon}
backgroundColor={colors.transparent}
underlayColor={colors.transparent}
{...props}
>
{children}
</Icon.Button>
)
export default IconButton
<file_sep>import React, { Component } from 'react'
import { StyleSheet, Animated, Easing } from 'react-native'
const styles = StyleSheet.create({
view: {
position: 'absolute',
height: '100%',
width: '100%'
}
})
class SlideUp extends Component {
constructor (props) {
super(props)
this.state = { anim: new Animated.Value(props.show ? 0 : 1) }
}
componentWillReceiveProps (props) {
let { show, duration, easing = Easing.inOut(Easing.quad) } = props
let animConfig = { toValue: show ? 0 : 1, duration, easing }
Animated.timing(this.state.anim, animConfig).start()
}
render () {
let animation = {
top: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: ['0%', '100%']
})
}
return (
<Animated.View style={[styles.view, animation]}>
{this.props.children}
</Animated.View>
)
}
}
export default SlideUp
<file_sep>import { combineReducers } from 'redux'
import login from './login'
import * as A from '../actions'
// import { walletReducer, blockchainDataReducer } from 'dream-wallet/lib/reducers'
const dreamWalletReducers = require('dream-wallet/src/reducers')
import * as R from 'ramda'
// import { SAVE_SESSION, PANEL_SWITCH } from '../actions'
// import { merge } from 'ramda'
// import { reducer as formReducer } from 'redux-form'
const rehydrated = (state = false, action) => {
let { type } = action
switch (type) {
case A.REHYDRATION_COMPLETE: {
return true
}
default:
return state
}
}
const INIT = 0
const counter = (state = INIT, action) => {
let { type } = action
switch (type) {
case 'COUNT_UP': {
return state + 1
}
case 'COUNT_DOWN': {
return state - 1
}
default:
return state
}
}
const CREDENTIALS_INITIAL_STATE = {
guid: null,
sharedKey: null,
password: <PASSWORD>,
xpub: null,
pinEntry: null,
localKey: null
}
const credentials = (state = CREDENTIALS_INITIAL_STATE, action) => {
let { type, payload } = action
switch (type) {
case A.PERSIST_CREDENTIALS: {
return payload
}
default:
return state
}
}
// const session = (state = {}, action) => {
// let { type } = action
// switch (type) {
// case SAVE_SESSION: {
// return merge(state, action.payload)
// }
// default:
// return state
// }
// }
//
// const panel = (state = 'login', action) => {
// let { type, payload } = action
// switch (type) {
// case PANEL_SWITCH: {
// return payload
// }
// default:
// return state
// }
// }
// const reducers = ({wpath, dpath}) => combineReducers({
// panel: panel,
// form: formReducer,
// session: session,
// loginState: login,
// [dpath]: blockchainDataReducer,
// [wpath]: walletReducer
// })
const reducers = ({wpath, dpath}) => combineReducers({
rehydrated: rehydrated,
counter: counter,
loginState: login,
credentials: credentials,
[dpath]: dreamWalletReducers.blockchainDataReducer,
[wpath]: dreamWalletReducers.walletReducer
})
export default reducers
<file_sep>import { AppRegistry } from 'react-native'
const App = require('./ios-app').default
AppRegistry.registerComponent('ReactNativify', () => App)
<file_sep>import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Button
} from 'react-native'
// import stylesApp from './styles/styles'
// import colors from './styles/colors'
import * as actions from '../actions'
import * as C from '../config'
import { connect } from 'react-redux'
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
}
})
class LoggedIn extends Component {
constructor (props) {
super(props)
}
render () {
const info = this.props.data.get('walletInfo').toJS();
return (
<View>
<Text> guid: { this.props.payload.get('walletImmutable').get('guid') } </Text>
<Text> transactions: { info.n_tx } </Text>
<Text> Balance: { info.final_balance } </Text>
<Text> Login pending: { this.props.loginState.pending.toString() }</Text>
<Text> Login success: { this.props.loginState.success.toString() }</Text>
<Text> Login error: { this.props.loginState.error }</Text>
<Text> Credentials: { JSON.stringify(this.props.credentials, null, 2) }</Text>
</View>
)
}
}
const mapStateToProps = state => ({
payload: state[C.WALLET_IMMUTABLE_PATH],
data: state[C.BLOCKCHAIN_DATA_PATH],
loginState: state.loginState,
credentials: state.credentials
})
const mapDispatchToProps = dispatch => ({
dispatch
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoggedIn)
<file_sep>import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Button
} from 'react-native'
import * as actions from '../actions'
import * as C from '../config'
import { connect } from 'react-redux'
let countUp = () => ({ type: 'COUNT_UP' })
let countDown = () => ({ type: 'COUNT_DOWN' })
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
}
})
class Counter extends Component {
constructor (props) {
super(props)
}
countUp () {
this.props.dispatch(countUp())
}
countDown () {
this.props.dispatch(countDown())
}
render () {
return (
<View>
<Text> { this.props.counter } </Text>
<Button onPress={this.countUp.bind(this)} title='Up' />
<Button onPress={this.countDown.bind(this)} title='Down' />
</View>
)
}
}
const mapStateToProps = state => ({
counter: state.counter,
})
const mapDispatchToProps = dispatch => ({
dispatch
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
| 9c03b36ceb89aacffa602d8395823901859cc803 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | Horbi/merchant-app | 5cf0af9cb00229f790c6b92b001684d705755896 | 865967e2e7c3a16d1642c8bb084bb7aa6b7ba386 |
refs/heads/master | <repo_name>mateuszkarnia/diet<file_sep>/moduletime.py
import time
import calendar
def new_day(f):
f= open("dieta.txt","w+")
if datetime.time
else:
pass<file_sep>/creation_profile.py
import main
def get_int_data(text):
while True:
data_to_check = input(text)
try:
data_to_check = int(data_to_check)
return data_to_check
except ValueError:
print("That's now even a digit")
def caloric_formula():
weight = get_int_data('How much is your weight? ')
height = get_int_data('How much is your height? ')
old = get_int_data('How old are you? ')
food_calorie_formula = int(1.6 * (10 * weight + 6.25 * height - 5 * old))
burning_calorie_formula_male = int(655.1 + (9.563 * weight) + (1.85 * height) - (4.676 * old))
burning_calorie_formula_woman = int(66.5 + (13.75 * weight) + (5.003 * height) - (6.775 * old))
return food_calorie_formula, burning_calorie_formula_male, burning_calorie_formula_woman
def get_needed_calories():
print('Hello Sir/Madam')
print("Now we need to get yours daily caloric demand.\nDo you already know it[1] or would you like to count it[2]?")
pressedkey = main.getch()
if pressedkey == '1':
return known_information()
elif pressedkey == '2':
return count_information()
def known_information():
x = get_int_data('Enter your daily caloric demand: ')
dates = caloric_formula()
sex = input('\nAre you male[m] or female[f]?')
return x, dates[1], dates[2], sex
def count_information():
print('Please answer on the following questions.')
sex = sex_choice()
if sex == 'm':
dates = caloric_formula()
return dates[0] - 161, dates[1], dates[2], 'm'
elif sex == 'f':
dates = caloric_formula()
return dates[0] + 5, dates[1], dates[2], 'f'
def sex_choice():
while True:
print('\nAre you male[m] or female[f]?')
sex = main.getch()
if sex == 'm':
return 'm'
elif sex == 'f':
return 'f'
else:
print("Yes, it's foolproof")
def export_to_file(data, mode='w'):
with open('demand_calories.txt', mode) as file:
for element in data:
if element == data[-1]:
file.write(str(element))
else:
file.write(str(element) + ',')
def export_to_file_int(data, mode='w'):
with open('demand_calories.txt', mode) as file:
file.write(str(data))
<file_sep>/main.py
import os
import time
import math
import shutil
import data_manager
import sys
import creation_profile
class color:
PURPLE = '\033[95m0'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def print_menu(menu, upper):
columns = shutil.get_terminal_size().columns
for option in range(len(menu)):
if option == upper:
print(color.BOLD + color.YELLOW + menu[option].upper().center(columns) + color.END)
else:
print(menu[option].center(columns))
def get_input():
options_to_chose = ['Add food and callories what you eat.', 'Add excersise and callories burning', 'Show list of food.',
'Show list of excersises.', 'Exit\n', "Press 'ENTER' to choose"]
current = 0
pressedkey = ''
os.system('clear')
while pressedkey.lower() != 'e':
os.system('clear')
print_menu(options_to_chose, current)
pressedkey = getch()
if pressedkey.lower() == 'w':
if current > 0:
current -= 1
elif pressedkey.lower() == 's':
if current < 4:
current += 1
return current
def pause():
columns = shutil.get_terminal_size().columns
print('\n')
print('Press any key to display a menu.'.center(columns))
next_step = getch()
def print_ascii():
os.system('clear')
columns = shutil.get_terminal_size().columns
print(color.GREEN + " <}\\".center(columns) + color.END)
print(color.BOLD + color.RED + " .--\--.".center(columns))
print(" / ` \\".center(columns))
print(" | |".center(columns))
print(" \ /".center(columns))
print(" '-'-'".center(columns) + color.END)
pause()
def introduction_screen():
print_ascii()
x = creation_profile.get_needed_calories()
if type(x) is tuple:
x = list(x)
creation_profile.export_to_file(x)
else:
creation_profile.export_to_file_int(x)
def run_function(current_choice):
choice = current_choice
if choice == 0:
dict_of_food = {}
data_manager.add_food(dict_of_food)
elif choice == 1:
dict_of_excersises = {}
data_manager.add_excersise(dict_of_excersises)
elif choice == 2:
dict_of_food = {}
data_manager.show_list_of_food()
x = data_manager.import_file(filename='food.txt')
value = data_manager.calculate(x)
data_manager.show_informations(value)
pause()
elif choice == 3:
dict_of_excersises = {}
data_manager.show_list_of_excersises()
pause()
elif choice == 4:
sys.exit()
def main():
while True:
run_function(get_input())
if __name__ == '__main__':
introduction_screen()
main()
<file_sep>/data_manager.py
import os
def add_food(dict_of_food):
name_of_food = input("Enter the name of the food: ")
food_calorie = input("Enter the amount of calories: ")
print("That's not a correct input")
dict_of_food[name_of_food] = food_calorie
fout = "food.txt"
fo = open(fout, "a")
for k, v in dict_of_food.items():
fo.write(str(k) + " " + v + " " + 'kcl\n')
def import_file(filename='food.txt'):
file_to_open = open(filename)
list_from_file = file_to_open.readlines()
for i in range(len(list_from_file)):
list_from_file[i] = list_from_file[i].replace("/n", "").split(" ")
return list_from_file
def show_informations(calories, filename="demand_calories.txt"):
demand_calories = []
with open(filename, "r") as f:
for line in f:
line = line.split(',')
demand_calories.append(line)
print('________________________')
print("\nYou need to eat", (demand_calories[0][0]), "kcl\n")
if demand_calories[0][3] == 'm':
print("You need to burn ", int(int(demand_calories[0][2])/10), "kcl per day to lead a healthy lifestyle.\n")
else:
print("You need to burn", int(int(demand_calories[0][1])/10), "kcl per day to lead a healthy lifestyle.\n")
print('________________________')
if calories > int(demand_calories[0][0]) - 50 and calories < int(demand_calories[0][0]) + 50:
print("\nYou ate ", calories, " kcl That's perfect!")
elif calories < int(demand_calories[0][0]):
print("\nYou ate ", calories, " kcl That's too low!")
elif calories > int(demand_calories[0][0]):
print("\nYou ate ", calories, " kcl That's too much!")
def check_excersises(calories, filename="demand_calories.txt"):
with open(filename, "r") as f:
for line in f:
demand_calories = int(line)
print("\nYou need ", demand_calories, " kcl\n")
if calories > demand_calories - 50 and calories < demand_calories + 50:
print("\n", calories, " kcl That's perfect")
elif calories < demand_calories:
print("\n", calories, " kcl That's too low!")
elif calories > demand_calories:
print("\n", calories, " kcl That's too much!")
def calculate(list_a):
count = 0
for i in range(len(list_a)):
count += int(list_a[i][1])
return count
def show_list_of_food():
print("Your list of food: \n")
with open("food.txt", "r") as f:
for line in f:
print(line, end='')
def show_list_of_excersises():
print("Your list of excersises: \n")
with open("excersises.txt", "r") as f:
for line in f:
print(line, end='')
def add_excersise(dict_of_excersises):
name_of_excersise = input("Enter the name of the excersise: ")
calories_burning = input("Enter the amount of calories burning: ")
dict_of_excersises[name_of_excersise] = calories_burning
fout = "excersises.txt"
fo = open(fout, "a")
for k, v in dict_of_excersises.items():
fo.write(str(k) + " " + v + " " + 'kcl\n')
| 10b38b9ec3311d8a4d19b66ca15498f9c47b8750 | [
"Python"
] | 4 | Python | mateuszkarnia/diet | 63cb51e51d0d7f09e78886195b950b83f30c1f37 | 43f5aed42c80022ec9540303351f69143007ce02 |
refs/heads/master | <file_sep>from django.db import models
from django.contrib.auth.models import AbstractUser
class CloudUser(AbstractUser):
root_path = models.CharField(max_length=128)
trash_path = models.CharField(max_length=128)
class GooglePhotosSync(models.Model):
user = models.ForeignKey(CloudUser, on_delete=models.CASCADE)
g_token = models.CharField(max_length=256, default="", null=True)
g_refresh_token = models.CharField(max_length=256, default="", null=True)
pics_folder = models.CharField(max_length=128)
last_pic = models.CharField(max_length=256, default="", null=True)
last_sync = models.DateTimeField(null=True)
last_sync_result = models.BooleanField(null=True)
<file_sep>let current_folder = window.location.pathname.replace(/^(\/cloud\/)/, "").replace(/\/$/, "");
let trash;
$(document).ready(function() {
if (current_folder.startsWith("--")) {
trash = true;
current_folder = current_folder.replace(/^(--)/, "");
$('#menu-trash').addClass("checked-menu");
} else {
trash = false;
current_folder = current_folder.replace(/^(-)/, "");
$('#menu-files').addClass("checked-menu");
}
current_folder = current_folder.replace(/^\//, "");
console.log("current_folder: "+current_folder);
if (current_folder) $('#parent').show();
else $('#parent').hide();
let root = "trash://";
if (!trash) {
$('#upload-files, #upload-folder').show();
root = "files://";
} else {
$('#paste').hide();
}
$.ajax({
type: "POST",
url: "/cloud/get-folder",
data: { 'folder': root + current_folder },
success: function(data) {
pc = new PolpettaCloud(root, current_folder, "grid", data, trash);
set_buttons_triggers();
}
});
$.getJSON( "/cloud/get-gp-sync-status", display_gp_sync);
$('#sync-now').click(function(){
$('#sync-last > span').text("synching...")
let gp_sync = $('#gp-sync');
gp_sync.css('cursor', 'progress');
$.getJSON( "/cloud/gp-sync", function (data) {
display_gp_sync(data);
$('#gp-sync').css('cursor', 'default');
if (data["pics_folder"]===current_folder) pc.update_folder();
});
gp_sync.css('cursor', 'default');
});
$('#main').on("dblclick", ".type-dir", function() {
let t = "";
if (trash) t = "-";
if (!current_folder) {
window.location.href = window.location.origin+"/cloud/-"+t+"/"+$(this).html();
} else {
window.location.href = window.location.origin+"/cloud/-"+t+"/"+current_folder+"/"+$(this).html();
}
});
});
function set_buttons_triggers() {
$('#parent').click(function(){
window.location.href = window.location.href.replace(/\/[^/]+$/, ''); // magic
});
$('#table-container, #grid-container').on("mousedown", function(e) {
if (e.shiftKey) e.preventDefault();
});
$('#table-files').on("click", "tbody tr", function(event) {
pc.click_entry(event, $(this), '#table-files tbody tr');
});
$('#grid-container').on("click", ".grid-element", function(event) {
pc.click_entry(event, $(this), '#grid-container>.grid-element');
});
$('#delete').click(pc.action_delete);
$('#restore').click(pc.action_restore);
$('#perm-delete').click(pc.action_perm_delete);
$('#download').click(pc.action_download);
$('#rename').click(pc.action_rename);
$('#create-folder').click(pc.action_create_folder);
$('#copy').click(pc.action_copy);
$('#cut').click(pc.action_cut);
$('#paste').click(pc.action_paste);
$('#upload-files').click(function() {
$('#upload-files-hidden').trigger('click');
});
//$('#upload-files-hidden').change(pc.action_upload_file());
$('#show-grid').click(function(){
pc.set_visualization_mode("grid");
});
$('#show-table').click(function(){
pc.set_visualization_mode("table");
});
}
function display_gp_sync(sync_state) {
let last_p = $('#sync-last > span');
let res = "red";
$('#sync-status > p').hide();
if (sync_state["last_sync_result"]==null) {
last_p.text("NEVER");
if (sync_state["last_sync"] === "NO_CONSENT") $('#sync-no-consent').show();
} else {
last_p.text(sync_state["last_sync"]);
if (sync_state["last_sync_result"]) {
res = "green";
if (sync_state["num_downloaded"]>=0) {
$('#sync-ok > span').text(sync_state["num_downloaded"]);
$('#sync-ok').show();
}
} else {
$('#sync-unsucc').show();
}
}
last_p.attr("class", res);
}<file_sep>#from django.test import TestCase
import unittest
from unittest.mock import patch, call
from cloud.models import GDrive_Index, CloudUser
import cloud.google_api as g_api
# will test on production db, BAD GAB!
class GoogleApiTest(unittest.TestCase):
def setUp(self):
self.user = CloudUser.objects.get(username="test")
GDrive_Index.objects.filter(user=self.user).delete()
def tearDown(self):
#GDrive_Index.objects.filter(user=self.user).delete()
pass
def test_upload_and_delete_file(self): # I know, not an unit test
test_file = GDrive_Index.objects.create(
user = self.user,
gdrive_id = "",
parent_gdrive_id = "",
path = "test.txt",
is_dirty = False,
is_dir = False
)
upload = g_api.gdrive_upload_file(self.user, test_file)
self.assertEqual(upload["id"], test_file.gdrive_id)
delete = g_api.gdrive_delete(self.user, test_file)
self.assertEqual(delete.status_code, 204)
self.assertEqual(test_file.id, None)
def test_check_dirty_was_deleted(self):
with patch.object(g_api, 'gdrive_delete') as mock:
GDrive_Index.objects.create(
user = self.user,
gdrive_id = "anatra",
parent_gdrive_id = "",
path = "file_that_doesnt_exist.txt",
is_dirty = True,
is_dir = False
)
g_api.gdrive_check_dirty(self.user)
mock.assert_called()
def test_check_dirty_new_single_file(self):
with patch.object(g_api, 'gdrive_upload_file') as mock:
GDrive_Index.objects.create(
user = self.user,
gdrive_id = "",
parent_gdrive_id = "actual_parent_id",
path = "test.txt",
is_dirty = True,
is_dir = False
)
g_api.gdrive_check_dirty(self.user)
mock.assert_called()
def test_check_dirty_new_file_with_new_parent(self):
with patch.object(g_api, 'gdrive_upload_file') as mock:
test_file = GDrive_Index.objects.create(
user = self.user,
gdrive_id = "",
parent_gdrive_id = "",
path = "test/test.txt",
is_dirty = True,
is_dir = False
)
test_parent = GDrive_Index.objects.create(
user = self.user,
gdrive_id = "",
parent_gdrive_id = "",
path = "test",
is_dirty = True,
is_dir = True
)
def set_gdrive_id(u, e): e.gdrive_id = "anatra"
mock.side_effect = set_gdrive_id
g_api.gdrive_check_dirty(self.user)
calls = [call(self.user, test_parent), call(self.user, test_file)]
self.assertEqual(mock.mock_calls, calls)
def test_check_dirty_modified(self):
with patch.object(g_api, 'gdrive_upload_file') as mock:
GDrive_Index.objects.create(
user = self.user,
gdrive_id = "anatra",
parent_gdrive_id = "actual_parent_id",
path = "test.txt",
is_dirty = True,
is_dir = False
)
g_api.gdrive_check_dirty(self.user)
mock.assert_called()
<file_sep>from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CloudUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CloudUser
list_display = ['username', 'email', 'root_path', 'trash_path']
fieldsets = (
(('User'), {'fields': ('username', 'email', 'root_path', 'trash_path')}),
)
admin.site.register(CloudUser, CustomUserAdmin)
<file_sep>let pc;
class PolpettaCloud {
constructor(root, current_folder, visualization_mode, files, trash) {
pc = this;
this.current_folder = current_folder;
this.files = files;
this.trash = trash;
this.root = root;
this.update_files(files, false);
this.set_visualization_mode(visualization_mode);
this.fill_info();
this.build_path_bar();
}
update_files(new_files, fill=true) {
pc.files = new_files;
pc.last_selected_index = -1;
pc.selected_entries = [];
pc.selected_indexes = [];
pc.fill_info();
if (fill) {
if (pc.visualization_mode === "table") pc.fill_table();
else pc.fill_grid();
}
}
update_folder() {
$.ajax({
type: "POST",
url: "/cloud/get-folder",
data: { 'folder': pc.root+pc.current_folder },
success: pc.update_files
});
}
set_visualization_mode(mode) {
pc.visualization_mode = mode;
if (mode==="table") {
$('#show-table').hide();
$('#table-container').show();
$('#show-grid').show();
$('#grid-container').hide();
pc.fill_table();
} else {
$('#show-table').show();
$('#table-container').hide();
$('#show-grid').hide();
$('#grid-container').show();
pc.fill_grid();
}
}
fill_table() {
let content = '';
pc.files.forEach(function(entry) {
content += '<tr class="entry">';
content += '<td class="entry-name type-'+entry['type']+'">'+entry['name']+'</td>';
content += '<td>'+entry['size']+'</td>';
content += '<td>'+entry['last_mod']+'</td>';
content += '</tr>';
});
$('#table-files tbody').html(content);
}
fill_grid() {
let content = '';
let pic;
pc.files.forEach(function(entry) {
content += '<div class="entry grid-element" title="'+entry['name']+'">';
pic = '<img src="'+pc.get_icon_url(entry['name'], entry['type'])+'" class="grid-pic-horizontal">';
content += '<div class="grid-pic">'+pic+'</div>';
content += '<div class="grid-text entry-name type-'+entry['type']+'">'+entry['name']+'</div>';
content += '</div>';
});
$('#grid-container').html(content);
$('.grid-pic > .grid-pic-horizontal').each(function () {
if ($(this).height()>$(this).width()) {
$(this).attr("class", "grid-pic-vertical");
}
});
}
fill_info() {
let name, img;
let size = 0;
if (pc.selected_indexes.length < 1) {
name = pc.current_folder;
img = "/static/cloud/pics/icons/folder.png";
pc.files.forEach(function (entry) {
size += entry["raw_size"];
});
size = readable_size(size);
} else if (pc.selected_indexes.length === 1) {
let sel = pc.files[pc.selected_indexes[0]];
name = sel['name'];
img = pc.get_icon_url(sel["name"], sel["type"]);
size = sel["size"];
} else {
name = "Multiple files";
img = "/static/cloud/pics/icons/files.png";
pc.selected_indexes.forEach(function (i) {
size += pc.files[i]["raw_size"];
});
size = readable_size(size);
}
$('#info-name').text(name).prop("title", name);
$('#info-img').html('<img src="' + img + '" class="grid-pic-horizontal">');
$('#info-size> span').text(size);
let img_el = $('#info-img > img').first();
if (img_el.height() < img_el.width()) {
img_el.attr("class", "grid-pic-vertical");
}
}
get_icon_url(filename, filetype) {
if (filetype==="dir") {
return '/static/cloud/pics/icons/folder.png';
} else if (filename.endsWith(".jpg") || filename.endsWith(".png")) {
if (trash) return '/cloud/get-trash/'+pc.current_folder+"/"+filename;
return '/cloud/get-file/'+pc.current_folder+"/"+filename;
} else if (filename.endsWith(".pdf")) {
return '/static/cloud/pics/icons/pdf.png';
} else if (filename.endsWith(".txt")) {
return '/static/cloud/pics/icons/txt.png';
} else {
return '/static/cloud/pics/icons/file.png';
}
}
build_path_bar() {
let nav_path = $("#nav-path");
nav_path.html("");
let cur_path = "";
let path = pc.current_folder;
if (path.length>0) path = "/"+path;
path.split("/").forEach(function(folder) {
cur_path += folder+"/";
nav_path.append($("<div class='nav-path-button' data-path='"+cur_path+"'>").text(folder+"/"));
});
$(".nav-path-button").click(function(){
let t = "";
if (trash) t = "-";
window.location.href = window.location.origin + "/cloud/-" + t + $(this).attr("data-path");
});
}
click_entry(event, element, selector) {
if (event.ctrlKey) {
element.toggleClass('checked-entry');
pc.last_selected_index = element.index();
} else if (event.shiftKey && pc.last_selected_index>-1) {
let indexes = [element.index(), pc.last_selected_index];
indexes.sort(function(a, b){return a-b});
for (let i = indexes[0]; i <= indexes[1]; i++) {
$(selector).eq(i).addClass('checked-entry');
}
pc.last_selected_index = -1;
} else {
$("#main .checked-entry").removeClass('checked-entry');
element.addClass('checked-entry');
pc.last_selected_index = element.index();
}
pc.selected_entries = [];
pc.selected_indexes = [];
$('.checked-entry').each(function() {
pc.selected_entries.push($(this).find(".entry-name").text());
pc.selected_indexes.push($(this).index());
});
let l = pc.selected_entries.length;
if (l>0) {
if (pc.trash) {
$('#perm-delete, #restore').show();
} else {
$('#copy, #cut, #delete, #paste, #download').show();
if (l === 1) $('#rename').show();
else $('#rename').hide();
}
} else {
$('#copy, #cut, #delete, #paste, #rename, #restore').hide();
}
pc.fill_info();
console.log("sel_entries: "+pc.selected_entries);
}
action_delete() {
if (!pc.selected_entries.length) return;
$.ajax({
url: '/cloud/delete',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'to_delete': pc.selected_entries
},
success: pc.update_files
});
}
action_restore() {
if (!pc.selected_entries.length) return;
$.ajax({
url: '/cloud/restore',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'to_restore': pc.selected_entries
},
success: pc.update_files
});
}
action_perm_delete() {
if (!pc.selected_entries.length) return;
$.ajax({
url: '/cloud/perm-delete',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'to_delete': pc.selected_entries
},
success: pc.update_files
});
}
action_download() {
if (!pc.selected_entries.length) return;
let fd = new FormData();
fd.append('folder', pc.root+pc.current_folder);
pc.selected_entries.forEach(function(entry) {
fd.append('to_download[]', entry);
});
let request = new XMLHttpRequest();
request.open("POST", "/cloud/download");
request.responseType = 'blob';
request.send(fd);
request.onload = function(e) {
let blob = new Blob([this.response], {type: this.response.type});
let hidden_a = $('#downloader');
let url = window.URL.createObjectURL(blob);
hidden_a.attr('href', url);
hidden_a.attr('download', this.getResponseHeader("FILENAME"));
hidden_a[0].click();
window.URL.revokeObjectURL(url);
};
}
action_rename() {
if (pc.selected_entries.length!==1) return;
let new_name = prompt("New name:", pc.selected_entries[0]);
// TODO: checks on new_name
if (new_name != null && new_name !== "") {
$.ajax({
url: '/cloud/rename',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'old_path': pc.selected_entries[0],
'new_path': new_name
},
success: pc.update_files
});
}
}
action_create_folder() {
let name = prompt("Folder name:", "polpetta");
if (name != null && name !== "") {
$.ajax({
url: '/cloud/create-folder',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'name': name
},
success: pc.update_files
});
}
}
action_copy() {
if (!pc.selected_entries.length) return;
$.ajax({
url: '/cloud/copy',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'to_copy[]': pc.selected_entries
},
success: function() {
$('#paste').show();
}
});
}
action_cut() {
if (!pc.selected_entries.length) return;
$.ajax({
url: '/cloud/cut',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder,
'to_cut': pc.selected_entries
},
success: function() {
$('#paste').show();
}
});
}
action_paste() {
$.ajax({ url: '/cloud/paste',
type: 'POST',
data: {
'folder': pc.root+pc.current_folder
},
success: pc.update_files
});
}
action_upload_file() {
let fd = new FormData();
let files_to_upload = $("#upload-files-hidden")[0].files;
for (let i = 0; i < files_to_upload.length; i++) {
fd.append('files[]', files_to_upload[i]);
}
fd.append('folder', pc.root+pc.current_folder);
$.ajax({
url: '/cloud/upload-files',
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false,
success: pc.update_files
});
$('#upload-files-hidden').val('');
}
}
function readable_size(raw_size) {
let unit = ["B", "KB", "MB", "GB", "TB"];
let i = 0;
while ((raw_size/1000)>=1) {
i++;
raw_size /= 1000;
}
return raw_size.toFixed(2)+unit[i];
}
<file_sep># Generated by Django 3.1.2 on 2020-12-29 17:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cloud', '0004_googlephotossync_last_sync_result'),
]
operations = [
migrations.AlterField(
model_name='googlephotossync',
name='last_sync_result',
field=models.BooleanField(null=True),
),
]
<file_sep>from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse, FileResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.conf import settings
import os
from datetime import datetime
from shutil import copy2 as sh_copy, copytree, make_archive
import zipfile
from tempfile import TemporaryDirectory
CLOUD_ROOT = settings.CLOUD_ROOT
@login_required
def index(request, folder=''):
return render(request, 'cloud/index.html')
def login_action(request):
username = request.POST['usr']
password = request.POST['pwd']
user = authenticate(request, username=username, password=<PASSWORD>)
if user is not None:
login(request, user)
return redirect('/cloud')
return HttpResponse(status=403)
def login_user(request):
return render(request, 'cloud/login.html')
def logout_action(request):
logout(request)
return redirect('/cloud/login/')
@login_required
def get_folder(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
except KeyError as e:
print(e)
return HttpResponse(status=400)
try:
files = scan_folder(folder)
except OSError as e:
print(e)
return HttpResponse(status=422)
return JsonResponse(files, safe=False)
@login_required
def perm_delete(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
for filename in request.POST.getlist('to_delete[]'):
os.remove(os.path.join(folder, filename))
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except KeyError as e:
print(e)
return HttpResponse(status=400)
except OSError as e:
print(e)
return HttpResponse(status=422)
@login_required
def delete(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
for filename in request.POST.getlist('to_delete[]'):
old = os.path.join(folder, filename)
new = os.path.join(get_user_trash(request.user), filename)
while os.path.exists(new): new += '.copy'
os.rename(old, new)
# TODO: manage trash
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except KeyError as e:
print(e)
return HttpResponse(status=400)
except OSError as e:
print(e)
return HttpResponse(status=422)
@login_required
def restore(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
for filename in request.POST.getlist('to_restore[]'):
old = os.path.join(folder, filename)
new = os.path.join(get_user_root(request.user), filename)
while os.path.exists(new): new += '.copy'
os.rename(old, new)
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except KeyError as e:
print(e)
return HttpResponse(status=400)
except OSError as e:
print(e)
return HttpResponse(status=422)
@login_required
def rename(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
old = os.path.join(folder, request.POST['old_path'])
new = os.path.join(folder, request.POST['new_path'])
while os.path.exists(new): new += '.copy'
os.rename(old, new)
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except OSError as e:
print(e)
return HttpResponse(status=422)
except KeyError as e:
print(e)
return HttpResponse(status=400)
@login_required
def create_folder(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
full_path = os.path.join(folder, request.POST['name'])
os.makedirs(full_path)
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except OSError as e:
print(e)
return HttpResponse(status=422)
except KeyError as e:
print(e)
return HttpResponse(status=400)
@login_required
def copy(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
paths = []
for filename in request.POST.getlist('to_copy[]'):
paths.append(os.path.join(folder, filename))
except KeyError as e:
print(e)
return HttpResponse(status=400)
request.session['clipboard'] = paths
request.session['clipboard_mode'] = 'copy'
return HttpResponse(status=204)
@login_required
def cut(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
paths = []
for filename in request.POST.getlist('to_cut[]'):
paths.append(os.path.join(folder, filename))
except KeyError as e:
print(e)
return HttpResponse(status=400)
request.session['clipboard'] = paths
request.session['clipboard_mode'] = 'cut'
return HttpResponse(status=204)
@login_required
def paste(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
mode = request.session['clipboard_mode']
for path in request.session['clipboard']:
new_path = os.path.join(folder, os.path.basename(path))
while os.path.exists(new_path): new_path += '.copy'
if mode == 'cut':
os.rename(path, new_path)
elif mode == 'copy':
sh_copy(path, new_path)
if mode == 'cut': del request.session['clipboard']
files = scan_folder(folder)
return JsonResponse(files, safe=False)
except KeyError as e:
print(e)
return HttpResponse(status=400)
except OSError as e:
print(e)
return HttpResponse(status=422)
@login_required
def upload_files(request):
folder = get_full_path(request.user, request.POST['folder'])
for uploaded_file in request.FILES.getlist('files[]'):
full_path = os.path.join(folder, uploaded_file.name)
with open(full_path, 'wb+') as f:
for chunk in uploaded_file.chunks():
f.write(chunk)
files = scan_folder(folder)
return JsonResponse(files, safe=False)
@login_required
def upload_folder(request): # TODO
return HttpResponse('ok')
@login_required
def get_file(request, file_path):
response = HttpResponse()
response['X-Accel-Redirect'] = '/files/'+str(request.user.id)+"/files/"+file_path
return response
@login_required
def download(request):
try:
folder = get_full_path(request.user, request.POST['folder'])
to_download = request.POST.getlist('to_download[]')
num_files = len(to_download)
if num_files == 0: return HttpResponse(status=422)
if num_files == 1:
file_path = os.path.join(folder, to_download[0])
if os.path.isfile(file_path):
response = FileResponse(open(file_path, 'rb'))
response["FILENAME"] = to_download[0]
else:
with TemporaryDirectory() as temp_dir:
zip_path = make_archive(os.path.join(temp_dir, to_download[0]), "zip", file_path)
response = FileResponse(open(zip_path, 'rb'))
response["FILENAME"] = to_download[0]+".zip"
else:
with TemporaryDirectory() as temp_dir:
tmp_files = os.path.join(temp_dir, "files")
os.mkdir(tmp_files)
for f in to_download:
f_path = os.path.join(folder, f)
if os.path.isfile(f_path): sh_copy(f_path, tmp_files)
else: copytree(f_path, os.path.join(tmp_files, f))
zip_path = make_archive(os.path.join(temp_dir, "archive"), "zip", tmp_files)
response = FileResponse(open(zip_path, 'rb'))
response["FILENAME"] = "download.zip"
return response
except KeyError as e:
print(e)
return HttpResponse(status=400)
except OSError as e:
print(e)
return HttpResponse(status=422)
@login_required
def get_trash(request, file_path):
response = HttpResponse()
response['X-Accel-Redirect'] = '/files/'+str(request.user.id)+"/trash/"+file_path
return response
@login_required
def get_avatar(request):
response = HttpResponse()
response['X-Accel-Redirect'] = '/files/'+str(request.user.id)+"/avatar.png"
return response
def scan_folder(path):
files = []
for entry in os.scandir(path):
file_size = get_size(entry)
files.append({
'type': 'dir' if entry.is_dir() else 'file',
'name': entry.name,
'size': readable_size(file_size),
'raw_size': file_size,
'last_mod': get_last_mod(entry)
})
return files
def get_size(entry):
if entry.is_file():
return os.stat(entry.path).st_size
else:
size = 0
for i in os.scandir(entry.path):
size += get_size(i)
return size
def readable_size(size):
for i in ("B", "KB", "MB", "GB", "TB"):
if size / 1000 >= 1:
size /= 1000
else:
break
return str(round(size, 1)) + i
def get_last_mod(entry):
timestamp = os.stat(entry.path).st_mtime
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M')
def get_user_root(user):
return os.path.join(CLOUD_ROOT, str(user.id)+"/files")
def get_user_trash(user):
return os.path.join(CLOUD_ROOT, str(user.id)+"/trash")
def get_full_path(user, path):
if path.startswith("files://"):
return path.replace("files://", CLOUD_ROOT + str(user.id) + "/files/")
elif path.startswith("trash://"):
return path.replace("trash://", CLOUD_ROOT + str(user.id) + "/trash/")
<file_sep>from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CloudUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CloudUser
fields = ('username', 'email', 'root_path', 'trash_path')
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm):
model = CloudUser
fields = ('username', 'email', 'root_path', 'trash_path')
<file_sep>from os.path import join
from datetime import datetime
import google.oauth2.credentials
import google_auth_oauthlib.flow
from google.auth.transport.requests import AuthorizedSession
from django.shortcuts import redirect
from django.http import HttpResponse, JsonResponse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from cloud.models import GooglePhotosSync
from cloud.views import get_user_root
@login_required
def test_endpoint(request):
GooglePhotosSync.objects.all().delete()
#fetch_new_photos(request.user)
return HttpResponse(status=204)
def create_session(g_token, g_refresh_token):
credentials = google.oauth2.credentials.Credentials(
token=g_token,
refresh_token=g_refresh_token,
client_id=settings.CLIENT_ID,
client_secret=settings.CLIENT_SECRET,
token_uri=settings.TOKEN_URI
)
return AuthorizedSession(credentials)
@login_required
def get_google_sync_status(request, num_downloaded=-1):
try:
gp_data = GooglePhotosSync.objects.get(user=request.user)
if gp_data.last_sync:
last = readable_delta(timezone.now() - gp_data.last_sync)+"ago"
else:
last = "NEVER"
res = {
"last_sync": last,
"last_sync_result": gp_data.last_sync_result,
"num_downloaded": num_downloaded,
"pics_folder": gp_data.pics_folder
}
except GooglePhotosSync.DoesNotExist:
res = {"last_sync": "NO_CONSENT", "last_sync_result": None}
return JsonResponse(res)
@login_required
def google_sync_now(request):
res = fetch_new_photos(request.user)
if res<0: redirect('/cloud/google-consent')
return get_google_sync_status(request, res)
def fetch_new_photos(user):
gp_data = GooglePhotosSync.objects.get(user=user)
session = create_session(gp_data.g_token, gp_data.g_refresh_token)
new_photos = list_new_photos(session, gp_data)
if new_photos == False:
gp_data.last_sync_result = False
gp_data.last_sync = timezone.now()
gp_data.save()
return -1
folder = get_user_root(user) + gp_data.pics_folder
download_photos(session, folder, new_photos)
session.close()
gp_data.last_sync_result = True
gp_data.save()
return len(new_photos)
def list_new_photos(session, gp_data):
gp_data.last_pic = "gluglu" # REMOVE BEFORE FLIGHT
url = 'https://photoslibrary.googleapis.com/v1/mediaItems'
params = {
"pageSize": 10,
"pageToken": ""
}
first_id = None
last_id = gp_data.last_pic
to_download = []
quack = True
while quack:
page = session.get(url, params=params)
if page.status_code != 200: return False
for photo in page.json()['mediaItems']:
if not first_id: first_id = photo["id"]
if photo["id"] == last_id:
quack = False
break
to_download.append((photo["baseUrl"], photo["filename"]))
if 'nextPageToken' in page: params["pageToken"] = page["nextPageToken"]
else: break
if first_id:
gp_data.last_pic = first_id
gp_data.last_sync = datetime.now()
gp_data.save()
return to_download
def download_photos(session, folder, to_download: list):
for photo_url, photo_name in to_download:
res = session.get(photo_url+"=d")
if res.status_code == 200:
dest = join(folder, photo_name)
with open(dest, 'wb') as f:
f.write(res.content)
@login_required
def google_consent(request):
scopes = [
'https://www.googleapis.com/auth/photoslibrary.readonly'
]
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=scopes)
flow.redirect_uri = 'http://localhost/cloud/oauth2callback'
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true')
user_tokens = GooglePhotosSync.objects.get_or_create(user=request.user)[0]
user_tokens.g_token = flow.code_verifier
user_tokens.save()
return redirect(authorization_url)
def oauth2_callback(request):
user_tokens = GooglePhotosSync.objects.get(user=request.user)
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=None)
flow.code_verifier = user_tokens.g_token
flow.redirect_uri = 'http://localhost/cloud/oauth2callback'
flow.fetch_token(code=request.GET['code'])
user_tokens.g_token = flow.credentials.token
if flow.credentials.refresh_token:
user_tokens.g_refresh_token = flow.credentials.refresh_token
if not user_tokens.pics_folder:
user_tokens.pics_folder = "/Pictures"
user_tokens.save()
return redirect('/cloud')
def readable_delta(delta):
ts = [delta.days] + [0] * 3
ts[1], ts[2] = divmod(delta.seconds, 3600)
ts[2] //= 60
ts_readable = ""
for i, s in enumerate(["d", "h", "m"]):
if ts[i] == 0 and i < 2: continue
ts_readable += str(ts[i]) + s + " "
return ts_readable
<file_sep>from django.urls import path
from django.views.generic import RedirectView
import cloud.google_api
from . import views
from . import google_api
app_name = 'cloud'
urlpatterns = [
path('', views.index),
path('-/<path:folder>', views.index),
path('-/', RedirectView.as_view(url='/cloud')),
path('--/<path:folder>', views.index),
path('--/', views.index),
path('login-action/', views.login_action),
path('login/', views.login_user),
path('logout/', views.logout_action),
path('get-avatar', views.get_avatar),
path('get-folder', views.get_folder),
path('delete', views.delete),
path('restore', views.restore),
path('perm-delete', views.perm_delete),
path('download', views.download),
path('rename', views.rename),
path('create-folder', views.create_folder),
path('copy', views.copy),
path('cut', views.cut),
path('paste', views.paste),
path('upload-files', views.upload_files),
path('get-file/<path:file_path>', views.get_file),
path('get-trash/<path:file_path>', views.get_trash),
path('test', google_api.test_endpoint),
path('gp-sync', cloud.google_api.google_sync_now),
path('get-gp-sync-status', cloud.google_api.get_google_sync_status),
path('google-consent', cloud.google_api.google_consent),
path('oauth2callback', cloud.google_api.oauth2_callback)
]
<file_sep># Generated by Django 3.1.2 on 2020-12-12 12:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cloud', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='GooglePhotosSync',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('g_token', models.CharField(default='', max_length=256, null=True)),
('g_refresh_token', models.CharField(default='', max_length=256, null=True)),
('pics_folder', models.CharField(max_length=128)),
('last_pic', models.CharField(default='', max_length=256, null=True)),
('last_sync', models.DateTimeField()),
],
),
migrations.RemoveField(
model_name='clouduser',
name='pics_default',
),
migrations.AlterField(
model_name='clouduser',
name='root_path',
field=models.CharField(max_length=128),
),
migrations.AlterField(
model_name='clouduser',
name='trash_path',
field=models.CharField(max_length=128),
),
migrations.DeleteModel(
name='GoogleTokens',
),
migrations.AddField(
model_name='googlephotossync',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| f7a9208932ed828d1c2d6131d2ca2163f65cc837 | [
"JavaScript",
"Python"
] | 11 | Python | gabrielecapparella/PolpettaCloud | 888bb44b83e0df1c805a71cc84d6e01fe631bcea | 168063301b8f4fac33223ae3a0d59b7eb30918b1 |
refs/heads/master | <repo_name>tylkas/two-factor-auth<file_sep>/manager.cpp
#include <getopt.h>
#include <ctime>
#include <cstdio>
#include "libs/tfldap.h"
#include "libs/tftotp.h"
#include <boost/array.hpp>
void show_help(char *name);
int check_uniq_account(TFLdap *ldap, string dn, string *fdn);
int main(int argc, char **argv)
{
int c;
string ban = "";
bool with_args = false;
bool is_adding = false;
bool is_deleting = false;
bool todo_token = false;
bool todo_qr = false;
char *attrs_null[] = {NULL};
char *attrs_object[] = {"twoFactorData", NULL};
char *attrs_twofactor[] = {"twoFactorToken", "twoFactorIPs",
"twoFactorGlobal", "twoFactorGlobalAllowed",
"twoFactorSuccess", "twoFactorFail", NULL};
char *attrs_twofactor_default_vals[][2] = {{"", NULL},
{"", NULL},
{"-1", NULL},
{"FALSE", NULL},
{"0", NULL},
{"0", NULL},
{NULL, NULL}};
string dn = "";
// Turn off getopt errors
opterr = 0;
while ( (c = getopt(argc, argv, "ab:df:tq")) != -1 ) {
with_args = true;
switch (c) {
case 'a':
is_adding = true;
continue;
case 'b':
ban.append(optarg);
if ( ban != "-" )
for ( unsigned int i = 0 ; i < ban.size() ; i++ )
if ( !isdigit(ban[i]) ) {
cerr << "Argument -b requires a number or \"-\" (" << ban << " NaN)" << endl;
exit(-1);
}
continue;
case 'd':
is_deleting = true;
continue;
case 'f':
dn = optarg;
continue;
case 't':
todo_token = true;
continue;
case 'q':
todo_qr = true;
continue;
case '?':
if ((optopt == 'f') | (optopt == 'b'))
cerr << "Option -" << (char)optopt << " requires an argument" << endl;
else if (isprint (optopt))
cerr << "Unknown option \"-" << (char)optopt << "\"" << endl;
show_help(argv[0]);
}
}
if (with_args == false)
show_help(argv[0]);
TFLdap ldap;
string fdn = "";
ldap.bind();
/*
* Managing two-factor class
*/
if ((is_adding) | (is_deleting)) {
if (is_adding == is_deleting) {
cerr << "Sorry, but you can not ADD and DELETE two-factow attributes at the same time" << endl;
// 1 - 1 == :P
return -1;
}
if (dn.size() == 0) {
cerr << "Ldap filter (-u) is not defined" << endl;
return -1;
}
// Check for unique account
if ( check_uniq_account(&ldap, dn, &fdn) != 1 )
return 0;
// Writing data
if (is_adding) {
cout << "Adding two-factor objectClass to account: " << fdn << endl;
cout << "- Object class \"" << attrs_object[0] << "\"..." << endl;
if (ldap.modify(fdn, LDAP_MOD_INCREMENT, "objectClass", attrs_object) == 20)
// (20) Type or value exists
cerr << "Account already have two-factor attributes" << endl;
else
for (uint i = 0; i < sizeof(attrs_twofactor)/sizeof(*attrs_twofactor)-1; i++) {
cout << "- Attribute \"" << attrs_twofactor[i] << "\"..." << endl;
ldap.modify(fdn, LDAP_MOD_REPLACE, attrs_twofactor[i], attrs_twofactor_default_vals[i]);
}
} else {
cout << "Deleting two-factor objectClass from account: " << fdn << endl;
cout << "Please, confirm (yes): ";
string answer;
cin >> answer;
if (answer != "yes")
return 0;
// Removing two-factor attributes
for (uint i = 0; i < sizeof(attrs_twofactor)/sizeof(*attrs_twofactor)-1; i++) {
cout << "- Attribute \"" << attrs_twofactor[i] << "\"..." << endl;
ldap.modify(fdn, LDAP_MOD_REPLACE, attrs_twofactor[i], attrs_null);
}
// Removing object
cout << "- Object class \"" << attrs_object[0] << "\"..." << endl;
ldap.remove_value(dn, "objectClass", attrs_object[0]);
}
}
if ((todo_token) & (is_deleting == false)) {
// Check for unique account
if ( check_uniq_account(&ldap, dn, &fdn) != 1 )
return 0;
// Check two-factor class exist
vector<string> chck = ldap.get_values(dn, "objectClass");
bool fail = true;
for (vector<string>::iterator it = chck.begin() ; it != chck.end(); ++it)
if (*it == attrs_object[0])
fail = false;
if (fail) {
cerr << "Object haven't two-factor class yet" << endl;
return 0;
}
char *values[2] = {NULL, NULL};
cout << "- Generating random token..." << endl;
string token = ""; //(const char*)TOTP::get_random_seed32();
values[0] = const_cast<char*>(token.c_str());
cout << "- Replacing current token..." << endl;
cout << "[DEBUG] token: " << token << endl;
ldap.modify(fdn, LDAP_MOD_REPLACE, attrs_twofactor[0], values);
}
if ( ban.size() > 0 ) {
// Check for unique account
if ( check_uniq_account(&ldap, dn, &fdn) != 1 )
return 0;
// Check two-factor class exist
vector<string> chck = ldap.get_values(dn, "objectClass");
bool fail = true;
for (vector<string>::iterator it = chck.begin() ; it != chck.end(); ++it)
if (*it == attrs_object[0])
fail = false;
if (fail) {
cerr << "Object haven't two-factor class yet" << endl;
return 0;
}
char *values[] = {"-1", NULL};
if ( ban != "0" ) {
ostringstream ban_t;
if ( ban == "-" ) {
cout << "- Removing ban..." << endl;
ban_t << 0;
} else {
cout << "- Applying temporary ban..." << endl;
ban_t << 0 - ( atoi(ban.c_str()) + time(0) );
}
values[0] = const_cast<char*>(ban_t.str().c_str());
} else
cout << "- Applying permanent ban..." << endl;
ldap.modify(fdn, LDAP_MOD_REPLACE, attrs_twofactor[2], values);
}
if (todo_qr) {
// Check for unique account
if ( check_uniq_account(&ldap, dn, &fdn) != 1 )
return 0;
// Check two-factor class exist
vector<string> chck = ldap.get_values(dn, "objectClass");
bool fail = true;
for (vector<string>::iterator it = chck.begin() ; it != chck.end(); ++it)
if (*it == attrs_object[0])
fail = false;
if (fail) {
cerr << "Object haven't two-factor class yet" << endl;
return 0;
}
// string asdasd = "I hate base32";
// cout << "Source string: " << asdasd << endl;
// int len = Base32::GetEncode32Length(asdasd.size()) ;
// unsigned char *encoded = new unsigned char [ len ];
// Base32::Encode32((unsigned char*)asdasd.c_str(), asdasd.size(), encoded);
// cout << "Encoded string: " << encoded << endl;
// Base32::Map32(encoded, len, alpha);
// cout << "Mapped encoded string: " << encoded << endl;
// Base32::Unmap32(encoded, len, alpha);
// cout << "Unmapped encoded string: " << encoded << endl;
// unsigned char *decoded = new unsigned char [ Base32::GetDecode32Length(len) ];
// Base32::Decode32(encoded, len, decoded);
// cout << "Decoded string: " << decoded << endl;
cout << "Account: " << fdn << endl;
cout << "Token: " << ldap.get_value(dn, attrs_twofactor[0]) << endl;
TFTOTP totp(ldap.get_value(dn, attrs_twofactor[0]));
cout << "TOTP code32: " << totp.generateCode() << endl;
}
return 0;
}
void show_help(char *name) {
cout << "Usage: " << name << " [OPTION...]" << endl;
cout << endl;
cout << " -a add two factor objectClass and attributes to object" << endl;
cout << " -b -|INTEGER \"-\" used to remove ban, \"0\" for permanent ban," << endl;
cout << " positive number used as period for temporary ban" << endl;
cout << " -d delete two factor objectClass and attributes from object" << endl;
cout << " -f STRING ldap filter (man ldapsearch)" << endl;
cout << " -t generate or regenerate TOTP token for object" << endl;
cout << endl;
cout << "Report bugs to https://github.com/tylkas/two-factor-auth/issues" << endl;
exit(0);
}
int check_uniq_account(TFLdap *ldap, string dn, string *fdn) {
ptree ldap_res;
if (dn.size() == 0) {
cerr << "Please, specify ldap filter (-f)" << endl;
return -1;
}
switch (ldap->is_dn_uniq(dn)) {
case TFLDAP_FILTER_RES_NOT_FOUND:
cerr << "Ldap filter \"" << dn << "\" returns empty results" << endl;
return 0;
case TFLDAP_FILTER_RES_IS_NOT_UNIQ:
cerr << "Ldap filter \"" << dn << "\" returns more than 1 result. ";
cerr << "Suggested accounts:" << endl;
ldap_res = ldap->search(dn);
BOOST_FOREACH(const ptree::value_type &e, ldap_res)
if (e.second.get<string>("") == "Full DN")
cerr << "- " << ptree_dn_decode(e.first) << endl;
return 0;
case TFLDAP_FILTER_RES_IS_UNIQ:
ldap_res = ldap->search(dn);
BOOST_FOREACH(const ptree::value_type &e, ldap_res)
if (e.second.get<string>("") == "Full DN")
*fdn = ptree_dn_decode(e.first);
return 1;
}
return -1;
}
<file_sep>/libs/tfldap.h
#ifndef TFLDAP_H
#define TFLDAP_H
#include <ldap.h>
#include <string>
#include <iostream>
#include <vector>
#include <boost/property_tree/ptree.hpp>
#include <boost/foreach.hpp>
#include "config.h"
using namespace std;
using namespace boost::property_tree;
#define LDAP_MOD_INC_OR_ADD (0x0201)
#define LDAP_MOD_ADD_OR_REPLACE (0x0202)
#define LDAP_MOD_INC_OR_ADD_OR_REPLACE (0x0203)
#define TFLDAP_FILTER_RES_IS_UNIQ 0
#define TFLDAP_FILTER_RES_IS_NOT_UNIQ 1
#define TFLDAP_FILTER_RES_NOT_FOUND -1
string ptree_dn_encode(string);
string ptree_dn_decode(string);
class TFLdap {
LDAP *ld;
berval cred, *server_creds;
int version = LDAP_VERSION3;
public:
TFLdap();
~TFLdap();
int bind();
ptree search(string ldapfilter);
ptree search(string ldapfilter, char **attrs);
int modify(string fdn, int mod_op, char *attr, char **values);
string get_value(string dn, char *attr);
vector<string> get_values(string dn, char *attr);
int remove_value(string dn, char *attr, char *value);
int is_dn_uniq(string searchdn);
private:
int _modify_add(string fdn, char *attr, char **values);
int _modify_increment(string fdn, char *attr, char **values);
int _modify_replace(string fdn, char *attr, char **values);
};
#endif // TFLDAP_H
<file_sep>/ldap.schema/Makefile
tmp_dir = /tmp/ldif
schema = two-factor_openldap
pretty = twoFactor
all:
mkdir $(tmp_dir)
echo "include $(schema).schema" > $(tmp_dir)/$(schema).conf
slaptest -f $(tmp_dir)/$(schema).conf -F $(tmp_dir)
find $(tmp_dir) -name *$(schema).ldif -exec cp {} $(tmp_dir)/$(schema).ldif \;
sed -r "/^(\#|structural|entry[C|U]|creat[e|o]|modif[i|y])/d" -i $(tmp_dir)/$(schema).ldif
sed "s/{.}$(schema)/$(pretty)/" -i $(tmp_dir)/$(schema).ldif
sed "s/cn=$(pretty)/cn=$(pretty),cn=schema,cn=config/" -i $(tmp_dir)/$(schema).ldif
@printf "\nNow you are able to import LDIF. Example:"
@printf "\n\n ldapadd -WD cn=admin,cn=config -f $(tmp_dir)/$(schema).ldif"
@printf "\n\nIf you will get error like \"Invalid credentials (49)\" - check admin account/password.\n\n"
clean:
[ \! -d $(tmp_dir) ] || rm -rf $(tmp_dir)
<file_sep>/libs/tftotp.cpp
#include "tftotp.h"
TFTOTP::TFTOTP(string input)
{
token32 = input;
token32_len = input.size();
decodeToken(); // TODO: add check for result
}
string TFTOTP::generateCode()
{
int date = time(NULL) / TFTOTP_PERIOD;
hmacSHA1(date);
if (token32 == vtos(ctov(vtoc(stov(token32)))))
return "Match";
else
return "Not match!!!";
}
int TFTOTP::hmacSHA1(int date)
{
// Formating date to useful form ?
// vector<unsigned char> divided_date;
// If token is too long - will use hash instead of token
if (token_len > TFTOTP_SHA_BLOCK) {
// -> Update token with calculated hash
token = ctov(SHA1(vtoc(token), token_len, 0));
// -> Update token length
token_len = token.size();
}
if (token_len < TFTOTP_SHA_BLOCK) {
// Fill token with NULL up to end of block
for (int i=token_len; i<TFTOTP_SHA_BLOCK; ++i)
token.push_back(0);
// -> Update token length
token_len = token.size();
}
// Fill inner and outer vectors for HMAC-SHA calculation
vector<unsigned char> ipad;
vector<unsigned char> opad;
for (int i=0; i<TFTOTP_SHA_BLOCK; ++i) {
ipad.push_back(TFTOTP_IN_DIG);
opad.push_back(TFTOTP_OUT_DIG);
}
// Calculating XOR
ipad = vxor(ipad, token);
opad = vxor(opad, token);
vector<unsigned char> buffer;
// Step 1
// Concat ipad with date and get hash from
buffer = ipad;
buffer.push_back(date);
buffer = ctov(SHA1(vtoc(buffer), buffer.size(), 0));
printHex("buffer with ipad", buffer);
// Step 2
// Concat opad with previous hash and get hash from
buffer.insert(buffer.begin(), opad.begin(), opad.end() );
buffer = ctov(SHA1(vtoc(buffer), buffer.size(), 0));
printHex("buffer with opad", buffer);
// Step 3
// Get last 4 bits from last value as offset
int offset = buffer.at(TFTOTP_SHA_LEN - 1) & 0xf;
// Step 4
// Cut block and execute dynamic truncation
vector<unsigned char> totp_block;
for (int i=0; i<4; ++i) {
totp_block.push_back(buffer.at(offset + i) & ( i==0 ? 0x7f : 0x77 ) );
}
printHex("totp_block", totp_block);
// TODO: Convert block to digits
return TFTOTP_SUCCESS;
}
vector<unsigned char> TFTOTP::vxor(vector<unsigned char> a, vector<unsigned char> b)
{
vector<unsigned char> output;
// Length will be max of incoming vector sizes
unsigned int output_len = ( a.size() > b.size() ? a.size() : b.size() );
for (unsigned int i=0; i < output_len; ++i) {
output.push_back( ( i < a.size() ? a.at(i) : 0) ^ ( i < b.size() ? b.at(i) : 0) );
}
return output;
}
int TFTOTP::decodeToken()
{
unsigned char *_token32 = vtoc(stov(token32));
// Unmaping token with defined alphabet
if (!Base32::Unmap32(_token32, token32_len, alphabet)) {
cerr << "[TFTOTP::decodeToken] error on unmapping token" << endl;
return 1; // TODO: replace with errno definition
}
// -> Update length for decoded token
token_len = Base32::GetDecode32Length(token32_len);
// Initialize temporary array to work with Base32::Decode32
unsigned char *_token = new unsigned char [token_len];
// Decoding unmapped array
if (!Base32::Decode32(_token32, token32_len, _token)) {
cerr << "[TFTOTP::decodeToken] error on decoding token" << endl;
return 2; // TODO: replace with errno definition
}
// -> Update decoded token value
token = ctov(_token);
return TFTOTP_SUCCESS;
}
int TFTOTP::encodeToken()
{
// -> Update length for encoded token
token32_len = Base32::GetEncode32Length(token_len);
// Initialize temporary array to work with Base32::Encode32
unsigned char *_token32 = new unsigned char [token32_len];
// Encoding token in base32
if (!Base32::Encode32(vtoc(token), token_len, _token32)) {
cerr << "[TFTOTP::encodeToken] error on encoding token" << endl;
return 3; // TODO: replace with errno definition
}
// Maping token
if (!Base32::Map32(_token32, token32_len, alphabet)) {
cerr << "[TFTOTP::encodeToken] error on maping token" << endl;
return 4; // TODO: replace with errno definition
}
// -> Update encoded token value
token32 = vtos(ctov(_token32));
return TFTOTP_SUCCESS;
}
// Vector to string
string TFTOTP::vtos(vector<unsigned char> input)
{
string output = "";
for (vector<unsigned char>::iterator it = input.begin() ; it != input.end(); ++it)
output.append(1, static_cast<char>(*it));
return output;
}
// String to vector
vector<unsigned char> TFTOTP::stov(string input)
{
vector<unsigned char> output;
for (unsigned int i=0; i<input.size(); ++i)
output.push_back(input[i]);
return output;
}
// Vector to unsigned char array
unsigned char *TFTOTP::vtoc(vector<unsigned char> input)
{
unsigned char *output = new unsigned char [input.size()];
int i = 0;
for (vector<unsigned char>::iterator it = input.begin() ; it != input.end(); ++it) {
output[i] = *it;
++i;
}
return output;
}
// Unsigned char array to vector
vector<unsigned char> TFTOTP::ctov(unsigned char *input)
{
vector<unsigned char> output;
for (unsigned int i=0; i<strlen((char*)input); ++i)
output.push_back(input[i]);
return output;
}
// Print vector in HEX
void TFTOTP::printHex(string name, vector<unsigned char> input)
{
cout << name << ": " << setfill('0');
for (vector<unsigned char>::iterator it = input.begin(); it != input.end(); ++it)
cout << ( it != input.begin() ? ":" : "" ) << hex << setw(2) << (int)*it;
cout << endl;
}
<file_sep>/config.h
#ifndef CONFIG_H
#define CONFIG_H
// LDAP related definitions
#define ldap_url "ldap://ldap.local"
#define ldap_base "dc=local"
#define ldap_dn "cn=admin,dc=local"
#define ldap_pass "<PASSWORD>"
#define ldap_dn_dot_replacer "**" // ptree uses dot char as in key separator
//
#endif // CONFIG_H
<file_sep>/libs/tftotp.h
#ifndef TFTOTP_H
#define TFTOTP_H
#include "libs/Base32.h"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
#include <time.h>
#include <openssl/hmac.h>
#include <openssl/sha.h>
// TOTP will return 6-digits code
#define TFTOTP_DIGITS 6
// TOTP period in seconds
#define TFTOTP_PERIOD 30
// Length for raw seed from /dev/random
#define TFTOTP_SEED_LEN 16
// Length for hash result
#define TFTOTP_SHA_LEN 20
// Length for blocks which used in hashing
#define TFTOTP_SHA_BLOCK 64
// TOTP inner digits char (for XORing)
#define TFTOTP_IN_DIG 0x36
// TOTP outer digits char (for XORing)
#define TFTOTP_OUT_DIG 0x5c
// Base32 alphabet
#define alphabet (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
// Define errors
#define TFTOTP_SUCCESS 0
using namespace std;
class TFTOTP
{
public:
// =======
// Methods
// Constructor
TFTOTP(string token);
// Destructor
// ~TFTOTP();
// Get OTP code
string generateCode();
// Generate random token
static string getRandomToken();
private:
// ==========
// Attributes
string token32;
unsigned int token32_len;
vector<unsigned char> token;
unsigned int token_len;
// =======
// Methods
// HMAC-SHA1
int hmacSHA1(int date);
// XOR for vectors
vector<unsigned char> vxor(vector<unsigned char> a, vector<unsigned char> b);
// Decode token
// result: attribute token will get decoded value of token_raw
int decodeToken();
// Encode token
// result: attribute token32 will get base32 value of token_raw
int encodeToken();
// Vector to string
string vtos(vector<unsigned char> input);
// String to vector
vector<unsigned char> stov(string input);
// Vector to unsigned char array
unsigned char *vtoc(vector<unsigned char> input);
// Unsigned char array to vector
vector<unsigned char> ctov(unsigned char *input);
// Debug: output vector in HEX format
void printHex(string name, vector<unsigned char> input);
};
#endif // TFTOTP_H
<file_sep>/libs/Base32.h
//////////////////////////////////////////////////////////////////////
// Base32.h (C) https://madebits.github.io/#r/cpp-base32.md
//////////////////////////////////////////////////////////////////////
#if !defined(_BASE32_H_)
#define _BASE32_H_
#include <string.h>
/*
Base32 encoding / decoding.
Encode32 outputs at out bytes with values from 0 to 32 that can be mapped to 32 signs.
Decode32 input is the output of Encode32. The out parameters should be unsigned char[] of
length GetDecode32Length(inLen) and GetEncode32Length(inLen) respectively.
To map the output of Encode32 to an alphabet of 32 characters use Map32.
To unmap back the output of Map32 to an array understood by Decode32 use Unmap32.
Both Map32 and Unmap32 do inplace modification of the inout32 array.
The alpha32 array must be exactly 32 chars long.
*/
struct Base32
{
static bool Decode32(unsigned char* in, int inLen, unsigned char* out);
static bool Encode32(unsigned char* in, int inLen, unsigned char* out);
static int GetDecode32Length(int bytes);
static int GetEncode32Length(int bytes);
static bool Map32(unsigned char* inout32, int inout32Len, unsigned char* alpha32);
static bool Unmap32(unsigned char* inout32, int inout32Len, unsigned char* alpha32);
};
#endif
<file_sep>/libs/totp.cpp
/*
* This code is an rewrited version of https://github.com/gonrada/TOTP-Generator
* Thanks to <NAME>, which allowed me to use it.
*/
#include "totp.h"
#include <iomanip>
unsigned char * TOTP::get_random_seed32(void) {
unsigned char *seed = (unsigned char *)malloc(TOTP_SEED_LEN);
FILE *seedSrc = fopen("/dev/urandom", "r");
if(!seedSrc)
cerr << "[TOTP::get_random_seed] Error opening /dev/random for read" << endl;
else {
fread(seed, TOTP_SEED_LEN, 1, seedSrc);
fclose(seedSrc);
}
int length = Base32::GetEncode32Length(TOTP_SEED_LEN);
unsigned char *token = new unsigned char[length];
if (Base32::Encode32(seed, TOTP_SEED_LEN, token)) {
if (Base32::Map32(token, length, alpha)) {
return token;
}
}
return (unsigned char *)"error";
}
string TOTP::get_totp32(string stoken) {
// Get unix timestamp divided by period (30 sec is default)
unsigned long date = floor(time(NULL) / TOTP_PERIOD);
cout << "Date: " << date << endl;
// Divide by blocks
uint8_t challenge[8];
for (int i = 8; i--; date >>= 8) {
challenge[i] = date;
}
// Decoding from base32
uint8_t token32[stoken.size()];
memcpy(token32, stoken.c_str(), stoken.size());
if (!Base32::Unmap32(token32, stoken.size(), alpha)) {
cerr << "[TOTP::get_totp32] error on unmapping input string" << endl;
return "error";
}
int length = (stoken.size() + 7)/8*5;
//int length = Base32::GetDecode32Length(stoken.size());
uint8_t useed[length];
memset(useed, 0 , length);
if (!Base32::Decode32(token32, length, useed)) {
cerr << "[TOTP::get_totp32] error on decoding input string" << endl;
return "error";
}
// Copy decoded token to required data type
uint8_t seed[length];
memset(seed, 0, length);
memcpy(seed, useed, length);
// Generate HMAC-SHA1
uint8_t *result[TOTP_SHA_LEN];
hmac_sha1(seed, length, challenge, 8, result[0]);
/*
// Test for HMAC-SHA1
hmac_sha1((uint8_t *) "1", 1, (uint8_t *) "2", 1, result[0]);
// Result must be equal "fb:db:1d:1b:18:aa:6c:08:32:4b:7d:64:b7:1f:b7:63:70:69:0e:1d"
hmac_sha1((uint8_t *) "1", 1, (uint8_t *) "2", 1, result[0]);
// Result must be equal "d0:75:ca:12:b8:25:9a:0b:27:43:8f:07:53:14:a3:bb:88:a9:27:b5"
*/
// Return last TOTP_DIGITS digits
unsigned int totp = dynamic_truncation(result[0]);
cout << "Bin code (hex): \t"
<< (totp >>24 & 0xff) << ":"
<< (totp >>16 & 0xff) << ":"
<< (totp >>8 & 0xff) << ":"
<< (totp & 0xff) << endl;
// Return results ... why stream? Just for fun
ostringstream res;
res << totp;
// If code shorter than required amount
if (res.str().size() < TOTP_DIGITS) {
string sres = res.str();
while (sres.size() < TOTP_DIGITS)
sres.insert(sres.begin(), '0');
return sres;
}
return res.str();
}
unsigned int TOTP::dynamic_truncation(uint8_t *input)
{
// Offset used to get special item number to get TOTP code
int offset = input[TOTP_SHA_LEN - 1] & 0xf;
// Cut code
unsigned int bin_code = 0;
for (int i = 0; i < 4; ++i) {
bin_code <<= 8;
bin_code |= input[offset + i];
}
// Return last TOTP_DIGITS digits
bin_code &= 0x7FFFFFFF;
bin_code %= (int) pow(10.0, TOTP_DIGITS);
return bin_code;
}
void TOTP::hmac_sha1(uint8_t * key, int key_len, uint8_t * data, int data_len, uint8_t *ressha) {
// Adjusting key length
uint8_t adj_key[TOTP_SHA_BLOCK];
memset(adj_key, 0, TOTP_SHA_BLOCK);
// If key is too long - will use hash instead of
if (key_len > TOTP_SHA_BLOCK)
SHA1(key, key_len, adj_key);
else
memcpy(adj_key, key, key_len);
// Debug output
cout << setfill('0');
cout << "Result #0 (hex):\t";
for (int i=0; i< TOTP_SHA_LEN; i++)
cout << (i==0?"":":") << hex << setw(2) << (int)ressha[i];
cout << endl;
// Calculate with inner digits
uint8_t ipad[TOTP_SHA_BLOCK];
memset(ipad, TOTP_IN_DIG, TOTP_SHA_BLOCK);
for (int i=0; i<TOTP_SHA_BLOCK; i++)
ipad[i] ^= adj_key[i];
uint8_t in_buffer[TOTP_SHA_BLOCK + data_len];
memset(in_buffer, 0, TOTP_SHA_BLOCK + data_len);
memcpy(in_buffer, ipad, TOTP_SHA_BLOCK);
memcpy(&in_buffer[TOTP_SHA_BLOCK], data, data_len);
SHA1(in_buffer, TOTP_SHA_BLOCK + data_len, ressha);
// Debug output
cout << "Result #1 (hex):\t";
for (int i=0; i< TOTP_SHA_LEN; i++)
cout << (i==0?"":":") << hex << setw(2) << (int)ressha[i];
cout << endl;
// Calculate with outer digits
uint8_t opad[TOTP_SHA_BLOCK];
memset(opad, TOTP_OUT_DIG, TOTP_SHA_BLOCK);
for (int i=0; i<TOTP_SHA_BLOCK; i++)
opad[i] ^= adj_key[i];
uint8_t out_buffer[TOTP_SHA_BLOCK + TOTP_SHA_LEN];
memset(out_buffer, 0, TOTP_SHA_BLOCK + TOTP_SHA_LEN);
memcpy(out_buffer, opad, TOTP_SHA_BLOCK);
memcpy(&out_buffer[TOTP_SHA_BLOCK], ressha, TOTP_SHA_LEN);
SHA1(out_buffer, TOTP_SHA_BLOCK + TOTP_SHA_LEN, ressha);
// Debug output
cout << "Result #2 (hex):\t";
for (int i=0; i< TOTP_SHA_LEN; i++)
cout << (i==0?"":":") << hex << setw(2) << (int)ressha[i];
cout << endl;
}
<file_sep>/libs/tfldap.cpp
#include "tfldap.h"
string ptree_dn_encode(string s) {
int pos = 0;
while( ( pos = s.find(".") ) != -1 )
s.replace(pos, 1, ldap_dn_dot_replacer);
return s;
}
string ptree_dn_decode(string s) {
int pos = 0;
while( ( pos = s.find(ldap_dn_dot_replacer) ) != -1 )
s.replace(pos, sizeof(ldap_dn_dot_replacer)/sizeof(char) -1, ".");
return s;
}
TFLdap::TFLdap()
{
cred.bv_val = ldap_pass;
cred.bv_len = sizeof(ldap_pass)-1;
}
TFLdap::~TFLdap() {
// Unbind from LDAP
ldap_unbind_ext_s(ld, NULL, NULL);
}
int TFLdap::bind() {
ldap_initialize(&ld, ldap_url);
ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
int res = ldap_sasl_bind_s(ld, ldap_dn, LDAP_SASL_AUTOMATIC, &cred, NULL, NULL, &server_creds);
if ( res != LDAP_SUCCESS) {
cerr << "[TFLdap::bind] Error occured: " << res << endl << ldap_err2string(res) << endl;
exit(-1);
}
return res;
}
ptree TFLdap::search(string ldapfilter) {
return search(ldapfilter, NULL);
}
ptree TFLdap::search(string ldapfilter, char **attrs) {
ptree res;
LDAPMessage *ldap_result;
BerElement *ber;
int r = ldap_search_ext_s(ld, ldap_base, LDAP_SCOPE_SUBTREE,
ldapfilter.c_str(), attrs, 0, NULL, NULL,
LDAP_NO_LIMIT, LDAP_NO_LIMIT, &ldap_result);
if ( r != LDAP_SUCCESS) {
cerr << "[TFLdap::search] error occured: (" << r << ") " << ldap_err2string(r) << endl;
} else {
// Get ldap entry
for (LDAPMessage *entry = ldap_first_entry(ld, ldap_result); entry != NULL; entry = ldap_next_entry(ld, entry)) {
// Put full DN
string fdn = ptree_dn_encode(ldap_get_dn(ld, entry));
res.add(fdn, "Full DN");
// Get attributes
for (char *attr = ldap_first_attribute(ld, entry, &ber); attr != NULL; attr = ldap_next_attribute(ld, entry, ber)) {
// Get values
berval **values = ldap_get_values_len(ld, entry, attr);
for (int i = 0; i < ldap_count_values_len(values); i++)
res.add(fdn + string(".") + string(attr), values[i]->bv_val);
ldap_value_free_len(values);
}
if ( ber != NULL )
ber_free(ber, 0);
// If entry does not have any provided attrs
if ( res.get_child(fdn).size() == 0 )
res.pop_back();
}
ldap_msgfree(ldap_result);
}
return res;
}
int TFLdap::is_dn_uniq(string searchdn) {
ptree res;
res = search(searchdn);
switch (res.size()) {
case 0:
return TFLDAP_FILTER_RES_NOT_FOUND;
case 1:
return TFLDAP_FILTER_RES_IS_UNIQ;
default:
return TFLDAP_FILTER_RES_IS_NOT_UNIQ;
}
}
int TFLdap::_modify_add(string fdn, char *attr, char **values) {
LDAPMod mod;
mod.mod_op = LDAP_MOD_ADD;
mod.mod_type = attr;
mod.mod_values = values;
LDAPMod *mods[2];
mods[0] = &mod;
mods[1] = NULL;
int res = ldap_add_ext_s(ld, fdn.c_str(), mods, NULL, NULL);
if ( res != LDAP_SUCCESS )
cerr << "[TFLdap::_modify_add] error occured: (" << res << ") " << ldap_err2string(res) << endl;
return res;
}
int TFLdap::_modify_increment(string fdn, char *attr, char **values) {
LDAPMod mod;
mod.mod_op = LDAP_MOD_INCREMENT;
mod.mod_type = attr;
mod.mod_values = values;
LDAPMod *mods[2];
mods[0] = &mod;
mods[1] = NULL;
int res = ldap_modify_ext_s(ld, fdn.c_str(), mods, NULL, NULL);
if ( res == LDAP_SUCCESS )
return res;
// Gather current values
string dn = fdn.substr(0, fdn.find(','));
vector<string> res_attrs;
char *attrs[2] = {attr, NULL};
ptree sres = search(dn, attrs);
BOOST_FOREACH(const ptree::value_type &e, sres)
if (( e.second.get<string>("") == "Full DN") & ( fdn == ptree_dn_decode(e.first))) {
BOOST_FOREACH(const ptree::value_type &v, sres.get_child(e.first))
if ( v.first == attr )
res_attrs.insert(res_attrs.end(), v.second.get<string>(""));
}
// Append new values
for ( unsigned int i = 0; i < sizeof(values)/sizeof(*values); i++)
res_attrs.insert(res_attrs.end(), values[i]);
// Make new array of values
char **res_values = new char*[res_attrs.size() + 1];
for ( unsigned int i = 0; i < res_attrs.size(); i++)
res_values[i] = const_cast<char*>(res_attrs[i].c_str());
res_values[res_attrs.size()] = NULL;
// Execute modify ;)
return _modify_replace(fdn, attr, res_values);
}
int TFLdap::_modify_replace(string fdn, char *attr, char **values) {
LDAPMod mod;
mod.mod_op = LDAP_MOD_REPLACE;
mod.mod_type = attr;
mod.mod_values = values;
LDAPMod *mods[2];
mods[0] = &mod;
mods[1] = NULL;
int res = ldap_modify_ext_s(ld, fdn.c_str(), mods, NULL, NULL);
if ( res != LDAP_SUCCESS )
cerr << "[TFLdap::_modify_replace] error occured: (" << res << ") " << ldap_err2string(res) << endl;
return res;
}
int TFLdap::modify(string fdn, int mod_op, char *attr, char **values) {
int res;
switch (mod_op) {
case LDAP_MOD_ADD:
return _modify_add(fdn, attr, values);
case LDAP_MOD_INCREMENT:
return _modify_increment(fdn, attr, values);
case LDAP_MOD_REPLACE:
return _modify_replace(fdn, attr, values);
case LDAP_MOD_INC_OR_ADD:
res = modify(fdn, LDAP_MOD_INCREMENT, attr, values);
if ( res != LDAP_SUCCESS )
res = modify(fdn, LDAP_MOD_ADD, attr, values);
return res;
case LDAP_MOD_ADD_OR_REPLACE:
res = modify(fdn, LDAP_MOD_ADD, attr, values);
if ( res != LDAP_SUCCESS )
res = modify(fdn, LDAP_MOD_REPLACE, attr, values);
return res;
// Use it with attention!
// If even 1 value from argument is already presented in an object -
// ALL attribute values will be REPLACED with a new array
case LDAP_MOD_INC_OR_ADD_OR_REPLACE:
res = modify(fdn, LDAP_MOD_INCREMENT, attr, values);
if ( res != LDAP_SUCCESS )
res = modify(fdn, LDAP_MOD_ADD, attr, values);
if ( res != LDAP_SUCCESS )
res = modify(fdn, LDAP_MOD_REPLACE, attr, values);
return res;
default:
cerr << "Used unsupported modify method in TFLdap::modify(): " << mod_op << endl;
return -1;
}
}
int TFLdap::remove_value(string dn, char *attr, char *value) {
ptree sres = search(dn);
string fdn;
vector<string> res_attrs;
BOOST_FOREACH(const ptree::value_type &e, sres) {
if ( e.second.get<string>("") == "Full DN")
fdn = ptree_dn_decode(e.first);
BOOST_FOREACH(const ptree::value_type &v, sres.get_child(e.first))
if (( v.first == attr ) & (v.second.get<string>("") != value))
res_attrs.insert(res_attrs.end(), v.second.get<string>(""));
}
char **res_values = new char*[res_attrs.size() + 1];
for ( unsigned int i = 0; i < res_attrs.size(); i++)
res_values[i] = const_cast<char*>(res_attrs[i].c_str());
res_values[res_attrs.size()] = NULL;
return modify(fdn, LDAP_MOD_REPLACE, attr, res_values);
}
string TFLdap::get_value(string dn, char *attr) {
ptree sres = search(dn);
string res;
BOOST_FOREACH(const ptree::value_type &e, sres)
BOOST_FOREACH(const ptree::value_type &v, sres.get_child(e.first))
if ( v.first == attr )
res = v.second.get<string>("");
return res;
}
vector<string> TFLdap::get_values(string dn, char *attr) {
ptree sres = search(dn);
vector<string> res;
BOOST_FOREACH(const ptree::value_type &e, sres)
BOOST_FOREACH(const ptree::value_type &v, sres.get_child(e.first))
if ( v.first == attr )
res.insert(res.end(), v.second.get<string>(""));
return res;
}
<file_sep>/libs/totp.h
/*
* This code is an rewrited version of https://github.com/gonrada/TOTP-Generator
* Thanks to <NAME>, which allowed me to use it.
*/
#ifndef TOTP_H
#define TOTP_H
#include "libs/Base32.h"
#include <stdint-gcc.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <cstring>
#include <iostream>
#include <time.h>
#include <sstream>
#include <math.h>
#define TOTP_SEED_LEN 16
#define TOTP_DIGITS 6
#define TOTP_PERIOD 30
#define TOTP_SHA_LEN 20
#define TOTP_SHA_BLOCK 64
#define TOTP_IN_DIG 0x36
#define TOTP_OUT_DIG 0x5c
#define alpha (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
using namespace std;
class TOTP
{
public:
TOTP();
~TOTP();
static unsigned char * get_random_seed32(void);
static string get_totp32(string);
private:
static unsigned int dynamic_truncation(uint8_t *input);
static void hmac_sha1(uint8_t * key, int key_len, uint8_t * data, int data_len, uint8_t *result);
};
#endif // TOTP_H
<file_sep>/libs/Base32.cpp
//////////////////////////////////////////////////////////////////////
// Base32.cpp
// (c) <NAME> http://madebits.com
// https://madebits.github.io/#r/cpp-base32.md
//////////////////////////////////////////////////////////////////////
#include "Base32.h"
int Base32::GetEncode32Length(int bytes)
{
int bits = bytes * 8;
int length = bits / 5;
if((bits % 5) > 0)
{
length++;
}
return length;
}
int Base32::GetDecode32Length(int bytes)
{
int bits = bytes * 5;
int length = bits / 8;
return length;
}
static bool Encode32Block(unsigned char* in5, unsigned char* out8)
{
// pack 5 bytes
unsigned long int buffer = 0;
for(int i = 0; i < 5; i++)
{
if(i != 0)
{
buffer = (buffer << 8);
}
buffer = buffer | in5[i];
}
// output 8 bytes
for(int j = 7; j >= 0; j--)
{
buffer = buffer << (24 + (7 - j) * 5);
buffer = buffer >> (24 + (7 - j) * 5);
unsigned char c = (unsigned char)(buffer >> (j * 5));
// self check
if(c >= 32) return false;
out8[7 - j] = c;
}
return true;
}
bool Base32::Encode32(unsigned char* in, int inLen, unsigned char* out)
{
if((in == 0) || (inLen <= 0) || (out == 0)) return false;
int d = inLen / 5;
int r = inLen % 5;
unsigned char outBuff[8];
for(int j = 0; j < d; j++)
{
if(!Encode32Block(&in[j * 5], &outBuff[0])) return false;
memmove(&out[j * 8], &outBuff[0], sizeof(unsigned char) * 8);
}
unsigned char padd[5];
memset(padd, 0, sizeof(unsigned char) * 5);
for(int i = 0; i < r; i++)
{
padd[i] = in[inLen - r + i];
}
if(!Encode32Block(&padd[0], &outBuff[0])) return false;
memmove(&out[d * 8], &outBuff[0], sizeof(unsigned char) * GetEncode32Length(r));
return true;
}
static bool Decode32Block(unsigned char* in8, unsigned char* out5)
{
// pack 8 bytes
unsigned long int buffer = 0;
for(int i = 0; i < 8; i++)
{
// input check
if(in8[i] >= 32) return false;
if(i != 0)
{
buffer = (buffer << 5);
}
buffer = buffer | in8[i];
}
// output 5 bytes
for(int j = 4; j >= 0; j--)
{
out5[4 - j] = (unsigned char)(buffer >> (j * 8));
}
return true;
}
bool Base32::Decode32(unsigned char* in, int inLen, unsigned char* out)
{
if((in == 0) || (inLen <= 0) || (out == 0)) return false;
int d = inLen / 8;
int r = inLen % 8;
unsigned char outBuff[5];
for(int j = 0; j < d; j++)
{
if(!Decode32Block(&in[j * 8], &outBuff[0])) return false;
memmove(&out[j * 5], &outBuff[0], sizeof(unsigned char) * 5);
}
unsigned char padd[8];
memset(padd, 0, sizeof(unsigned char) * 8);
for(int i = 0; i < r; i++)
{
padd[i] = in[inLen - r + i];
}
if(!Decode32Block(&padd[0], &outBuff[0])) return false;
memmove(&out[d * 5], &outBuff[0], sizeof(unsigned char) * GetDecode32Length(r));
return true;
}
bool Base32::Map32(unsigned char* inout32, int inout32Len, unsigned char* alpha32)
{
if((inout32 == 0) || (inout32Len <= 0) || (alpha32 == 0)) return false;
for(int i = 0; i < inout32Len; i++)
{
if(inout32[i] >=32) return false;
inout32[i] = alpha32[inout32[i]];
}
return true;
}
static void ReverseMap(unsigned char* inAlpha32, unsigned char* outMap)
{
memset(outMap, 0, sizeof(unsigned char) * 256);
for(int i = 0; i < 32; i++)
{
outMap[(int)inAlpha32[i]] = i;
}
}
bool Base32::Unmap32(unsigned char* inout32, int inout32Len, unsigned char* alpha32)
{
if((inout32 == 0) || (inout32Len <= 0) || (alpha32 == 0)) return false;
unsigned char rmap[256];
ReverseMap(alpha32, rmap);
for(int i = 0; i < inout32Len; i++)
{
inout32[i] = rmap[(int)inout32[i]];
}
return true;
}
<file_sep>/README.md
# two-factor-auth
Two-factor auth for SSH + LDAP
Dependencies:
- libboost-dev
---
## Manager
### Actions (rw)
- Add two-factor attrs
- Remove two-factor attrs
- (Re)generate TOTP token
- (Un)ban account
### Reports (ro)
- :soon: Generate QR code for TOTP token
- :soon: Show accounts with active sessions
- :soon: Show banned accounts
- :soon: List all accounts with two-factor
<file_sep>/ldap.schema/README.md
# How to deploy schema into OpenLDAP
What you will need in Debian:
- ldap-server
- ldap-utils
- make
Steps:
- cd ldap.schema/
- make
| 281cf319dcc8886ec8830c04fbfd26f4351cd595 | [
"Markdown",
"C",
"Makefile",
"C++"
] | 13 | C++ | tylkas/two-factor-auth | aab6d202584c740bb990b9268e04a4d8c0e5e819 | e91f2ecf38a54e4571553cdc7e0bf22a79f58a67 |
refs/heads/master | <file_sep>// プライバシーポリシーにチェックが入ってないとエラーメッセージを出す
//id="privacyPolicy--agree"
$(function() {
//始めにjQueryで送信ボタンを無効化する
$('.p-form__submit').prop("disabled", true);
//プライバシーポリシーがチェックされていたら
$('#privacyPolicy--agree').on('click', function() {
if ( $(this).prop('checked') == false ) {
//送信ボタンを復活
$('.p-form__submit').prop("disabled", true);
}
else {
//送信ボタンを閉じる
$('.p-form__submit').prop("disabled", false);
}
});
});<file_sep>// プライバシーポリシーにチェックが入ってないとエラーメッセージを出す
//id="privacyPolicy--agree"
$(function() {
//始めにjQueryで送信ボタンを無効化する
$('.p-form__submit').prop("disabled", true);
//始めにjQueryで必須欄を加工する
//$('form input:required').each(function () {
//$(this).prev("label").addClass("required");
//});
//入力欄の操作時
$('form input:required').change(function () {
//必須項目が空かどうかフラグ
let flag = true;
//必須項目をひとつずつチェック
$('form input:required').each(function(e) {
//もしinput textの必須項目が空なら
if ($('form input:required').eq(e).val() === "") {
flag = false;
//メールアドレスのタイプが選ばれていない場合は
}else if($(".p-form__mailType:checked").length == 0){
flag = false;
//基本情報登録がされてされていなければ
}else if(!$('input[name=register]').is(":checked")){
flag = false;
//プライバシーポリシーがチェックされてされていなければ
}else if( $('#privacyPolicy--agree').prop('checked') == false ){
flag = false;
}else{
//何もしない
}
});
//全て埋まっていたら
if (flag) {
//送信ボタンを復活
$('.p-form__submit').prop("disabled", false);
}
else {
//送信ボタンを閉じる
$('.p-form__submit').prop("disabled", true);
}
});
}); | d59e86ccef0567e0b6d2eba5521a471db2c272a0 | [
"JavaScript"
] | 2 | JavaScript | narumiyamazaki/Form_sample2 | 3db5f3a41efed7224fea5dbd909d73d6540f6d04 | c97e383b923c3a2474062df5bcca7711c2b83cc3 |
refs/heads/master | <repo_name>megaconfidence/boromi<file_sep>/src/routes/Admin.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import TopBar from '../components/TopBar';
import Card from '../components/Card';
import { Fragment, useEffect, useState } from 'react';
import fetcher from '../utils/fetcher';
import Loading from '../components/Loading';
import mq from '../utils/mq';
const Admin = ({ location: { pathname }, history }) => {
const [loan, setLoan] = useState([]);
const [showLoading, setShowLoading] = useState(false);
const handleViewClick = ({ id }) => {
history.push(`/detail/${id}`);
};
useEffect(() => {
(async () => {
setShowLoading(true);
const [error, { data }] = await fetcher(
'get',
`${process.env.REACT_APP_API}/api/loan`
);
if (error) console.log({ error });
if (data) {
setLoan(data);
}
setShowLoading(false);
})();
}, []);
return (
<div>
{showLoading ? <Loading /> : null}
<TopBar
ccss={{ textTransform: 'capitalize' }}
pathname={pathname}
history={history}
>
Your Loans
</TopBar>
<div
css={{
margin: '0 auto',
maxWidth: 'calc(100% - 2rem)',
[mq[0]]: { maxWidth: '650px' },
}}
>
{loan[0] ? (
<Fragment>
<p
css={{
color: '#7b8fa2',
fontWeight: '600',
fontSize: '.8125rem',
letterSpacing: '1.5px',
margin: '50px 0 1.5rem',
textTransform: 'uppercase',
}}
>
active
</p>
<Card
cta='view'
id={loan[0]._id}
title={loan[0].plan}
ctaCB={handleViewClick}
content={loan[0].paymentperiod + ' payment period'}
/>
</Fragment>
) : (
<div
css={{ textAlign: 'center', fontSize: '.875rem', color: '#58646d' }}
>
You have not made any loans. Click on <strong>New Loan</strong>{' '}
button to get started
</div>
)}
{loan.length > 1 ? (
<Fragment>
<p
css={{
color: '#7b8fa2',
fontWeight: '600',
fontSize: '.8125rem',
letterSpacing: '1.5px',
margin: '50px 0 1.5rem',
textTransform: 'uppercase',
}}
>
other
</p>
{loan.slice(1).map((l, k) => (
<Card
key={k}
cta='view'
id={l._id}
title={l.plan}
ctaCB={handleViewClick}
content={l.paymentperiod + ' payment period'}
/>
))}
</Fragment>
) : null}
</div>
</div>
);
};
export default Admin;
<file_sep>/src/App.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom';
import Home from './routes/Home';
import Login from './routes/Login';
import Loan from './routes/Loan';
import Request from './routes/Request';
import Repayment from './routes/Repayment';
import Admin from './routes/Admin';
import Detail from './routes/Detail';
import Protect from './components/Protect';
function App() {
return (
<div
className='App'
css={{ fontFamily: "'Noto Sans JP', sans-serif !Important", position: 'relative' }}
>
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/loan'>
<Protect component={Loan} />
</Route>
<Route exact path='/request'>
<Protect component={Request} />
</Route>
<Route exact path='/repayment'>
<Protect component={Repayment} />
</Route>
<Route exact path='/admin'>
<Protect component={Admin} />
</Route>
<Route exact path='/detail/:id'>
<Protect component={Detail} />
</Route>
</Switch>
</Router>
<div css={{ marginTop: '50px' }}></div>
</div>
);
}
export default App;
<file_sep>/src/routes/Home.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { Link } from 'react-router-dom';
import Button from '../components/Button';
const Home = () => {
return (
<div>
<div
css={{
width: '100vw',
height: '100vh',
filter: 'blur(5px)',
position: 'absolute',
}}
></div>
<nav></nav>
<div
css={{
top: '50%',
left: '50%',
color: '#000',
position: 'fixed',
transform: 'translate(-50%, -50%)',
}}
>
<header>
<div
css={{
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
}}
>
<img
css={{ width: '50px' }}
src='/image/boromi_dark.png'
alt='boromi'
/>
<span
css={{
fontSize: '3em',
}}
>
Boromi
</span>
</div>
</header>
<section css={{ textAlign: 'center' }}>
<div
css={{
display: 'flex',
margin: '30px 0',
lineHeight: '1.5',
justifyContent: 'center',
}}
>
<div css={{ maxWidth: '500px' }}>
<p>
Do you have an urgent need for cash to settle bills, take care
of emergencies or grab an opportunity? Does payday seem so far
and bills are piling up? Don’t worry! Boromi has got you covered.
</p>
<p>
Apply for a loan now and get the funds in less than 5 minuts.
</p>
</div>
</div>
<Link to='/login'>
<Button>get started</Button>
</Link>
</section>
</div>
</div>
);
};
export default Home;
<file_sep>/src/routes/Repayment.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import Button from '../components/Button';
import { useState } from 'react';
import TopBar from '../components/TopBar';
import fetcher from '../utils/fetcher';
import Loading from '../components/Loading';
import mq from '../utils/mq';
const Repayment = ({ history: { goBack, push } }) => {
const [paymentperiod, setPaymentPeriod] = useState('weekly');
const [paymentamount, setPaymentAmount] = useState('');
const [showLoading, setShowLoading] = useState(false);
const handleContinue = async () => {
setShowLoading(true);
const loan = JSON.parse(localStorage.getItem('loan'));
const payLoad = { ...loan, paymentperiod, paymentamount };
localStorage.setItem('loan', JSON.stringify(payLoad));
const [error, { data }] = await fetcher(
'post',
`${process.env.REACT_APP_API}/api/loan`,
payLoad
);
if (error) console.log({ error });
if (data) {
localStorage.removeItem('loan');
push('/admin');
}
setShowLoading(false);
};
return (
<div>
{showLoading ? <Loading /> : null}
<TopBar>Repayment</TopBar>
<div
css={{
margin: '0 auto',
borderRadius: '6px',
maxWidth: 'calc(100% - 2rem)',
[mq[0]]: { maxWidth: '650px' },
boxShadow: '0 0 20px 0 rgba(46,61,73,.15)',
}}
>
<div
css={{
padding: '70px',
color: '#2e3d49',
fontWeight: '300',
borderTopLeftRadius: '6px',
borderTopRightRadius: '6px',
background: 'linear-gradient(224.86deg,#d6bff9,#f7f7f7)',
}}
>
<div
css={{
fontSize: '1.7rem',
marginTop: '15px',
marginBottom: '1em',
textTransform: 'capitalize',
}}
>
loan repayment information
</div>
<div>Please provide answers to the following questions</div>
</div>
<form onSubmit={(e) => e.preventDefault()}>
<div
css={{
color: '#525c65',
padding: '15px 70px 45px',
label: {
display: 'block',
margin: '.8rem 0',
},
'input[type="radio"]': {
width: '12px',
height: '12px',
appearance: 'none',
borderRadius: '50%',
border: '1px solid #999',
transition: '0.2 all linear',
':checked': {
border: '3px solid #9d5ffa',
boxShadow: '0 0 0 1px #9d5ffa,0 2px 1px 0 rgba(46,60,73,.05)',
},
},
}}
>
<div>
<p>Select a repayment period:</p>
<label>
<input
type='radio'
name='paymentperiod'
value='weekly'
checked={paymentperiod === 'weekly'}
onChange={({ target }) => {
setPaymentPeriod(target.value);
}}
/>
Weekly
</label>
<label>
<input
type='radio'
name='paymentperiod'
value='monthly'
checked={paymentperiod === 'monthly'}
onChange={({ target }) => {
setPaymentPeriod(target.value);
}}
/>
Monthly
</label>
<label>
<input
type='radio'
name='paymentperiod'
value='yearly'
checked={paymentperiod === 'yearly'}
onChange={({ target }) => {
setPaymentPeriod(target.value);
}}
/>
Yearly
</label>
</div>
<div css={{ marginTop: '2.5rem' }}>
<p>Repayment amount for the specified period:</p>
<p
css={{
color: '#7d97ad',
fontSize: '0.8rem',
fontStyle: 'italic',
}}
>
Please note, this is not optional.
</p>
<input
css={{
width: '100%',
height: '44px',
color: '#2e3d49',
fontSize: '14px',
borderRadius: '4px',
paddingLeft: '15px',
paddingRight: '15px',
border: '1px solid #dbe2e8',
boxShadow: '5px 5px 10px 0 rgba(0,0,0,.05)',
':focus': {
boxShadow: '0 0 0 4px #9d5ffa ',
},
}}
value={paymentamount}
required
onChange={({ target }) => {
setPaymentAmount(target.value);
}}
type='number'
/>
</div>
</div>
<div
css={{
display: 'flex',
padding: '25px 40px',
[mq[0]]: {
padding: '45px 70px',
},
borderTop: '1px solid #dbe2e8',
justifyContent: 'space-between',
}}
>
<Button
ccss={{
color: '#8796a4',
backgroundColor: '#dbe2e8',
':hover': { backgroundColor: '#c8d0d7' },
}}
onClick={() => goBack()}
>
back
</Button>
<Button type='submit' onClick={handleContinue}>
continue
</Button>
</div>
</form>
</div>
</div>
);
};
export default Repayment;
<file_sep>/src/utils/fetcher.js
const fetcher = async (method, url, data) => {
try {
const response = await fetch(url, {
method,
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: localStorage.getItem('token'),
},
});
const res = await response.json();
return [null, res];
} catch (error) {
return [error, {}];
}
};
export default fetcher;
<file_sep>/src/routes/Request.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { useState } from 'react';
import Button from '../components/Button';
import TopBar from '../components/TopBar';
import mq from '../utils/mq';
const Request = ({ history: { goBack, push } }) => {
const [category, setCategory] = useState('personal');
const [amount, setAmount] = useState('');
const handleContinue = () => {
const loan = JSON.parse(localStorage.getItem('loan'));
localStorage.setItem('loan', JSON.stringify({ ...loan, category, amount }));
push('/repayment');
};
return (
<div>
<TopBar>Request</TopBar>
<div
css={{
margin: '0 auto',
borderRadius: '6px',
maxWidth: 'calc(100% - 2rem)',
[mq[0]]: { maxWidth: '650px' },
boxShadow: '0 0 20px 0 rgba(46,61,73,.15)',
}}
>
<div
css={{
padding: '70px',
color: '#2e3d49',
fontWeight: '300',
borderTopLeftRadius: '6px',
borderTopRightRadius: '6px',
background: 'linear-gradient(224.86deg,#d6bff9,#f7f7f7)',
}}
>
<div
css={{
fontSize: '1.7rem',
marginTop: '15px',
marginBottom: '1em',
textTransform: 'capitalize',
}}
>
loan request information
</div>
<div>Please provide answers to the following questions</div>
</div>
<form onSubmit={(e) => e.preventDefault()}>
<div
css={{
color: '#525c65',
padding: '15px 70px 45px',
label: {
display: 'block',
margin: '.8rem 0',
},
'input[type="radio"]': {
width: '12px',
height: '12px',
appearance: 'none',
borderRadius: '50%',
border: '1px solid #999',
transition: '0.2 all linear',
':checked': {
border: '3px solid #9d5ffa',
boxShadow: '0 0 0 1px #9d5ffa,0 2px 1px 0 rgba(46,60,73,.05)',
},
},
}}
>
<div>
<p>Select a loan category:</p>
<label>
<input
type='radio'
name='category'
value='personal'
checked={category === 'personal'}
onChange={({ target }) => {
setCategory(target.value);
}}
/>
Personal
</label>
<label>
<input
type='radio'
name='category'
value='business'
checked={category === 'business'}
onChange={({ target }) => {
setCategory(target.value);
}}
/>
Business
</label>
<label>
<input
type='radio'
name='category'
value='religious'
checked={category === 'religious'}
onChange={({ target }) => {
setCategory(target.value);
}}
/>
Religious
</label>
</div>
<div css={{ marginTop: '2.5rem' }}>
<p>Enter loan amount:</p>
<p
css={{
color: '#7d97ad',
fontSize: '0.8rem',
fontStyle: 'italic',
}}
>
Please note, this is not optional.
</p>
<input
css={{
width: '100%',
height: '44px',
color: '#2e3d49',
fontSize: '14px',
borderRadius: '4px',
paddingLeft: '15px',
paddingRight: '15px',
border: '1px solid #dbe2e8',
boxShadow: '5px 5px 10px 0 rgba(0,0,0,.05)',
':focus': {
boxShadow: '0 0 0 4px #9d5ffa ',
},
}}
value={amount}
required
onChange={({ target }) => {
setAmount(target.value);
}}
type='number'
/>
</div>
</div>
<div
css={{
display: 'flex',
padding: '25px 40px',
[mq[0]]: {
padding: '45px 70px',
},
borderTop: '1px solid #dbe2e8',
justifyContent: 'space-between',
}}
>
<Button
ccss={{
color: '#8796a4',
backgroundColor: '#dbe2e8',
':hover': { backgroundColor: '#c8d0d7' },
}}
onClick={() => goBack()}
>
back
</Button>
<Button type='submit' onClick={handleContinue}>
continue
</Button>
</div>
</form>
</div>
</div>
);
};
export default Request;
<file_sep>/src/routes/Detail.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { useEffect, useState } from 'react';
import Button from '../components/Button';
import Loading from '../components/Loading';
import TopBar from '../components/TopBar';
import fetcher from '../utils/fetcher';
import mq from '../utils/mq';
import moment from 'moment';
const Detail = ({ location: { pathname }, history: { goBack } }) => {
const [loan, setLoan] = useState({ amount: 0, paymentamount: 0 });
const [showLoading, setShowLoading] = useState(false);
useEffect(() => {
const id = pathname.replace('/detail/', '');
(async () => {
setShowLoading(true);
const [error, { data }] = await fetcher(
'get',
`${process.env.REACT_APP_API}/api/loan/${id}`
);
if (error) console.log({ error });
if (data) setLoan(data);
setShowLoading(false);
})();
}, [pathname]);
return (
<div>
{showLoading ? <Loading /> : null}
<TopBar ccss={{ textTransform: 'capitalize' }}>details</TopBar>
<div
css={{
padding: '2rem',
margin: '0 auto',
borderRadius: '6px',
maxWidth: 'calc(100% - 6rem)',
[mq[0]]: { maxWidth: '650px' },
boxShadow: '0 0 20px 0 rgba(46,61,73,.15)',
}}
>
<header
css={{
fontWeight: '300',
fontSize: '1.7rem',
textAlign: 'center',
textTransform: 'capitalize',
}}
>
Loan Information
</header>
<div
css={{
color: '#58646d',
}}
>
<p>
Amount:{' '}
<strong>
N {String(loan.amount).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
</strong>
</p>
<p>
Plan Type: <strong>{loan.plan}</strong>
</p>
<p>
Category: <strong>{loan.category}</strong>
</p>
<p>
Payment Period: <strong>{loan.paymentperiod}</strong>
</p>
<p>
Payment Amount:{' '}
<strong>
N{' '}
{String(loan.paymentamount)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
</strong>
</p>
<p>
Loan Date:{' '}
<strong>{moment(loan.createdAt).format('MMM Do YY')}</strong>
</p>
<p>
Loan ID: <strong>{loan._id}</strong>
</p>
</div>
<Button
ccss={{ display: 'block', margin: '20px auto 0' }}
onClick={() => goBack()}
>
Back
</Button>
</div>
</div>
);
};
export default Detail;
<file_sep>/src/components/Protect.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { Redirect, Route } from 'react-router-dom';
const Protect = ({ component: Component, ...rest }) => {
const token = localStorage.getItem('token');
if (!token) return <Redirect to='/login' />;
return <Route render={(props) => <Component {...props} {...rest} />} />;
};
export default Protect;
<file_sep>/src/components/Button.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
const Button = ({ children, ccss, ...props }) => {
return (
<button
{...props}
css={{
color: '#fff',
border: 'none',
fontWeight: 600,
maxWidth: '100%',
cursor: 'pointer',
overflow: 'hidden',
textAlign: 'center',
borderRadius: '4px',
whiteSpace: 'nowrap',
padding: '1.2em 2em',
background: '#9d5ffa',
letterSpacing: '.165em',
display: 'inline-block',
textOverflow: 'ellipsis',
textTransform: 'uppercase',
fontFamily: 'Open Sans,sans-serif',
WebkitFontSmoothing: 'antialiased',
boxShadow: '12px 15px 20px rgba(0,0,0,.1)',
transition:
'box-shadow .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out',
':hover': {
background: '#7748bd',
boxShadow: '2px 4px 8px 0 rgba(0,0,0,.1)',
},
...ccss,
fontSize: '12px',
}}
>
{children}
</button>
);
};
export default Button;
<file_sep>/src/routes/Loan.js
/** @jsx jsx */
import { jsx } from '@emotion/core';
import TopBar from '../components/TopBar';
import Card from '../components/Card';
import { useState } from 'react';
import { Redirect } from 'react-router-dom';
import mq from '../utils/mq';
const Loan = ({ location: { pathname } }) => {
const [toRequestPage, setToRequestPage] = useState(false);
const handleCTA = ({ title }) => {
localStorage.setItem('loan', JSON.stringify({ plan: title }));
setToRequestPage(true);
};
if (toRequestPage) return <Redirect to='/request' />;
return (
<div>
<TopBar ccss={{ textTransform: 'capitalize' }} pathname={pathname}>
plans
</TopBar>
<div
css={{
margin: '0 auto',
maxWidth: 'calc(100% - 2rem)',
[mq[0]]: { maxWidth: '650px' },
}}
>
<Card
ccss={{ backgroundColor: '#9d5ffa1c' }}
title='basic'
content='This is the best loan plan for individuals with flexible interest rates and replayment plan. It is quick fast and convinient and helps you reach your next financial goals, with less fees, unprecedented service, and awesome loan help.'
cta='start plan'
ctaCB={handleCTA}
/>
<Card
title='standard'
content='This is a friendly plan for SMEs and entrepreneurs, looking for quick cash to grow their business. It enables you withdraw from your account beyond your actual balance and with an agreed repayment plan.'
cta='start plan'
ctaCB={handleCTA}
/>
<Card
title='premium'
content='This plan is designed to assist clients with business emergencies. It enables you withdraw from your account beyond your actual balance and with an agreed repayment plan. Overdraft enables clients have access to funds for emergencies at a very competitive interest.'
cta='start plan'
ctaCB={handleCTA}
/>
</div>
</div>
);
};
export default Loan;
| e230fbcc6205c1f7adbc558985feaa817c7e21d1 | [
"JavaScript"
] | 10 | JavaScript | megaconfidence/boromi | 168c9946d8bc68f3db30566f2f3b567eed95c688 | 9f805d395d1634ba28083d608cd2da6399c6a9a5 |
refs/heads/master | <file_sep>var downcache = require("downcache"),
cheerio = require("cheerio"),
url = require("url"),
decode = require('ent/decode');
/*
downcache.set({
log: "verbose"
//dir: "/Users/cwilson1130/Desktop/data/movies/"
});
*/
// match a user-inputed to the most likely query
var resolve = module.exports.resolve = function(type, name, callback) {
var url = "http://www.imdb.com/xml/find?json=1&nr=1&" + (type==="title"? "tt" : "nm") + "=on&q=" + name;
downcache(url, function(err, resp, body) {
var suggestions = JSON.parse(body);
if (!suggestions) {
console.log("No response", url);
return;
}
var key = type + "_popular";
if (suggestions[key]) {
console.log("Matched input '" + name + "' to " + suggestions[key][0][type] + " (" + suggestions[key][0].description.replace(/<.*?>/g,"").replace(/\s+/g, " ") + ")");
callback(suggestions[key][0].id);
return;
}
});
}
module.exports.actor = function(args, callback) {
if (typeof args === "string") {
args = { name: args };
}
if (args.id) {
get_actor_by_id(args.id, callback);
} else if (args.name) {
resolve("name", args.name, function(id) {
get_actor_by_id(id, callback);
});
}
}
module.exports.movie = function(args, callback) {
if (typeof args === "string") {
args = { name: args };
}
if (args.id) {
get_movie_by_id(args.id, callback);
} else if (args.name) {
resolve("title", args.name, function(id) {
get_movie_by_id(id, callback);
});
}
}
module.exports.oscars = require("./imdb/oscars.js");
var get_actor_by_id = module.exports.actor_by_id = require("./imdb/actor.js");
var get_movie_by_id = module.exports.movie_by_id = require("./imdb/movie.js");
var list = module.exports.list = require("./imdb/list.js");
var globes = module.exports.globes = require("./imdb/globes.js");<file_sep>var downcache = require("downcache");
var cheerio = require("cheerio");
var BASE = "http://www.imdb.com";
var shows = [];
var movies = [];
var get_movies_page = function(url, callback, terminal) {
// function to evaluate when to stop recursing
terminal = terminal || function() { return false; }
var isTerminal = false;
//console.log(url);
downcache(BASE + url, function(err, resp, body) {
var $ = cheerio.load(body);
$(".results > tr").each(function(i, v) {
if (!$(v).hasClass("detailed")) {
return;
}
console.log($(v).find("td.title > a").text().trim());
var movie = {
title: $(v).find("td.title > a").text().trim(),
imdb: $(v).find("td.title > a").attr("href").split("/")[2],
year: parseInt($(v).find(".year_type").text().replace("(", "").replace(")","").trim()),
gross: $(v).find("td.sort_col").text().trim(),
genres: [],
summary: $(v).find(".outline").text().trim(),
runtime: parseInt($(v).find(".runtime").text().replace(" mins.", "").trim())
};
movie.revenue = parseFloat(movie.gross.replace(/[^0-9\.]+/g, "")) || 0;
if (movie.gross.slice(-1) === "B") {
movie.revenue *= 1000000000;
} else if (movie.gross.slice(-1) === "M") {
movie.revenue *= 1000000;
} else if (movie.gross.slice(-1) === "K") {
movie.revenue *= 1000;
}
// genres
$(v).find(".genre a").each(function(ii, vv) {
movie.genres.push($(vv).text().trim());
});
// rating
var rating = $(v).find(".certificate span");
if (rating.length) {
movie.rating = rating.attr("title").replace("_", " ");
} else {
movie.rating = "N/A";
}
// stars
var stars = $(v).find(".rating");
if (stars.length) {
movie.stars = parseFloat(stars.attr("id").split("|")[2]);
} else {
movie.stars = "N/A";
}
isTerminal = terminal(movie);
if (!isTerminal && movie.revenue) {
movies.push(movie);
}
});
var pagination = $(".pagination a").last();
if ($(pagination).html().split("&")[0] == "Next" && !isTerminal) {
get_movies_page($(pagination).attr("href"), callback, terminal);
} else {
callback(movies);
}
});
}
var get_tvshows_page = function(url, callback, terminal) {
// function to evaluate when to stop recursing
terminal = terminal || function() { return false; }
//console.log(url);
downcache(BASE + url, function(err, resp, body) {
//console.log(BASE + url);
var $ = cheerio.load(body, {
decodeEntities: false // $num was getting converted to '#''
});
$(".results > tr").each(function(i, v) {
if (!$(v).hasClass("detailed")) {
return;
}
shows.push({
title: $(v).find("td.title > a").text().trim(),
link: $(v).find("td.title > a").attr("href").split("/")[2],
rating: parseFloat($(v).find(".rating-rating .value").text().trim())
});
});
var pagination = $(".pagination a").last();
if ($(pagination).html().split("&")[0] == "Next" && !terminal(shows)) {
get_tvshows_page($(pagination).attr("href"), callback, terminal);
} else {
callback(shows);
}
});
}
module.exports = {
movies: function(callback, terminal) {
callback = callback || function(d) { console.log(d); }
get_movies_page("/search/title?at=0&countries=us&sort=boxoffice_gross_us&start=1", callback, terminal);
},
tvshows: function(callback, terminal) {
callback = callback || function(d) { console.log(d); }
get_tvshows_page("/search/title?at=0&num_votes=5000,&sort=user_rating&title_type=tv_series", callback, terminal);
}
};<file_sep>var imdb = require("../lib/imdb");
imdb.actor({ name: "<NAME>" }, function(actor) {
console.log(actor);
});<file_sep>#IMDB to JSON
This is a simple scraper that converts the relevant parts of an actor or movie page on IMDB to a JSON document. Feel free to open an issue or submit a pull request if there are parts of the page that we have not yet added to the scraper.
This module uses [downcache](https://www.npmjs.com/package/downcache) to store a local copy of each requested page on your local machine.
## Installation
npm install
## Command Line Usage
# movie by vernacular name
node index.js movie --name="The Godfather" > thegodfather.json
# actor by vernacular name
node index.js actor --name="<NAME>" > julianne_moore.json
# movie by IDMB id
node index.js movie --id=tt0074281 > carwash.json
# actor by IDMB id
node index.js actor --id=nm0001640 > richard_pryor.json
In the first two cases, the script uses the [undocumented IMDB search API](http://stackoverflow.com/a/7744369/1779735) to resolve the input to a page. It's anecdotally very accurate, but be careful if you're running a large number of names through it to check them afterward.
## API Usage
var imdb = require("movie-data");
imdb.actor_by_id("nm0001640", function(actor) {
console.log(actor);
});
// other methods are "actor", "movie", "movie_by_id"
### Downcache usage
By default, downcache creates a local directory named "cache" for storing the HTML pages you request. You can adjust downcache's settings from the parent script if you so desire:
var imdb = require("movie-data"),
downcache = require("downcache");
downcache.set({
dir: "/Users/myname/Desktop/movies/",
log: "verbose"
});
imdb.movie("Mean Girls", function(movie) {
console.log(movie);
});
##JSON
The JSON should be fairly self explanatory. Here's are condensed examples:
{ id: 'tt0068646',
name: 'The Godfather',
date: '1972',
imdb_photo: 'http://ia.media-imdb.com/images/M/MV5BMjEyMjcyNDI4MF5BMl5BanBnXkFtZTcwMDA5Mzg3OA@@._V1_SX214_AL_.jpg',
info:
{ director: [ [Object] ],
writers: [ [Object], [Object] ],
stars: [ [Object], [Object], [Object] ] },
actors:
[ { name: '<NAME>',
id: 'nm0000008',
character: '<NAME>' },
{ name: '<NAME>',
id: 'nm0000199',
character: '<NAME>' },
{ name: '<NAME>',
id: 'nm0001001',
character: '<NAME>' },
{ name: '<NAME>',
id: 'nm0144710',
...
And an actor readout:
{ id: 'nm0000194',
name: '<NAME>',
imdb_photo: 'http://ia.media-imdb.com/images/M/MV5BMTM5NDI1MjE2Ml5BMl5BanBnXkFtZTgwNDE0Nzk0MDE@._V1_SY317_CR7,0,214,317_AL_.jpg',
movies:
[ { year: '2015',
name: 'Maggie'<NAME>',
id: 'tt3471098',
characters: {},
type: 'Movie',
status: 'filming' },
{ year: '2015',
name: 'The Hunger Games: Mockingjay - Part 2',
id: 'tt1951266',
characters: [Object],
type: 'Movie',
status: 'post-production' },
{ year: '2015',
name: 'Freeheld',
id: 'tt1658801',
characters: [Object],
type: 'Movie',
status: 'post-production' },
{ year: '2014/I',
name: '<NAME>',
id: 'tt1121096',
characters: [Object],
type: 'Movie',
status: null },
{ year: '2014',
name: 'The Hunger Games: Mockingjay - Part 1',
id: 'tt1951265',
characters: [Object],
type: 'Movie',
status: null },
{ year: '2014',
name: '<NAME>',
id: 'tt3316960',
characters: [Object],
type: 'Movie',
status: null },
{ year: '2014',
name: '<NAME>',
id: 'tt2172584',
characters: [Object],
type: 'Movie',
status: null },
{ year: '1987',
name: 'I'<NAME>',
id: 'tt0092378',
characters: [Object],
type: 'TV Mini-Series',
status: null } ],
stats:
{ 'Date of Birth':
{ birth_monthday: '12-3',
birth_year: '1960',
birth_place: 'Fayetteville, North Carolina, USA' },
'Birth Name': '<NAME>',
Nickname: 'Juli',
Height: '5\' 4" (1.63 m)' } }
| d3b25db547c417683a72cf319b7a46f97d6056b4 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | TimeMagazine/movie-data | b4ef4d1ecd76d941e1bd10037c0357438060788e | 8266b9108fe9c1cd79878448764a5478e6ae0310 |
refs/heads/master | <file_sep>jQuery Enquete Form Builder Plug-In
===================================
[](https://travis-ci.org/tetsuwo/jquery-enquete-form-builder)
"jquery-enquete-form-builder" is a plug-in for build the Enquete Form.
View Demonstration
------------------
<http://jsdo.it/tetsuwo/z5tn>
<file_sep>
var $enquete = jQuery('#enquete-form-test-1').enqueteFormBuilder({
defaultItems: [],
debug: true,
minItem: 1,
maxItem: 20
});
describe('jQuery.enqueteFormBuilder', function() {
it('getConfg', function() {
expect($enquete.getConfig().debug).toBeTruthy();
expect($enquete.getConfig().minItem).toEqual(1);
expect($enquete.getConfig().maxItem).toEqual(20);
});
it('addItem', function() {
$enquete.getContents().eq(0)
.find($enquete.getClassName('form-title', true)).val('AUTO-1').change();
expect($enquete.getItems().length).toEqual(1);
$enquete.addItem(true, 'test-1');
$enquete.getItem('test-1')
.find($enquete.getClassName('form-title', true)).val('TEST-1').change();
expect($enquete.getItems().length).toEqual(2);
$enquete.addItem(true, 'test-2');
$enquete.getItem('test-2')
.find($enquete.getClassName('form-title', true)).val('TEST-2').change();
expect($enquete.getItems().length).toEqual(3);
$enquete.addItem(true, 'test-3');
$enquete.getItem('test-3')
.find($enquete.getClassName('form-title', true)).val('TEST-3').change();
expect($enquete.getItems().length).toEqual(4);
$enquete.addItem(true, 'test-4');
$enquete.getItem('test-4')
.find($enquete.getClassName('form-title', true)).val('TEST-4').change();
expect($enquete.getItems().length).toEqual(5);
});
it('moveUpItem', function() {
var $target = $enquete.getContents().eq(2);
$target
.find($enquete.getClassName('form-type', true))
.val('checkbox').change();
$enquete.getItems().eq(2)
.find($enquete.getClassName('up-item', true)).click();
var afterValue = $enquete.getContents().eq(1)
.find($enquete.getClassName('form-type', true))
.find(':selected').val();
expect(afterValue).toEqual('checkbox');
});
it('moveDownItem', function() {
var $target = $enquete.getContents().eq(2);
$target
.find($enquete.getClassName('form-type', true))
.val('radio').change();
$enquete.getItems().eq(1)
.find($enquete.getClassName('down-item', true)).click();
var afterValue = $enquete.getContents().eq(1)
.find($enquete.getClassName('form-type', true))
.find(':selected').val();
expect(afterValue).toEqual('radio');
});
it('deleteItem', function() {
$enquete.deleteItem('new-item-0');
expect($enquete.getItems().length).toEqual(4);
});
});
<file_sep>
var enqueteItems2 = [
{"id":"7","title":"\u6027\u5225","type":"radio","index":"1","note":"","isNew":false,"isRequired":true,"isDeleted":false,"options":[{"id":"5","isNew":false,"isDeleted":false,"content":"\u5973\u6027"},{"id":"4","isNew":false,"isDeleted":false,"content":"\u7537\u6027"}]},
{"id":"8","title":"\u8077\u696d","type":"text","index":"2","note":"","isNew":false,"isRequired":true,"isDeleted":false,"options":[{"id":"6","isNew":false,"isDeleted":false,"content":"\u5927\u5de5"}]},
{"id":"9","title":"12345","type":"checkbox","index":"3","note":"","isNew":false,"isRequired":false,"isDeleted":false,"options":[{"id":"7","isNew":false,"isDeleted":false,"content":"1"},{"id":"8","isNew":false,"isDeleted":false,"content":"2"},{"id":"9","isNew":false,"isDeleted":false,"content":"3"}]},
{"id":"11","title":"\u30dd\u30fc\u30c8\u30d5\u30a9\u30ea\u30aa URL","type":"text","index":"4","note":"","isNew":false,"isRequired":false,"isDeleted":false,"options":[{"id":"13","isNew":false,"isDeleted":false,"content":"1"},{"id":"14","isNew":false,"isDeleted":false,"content":"2"},{"id":"15","isNew":false,"isDeleted":false,"content":"3"}]},
{"id":"10","title":"\u4f4f\u6240","type":"text","index":"5","note":"","isNew":false,"isRequired":false,"isDeleted":false,
"options":[
{"id":"10","isNew":false,"isDeleted":false,"content":"1"},{"id":"11","isNew":false,"isDeleted":false,"content":"2"},{"id":"12","isNew":false,"isDeleted":false,"content":"3"}
]
}
];
var $enquete2 = jQuery('#enquete-form-test-2').enqueteFormBuilder({
debug: true,
minItem: 3,
maxItem: 10,
defaultItems: enqueteItems2
});
describe('jQuery.enqueteFormBuilder({defaultData})', function() {
it('getConfg', function() {
expect($enquete2.getConfig().debug).toBeTruthy();
expect($enquete2.getConfig().minItem).toEqual(3);
expect($enquete2.getConfig().maxItem).toEqual(10);
});
it('addItem', function() {
expect($enquete2.getItems().length).toEqual(enqueteItems2.length);
});
it('moveUpItem', function() {
var beforeValue = $enquete2.getContents().eq(2)
.find($enquete2.getClassName('form-type', true))
.find(':selected').val();
$enquete2.getItems().eq(2)
.find($enquete2.getClassName('up-item', true)).click();
var afterValue = $enquete2.getContents().eq(1)
.find($enquete2.getClassName('form-type', true))
.find(':selected').val();
expect(afterValue).toEqual(beforeValue);
});
it('moveDownItem', function() {
var beforeValue = $enquete2.getContents().eq(0)
.find($enquete2.getClassName('form-type', true))
.find(':selected').val();
$enquete2.getItems().eq(0)
.find($enquete2.getClassName('down-item', true)).click();
var afterValue = $enquete2.getContents().eq(1)
.find($enquete2.getClassName('form-type', true))
.find(':selected').val();
expect(afterValue).toEqual(beforeValue);
});
});
| 9bb494cda495737a5e0645c68392cdf3e0882fb2 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | tetsuwo/jquery-enquete-form-builder | 592cb86f3478e344d2d73e2e15828bcf78449b8c | 16a6037db2a2cc46537ea224a94f5023e4dfbe40 |
refs/heads/master | <repo_name>theapache64/livedata_transformation_example<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/map/MapActivityModule.java
package com.theah64.livedata_transformation_example.ui.activities.map;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;
import dagger.Module;
import dagger.Provides;
@Module
class MapActivityModule {
private final FragmentActivity fragmentActivity;
MapActivityModule(FragmentActivity fragmentActivity) {
this.fragmentActivity = fragmentActivity;
}
@Provides
MapActivityViewModel provideMapTransformationViewModel() {
return ViewModelProviders.of(fragmentActivity)
.get(MapActivityViewModel.class);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/switch_map/SwitchMapActivityComponent.java
package com.theah64.livedata_transformation_example.ui.activities.switch_map;
import com.theah64.livedata_transformation_example.di.base.ActivityModule;
import dagger.Subcomponent;
@Subcomponent(modules = SwitchMapActivityModule.class)
public interface SwitchMapActivityComponent {
void inject(SwitchMapActivity activity);
@Subcomponent.Builder
interface Builder {
Builder activityModule(ActivityModule activityModule);
Builder switchMapTransformationActivityModule(SwitchMapActivityModule activityModule);
SwitchMapActivityComponent build();
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/main/MainActivityViewModelFactory.java
package com.theah64.livedata_transformation_example.ui.activities.main;
import com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters.MenuAdapter;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class MainActivityViewModelFactory implements ViewModelProvider.Factory {
private final MenuAdapter menuAdapter;
MainActivityViewModelFactory(MenuAdapter menuAdapter) {
this.menuAdapter = menuAdapter;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new MainActivityViewModel(menuAdapter);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/data/remote/models/SearchResponse.java
package com.theah64.livedata_transformation_example.data.remote.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class SearchResponse extends BaseAPIResponse<SearchResponse.Data> {
public SearchResponse(boolean error, String message, Data data) {
super(error, message, data);
}
public static class Data {
@SerializedName("users")
private final List<User> users;
public Data(List<User> users) {
this.users = users;
}
public List<User> getUsers() {
return users;
}
}
public static class User {
@SerializedName("name")
private final String name;
@SerializedName("image")
private final String image;
public User(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
}
}
<file_sep>/README.md
# livedata_transformation_example
A simple app to show LiveData Transformation, built using ( MVVM + Dagger2 + Retrofit + RxJava + DataBinding )
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/switch_map/SwitchMapViewModelFactory.java
package com.theah64.livedata_transformation_example.ui.activities.switch_map;
import com.theah64.livedata_transformation_example.data.remote.ApiRepository;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class SwitchMapViewModelFactory implements ViewModelProvider.Factory {
private ApiRepository apiRepository;
@Inject
SwitchMapViewModelFactory(ApiRepository apiRepository) {
this.apiRepository = apiRepository;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new SwitchMapViewModel(apiRepository);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/util/SingleLiveEvent.java
package com.theah64.livedata_transformation_example.util;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
public class SingleLiveEvent extends MutableLiveData<Boolean> {
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super Boolean> observer) {
super.observe(owner, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
observer.onChanged(aBoolean);
removeObserver(this);
}
});
}
public void done() {
setValue(true);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/map/MapActivityComponent.java
package com.theah64.livedata_transformation_example.ui.activities.map;
import dagger.Component;
@Component(modules = MapActivityModule.class)
public interface MapActivityComponent {
void inject(MapActivity mapTransformationActivity);
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/map/MapActivityViewModel.java
package com.theah64.livedata_transformation_example.ui.activities.map;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
public class MapActivityViewModel extends ViewModel {
public String name;
private MutableLiveData<String> user = new MutableLiveData<>();
private LiveData<String> toastMessage = Transformations.map(user, input ->
input == null || input.isEmpty() ? "Please enter your name " : "User added : " + input
);
public void onAddUserClicked(String name) {
user.setValue(name);
}
LiveData<String> getToastMessage() {
return toastMessage;
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/switch_map/SwitchMapActivityModule.java
package com.theah64.livedata_transformation_example.ui.activities.switch_map;
import android.content.Context;
import com.theah64.livedata_transformation_example.data.remote.ApiRepository;
import com.theah64.livedata_transformation_example.di.base.ActivityModule;
import com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters.UsersAdapter;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;
import dagger.Module;
import dagger.Provides;
@Module(includes = {ActivityModule.class})
public class SwitchMapActivityModule {
@Provides
UsersAdapter provideUsersAdapter(final Context context) {
return new UsersAdapter(context);
}
@Provides
SwitchMapViewModelFactory provideSwitchMapTransformationViewModelFactory(ApiRepository apiRepository) {
return new SwitchMapViewModelFactory(apiRepository);
}
@Provides
SwitchMapViewModel provideSwitchMapTransformationViewModel(FragmentActivity fragmentActivity, SwitchMapViewModelFactory factory) {
return ViewModelProviders.of(
fragmentActivity,
factory
).get(SwitchMapViewModel.class);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/splash/SplashActivityViewModel.java
package com.theah64.livedata_transformation_example.ui.activities.splash;
import com.theah64.livedata_transformation_example.util.SingleLiveEvent;
import com.theah64.livedata_transformation_example.util.System;
import java.util.concurrent.TimeUnit;
import androidx.lifecycle.ViewModel;
import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
class SplashActivityViewModel extends ViewModel {
private static final long SPLASH_DURATION = 1500;
private final SingleLiveEvent timerEvent = new SingleLiveEvent();
void startTimer() {
Completable.complete()
.delay(SPLASH_DURATION, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(() -> {
System.out.println("Timer done");
timerEvent.done();
})
.subscribe();
}
SingleLiveEvent getTimerEvent() {
return timerEvent;
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/activities/splash/SplashActivity.java
package com.theah64.livedata_transformation_example.ui.activities.splash;
import android.os.Bundle;
import com.theah64.livedata_transformation_example.R;
import com.theah64.livedata_transformation_example.di.base.ActivityModule;
import com.theah64.livedata_transformation_example.ui.activities.base.BaseAppCompatActivity;
import com.theah64.livedata_transformation_example.ui.activities.main.MainActivity;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;
public class SplashActivity extends BaseAppCompatActivity {
@Inject
SplashActivityViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
DaggerSplashActivityComponent.builder()
.activityModule(new ActivityModule(this))
.splashActivityModule(new SplashActivityModule())
.build()
.inject(this);
// observing for navigation
viewModel.getTimerEvent().observe(this, ignore -> {
// timer finished
MainActivity.start(SplashActivity.this);
finish();
});
viewModel.startTimer();
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/adapters/recyclerview_adapters/UsersAdapter.java
package com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.theah64.livedata_transformation_example.data.remote.models.SearchResponse;
import com.theah64.livedata_transformation_example.databinding.UsersRowBinding;
import com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters.base.BaseDataBindingViewHolder;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
private List<SearchResponse.User> users = new ArrayList<>();
private final LayoutInflater layoutInflater;
public UsersAdapter(Context context) {
this.layoutInflater = LayoutInflater.from(context);
}
public void setUsers(List<SearchResponse.User> users) {
this.users = users;
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(
UsersRowBinding.inflate(
layoutInflater,
parent,
false
)
);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.getBinding().setUser(users.get(position));
}
@Override
public int getItemCount() {
return users.size();
}
class ViewHolder extends BaseDataBindingViewHolder<UsersRowBinding> {
ViewHolder(UsersRowBinding binding) {
super(binding);
}
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/ui/adapters/recyclerview_adapters/MenuAdapter.java
package com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.theah64.livedata_transformation_example.R;
import com.theah64.livedata_transformation_example.databinding.MenuItemsRowBinding;
import com.theah64.livedata_transformation_example.data.models.MenuItem;
import com.theah64.livedata_transformation_example.ui.adapters.recyclerview_adapters.base.BaseDataBindingViewHolder;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.ViewHolder> {
private final LayoutInflater layoutInflater;
private static final List<MenuItem> MENU_ITEMS = new ArrayList<>();
static {
MENU_ITEMS.add(new MenuItem(R.id.map, R.string.map_title, R.string.map_desc));
MENU_ITEMS.add(new MenuItem(R.id.switch_map, R.string.switch_map_title, R.string.switch_map_desc));
MENU_ITEMS.add(new MenuItem(R.id.custom_map, R.string.custom, R.string.custom_desc));
}
private final Callback callback;
@Inject
MenuAdapter(Context context, Callback callback) {
this.callback = callback;
this.layoutInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
final MenuItemsRowBinding binding = MenuItemsRowBinding.inflate(
layoutInflater,
parent,
false
);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.getBinding().setMenuItem(
MENU_ITEMS.get(position)
);
}
@Override
public int getItemCount() {
return MENU_ITEMS.size();
}
class ViewHolder extends BaseDataBindingViewHolder<MenuItemsRowBinding> {
ViewHolder(MenuItemsRowBinding binding) {
super(binding);
binding.getRoot().setOnClickListener(v -> {
MenuItem menuItem = MENU_ITEMS.get(getLayoutPosition());
callback.onItemClicked(menuItem);
});
}
}
public interface Callback {
void onItemClicked(MenuItem menuItem);
}
}
<file_sep>/app/src/main/java/com/theah64/livedata_transformation_example/util/System.java
package com.theah64.livedata_transformation_example.util;
import android.util.Log;
public class System {
public static class out {
public static void println(String message) {
Log.e("LogMessage", message);
}
}
}
| 9cc0b46558c5ae40da42143b7c25731efdab591a | [
"Markdown",
"Java"
] | 15 | Java | theapache64/livedata_transformation_example | a84d973a1254afe35b12a10b76d2ec880febc216 | 08c4d4bfe18d7646ecba27c400e301aa3d08f48d |
refs/heads/master | <repo_name>tiansongyan/JavaOne<file_sep>/1、简介.md
# Java面向对象编程
- 面向对象编程:模块化设计(可重复设计)
- 面向过程编程:解决当前问题
- 函数编程
## 面向对象编程:
- 封装性:内部的操作对外部不可见
- 继承性:
- 多态性:
## 面向对象编程三个阶段
- OOA(面相对象分析)
- OOD(面向对象设计)
- OOP(面向对象编程)
## 类与对象
类属于引用数据类型
<file_sep>/README.md
# JavaOne
## 入门学习
<file_sep>/hello.java
class Person { //定义一个类
String name;
int age;
public void info(){
System.out.println("name="+name+"、age="+age);
}
}
//声明并实例化对象
//类名称 对象名称=new类名称();
//分步进行对象的实例化
//声明对象:类名称 对象名称=null;
//实例化对象:对象名称=new 类名称();
//new:开辟内存
//所谓的性能调优,调整的就是内存问题
public class TestDemo{
public static void main(String args[]){
Person per=new Person();//实例化了一个per对象
per.name="张三"; //设置对象中的属性
per.age=18;
per.info();//调用类中的方法
}
}
//对象的产生分析
//引用数据类型
//数组、类、接口
//堆内存空间:保存真正的数据,保存对象的属性信息
//栈内存空间:保存堆内存的地址,对堆内存的操作权,保存对象名称
public class TestDemo{
public static void main(String args[]){
Person per =null;声明一个新的对象
per=new Person();//实例化了一个per对象
per.name="张三"; //设置对象中的属性
per.age=18;
per.info();//调用类中的方法
}
}
//NullPointerException 错误 为对象未实例化
| 342364c880930a1754e7c5368dc8523742d5ef37 | [
"Markdown",
"Java"
] | 3 | Markdown | tiansongyan/JavaOne | 1b5d890556f65f5a96dd18222bdbb6708970aec6 | 471cca06c3f1bc7a9580d59c5b9febe3f05175ab |
refs/heads/master | <file_sep>//对象属性值是“underfined”、任意函数以及symbol值,出现在非数组对象的属性值中时在序列化过程中会被忽略。
//JSON.stringify方法将一个JavaScript对象或值转换为JSON字符串,如果指定一个replace函数,则可以选择性的替换值,或者指定replacer是数组,则可选择性的仅包含数组指定的属性。
// 1、undefined、任意的函数以及symbol值,出现在非数组对象的属性值中时在序列化过程中会被忽略
// 2、undefined、任意的函数以及symbol值出现在数组中时会被转换成 null。
// 3、undefined、任意的函数以及symbol值被单独转换时,会返回 undefined
// 4、所有以symbol为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。
//5、NaN 和 Infinity 格式的数值及 null 都会被当做 null。
// 6、转换值如果有 toJSON() 方法,该方法定义什么值将被序列化。
// 7、Date 日期调用了 toJSON() 将其转换为了 string 字符串(同Date.toISOString()),因此会被当做字符串处理。
//8、当尝试去转换 BigInt 类型的值会抛出错误
const jsonstringify = (data) => {
const isCyclic = (obj) => {
let stackSet = new Set();
let detected = false;
const detect = (obj) => {
if (obj && typeof obj != "object") {
return;
}
if (stackSet.has(obj)) {
return (detected = true);
}
stackSet.add(obj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
detect(obj[key]);
}
}
stackSet.delete(obj);
};
detect(obj);
return detected;
};
if (isCyclic(data)) {
throw new TypeError(
"对包含循环引用的对象(对象之间相互引用,形成无限循环)"
);
}
if (typeof data === "bigint") {
throw new TypeError("BigInt类型不能转换");
}
const type = typeof data;
const commonKeys1 = ["undefined", "function", "symbol"];
const getType = (s) => {
return Object.prototype.toString
.call(s)
.replace(/\[object(.*?)\]/, "$1")
.toLowerCase();
};
if(type!='object'||data===null){
let result = data
if([NaN,Infinity,null].includes(data)){
result = 'null'
}else if(commonKeys1.includes(type)){
return undefined
}else if(type === 'string'){
result = '"'+ data +'"'
}
return String(result)
}else if(type ==='object'){
if(typeof data.toJSON ==='function'){
return jsonstringify(data.toJSON)
}else if(Array.isArray(data)){
let result = data.map((it)=>{
return commonKeys1.includes(typeof it) ? 'null' :jsonstringify
})
return `[${result}]`.replace(/'/g,'"')
}else{
if(['boolean','number'].includes(getType(data))){
return String(data)
}else if(getType(data)==='string'){
return '"'+data+'"'
}
}
}
};
<file_sep># codeByHand
ssh-keygen -t rsa -C "<EMAIL>"
id_rsa.pub copy
setting add new ssh
| e5515220108948dce560f2172d20fecf1a776e10 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | 3q7blx/codeByHand | abbe867d466ae5ef54f88a10c7a4d2bb6bcbb814 | 129dc6cabe11ae8f278ef71573ea85d091572a5b |
refs/heads/master | <file_sep>'use strict';
const fs = require('fs');
const path = require('path');
const execSync = require('child_process').execSync;
let files = fs.readdirSync('src');
for (let f of files) {
console.log(f);
try {
execSync('node ' + path.join('src', f), { stdio: 'inherit' });
} catch (err) {
console.error(err.message);
process.exit(1);
}
}
console.log('SUCCESS');
<file_sep>'use strict';
const assert = require('assert');
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function answer() {
console.log('Start');
await sleep(2000);
console.log('End');
return 42;
}
console.log('before');
var p = answer();
console.log('after');
assert(p instanceof Promise);
p.then(result => {
assert.equal(result, 42);
console.log('OK');
}).catch(err => console.error(err));
console.log('Bottom')<file_sep>[](https://travis-ci.org/dotchev/async-await)
# async-await
Demonstrate common async operations with both async.js and ES6 async-await.
Node.js [v7.6.0][1] brings official support for [async functions][2].
This is an [ES7 feature][3] that allows handling asynchronous operations in a clean way.
Here is an overview of major weapons at our disposal to fight [callback hell][4]:
* The popular [async][5] package
* [fibers][8] package in node.js
* [Promise][6] - since ES6 (Node.js v0.12)
* [Generators][7] - since ES6 (Node.js v4)
* [Async Functions][3] - since ES7 (Node.js v7.6.0)
## Async Functions
Here is a basic example of an async function:
```js
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async function answer() {
console.log('Start');
await sleep(2000);
console.log('End');
return 42;
}
var p = answer();
assert(p instanceof Promise);
p.then(result => {
assert.equal(result, 42);
console.log('OK');
}).catch(err => console.error(err));
```
[src/sleep.js](src/sleep.js)
It all starts and ends with a promise:
* ***await*** takes a promise and suspends the current script until the
promise is fulfilled. Then the script is resumed and ***await*** returns the
resolved value or throws the reject reason.
* ***await*** can appear _only_ in an ***async*** function
* ***async*** function always returns a promise, so one can ***await*** it
**Note** that ***await*** does not block the event queue, so node.js can process
other events while waiting for the promise.
## Promisify
We can easily promisify existing callback APIs using packages like [pify][9].
```js
const assert = require('assert');
const pify = require('pify');
const fs = pify(require('fs'));
async function main() {
let text = await fs.readFile(__filename, 'utf8');
assert(/some-token/.test(text));
try {
await fs.readFile('no-such-file', 'utf8');
assert(false, 'should throw');
} catch (err) {
assert.equal(err.code, 'ENOENT');
}
}
```
[src/promisify.js](src/promisify.js)
## Common Asynchronous Operations
### Waterfall
Execute several operations sequentially,
each one taking the result from the previous one.
[async](src/waterfall-async.js)
```js
function calc(x, cb) {
async.waterfall([
inc.bind(null, x),
double
], cb);
}
```
[async-await](src/waterfall-await.js)
```js
async function calc(x) {
let r = await inc(x);
return await double(r);
}
```
### Parallel
Start several operations in parallel and wait all of them to complete.
[async](src/parallel-async.js)
```js
function calc(x, cb) {
async.parallel([
inc.bind(null, x),
double.bind(null, x)
], cb);
}
```
[async-await](src/parallel-await.js)
```js
async function calc(x) {
return await Promise.all([inc(x), double(x)]);
}
```
### Race
Start several operations in parallel and get the result of the first one to complete.
[async](src/race-async.js)
```js
function calc(x, y, cb) {
async.race([
inc.bind(null, x),
double.bind(null, y)
], cb);
}
```
[async-await](src/race-await.js)
```js
async function calc(x, y) {
return await Promise.race([inc(x), double(y)]);
}
```
### Map
Execute the same operation for each array element in parallel.
[async](src/map-async.js)
```js
function calc(arr, cb) {
async.map(arr, inc, cb);
}
```
[async-await](src/map-await.js)
```js
async function calc(arr) {
return await Promise.all(arr.map(inc));
}
```
### Map Series
Execute the same operation for each array element sequentially.
[async](src/mapSeries-async.js)
```js
function calc(arr, cb) {
async.mapSeries(arr, inc, cb);
}
```
[async-await](src/mapSeries-await.js)
```js
async function calc(arr) {
return await bluebird.mapSeries(arr, inc);
}
```
## See Also
[6 Reasons Why JavaScript’s Async/Await Blows Promises Away][10]
While it compares async functions to promises, the same issues are valid also with callbacks.
[1]: https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V7.md#7.6.0
[2]: https://developers.google.com/web/fundamentals/getting-started/primers/async-functions
[3]: https://tc39.github.io/ecmascript-asyncawait/
[4]: http://callbackhell.com/
[5]: http://caolan.github.io/async/
[6]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
[7]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*
[8]: https://github.com/laverdet/node-fibers
[9]: https://github.com/sindresorhus/pify
[10]: https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9
<file_sep>'use strict';
const assert = require('assert');
const async = require('async');
const { inc, double } = require('../tools-async');
function calc(x, cb) {
async.waterfall([
inc.bind(null, x),
double
], cb);
}
calc(3, (err, result) => {
assert(!err);
assert.equal(result, 8);
calc(5, (err, result) => {
assert(err && /12/.test(err.message));
console.log('OK');
});
});
<file_sep>'use strict';
const assert = require('assert');
const { inc, double } = require('../tools-await');
async function calc(x, y) {
return await Promise.race([inc(x), double(y)]);
}
async function main() {
let result = await calc(3, 4);
assert.equal(result, 4);
try {
result = await calc(9, 6);
assert(false, 'should throw');
} catch (err) {
assert(/12/.test(err.message));
}
}
main().then(() => {
console.log('OK');
}).catch(err => {
console.error(err);
});
<file_sep>'use strict';
module.exports = { inc, double };
function inc(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
++x;
if (x > 10) reject(new Error('Out of range: ' + x));
else resolve(x);
}, x);
});
}
function double(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
x *= 2;
if (x > 10) reject(new Error('Out of range: ' + x));
else resolve(x);
}, x);
});
}
<file_sep>'use strict';
const assert = require('assert');
const { inc, double } = require('../tools-await');
async function calc(x) {
return await Promise.all([inc(x), double(x)]);
}
async function main() {
let result = await calc(3);
assert.deepEqual(result, [4, 6]);
try {
result = await calc(6);
assert(false, 'should throw');
} catch (err) {
assert(/12/.test(err.message));
}
}
main().then(() => {
console.log('OK');
}).catch(err => {
console.error(err);
});
<file_sep>'use strict';
const assert = require('assert');
const async = require('async');
const { inc, double } = require('../tools-async');
function calc(x, y, cb) {
async.race([
inc.bind(null, x),
double.bind(null, y)
], cb);
}
calc(3, 4, (err, result) => {
assert(!err);
assert.equal(result, 4);
calc(9, 6, (err, result) => {
assert(err && /12/.test(err.message));
console.log('OK');
});
});
| 93f45687e25d69524294cf0717c7f809d4a5dadf | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | dotchev/async-await | b69d4d6a748d16bd84d6845657b467d30ffc6018 | 47117c1a04d9021a2565587a95f729cd497a45e4 |
refs/heads/master | <file_sep>module github.com/Atreyagaurav/cpytree
go 1.17
<file_sep>package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
type Tree struct {
Parent *Tree
Rank int
ChildNum int
Value string
Children map[string]*Tree
}
func (t *Tree) AddChild(cstr string) *Tree {
ch, ok := t.Children[cstr]
if ok {
return ch
} else {
c := &Tree{Value: cstr, Children: make(map[string]*Tree)}
c.Parent = t
t.Children[cstr] = c
t.ChildNum += 1
c.Rank = t.Rank + 1
return c
}
}
// func (t *Tree) ConnectChild(c *Tree) *Tree {
// t.ChildNum += 1
// t.Children = append(t.Children, c)
// c.Parent = t
// c.Rank = t.Rank + 1
// return c
// }
func (t *Tree) AddChildFromString(path string) *Tree {
vals := strings.Split(path, "/")
c := t
for _, p := range vals {
c = c.AddChild(p)
}
return c
}
func (t *Tree) Construct() {
for _, c := range t.Children {
c.Construct()
}
if t.ChildNum == 0 {
path := t.GetFull("/")
file, err := os.OpenFile("makedir.sh", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
log.Print("Error in reading file:", "makedir.sh")
}
file.WriteString(fmt.Sprintf("mkdir -p %s\n", path))
file.Close()
// os.MkdirAll(path, 0700)
}
}
func (t *Tree) GetFull(s string) string {
path := t.Value
if t.Parent == nil {
// cw, _ := os.Getwd()
// return cw + s + path
return path
} else {
return fmt.Sprintf("%s%s%s", t.Parent.GetFull(s), s, t.Value)
}
}
func (t *Tree) Show() {
for i := 0; i < t.Rank; i++ {
fmt.Print(" ")
}
fmt.Printf("%s\n", t.Value)
for _, c := range t.Children {
c.Show()
}
}
func main() {
args := os.Args[1:]
thispath, _ := os.Getwd()
// MakeDirectoryTree(args)
var pathList []string
t := &Tree{Value: ".", Children: make(map[string]*Tree)}
if len(args) == 1 {
filepath.Walk(args[0], func(path string, info os.FileInfo, err error) error {
if filepath.IsAbs(path) {
path, _ = filepath.Rel(thispath, path)
}
fi, _ := os.Stat(path)
if fi.IsDir() && path[0:1] != "." {
pathList = append(pathList, path)
t.AddChildFromString(path)
}
return nil
})
} else {
for _, v := range args {
t.AddChildFromString(v)
}
}
// t.Show()
os.Remove("makedir.sh")
t.Construct()
return
}
| 816bae2bbd57cbddb0b82b6abfd013616465addf | [
"Go",
"Go Module"
] | 2 | Go Module | Atreyagaurav/cpytree | 491d6c6160a2cedc1bf109dc3607fe5b1fd126b7 | abd3c1b1fc5b9cdd8133a7e755447d6fe06a6344 |
refs/heads/master | <file_sep>package com.huahuacaocao.hhcc_common.base.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* 防止listview和gridview、ScrollView的冲突
* @author zsl
* @blog http://blog.csdn.net/yy1300326388
*
*/
public class MyListView extends ListView {
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//防止数据显示不全
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
<file_sep>package com.segmentfault.hackathon.adapters;
import android.content.Context;
import com.huahuacaocao.hhcc_common.base.adapter.UniversalAdapter;
import com.huahuacaocao.hhcc_common.base.adapter.ViewHolder;
import com.huahuacaocao.hhcc_common.base.view.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.segmentfault.hackathon.R;
import com.segmentfault.hackathon.entity.FlowerEntity;
import java.util.List;
/**
* 搜索花的Adapter
*
* @author zsl
*
*/
public class FlowerAdapter extends UniversalAdapter<FlowerEntity> {
public FlowerAdapter(Context context, List<FlowerEntity> mlists,
int layoutId) {
super(context, mlists, R.layout.lv_search_flower_item);
}
@Override
public void convert(ViewHolder holder, FlowerEntity t, int position) {
holder.setText(R.id.search_flower_item_tv_name, t.getPlant_name());
//设置头像
CircleImageView circleImageView=holder.getView(R.id.search_flower_item_iv_icon);
ImageLoader.getInstance().displayImage(t.getImages(), circleImageView);
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base.config;
/**
* Created by zsl on 15/10/8.
*/
public class CodeList {
// 照相
public static final int CAMERA = 1001;
// 相册
public static final int CAPTURE = 1002;
// 剪裁
public static final int CROP = 1003;
// 选择剪裁方式
public static final int SELECTIMAGE = 1004;
}
<file_sep># Hackathon
Hackathon
<file_sep>package com.huahuacaocao.hhcc_common.base;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Toast;
import com.huahuacaocao.hhcc_common.base.utils.SystemBarTintManager;
import com.huahuacaocao.hhcc_common.base.utils.TitleBarUtils;
/**
* Created by zsl on 15/8/13.
* Base Fragment所有的Fagment类都继承自这个类
* 上下文(getActivity())统一用mActivity
* getView() 统一用mView
*/
public class BaseFragment extends Fragment {
//透明状态栏
protected SystemBarTintManager mTintManager;
//是否支持透明状态栏
protected boolean isSystemBarTint;
//上下文
protected FragmentActivity mActivity;
//跟节点view
protected View mView;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mView = getView();
mActivity = getActivity();
//创建沉浸式状态栏
TitleBarUtils.setTranslucentStatus(mActivity);
mTintManager = new SystemBarTintManager(mActivity);
isSystemBarTint = mTintManager.isSystemBarTint();
//设置透明状态来为黑色字体
mTintManager.setStatusBarDarkMode(false, mActivity);
}
/**
* 设置TitleBarPadding
*
* @param view
*/
protected void setTitleBarPadding(View view) {
TitleBarUtils.setTitleBarFromPadding(mActivity, mTintManager, view);
}
/**
* 显示长的吐司
* @param content
*/
protected void showLongToast(String content){
Toast.makeText(mActivity, "" + content, Toast.LENGTH_LONG).show();
}
/**
* 显示短的吐司
* @param content
*/
protected void showShortToast(String content){
Toast.makeText(mActivity, "", Toast.LENGTH_SHORT).show();
}
/**
* startActivity
* @param cls
*/
protected void baseStartActivity(Class<?> cls){
Intent intent=new Intent(mActivity,cls);
startActivity(intent);
}
/**
* startActivityForResult
* @param cls
* @param requestCode
*/
protected void baseStartActivityForResult(Class<?> cls,int requestCode){
Intent intent=new Intent(mActivity,cls);
startActivityForResult(intent, requestCode);
}
}
<file_sep>package com.segmentfault.hackathon.application;
import android.app.Application;
import android.content.Context;
import com.bugtags.library.Bugtags;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.orhanobut.logger.Logger;
import com.segmentfault.hackathon.R;
import com.segmentfault.hackathon.config.AppConfig;
/**
* Created by zsl on 15/10/24.
*/
public class MyApplication extends Application{
private static MyApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance=this;
//init BugTags
Bugtags.start("6e842653797324611e93598d56bf23b4", this, Bugtags.BTGInvocationEventBubble);
//初始化logger
Logger.init(AppConfig.LOG_TAG);
/**
* 初始化ImageLoader
*/
DisplayImageOptions options = new DisplayImageOptions.Builder()
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.mipmap.img_no_photos)
.showImageOnLoading(R.mipmap.img_no_photos)
.showImageOnFail(R.mipmap.img_no_photos)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
}
public static Context getAppContext() {
return sInstance;
}
}
<file_sep>package com.segmentfault.hackathon.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.afollestad.materialdialogs.MaterialDialog;
import com.huahuacaocao.hhcc_common.base.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.segmentfault.hackathon.application.MyApplication;
import com.segmentfault.hackathon.config.AppConfig;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* 网络请求的工具类
*
* @author zsl
*/
public class RestClient {
//AsyncHttpClient对象
private static AsyncHttpClient client = new AsyncHttpClient();
static {
client.setTimeout(5000);
}
private static MaterialDialog materialDialog;
/**
* get 请求
*
* @param url
* @param params
* @param responseHandler
*/
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
NetworkState();
client.get(getAbsoluteUrl(url), getAbsoluteParams(params), responseHandler);
}
/**
* post请求
*
* @param url
* @param params
* @param responseHandler
*/
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
NetworkState();
client.post(getAbsoluteUrl(url), getAbsoluteParams(params), responseHandler);
}
/**
* put 请求
*
* @param url
* @param params
* @param responseHandler
*/
public static void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
NetworkState();
client.put(getAbsoluteUrl(url), getAbsoluteParams(params), responseHandler);
}
/**
* delete请求
*
* @param url
* @param params
* @param responseHandler
*/
public static void delete(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
NetworkState();
client.delete(getAbsoluteUrl(url), params, responseHandler);
}
/**
* 获得到最终的url地址
*
* @param relativeUrl
* @return
*/
private static String getAbsoluteUrl(String relativeUrl) {
return AppConfig.SERVER + relativeUrl;
}
/**
* 得到最终的url地址
*
* @param params
* @return
*/
private static RequestParams getAbsoluteParams(RequestParams params) {
params.add("app_version", AppConfig.APP_VERSION + "");
return params;
}
/**
* 判断网络状态
*
* @return
*/
public static boolean NetworkState() {
// 判断网络是否可用
if (!isNetworkAvailable(MyApplication.getAppContext())) {
ToastUtils.showShortToast(MyApplication.getAppContext(), "当前网络不可用");
cancelDialog();
return true;
}
return false;
}
/**
* 转码请求
*
* @param content
* @return
*/
public static String encode(String content) {
String urlString = "";
try {
urlString = URLEncoder.encode(content, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return urlString;
}
/**
* 检测当的网络(WLAN、3G/2G)状态
*
* @param context Context
* @return true 表示网络可用
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED) {
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
/**
* 显示loadingdialog
*/
public static void showMDDialog(Context context) {
materialDialog = new MaterialDialog.Builder(context)
.content("请稍等...")
.progress(true, 0)
.build();
materialDialog.show();
}
/**
* 取消loading dialog
*/
public static void cancelDialog() {
if (materialDialog != null && materialDialog.isShowing()) {
materialDialog.dismiss();
}
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base.utils;
import android.content.Context;
import android.widget.Toast;
public class ToastUtils {
/**
* 显示短吐司
* @param context
* @param message
*/
public static void showShortToast(Context context,String message){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 显示长吐司
* @param context
* @param message
*/
public static void showLongToast(Context context,String message){
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base.utils;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;
import com.huahuacaocao.hhcc_common.base.activitys.CropImageActivity;
import com.huahuacaocao.hhcc_common.base.activitys.SelectImageActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 图片的工具类
*
* @author zsl
*
*/
public class ImageUtils {
// URL
public static String systemUrl = "";
/**
* 获得到此时的URL
*
* @return
*/
public static Uri getImgTempUri(Context context) {
String path=Environment.getExternalStorageDirectory().getPath()+"/huahuacaocao_temp";
File file=new File(path);
if(!file.exists()) {
file.mkdir();
}
systemUrl=path+"/img_"+System.currentTimeMillis()+"_temp.jpg";
return Uri.fromFile(new File(systemUrl));
}
/**
* 获取systemUrl转换为uri
*
* @return
*/
public static Uri getUriBySystemUrl() {
return Uri.fromFile(new File(systemUrl));
}
/**
* 获取Url转换为uri
*
* @return
*/
public static Uri getUriByUrl(String urlString) {
return Uri.fromFile(new File(urlString));
}
/**
* 得到相机的Intent
*
* @return
*/
public static Intent getIntentFromCamera(Context context) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is
// capture
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImgTempUri(context));
return intent;
}
/**
* 得到相册的Intent
*
* @return
*/
public static Intent getIntentFromCapture() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
return intent;
}
/**
* 得到剪裁图片的Intent
* @param uri
* @return
*/
public static Intent getIntentFromPhotoZoom(Uri uri) {
Intent intent = new Intent();
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 700);
intent.putExtra("outputY", 700);
intent.putExtra("uri", uri); // 图片地址
return intent;
}
/**
* 得到剪裁图片的Intent ,包含CropImageActivity
* @param context
* @param uri
* @return
*/
public static Intent getIntentFromPhotoZoom(Context context,Uri uri) {
Intent intent = new Intent(context, CropImageActivity.class);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 700);
intent.putExtra("outputY", 700);
intent.putExtra("uri", uri); // 图片地址
return intent;
}
/**
* 得到选择图片的intent
* @param context 上下文
* @param isSelect0 是否启动相机(0:启动想起1:启动相册)
* @return
*/
public static Intent getIntentFromSelectImage(Context context,int isSelect0) {
Intent intent = new Intent(context, SelectImageActivity.class);
// outputX outputY 是裁剪图片宽高
intent.putExtra("isSelect0",isSelect0);
return intent;
}
// public static Intent getIntentFromPhotoZoom(Uri uri) {
// Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setDataAndType(uri, "image/*");
// intent.putExtra("crop", "true");
// // aspectX aspectY 是宽高的比例
// intent.putExtra("aspectX", 1);
// intent.putExtra("aspectY", 1);
// // outputX outputY 是裁剪图片宽高
// intent.putExtra("outputX", 700);
// intent.putExtra("outputY", 700);
// intent.putExtra("scale", true);
// intent.putExtra("return-data", false);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// intent.putExtra("noFaceDetection", true); // no face detection
// return intent;
// }
/**
* Bitmap对象保存味图片文件
*
* @param bitmap
* @return
*/
public static String saveBitmapFile(Context context, Bitmap bitmap) {
String path = "editplantinfo_"+System.currentTimeMillis()+"_temp.jpg";
try {
FileOutputStream fos = context.openFileOutput(path,
Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
path = context.getFilesDir() + "/" + path;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
/**
* Uri 转换为bitmap
*
* @param context
* @param uri
* @return
*/
public static Bitmap decodeUriAsBitmap(Context context, Uri uri) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}
/**
* 设置imageview的图片,通过ImageLoader
*
* @param url
* url地址
* @param imageView
* imageview
*/
public static void setImageView(String url, ImageView imageView) {
// 设置ImageView
ImageLoader.getInstance().displayImage(url, imageView);
}
}
<file_sep>package com.segmentfault.hackathon.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.huahuacaocao.hhcc_common.base.BaseFragment;
import com.segmentfault.hackathon.R;
public class QRCodeFragment extends BaseFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_qrcode, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initTitlebar();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
}
public void initData() {
}
// 初始化titilebar
private void initTitlebar() {
// titlebar
setTitleBarPadding(mView.findViewById(R.id.title_bar));
// 设置返回按钮
mView.findViewById(R.id.title_bar_return).setVisibility(View.GONE);
// 设置Title
((TextView) mView.findViewById(R.id.title_bar_title)).setText("扫描二维码");
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base.view;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ScrollView;
public class ScrollViewCommon extends ScrollView {
// titlebar
View title_bar;
// 主页的根节点
FrameLayout fl_page;
private Context mContext;
// 屏幕的高度
private int height = 0;
// 记录按下的Y坐标点
float mY = 0;
// 记录按下的Y滚动的距离
int sY = 0;
// statebar的高度
int top = 0;
// 是否支持透明的StartBar
boolean isStartBar;
// 回弹阻尼距离
private float ScrollY =0;
public ScrollViewCommon(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
initBounceListView();
}
public ScrollViewCommon(Context context) {
super(context);
mContext = context;
initBounceListView();
}
public ScrollViewCommon(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initBounceListView();
}
private void initBounceListView() {
final DisplayMetrics metrics = mContext.getResources()
.getDisplayMetrics();
height = metrics.heightPixels;
ScrollY=(float)(height/6);
Log.e("BasescroView", "height:" + height);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
if (action == MotionEvent.ACTION_DOWN) {
// 按下时的坐标点
mY = ev.getY(0);
// 按下时的滚动距离,判断在哪一屏
sY = this.getScrollY();
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
if (action == MotionEvent.ACTION_UP) {// 手指抬起时
Log.e("CustomScrollView", "sY:" + sY);
if (sY < height) {// 在第一屏滑动
float slideY1 = mY - ev.getY(0);
if (slideY1 > ScrollY && this.getScrollY() < height) {// 滑动的距离大于ScrollY,并且在第一屏内,则滚动到第二屏
smoothScrollTo(0, height);
return true;
}
if (slideY1 < ScrollY && this.getScrollY() < height) {// 滑动的距离小于ScrollY,并且在第一屏内,则返回第一屏
smoothScrollTo(0, 0);
return true;
}
} else {// 在第二屏滑动
float slideY2 = ev.getY(0) - mY;
if (slideY2 > ScrollY && this.getScrollY() < height) {// 滑动的距离大于ScrollY,并且在第二屏内,则滚动到第一屏
smoothScrollTo(0, 0);
return true;
}
if (slideY2 < ScrollY && this.getScrollY() < height) {// 滑动的距离小于ScrollY,并且在第二屏内,则返回第二屏
smoothScrollTo(0, height);
return true;
}
}
}
return super.onTouchEvent(ev);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// Log.e("CustomScrollView", "SY:" + this.getScrollY());
// 如果滑动的距离小于屏幕高度的1/2,titlebar显示
int mySY = this.getScrollY();
if (mySY < (height / 2)) {
TitleBarGone(false);
} else {
TitleBarGone(true);
}
// 到达顶部显示状态栏
if (mySY == 0 && isStartBar) {
// 显示状态栏
fl_page.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
// 防止抛滑动(如果滚动的距离小于等于屏幕高度,并且按下时的滚动高度大于屏幕高度,则滚动到第二屏的最顶端)
if (mySY <= height&&sY>height) {
smoothScrollTo(0, height);
}
super.onScrollChanged(l, t, oldl, oldt);
}
/**
* 设置titlebar和其他的参数
* @param title_bar titlebar
* @param fl_page 根节点
* @param top 状态栏的高度
* @param isStartBar 是否支持沉浸式状态栏
*/
public void setTitle_bar(View title_bar, FrameLayout fl_page, int top,
boolean isStartBar) {
this.title_bar = title_bar;
this.fl_page = fl_page;
this.top = top;
this.isStartBar = isStartBar;
if (!isStartBar) {
height = height - top;
}
}
/**
* 设置TitleBar隐藏
*
* @param isGone
*/
private void TitleBarGone(boolean isGone) {
if (title_bar != null) {
if (isGone) {
title_bar.setVisibility(View.GONE);
if (isStartBar) {
// 隐藏状态栏
fl_page.setSystemUiVisibility(View.INVISIBLE);
}
} else {
title_bar.setVisibility(View.VISIBLE);
}
}
}
/**
* 禁止ScrollView内布局变化后自动滚动
*/
@Override
protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
return 0;
}
/**
* 抛的事件
*/
@Override
public void fling(int velocityY) {
super.fling(velocityY);
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.bugtags.library.Bugtags;
import com.huahuacaocao.hhcc_common.base.utils.SystemBarTintManager;
import com.huahuacaocao.hhcc_common.base.utils.TitleBarUtils;
/**
* Created by zsl on 15/8/8.
* Base Activity 所有的Activity都继承自这个类
* 上下文统一用mActivity
*/
public class BaseActivity extends AppCompatActivity {
//透明状态栏
protected SystemBarTintManager mTintManager;
//是否支持透明状态栏
protected boolean isSystemBarTint;
//是否未miui6及以上系统
protected boolean isMiuiV6;
//上下文
protected Activity mActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = this;
//设置沉浸式状态栏
TitleBarUtils.setTranslucentStatus(this);
mTintManager = new SystemBarTintManager(this);
isMiuiV6 = mTintManager.isSystemBarTint();
isSystemBarTint = mTintManager.ismStatusBarAvailable();
//设置透明状态来为白色字体
mTintManager.setStatusBarDarkMode(false, this);
}
@Override
protected void onResume() {
super.onResume();
//注:回调 1
Bugtags.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
//注:回调 2
Bugtags.onPause(this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
//注:回调 3
Bugtags.onDispatchTouchEvent(this, event);
return super.dispatchTouchEvent(event);
}
/**
* 设置TitleBarPadding
*
* @param view
*/
protected void setTitleBarPadding(View view) {
TitleBarUtils.setTitleBarFromPadding(this, mTintManager, view);
}
/**
* 显示长的吐司
* @param content
*/
protected void showLongToast(String content){
Toast.makeText(mActivity, "" + content, Toast.LENGTH_LONG).show();
}
/**
* 显示短的吐司
* @param content
*/
protected void showShortToast(String content){
Toast.makeText(mActivity, "" + content, Toast.LENGTH_SHORT).show();
}
/**
* startActivity
* @param cls
*/
protected void baseStartActivity(Class<?> cls){
Intent intent=new Intent(mActivity,cls);
startActivity(intent);
}
/**
* startActivityForResult
* @param cls
* @param requestCode
*/
protected void baseStartActivityForResult(Class<?> cls,int requestCode){
Intent intent=new Intent(mActivity,cls);
startActivityForResult(intent, requestCode);
}
}
<file_sep>package com.huahuacaocao.hhcc_common.base.utils;
import android.annotation.SuppressLint;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@SuppressLint("SimpleDateFormat")
public class DateUtils {
static SimpleDateFormat sY_M_D_TZ = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS Z");
static SimpleDateFormat sY_M_D = new SimpleDateFormat("yyyy-MM-dd");
static SimpleDateFormat sYMD = new SimpleDateFormat("yyyy年MM月dd日");
static SimpleDateFormat sHMS = new SimpleDateFormat("HH:mm:ss");
static SimpleDateFormat sHM = new SimpleDateFormat("HH:mm");
/**
* long类型转换为年月日类型
*
* @param time
* @return
*/
public static String longToyearmonthday(long time) {
String timeString = sYMD.format(time);
return timeString;
}
/**
* long类型转换为年-月-日类型
*
* @param time
* @return
*/
public static String longToY_M_d(long time) {
String timeString = sY_M_D.format(time);
return timeString;
}
/**
* long类型转换为时:分:秒
*
* @param time
* @return
*/
public static String longTohourmins(long time) {
String timeString = sHMS.format(time);
return timeString;
}
/**
* long 类型转换为:分:秒
*
* @param time
* @return
*/
public static String longhourmin(long time) {
String timeString = sHM.format(time);
return timeString;
}
/**
* yyyy-MM-dd'T'HH:mm:ss.SSS Z 格式转为long
*
* @param date
* @return
*/
public static long longYMDTZ(String date) {
try {
return sY_M_D_TZ.parse((date.replace("Z", " UTC"))).getTime();
} catch (ParseException e) {
return System.currentTimeMillis();
}
}
/**
* 获得已经成长的天数
* @param date
* @return
*/
public static long getDay(String date) {
long createTime=longYMDTZ(date);
long dayTime=System.currentTimeMillis()-createTime;
return (long) Math.ceil(dayTime/86400000);
}
}
<file_sep>package com.segmentfault.hackathon.utils;
import android.text.TextUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.orhanobut.logger.Logger;
/**
* 控件的工具类
* @author zsl
*
*/
public class ViewUtils {
/**
* 设置webview
* @param webView
* @param url
*/
public static void setWebView(WebView webView,String url){
if (!TextUtils.isEmpty(url)) {
if (webView!=null) {
webView.loadUrl(url + "");
//开启javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
//控制在webview中打开所有链接
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String data = "<div style='text-align: center;'>加载失败<br/>请下拉刷新</div>";
view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
}
});
}else{
Logger.e("setWebView的 webView 不能为空");
}
}else{
Logger.e("setWebView的 url 不能为空");
}
}
}
<file_sep>include ':app', ':zsl_common'
project(':zsl_common').projectDir = new File('hhcc_common') | ee1a0ba0259747ed96e0c037d61bd120fe79dc6a | [
"Markdown",
"Java",
"Gradle"
] | 15 | Java | yy1300326388/Hackathon | 0002217d6e9a7223a6b142a515e32de0c31974ba | 4a3b3ebf61c880b846ade54974d575d891a60c2b |
refs/heads/master | <file_sep># My ansible tests
Watching ansible oreilly tutorials
## Assorted useful commands
> Update outdated python packages
```
pip install -U $(pip list -o | tail -n +3 | cut -f1 -d' ')
```
<file_sep>ansible alma9 -m setup -a "filter=ansible_local"
<file_sep># Roles
## Roles locations in precedence order (higher to lower)
* ./roles no dir do projeto
* ~/.ansible/roles
* /etc/ansible/roles
* /usr/share/ansible/roles
## [Using Roles (2.9)](https://docs.ansible.com/ansible/2.9/user_guide/playbooks_reuse_roles.html#using-roles)
* Classic
```
---
- hosts: webservers
roles:
- common
- webservers
```
* New
```
---
- hosts: webservers
tasks:
- debug:
msg: "before we run our role"
- import_role:
name: example
- include_role:
name: example
- debug:
msg: "after we ran our role"
```
| 1f42cae5e75e3d0edfd517cfa4cea71578cbb8dc | [
"Markdown",
"Shell"
] | 3 | Markdown | lebm/my-ansible-tests | b409a53b768212e338cab05d444d8dabe512d28a | 57837fbc71c5f6904c7ea0d58cb0a79110bd17f5 |
refs/heads/main | <repo_name>nebroni/inspectcsv<file_sep>/main.py
import re
import sys
def open_file_and_get_columns(name):
count = 0
with open(name, encoding='utf-8') as file:
column_names = file.readline().strip().split(',')
dict1 = dict(zip(column_names, [[] for _ in range(len(column_names))]))
desribtion = [i.strip().split(',') for i in file.readlines()]
for key in dict1:
for i in desribtion:
dict1[key].append(i[count])
count += 1
return dict1
def maximun(args):
nums = [len(i) for i in args]
for i in range(1, len(nums)):
if nums[i - 1] == nums[i]:
continue
else:
return False
return True
def max_length():
if maximun(columns[i]):
return len(columns[i][0])
max1 = len(max(columns[i], key=len))
return max1 + max1 * 0.25
def check_model(models):
# demo_patterns ver 1.0
pattern_email = r'[\w\.]+@[\w]+\.[\w]+'
pattern_boolean = r'[True|False]'
pattern_url = r'([https|http|ftp]+)://([\w\.]+)'
pattern_date = r'[\d{2}\.\d{2}+\.\d{4} | \d{4}\-\d{2}\-\d{2} | \d{2}\/\d{2}+\/\d{4}]'
# IntegerField()
if all([i.replace('-', '').isdigit() for i in models]):
for i in models:
if int(i) < 0:
return 'IntegerField()'
return 'PositiveIntegerField()'
# EmailField()
elif all([re.match(pattern_email, i) for i in models]):
return f'EmailField()'
# BooleanField()
elif all([re.match(pattern_boolean, i.title()) for i in models]):
return f'BooleanField()'
# URLField()
elif all([re.match(pattern_url, i) for i in models]):
return f'URLField()'
elif all([re.match(pattern_date, i) for i in models]):
return f'DateField()'
# default CharField()
else:
return f'CharField(max_length = {max_length()})'
name = sys.argv[1]
columns = open_file_and_get_columns(name)
with open('file.py', 'w') as f:
class_name = ''.join([i.title() for i in name[:-4].split('_')])
f.write(f'from django.db import models\n\n\n')
f.write(f'class {class_name}(models.Model):\n\t')
for i in columns:
f.write(f'{i} = models.{check_model(columns[i])}\n\t')
| f73f134d33349936736c573b15195816beef5f3e | [
"Python"
] | 1 | Python | nebroni/inspectcsv | 630b1e570654e692745d0ba1586da40e2989ccdd | c42f6f68b5539677f823968b9b3a1ad20530f24d |
refs/heads/master | <repo_name>BilalBudhani/ocean-dynamo<file_sep>/spec/dynamo/queries_spec.rb
require 'spec_helper'
describe CloudModel do
before :all do
CloudModel.establish_db_connection
CloudModel.delete_all
3.times { CloudModel.create! }
end
before :each do
@i = CloudModel.new
end
describe "find" do
it "find should barf on nonexistent keys" do
expect { CloudModel.find('some-nonexistent-key') }.to raise_error(OceanDynamo::RecordNotFound)
end
it "find should return an existing CloudModel with a dynamo_item when successful" do
@i.save!
found = CloudModel.find(@i.uuid, consistent: true)
expect(found).to be_a CloudModel
expect(found.dynamo_item).to be_an AWS::DynamoDB::Item
expect(found.new_record?).to eq false
end
it "find should return a CloudModel with initalised attributes" do
t = Time.now
@i.started_at = t
@i.save!
@i.started_at = nil
found = CloudModel.find(@i.uuid, consistent: true)
expect(found.started_at).not_to eq nil
end
it "find should be able to take an array arg" do
foo = CloudModel.create uuid: "foo"
bar = CloudModel.create uuid: "bar"
baz = CloudModel.create uuid: "baz"
expect(CloudModel.find(["foo", "bar"], consistent: true)).to eq [foo, bar]
end
end
describe "find_by_key" do
it "should not barf on nonexistent keys" do
expect { CloudModel.find_by_key('some-nonexistent-key') }.not_to raise_error
end
it "find should return an existing CloudModel with a dynamo_item when successful" do
@i.save!
found = CloudModel.find_by_key(@i.uuid, consistent: true)
expect(found).to be_a CloudModel
expect(found.dynamo_item).to be_an AWS::DynamoDB::Item
expect(found.new_record?).to eq false
end
it "find should return a CloudModel with initalised attributes" do
t = Time.now
@i.started_at = t
@i.save!
@i.started_at = nil
found = CloudModel.find_by_key(@i.uuid, consistent: true)
expect(found.started_at).not_to eq nil
end
end
it "should have a class method count" do
expect(CloudModel.count).to be_an Integer
end
describe "all" do
describe "(eventually consistent)" do
it "should return an array" do
expect(CloudModel.all).to be_an Array
end
it "should return an array of model instances" do
expect(CloudModel.all.first).to be_a CloudModel
end
it "should return as many instances as there are records in the table" do
expect(CloudModel.all.length).to eq CloudModel.count
end
end
describe "(consistent)" do
it "should accept a consistent: keyword parameter and hand it down to _setup_from_dynamo" do
CloudModel.delete_all
1.times { CloudModel.create! }
expect_any_instance_of(CloudModel).to receive(:_setup_from_dynamo).
with(anything, consistent: true)
CloudModel.all(consistent: true)
end
it "should return an array" do
expect(CloudModel.all(consistent: true)).to be_an Array
end
it "should return an array of model instances" do
expect(CloudModel.all(consistent: true).first).to be_a CloudModel
end
it "should return as many instances as there are records in the table" do
expect(CloudModel.all(consistent: true).length).to eq CloudModel.count
end
end
end
describe "find_each" do
before :each do
CloudModel.delete_all
24.times { CloudModel.create! }
end
describe "(eventually consistent)" do
it "should take a block" do
CloudModel.find_each { |item| }
end
it "should yield to the block as many times as there are items in the table" do
c = CloudModel.count
i = 0
CloudModel.find_each { |item| i += 1 }
expect(i).to eq c
end
it "should take the :limit keyword" do
c = CloudModel.count
i = 0
CloudModel.find_each(limit: 5) { |item| i += 1 }
expect(i).to eq 5
end
it "should take the :batch_size keyword and still process all items" do
c = CloudModel.count
i = 0
CloudModel.find_each(batch_size: 5) { |item| i += 1 }
expect(i).to eq c
end
end
describe "(consistent)" do
it "should accept a consistent: keyword parameter and hand it down to _setup_from_dynamo" do
CloudModel.delete_all
1.times { CloudModel.create! }
expect_any_instance_of(CloudModel).to receive(:_setup_from_dynamo).
with(anything, consistent: true)
CloudModel.find_each(consistent: true) { |item| }
end
it "should take a block" do
CloudModel.find_each(consistent: true) { |item| }
end
it "should yield to the block as many times as there are items in the table" do
c = CloudModel.count
i = 0
CloudModel.find_each(consistent: true) { |item| i += 1 }
expect(i).to eq c
end
it "should take the :limit keyword" do
c = CloudModel.count
i = 0
CloudModel.find_each(limit: 5, consistent: true) { |item| i += 1 }
expect(i).to eq 5
end
it "should take the :batch_size keyword and still process all items" do
c = CloudModel.count
i = 0
CloudModel.find_each(batch_size: 5, consistent: true) { |item| i += 1 }
expect(i).to eq c
end
end
end
end
<file_sep>/ocean-dynamo.gemspec
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "ocean-dynamo/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "ocean-dynamo"
s.version = OceanDynamo::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/OceanDev/ocean-dynamo"
s.summary = "OceanDynamo is a massively scalable Amazon DynamoDB near drop-in replacement for
ActiveRecord."
s.description =
"== OceanDynamo
OceanDynamo is a massively scalable Amazon DynamoDB near drop-in replacement for
ActiveRecord.
As one important use case for OceanDynamo is to facilitate the conversion of SQL
databases to no-SQL DynamoDB databases, it is important that the syntax and semantics
of OceanDynamo are as close as possible to those of ActiveRecord. This includes
callbacks, exceptions and method chaining semantics. OceanDynamo follows this pattern
closely and is of course based on ActiveModel.
The attribute and persistence layer of OceanDynamo is modeled on that of ActiveRecord:
+save+, +save!+, +create+, +update+, +update!+, +update_attributes+, +find_each+,
+destroy_all+, +delete_all+ and all the other methods you're used to are available.
The design goal is always to implement as much of the ActiveRecord interface as possible,
without compromising scalability. This makes the task of switching from SQL to no-SQL
much easier.
Thanks to its structural similarity to ActiveRecord, OceanDynamo works with FactoryGirl.
OceanDynamo uses primary indices to retrieve related table items, meaning it scales without
limits.
See also Ocean, a Rails framework for creating highly scalable SOAs in the cloud, in which
ocean-dynamo is used as a central component: http://wiki.oceanframework.net"
s.required_ruby_version = '>= 2.0.0'
s.license = 'MIT'
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "aws-sdk", '~> 1.0'
s.add_dependency "aws-sdk-core"
s.add_dependency "activemodel"
s.add_dependency "activesupport"
s.add_development_dependency "rails", "~> 4"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "simplecov"
s.add_development_dependency "factory_girl_rails", "~> 4.0"
end
<file_sep>/README.rdoc
== ocean-dynamo
OceanDynamo is a massively scalable Amazon DynamoDB near drop-in replacement for
ActiveRecord.
OceanDynamo requires Ruby 2.0 and Ruby on Rails 4.0.0 or later.
{<img src="https://badge.fury.io/rb/ocean-dynamo.png" alt="Gem Version" />}[http://badge.fury.io/rb/ocean-dynamo]
=== Features
As one important use case for OceanDynamo is to facilitate the conversion of SQL
databases to no-SQL DynamoDB databases, it is important that the syntax and semantics
of OceanDynamo are as close as possible to those of ActiveRecord. This includes
callbacks, exceptions and method chaining semantics. OceanDynamo follows this pattern
closely and is of course based on ActiveModel.
The attribute and persistence layer of OceanDynamo is modeled on that of ActiveRecord:
there's +save+, +save!+, +create+, +update+, +update!+, +update_attributes+, +find_each+,
+destroy_all+, +delete_all+ and all the other methods you're used to. The design goal
is always to implement as much of the ActiveRecord interface as possible, without
compromising scalability. This makes the task of switching from SQL to no-SQL much easier.
Thanks to its structural similarity to ActiveRecord, OceanDynamo works with FactoryGirl.
OceanDynamo uses only primary indices to retrieve related table items and collections,
which means it will scale without limits.
=== Example
==== Basic syntax
The following example shows the basic syntax for declaring a DynamoDB-based schema.
class AsyncJob < OceanDynamo::Table
dynamo_schema(:uuid) do
attribute :credentials, :string
attribute :token, :string, default: Proc { SecureRandom.uuid }
attribute :steps, :serialized, default: []
attribute :max_seconds_in_queue, :integer, default: 1.day
attribute :default_poison_limit, :integer, default: 5
attribute :default_step_time, :integer, default: 30
attribute :started_at, :datetime
attribute :last_completed_step, :integer
attribute :finished_at, :datetime
attribute :destroy_at, :datetime
attribute :created_by
attribute :updated_by
attribute :succeeded, :boolean, default: false
attribute :failed, :boolean, default: false
attribute :poison, :boolean, default: false
end
end
==== Attributes
Each attribute has a name, a type (+:string+, +:integer+, +:float+, +:datetime+, +:boolean+,
or +:serialized+) where +:string+ is the default. Each attribute also optionally has a default
value, which can be a Proc. The hash key attribute is by default +:id+ (overridden as +:uuid+ in
the example above) and is a +:string+.
The +:string+, +:integer+, +:float+ and +:datetime+ types can also store sets of their type.
Sets are represented as arrays, may not contain duplicates and may not be empty.
All attributes except the +:string+ type can take the value +nil+. Storing +nil+ for a string
value will return the empty string, <tt>""</tt>.
==== Schema args and options
+dynamo_schema+ takes args and many options. Here's the full syntax:
dynamo_schema(
table_hash_key = :id, # The name of the hash key attribute
table_range_key = nil, # The name of the range key attribute (or nil)
table_name: compute_table_name, # The basename of the DynamoDB table
table_name_prefix: nil, # A basename prefix string or nil
table_name_suffix: nil, # A basename suffix string or nil
read_capacity_units: 10, # Used only when creating a table
write_capacity_units: 5, # Used only when creating a table
connect: :late, # true, :late, nil/false
create: false, # If true, create the table if nonexistent
locking: :lock_version, # The name of the lock attribute or nil/false
timestamps: [:created_at, :updated_at] # A two-element array of timestamp columns, or nil/false
) do
# Attribute definitions
...
...
end
=== +has_many+ and +belongs_to+
==== Example
The following example shows how to set up +has_many+ / +belongs_to+ relations:
class Forum < OceanDynamo::Table
dynamo_schema do
attribute :name
attribute :description
end
has_many :topics, dependent: :destroy
end
class Topic < OceanDynamo::Table
dynamo_schema(:uuid) do
attribute :title
end
belongs_to :forum
has_many :posts, dependent: :destroy
end
class Post < OceanDynamo::Table
dynamo_schema(:uuid) do
attribute :body
end
belongs_to :topic, composite_key: true
end
The only non-standard aspect of the above is <tt>composite_key: true</tt>, which
is required as the Topic class itself has a +belongs_to+ relation and thus has
a composite key. This must be declared in the child class as it needs to know
how to retrieve its parent.
==== Restrictions
Restrictions for +belongs_to+ tables:
* The hash key must be specified and must not be +:id+.
* The range key must not be specified at all.
* +belongs_to+ can be specified only once in each class.
* +belongs_to+ must be placed after the +dynamo_schema+ attribute block.
Restrictions for +has_many+ tables:
* +has_many+ must be placed after the +dynamo_schema+ attribute block.
These restrictions allow OceanDynamo to implement the +has_many+ / +belongs_to+
relation in a very efficient and massively scalable way.
==== Implementation
+belongs_to+ claims the range key and uses it to store its own UUID, which normally
would be stored in the hash key attribute. Instead, the hash key attribute holds the
UUID of the parent. We have thus reversed the roles of these two fields. As a result,
all children have their parent UUID as their hash key, and their own UUID in their
range key.
This type of relation is even more efficient than its ActiveRecord counterpart as
it uses only primary indices in both directions of the +has_many+ / +belongs_to+
association. No scans.
Furthermore, since DynamoDB has powerful primary index searches involving substrings
and matching, the fact that the range key is a string can be used to implement
wildcard matching of additional attributes. This gives, amongst other things, the
equivalent of an SQL GROUP BY request, again without requiring any secondary indices.
It's our goal to use a similar technique to implement +has_and_belongs_to_many+ relations,
which means that secondary indices won't be necessary for the vast majority of
DynamoDB tables. This ultimately means reduced operational costs, as well as
reduced complexity.
=== Current State
OceanDynamo is fully usable as an ActiveModel and can be used by Rails
controllers. OceanDynamo implements much of the infrastructure of ActiveRecord;
for instance, +read_attribute+, +write_attribute+, and much of the control logic and
internal organisation.
* <tt>belongs_to :thingy</tt> now defines <tt>.build_thingy</tt> and <tt>.create_thingy</tt>.
* Work begun on collection proxies, etc.
=== Future milestones
* Association proxies, to implement ActiveRecord-style method chaining, e.g.:
<code>blog_entry.comments.build(body: "Cool!").save!</code>
* The +has_and_belongs_to_many+ assocation.
* A generator to install the <tt>config/aws.yml</tt> file.
=== Current use
OceanDynamo is currently used in the Ocean framework (http://wiki.oceanframework.net)
e.g. to implement highly scalable job queues. It will be used increasingly as features are
added to OceanDynamo and will eventually replace all ActiveRecord tables in Ocean.
== Installation
gem install ocean-dynamo
Then, locate the gem's directory and copy
spec/dummy/config/initializers/aws.rb
to your project's
config/initializers/aws.rb
Also copy
spec/dummy/config/aws.yml.example
to both the following locations in your project:
config/aws.yml.example
config/aws.yml
Enter your AWS credentials in the latter file. Eventually, there
will be a generator to copy these files for you, but for now you need to do it manually.
You also need +fake_dynamo+ to run DynamoDB locally: see below for installation instructions.
NB: You do not need an Amazon AWS account to run OceanDynamo locally.
== Documentation
* Ocean-dynamo gem on Rubygems: https://rubygems.org/gems/ocean-dynamo
* Ocean-dynamo gem API: http://rubydoc.info/gems/ocean-dynamo/frames
* Ocean-dynamo source and wiki: https://github.org/OceanDev/ocean-dynamo
See also Ocean, a Rails framework for creating highly scalable SOAs in the cloud, in which
OceanDynamo is used as a central component:
* http://wiki.oceanframework.net
== Contributing
Contributions are welcome. Fork in the usual way. OceanDynamo is developed using
TDD: the specs are extensive and test coverage is very near to 100 percent. Pull requests
will not be considered unless all tests pass and coverage is equally high or higher.
All contributed code must therefore also be exhaustively tested.
== Running the specs
To run the specs for the OceanDynamo gem, you must first install the bundle. It will download
a gem called +fake_dynamo+, which runs a local, in-memory functional clone of Amazon DynamoDB.
We use +fake_dynamo+ during development and testing.
First of all, copy the AWS configuration file from the template:
cp spec/dummy/config/aws.yml.example spec/dummy/config/aws.yml
NB: +aws.yml+ is excluded from source control. This allows you to enter your AWS credentials
safely. Note that +aws.yml.example+ is under source control: don't edit it.
Make sure your have version 0.1.3 of the +fake_dynamo+ gem. It implements the +2011-12-05+ version
of the DynamoDB API. We're not using the +2012-08-10+ version, as the +aws-sdk+ ruby gem
doesn't fully support it.
Next, start +fake_dynamo+:
fake_dynamo --port 4567
If this returns errors, make sure that <tt>/usr/local/var/fake_dynamo</tt> exists and
is writable:
sudo mkdir -p /usr/local/var/fake_dynamo
sudo chown peterb:staff /usr/local/var/fake_dynamo
When +fake_dynamo+ runs normally, open another window and issue the following command:
curl -X DELETE http://localhost:4567
This will reset the +fake_dynamo+ database. It's not a required operation when starting
+fake_dynamo+; we're just using it here as a test that the installation works. It will
be issued automatically as part of the test suite, so don't expect test data to survive
between runs.
With +fake_dynamo+ running, you should now be able to do
rspec
All tests should pass.
== Rails console
The Rails console is available from the built-in dummy application:
cd spec/dummy
rails console
This will, amongst other things, also create the CloudModel table if it doesn't already
exist. On Amazon, this will take a little while. With +fake_dynamo+, it's practically
instant.
When you leave the console, you must navigate back to the top directory (<tt>cd ../..</tt>)
in order to be able to run RSpec again.
<file_sep>/lib/ocean-dynamo/associations/has_many.rb
module OceanDynamo
module HasMany
def self.included(base)
base.extend(ClassMethods)
end
# ---------------------------------------------------------
#
# Class methods
#
# ---------------------------------------------------------
module ClassMethods
#
# Defines a +has_many+ relation to a +belongs_to+ class.
#
# The +dependent:+ keyword arg may be +:destroy+, +:delete+ or +:nullify+
# and have the same semantics as in ActiveRecord. With +:nullify+, however,
# the hash key is set to the string "NULL" rather than binary NULL, as
# DynamoDB doesn't permit storing empty fields.
#
def has_many(children, dependent: :nullify) # :children
children_attr = children.to_s.underscore # "children"
class_name = children_attr.classify # "Child"
define_class_if_not_defined(class_name)
child_class = class_name.constantize # Child
register_relation(child_class, :has_many)
# Handle children= after create and update
after_save do |p|
new_children = instance_variable_get("@#{children_attr}")
if new_children # TODO: only do this for dirty collections
write_children child_class, new_children
map_children child_class do |c|
next if new_children.include?(c)
c.destroy
end
end
true
end
if dependent == :destroy
before_destroy do |p|
map_children(child_class, &:destroy)
p.instance_variable_set "@#{children_attr}", nil
true
end
elsif dependent == :delete
before_destroy do |p|
delete_children(child_class)
p.instance_variable_set "@#{children_attr}", nil
end
elsif dependent == :nullify
before_destroy do |p|
nullify_children(child_class)
p.instance_variable_set "@#{children_attr}", nil
true
end
else
raise ArgumentError, ":dependent must be :destroy, :delete, or :nullify"
end
# Define accessors for instances
attr_accessor children_attr
self.class_eval "def #{children_attr}(force_reload=false)
@#{children_attr} = false if force_reload
@#{children_attr} ||= read_children(#{child_class})
end"
self.class_eval "def #{children_attr}=(value)
@#{children_attr} = value
end"
self.class_eval "def #{children_attr}?
@#{children_attr} ||= read_children(#{child_class})
@#{children_attr}.present?
end"
end
end
# ---------------------------------------------------------
#
# Instance variables and methods
#
# ---------------------------------------------------------
#
# Sets all has_many relations to nil.
#
def reload(*)
result = super
self.class.relations_of_type(:has_many).each do |klass|
attr_name = klass.to_s.pluralize.underscore
instance_variable_set("@#{attr_name}", nil)
end
result
end
protected
#
# Reads all children of a has_many relation.
#
def read_children(child_class) # :nodoc:
if new_record?
nil
else
result = Array.new
_late_connect?
child_items = child_class.dynamo_items
child_items.query(hash_value: id, range_gte: "0",
batch_size: 1000, select: :all) do |item_data|
result << child_class.new._setup_from_dynamo(item_data)
end
result
end
end
#
# Write all children in the arg, which should be nil or an array.
#
def write_children(child_class, arg) # :nodoc:
return nil if arg.blank?
raise AssociationTypeMismatch, "not an array or nil" if !arg.is_a?(Array)
raise AssociationTypeMismatch, "an array element is not a #{child_class}" unless arg.all? { |m| m.is_a?(child_class) }
# We now know that arg is an array containing only members of the child_class
arg.each(&:save!)
arg
end
#
# Takes a block and yields each child to it. Batched for scalability.
#
def map_children(child_class)
return if new_record?
child_items = child_class.dynamo_items
child_items.query(hash_value: id, range_gte: "0",
batch_size: 1000, select: :all) do |item_data|
yield child_class.new._setup_from_dynamo(item_data)
end
end
#
# Delete all children without instantiating them first.
#
def delete_children(child_class)
return if new_record?
child_items = child_class.dynamo_items
child_items.query(hash_value: id, range_gte: "0",
batch_size: 1000) do |item|
item.delete
end
end
#
# Set the hash key values of all children to the string "NULL", thereby turning them
# into orphans. Note that we're not setting the key to NULL as this isn't possible
# in DynamoDB. Instead, we're using the literal string "NULL".
#
def nullify_children(child_class)
return if new_record?
child_items = child_class.dynamo_items
child_items.query(hash_value: id, range_gte: "0",
batch_size: 1000, select: :all) do |item_data|
attrs = item_data.attributes
item_data.item.delete
attrs[child_class.table_hash_key.to_s] = "NULL"
child_items.create attrs
end
end
end
end
<file_sep>/spec/dynamo/composite_key_datetime_spec.rb
require 'spec_helper'
class Ragadish < OceanDynamo::Table
dynamo_schema(:uuid, :tempus, create:true, table_name_suffix: Api.basename_suffix) do
attribute :tempus, :datetime
end
end
describe Ragadish do
before :each do
Ragadish.delete_all
end
it "should set the keys correctly" do
expect(Ragadish.table_hash_key).to eq :uuid
expect(Ragadish.table_range_key).to eq :tempus
expect(Ragadish.fields).to include :tempus
end
it "should be instantiatiable" do
v = Ragadish.new
end
it "should be invalid if the range key is absent" do
v = Ragadish.new()
expect(v.valid?).to eq false
expect(v.errors.messages).to eq({tempus: ["can't be blank"]})
end
it "should be persistable when both args are specified" do
t = Time.now.utc
v = Ragadish.create! uuid: "foo", tempus: t
expect(v).to be_a Ragadish
expect(v.uuid).to eq "foo"
expect(v.tempus).to eq t
end
it "should assign a UUID to the hash key when unspecified" do
v = Ragadish.create! tempus: 1.year.from_now.utc
expect(v.uuid).to be_a String
expect(v.uuid).not_to eq ""
end
it "should not persist if the range key is empty or unspecified" do
expect { Ragadish.create! uuid: "foo", tempus: nil }.to raise_error(OceanDynamo::RecordInvalid)
expect { Ragadish.create! uuid: "foo", tempus: false }.to raise_error(OceanDynamo::RecordInvalid)
expect { Ragadish.create! uuid: "foo", tempus: "" }.to raise_error(OceanDynamo::RecordInvalid)
expect { Ragadish.create! uuid: "foo", tempus: " " }.to raise_error(OceanDynamo::RecordInvalid)
end
it "instances should be findable" do
t = 1.day.ago.utc
orig = Ragadish.create! tempus: t
found = Ragadish.find(orig.uuid, t, consistent: true)
expect(found.uuid).to eq orig.uuid
end
it "instances should be reloadable" do
i = Ragadish.create! uuid: "quux", tempus: Time.now.utc
i.reload
end
end
<file_sep>/spec/dummy/config/initializers/aws.rb
f = File.join(Rails.root, "config/aws.yml")
unless File.exists?(f)
puts
puts "-----------------------------------------------------------------------"
puts "AWS config file missing. Please copy config/aws.yml.example"
puts "to config/aws.yml and tailor its contents to suit your dev setup."
puts
puts "NB: aws.yml is excluded from git version control as it will contain"
puts " data private to your Ocean system."
puts "-----------------------------------------------------------------------"
puts
abort
end
require "aws-sdk"
AWS.config YAML.load(File.read(f))[Rails.env]
require "aws-sdk-core"
Aws.config = YAML.load(File.read(f))[Rails.env].except(:user_agent_prefix)
<file_sep>/lib/ocean-dynamo/queries.rb
module OceanDynamo
module Queries
# ---------------------------------------------------------
#
# Class methods
#
# ---------------------------------------------------------
def find(hash, range=nil, consistent: false)
return hash.collect {|elem| find elem, range, consistent: consistent } if hash.is_a?(Array)
_late_connect?
hash = hash.id if hash.kind_of?(Table) # TODO: We have (innocuous) leakage, fix!
range = range.to_i if range.is_a?(Time)
item = dynamo_items[hash, range]
unless item.exists?
raise RecordNotFound, "can't find a #{self} with primary key ['#{hash}', #{range.inspect}]"
end
new._setup_from_dynamo(item, consistent: consistent)
end
def find_by_key(*args)
find(*args)
rescue RecordNotFound
nil
end
alias find_by_id find_by_key
#
# The number of records in the table.
#
def count(**options)
_late_connect?
dynamo_items.count(options)
end
#
# Returns all records in the table.
#
def all(consistent: false, **options)
_late_connect?
result = []
if consistent
dynamo_items.each(options) do |item|
result << new._setup_from_dynamo(item, consistent: consistent)
end
else
dynamo_items.select(options) do |item_data|
result << new._setup_from_dynamo(item_data)
end
end
result
end
#
# Looping through a collection of records from the database (using the +all+ method,
# for example) is very inefficient since it will try to instantiate all the objects at once.
#
# In that case, batch processing methods allow you to work with the records in batches,
# thereby greatly reducing memory consumption.
#
def find_each(limit: nil, batch_size: 1000, consistent: false)
if consistent
dynamo_items.each(limit: limit, batch_size: batch_size) do |item|
yield new._setup_from_dynamo(item, consistent: consistent)
end
else
dynamo_items.select(limit: limit, batch_size: batch_size) do |item_data|
yield new._setup_from_dynamo(item_data)
end
end
true
end
# #
# # Yields each batch of records that was found by the find options as an array. The size of
# # each batch is set by the :batch_size option; the default is 1000.
# #
# # You can control the starting point for the batch processing by supplying the :start option.
# # This is especially useful if you want multiple workers dealing with the same processing queue. You can make worker 1 handle all the records between id 0 and 10,000 and worker 2 handle from 10,000 and beyond (by setting the :start option on that worker).
# #
# # It’s not possible to set the order.
# #
# def find_in_batches(start: nil, batch_size: 1000)
# []
# end
end
end
<file_sep>/spec/dynamo/associations/collection_association_spec.rb
require 'spec_helper'
# Association
# CollectionAssociation:
# HasAndBelongsToManyAssociation => has_and_belongs_to_many
# HasManyAssociation => has_many
# HasManyThroughAssociation + ThroughAssociation => has_many :through
class Owner < OceanDynamo::Table
dynamo_schema(create: true, table_name_suffix: Api.basename_suffix) do
attribute :thing
end
end
class Target < OceanDynamo::Table
dynamo_schema(create: true, table_name_suffix: Api.basename_suffix) do
attribute :name
end
end
module OceanDynamo
module Associations
describe CollectionAssociation do
before :each do
@o = Owner.create!
@r = double(klass: Target)
@ca = CollectionAssociation.new(@o, @r)
end
it "should inherit from Association" do
expect(@ca).to be_an Association
end
it "should have a reset method which sets @target to []" do
@ca.reset
expect(@ca.target).to eq []
expect(@ca.loaded?).to eq false
end
end
end
end
<file_sep>/spec/spec_helper.rb
require 'simplecov'
SimpleCov.start do
add_filter "/vendor/"
add_filter "spec/dummy/config/initializers/aws.rb"
end
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.infer_base_class_for_anonymous_controllers = false
config.order = 'random'
#config.include Rails.application.routes.url_helpers
# Make "FactoryGirl" superfluous
config.include FactoryGirl::Syntax::Methods
# To clear the fake_dynamo DB before and/or after each run, uncomment as desired:
config.before(:suite) { `curl -s -X DELETE http://localhost:4567` }
config.after(:suite) { `curl -s -X DELETE http://localhost:4567` }
end
class Api
#
# Special version of Api.adorn_basename.
#
def self.adorn_basename(basename, chef_env: "dev", rails_env: "development",
suffix_only: false)
fullname = suffix_only ? "_#{chef_env}" : "#{basename}_#{chef_env}"
local_ip = UDPSocket.open {|s| s.connect("172.16.17.32", 1); s.addr.last}.gsub('.', '-')
fullname += "_#{local_ip}_#{rails_env}"
fullname
end
#
# Special version of Api.basename_suffix.
#
def self.basename_suffix
adorn_basename '', suffix_only: true, rails_env: Rails.env
end
end
<file_sep>/lib/ocean-dynamo/tables.rb
module OceanDynamo
module Tables
def self.included(base)
base.extend(ClassMethods)
end
# ---------------------------------------------------------
#
# Class methods
#
# ---------------------------------------------------------
module ClassMethods
def dynamo_schema(table_hash_key=:id,
table_range_key=nil,
table_name: compute_table_name,
table_name_prefix: nil,
table_name_suffix: nil,
read_capacity_units: 10,
write_capacity_units: 5,
connect: :late,
create: false,
**keywords,
&block)
self.dynamo_client = nil
self.dynamo_table = nil
self.dynamo_items = nil
self.table_connected = false
self.table_connect_policy = connect
self.table_create_policy = create
self.table_hash_key = table_hash_key
self.table_range_key = table_range_key
self.table_name = table_name
self.table_name_prefix = table_name_prefix
self.table_name_suffix = table_name_suffix
self.table_read_capacity_units = read_capacity_units
self.table_write_capacity_units = write_capacity_units
# Connect if asked to
establish_db_connection if connect == true
end
def establish_db_connection
setup_dynamo
if dynamo_table.exists?
wait_until_table_is_active
self.table_connected = true
else
raise(TableNotFound, table_full_name) unless table_create_policy
create_table
end
set_dynamo_table_keys
end
def setup_dynamo
self.dynamo_client ||= AWS::DynamoDB.new
self.dynamo_table = dynamo_client.tables[table_full_name]
self.dynamo_items = dynamo_table.items
end
def wait_until_table_is_active
loop do
case dynamo_table.status
when :active
set_dynamo_table_keys
return
when :updating, :creating
sleep 1
next
when :deleting
sleep 1 while dynamo_table.exists?
create_table
return
else
raise UnknownTableStatus.new("Unknown DynamoDB table status '#{dynamo_table.status}'")
end
end
end
def set_dynamo_table_keys
hash_key_type = fields[table_hash_key][:type]
hash_key_type = :string if hash_key_type == :reference
dynamo_table.hash_key = [table_hash_key, hash_key_type]
if table_range_key
range_key_type = generalise_range_key_type
dynamo_table.range_key = [table_range_key, range_key_type]
end
end
def create_table
hash_key_type = fields[table_hash_key][:type]
hash_key_type = :string if hash_key_type == :reference
range_key_type = generalise_range_key_type
self.dynamo_table = dynamo_client.tables.create(table_full_name,
table_read_capacity_units, table_write_capacity_units,
hash_key: { table_hash_key => hash_key_type},
range_key: table_range_key && { table_range_key => range_key_type }
)
sleep 1 until dynamo_table.status == :active
setup_dynamo
true
end
def generalise_range_key_type
return false unless table_range_key
t = fields[table_range_key][:type]
return :string if t == :string
return :number if t == :integer
return :number if t == :float
return :number if t == :datetime
raise "Unsupported range key type: #{t}"
end
def delete_table
return false unless dynamo_table.exists? && dynamo_table.status == :active
dynamo_table.delete
true
end
end
# ---------------------------------------------------------
#
# Instance methods
#
# ---------------------------------------------------------
def initialize(*)
@dynamo_item = nil
super
end
end
end
<file_sep>/spec/dynamo/aws_table_spec.rb
require 'spec_helper'
describe CloudModel do
before :all do
CloudModel.establish_db_connection
end
before :each do
CloudModel.dynamo_client = nil
CloudModel.dynamo_table = nil
CloudModel.dynamo_items = nil
@saved_table_name = CloudModel.table_name
@saved_prefix = CloudModel.table_name_prefix
@saved_suffix = CloudModel.table_name_suffix
#CloudModel.table_name = "cloud_models"
#CloudModel.table_name_prefix = nil
#CloudModel.table_name_suffix = nil
end
after :each do
CloudModel.table_name = @saved_table_name
CloudModel.table_name_prefix = @saved_prefix
CloudModel.table_name_suffix = @saved_suffix
end
it "should have a table_name derived from the class" do
expect(CloudModel.table_name).to eq "cloud_models"
end
it "should handle a table_name derived from a namespaced class" do
expect(CloudNamespace::CloudModel.table_name).to eq "cloud_namespace_cloud_models"
end
it "should have a table_name_prefix" do
expect(CloudModel.table_name_prefix).to eq nil
CloudModel.table_name_prefix = "foo_"
expect(CloudModel.table_name_prefix).to eq "foo_"
end
it "should have a table_name_suffix" do
expect(CloudModel.table_name_suffix).to eq Api.basename_suffix
end
it "should have a table_full_name method" do
expect(CloudModel.table_full_name).to eq "cloud_models" + Api.basename_suffix
CloudModel.table_name_prefix = "foo_"
CloudModel.table_name_suffix = "_bar"
expect(CloudModel.table_full_name).to eq "foo_cloud_models_bar"
end
it "should have a dynamo_table class_variable" do
CloudModel.dynamo_table
CloudModel.new.dynamo_table
CloudModel.dynamo_table = true
expect { CloudModel.new.dynamo_table = true }.to raise_error
CloudModel.dynamo_table = nil
end
it "establish_db_connection should set dynamo_client, dynamo_table and dynamo_items" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).and_return(:active)
expect(CloudModel).not_to receive(:create_table)
expect(CloudModel.dynamo_client).to eq nil
expect(CloudModel.dynamo_table).to eq nil
expect(CloudModel.dynamo_items).to eq nil
CloudModel.establish_db_connection
expect(CloudModel.dynamo_client).to be_an AWS::DynamoDB
expect(CloudModel.dynamo_table).to be_an AWS::DynamoDB::Table
expect(CloudModel.dynamo_items).to be_an AWS::DynamoDB::ItemCollection
end
it "establish_db_connection should return true if the table exists and is active" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).and_return(:active)
expect(CloudModel).not_to receive(:create_table)
CloudModel.establish_db_connection
end
it "establish_db_connection should wait for the table to complete creation" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).
and_return(:creating, :creating, :creating, :creating, :active)
expect(Object).to receive(:sleep).with(1).exactly(4).times
expect(CloudModel).not_to receive(:create_table)
CloudModel.establish_db_connection
end
it "establish_db_connection should wait for the table to delete before trying to create it again" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).and_return(:deleting)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true, true, true, false)
expect(Object).to receive(:sleep).with(1).exactly(3).times
expect(CloudModel).to receive(:create_table).and_return(true)
CloudModel.establish_db_connection
end
it "establish_db_connection should try to create the table if it doesn't exist" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(false)
expect(CloudModel).to receive(:create_table).and_return(true)
CloudModel.establish_db_connection
end
it "establish_db_connection should barf on an unknown table status" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).twice.and_return(:syphilis)
expect(CloudModel).not_to receive(:create_table)
expect { CloudModel.establish_db_connection }.
to raise_error(OceanDynamo::UnknownTableStatus, "Unknown DynamoDB table status 'syphilis'")
end
it "create_table should try to create the table if it doesn't exist" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).and_return(false)
t = double(AWS::DynamoDB::Table)
allow(t).to receive(:status).and_return(:creating, :creating, :creating, :active)
allow(t).to receive(:hash_key=).once
allow(t).to receive(:range_key=).once
expect_any_instance_of(AWS::DynamoDB::TableCollection).to receive(:create).
with("cloud_models" + Api.basename_suffix,
10,
5,
hash_key: {uuid: :string},
range_key: nil).
and_return(t)
expect(Object).to receive(:sleep).with(1).exactly(3).times
CloudModel.establish_db_connection
end
it "delete_table should return true if the table was :active" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).twice.and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).twice.and_return(:active)
expect(CloudModel).not_to receive(:create_table)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:delete)
CloudModel.establish_db_connection
expect(CloudModel.delete_table).to eq true
end
it "delete_table should return false if the table wasn't :active" do
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:exists?).twice.and_return(true)
expect_any_instance_of(AWS::DynamoDB::Table).to receive(:status).and_return(:active, :deleting)
CloudModel.establish_db_connection
expect(CloudModel.delete_table).to eq false
end
it "should keep the connection between two instantiations" do
CloudModel.establish_db_connection
i1 = CloudModel.new
i1.save!
i2 = CloudModel.new
i2.save!
end
it "table_read_capacity_units should default to 10" do
expect(CloudModel.table_read_capacity_units).to eq 10
end
it "table_write_capacity_units should default to 5" do
expect(CloudModel.table_write_capacity_units).to eq 5
end
it "should have a table_connected variable" do
expect(CloudModel).to respond_to :table_connected
end
it "should have a table_connect_policy variable" do
expect(CloudModel).to respond_to :table_connect_policy
end
it "should have a table_create_policy variable" do
expect(CloudModel).to respond_to :table_create_policy
end
end
| 7a147f5f845c6496283fc21f315aa8091e85d61b | [
"RDoc",
"Ruby"
] | 11 | Ruby | BilalBudhani/ocean-dynamo | 0c199545701185a2816fb159bcc240b1e95107f8 | 263a30fd4709610ea827e73120126d7d7c00e6a2 |
refs/heads/master | <file_sep>from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=255)
price = models.PositiveIntegerField()
author = models.ForeignKey(Author, models.PROTECT)
def __str__(self):
return self.name<file_sep>from django.shortcuts import render
from django.db.models import Q
from .models import Book
from .filters import BookFilterSet
def index(request):
#### 舊的
# q = request.GET.get('q', '')
# books = Book.objects.all()
# if q:
# books = books.filter(name__icontains=q)
# return render(request, 'books/index.html', {
# 'books': books,
# })
#### 新的
filter = BookFilterSet(request.GET or None, queryset=Book.objects.all())
return render(request, 'books/filter-index.html', {
'filter': filter,
})
def result(request):
q = request.GET.get('q', '')
books = None
if q:
books = Book.objects.filter(
Q(name__icontains=q) | Q(author__name__icontains=q)
)
else:
filter = BookFilterSet(request.GET or None, queryset=Book.objects.all())
books = filter.qs
return render(request, 'books/result.html', {
'books': books,
})<file_sep># Generated by Django 2.2.1 on 2019-05-02 08:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
],
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('price', models.PositiveIntegerField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='books.Author')),
],
),
]
| dd9c6e7d8d398d740dace86bef70ce5d1acc0d2b | [
"Python"
] | 3 | Python | ki367159/django-filter | 8775600863f7da3b292de70cfc10775c491ce609 | 87834353762e1540ed6ceb3e4245669fa932a7d9 |
refs/heads/master | <repo_name>Reginara/projeto-CRUD-trybe<file_sep>/src/pages/MovieDetails.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import * as movieAPI from '../services/movieAPI';
import { Loading } from '../components';
class MovieDetails extends Component {
constructor(props) {
super(props);
this.state = {
movie: [],
loading: true,
};
this.deleteMovie = this.deleteMovie.bind(this);
}
componentDidMount() {
const { match } = this.props;
const { id } = match.params;
movieAPI.getMovie(id)
.then((data) => {
this.setState({ movie: data, loading: false });
})
.catch((error) => console.log(error));
}
deleteMovie() {
const { match } = this.props;
const { id } = match.params;
movieAPI.deleteMovie(id);
}
render() {
const { movie, loading } = this.state;
const { title, storyline, imagePath, genre, rating, subtitle } = movie;
const { match } = this.props;
const { id } = match.params;
if (loading) return <Loading />;
return (
<section data-testid="movie-details" className="movie-list">
<div>
<h2 className="movie-details-title">{ `Title: ${title}` }</h2>
<h3 className="movie-details-subtitle">{ `Subtitle: ${subtitle}` }</h3>
</div>
<div>
<img alt="Movie Cover" src={ `../${imagePath}` } className="details-image" />
<p className="movie-details-storyline">{ `Storyline: ${storyline}` }</p>
<h3 className="movie-details-genre">{ `Genre: ${genre}` }</h3>
<h4 className="movie-details-rating">{ `Rating: ${rating}` }</h4>
<Link to={ `/movies/${id}/edit` } className="button">EDITAR</Link>
<Link to="/" className="button">VOLTAR</Link>
<Link to="/" onClick={ this.deleteMovie } className="button">DELETAR</Link>
</div>
</section>
);
}
}
MovieDetails.propTypes = ({
match: PropTypes.objectOf(PropTypes.array),
id: PropTypes.number,
}).isRequired;
export default MovieDetails;
| 3872f2bbf8683b2962f8b41ad2aea825e4b1b397 | [
"JavaScript"
] | 1 | JavaScript | Reginara/projeto-CRUD-trybe | 979af01c198bfa581bda262002011787ea8eea6e | cc6c6bdeadaf64e5c2e0f8624005885b8edfb3c0 |
refs/heads/master | <repo_name>KarolisTru/node_jest_tasks<file_sep>/tasks/task3.test.js
const { motto1, motto2 } = require("./task3");
describe("Task #3", () => {
describe("motto1", () => {
performTestsFor(motto1);
});
describe("motto2", () => {
performTestsFor(motto2);
});
});
function performTestsFor(func) {
test(`should ${func.name}("Targaryen") to be "Fire and Blood"`, () => {
const result = func("Targaryen");
const expected = "Fire and Blood";
expect(result).toBe(expected);
});
test(`should ${func.name}("Martell") to be "Unbowed, Unbent, Unbroken"`, () => {
const result = func("Martell");
const expected = "Unbowed, Unbent, Unbroken";
expect(result).toBe(expected);
});
test(`should ${func.name}("Simpsons") to be undefined`, () => {
const result = func("Simpsons");
const expected = undefined;
expect(result).toBe(expected);
});
}
<file_sep>/tasks/task1.test.js
const { range1, range2 } = require("./task1");
// Suite
describe("Task #1", () => {
describe("range1", () => {
performTestsFor(range1);
});
describe("range2", () => {
performTestsFor(range2);
});
});
function performTestsFor(func) {
test(`should ${func.name}(x=1, y=10) to be [1, 2, 3, 4, 5, 6, 7, 8, 9]`, () => {
// Setup
// Execution
const result = func(1, 10);
const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// Assertion
expect(result).toEqual(expected);
});
test(`should ${func.name}(x=20, y=10) to be [20, 19, 18, 17, 16, 15, 14, 13, 12, 11]`, () => {
// Setup
// Execution
const result = func(20, 10);
const expected = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11];
// Assertion
expect(result).toEqual(expected);
});
test(`should ${func.name}(x=1.3, y=3.5) to be undefined`, () => {
// Setup
// Execution
const result = func(1.3, 3.5);
const expected = undefined;
// Assertion
expect(result).toEqual(expected);
});
}
<file_sep>/tasks/task4.js
//Not taking into consideration objects and arrays - they require additional logic w JSON stringify/parse
function removeDuplicates1(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if(isUnique(arr[i], newArr)) {
newArr.push(arr[i]);
}
}
return newArr;
}
//helper function for ES5 way
function isUnique(value, arr) {
for (let j = 0; j < arr.length; j++) {
if (arr[j] === value) {
return false;
} else continue;
}
return true;
}
function removeDuplicates2(arr) {
return [...new Set(arr)];
}
module.exports = {
removeDuplicates1,
removeDuplicates2
}<file_sep>/tasks/task5.js
function wordSearch(word, text) {
const searchRegex = new RegExp(word, 'i');
return searchRegex.test(text);
};
module.exports = {
wordSearch
}<file_sep>/tasks/task2.js
function sum1(){
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
function sum2(...args){
return args.reduce((prev, next) => prev + next, 0);
}
module.exports = {
sum1,
sum2
};<file_sep>/tasks/task8.js
function spy(func) {
let callCount = 0;
return function wrapper() {
callCount++;
wrapper.report = function () {
return ({ totalCalls: callCount });
};
return func.apply(this, arguments);
};
}
module.exports = {
spy
}
<file_sep>/tasks/task11.test.js
const {say} = require('./task11');
describe('Test #11', () => {
describe('say', () => {
test('should say("Hello, ")("it\'s me") to be "Hello, it\'s me"', () => {
const result = say("Hello, ")("it's me");
const expected = "Hello, it's me";
expect(result).toBe(expected);
})
})
})<file_sep>/tasks/task7.js
function sevenAte9(sequence) {
if(typeof sequence === "number") {
sequence = sequence.toString();
}
const answer = sequence.replace(/(?<=7)9(?=7)/g, "");
return answer;
}
module.exports = {
sevenAte9,
};
<file_sep>/tasks/task5.test.js
const {wordSearch} = require('./task5');
describe("Task #5", () => {
describe("wordSearch", () => {
test('should wordSearch("alibaba", "I always wanted to meet Alibaba, but did not manage to") return true', () => {
const result = wordSearch("alibaba", "I always wanted to meet Alibaba, but did not manage to");
const expected = true;
expect(result).toBe(expected);
});
test('should wordSearch("op op", "HoP op") return true', () => {
const result = wordSearch("op op", "HoP op");
const expected = true;
expect(result).toBe(expected);
})
test('should wordSearch("ran", "Brunger is not even a word") return true', () => {
const result = wordSearch("ran", "Brunger is not even a word");
const expected = false;
expect(result).toBe(expected);
})
});
})<file_sep>/tasks/task10.test.js
const { CalculatorES5, CalculatorES6 } = require("./task10.js");
describe("Task #10", () => {
describe("CalculatorES5", () => {
performTestsFor(CalculatorES5);
});
describe("CalculatorES6", () => {
performTestsFor(CalculatorES6);
});
});
function performTestsFor(Func) {
test(`should const calc = new ${Func.name}(0) be chainable and calc.add(5).multiply(2).add(20).divide(3).answer to be 10 `, () => {
const calc = new Func(0);
const result = calc.add(5).multiply(2).add(20).divide(3).answer;
const expected = 10;
expect(result).toBe(expected);
});
}
<file_sep>/tasks/task1.js
//what if numbers are equal
function range1(x, y){
if(!Number.isInteger(x) || !Number.isInteger(y)){
return undefined;
}
let newArr = [];
if (x < y) {
for (let i = x; i < y; i++) {
newArr.push(i);
}
} else if (x > y) {
for (let i = x; i > y; i--) {
newArr.push(i);
}
}
return newArr;
}
function range2(x, y){
if(!Number.isInteger(x) || !Number.isInteger(y)){
return undefined;
}
const isIncreasing = x < y;
const length = isIncreasing ? y - x : x - y;
return Array.from({ length }, (val, index) =>
isIncreasing ? x + index : x - index
);
}
module.exports = {
range1,
range2
};
<file_sep>/tasks/task8.test.js
const { spy } = require("./task8");
describe("Task #8", () => {
describe("spy", () => {
test("should spy function track times the wrapped function was called and return them if .report() method is called", () => {
function myFunc() {
return console.log("Hello");
}
const spied = spy(myFunc);
spied(1);
spied(2);
spied(100);
let result = spied.report();
const expected = { totalCalls: 3 };
expect(result).toEqual(expected);
});
});
});
<file_sep>/tasks/task9.js
function sumNumbers(arr){
let sum = 0;
if (!Array.isArray(arr)){
sum += arr;
} else {
for (let i = 0; i < arr.length; i++) {
sum += sumNumbers(arr[i]);
}
}
return sum;
}
module.exports = {
sumNumbers
}<file_sep>/tasks/task6.js
function sum(x) {
return (y) =>
typeof x === "number" && typeof y === "number" ? x + y : undefined;
}
module.exports = {
sum,
};
<file_sep>/tasks/task4.test.js
const { removeDuplicates1, removeDuplicates2 } = require("./task4");
describe("Task #4", () => {
describe("removeDuplicates1", () => {
performTestsFor(removeDuplicates1);
});
describe("removeDuplicates2", () => {
performTestsFor(removeDuplicates2);
});
});
function performTestsFor(func) {
test(`should ${func.name}([1, 2, 2, 2, 3, 5, 6, 3, 10, 8]) to strict equal [1, 2, 3, 5, 6, 10, 8]`, () => {
const result = func([1, 2, 2, 2, 3, 5, 6, 3, 10, 8]);
const expected = [1, 2, 3, 5, 6, 10, 8];
expect(result).toEqual(expected);
});
test(`should ${func.name}(['gg', 'btw', 'andy', 'btw', 'andy']) to strict equal ['gg', 'btw', 'andy']`, () => {
const result = func(["gg", "btw", "andy", "btw", "andy"]);
const expected = ["gg", "btw", "andy"];
expect(result).toEqual(expected);
});
}
| 8dc40c5a45b8ef5a2bd8108a55be1f9c82857cc5 | [
"JavaScript"
] | 15 | JavaScript | KarolisTru/node_jest_tasks | a21b31c7e4a21306a47e29d55b714bd690edb311 | 67a01229f8fb4f2770a2678d42b912ab642560dd |
refs/heads/master | <file_sep>package com.coefficient.rest.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.coefficient.rest.util.CoefficientLogger.CoefficientLoggerLevel;
/**
* Helps in reading log file based on date
*
*
*
*/
@Component
public class LoggerUtil {
@Value("${logger.base.path}")
private String LOGGER_BASE_PATH;
@Value("${logger.file.name}")
private String LOGGER_FILE_NAME;
@Value("${catalina.home.path}")
private String CATALINA_HOME_PATH;
/**
* Parse string to Date type
*
* @param date
* @return Date
* @throws ParseException
*/
public static Date convertToDateddMMyyyy(String date) throws ParseException {
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
if (date != null) {
return format.parse(date);
} else {
throw new NullPointerException();
}
}
/**
* Parse string to Date type
*
* @param date
* @return
* @throws ParseException
*/
public static Date convertToDateyyyyMMdd(String date) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (date != null) {
return format.parse(date);
} else {
throw new NullPointerException();
}
}
/**
* Method to convert java date to sql date type
*
* @param date
* @return
* @throws ParseException
*/
public static Date convertJavaDateToSqlDate(String date) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date utilDate = dateFormat.parse(date);
dateFormat.applyPattern("yyyy-MM-dd");
return convertToDateyyyyMMdd(dateFormat.format(utilDate));
}
/**
* This method will test if log starts with a date(dd-MM-yyyy) or not, if
* exist we will perform further operation
*
* @param date
* @return
*/
public static boolean isValidDateFormate(String date) {
return date.matches("^\\d{2}-\\d{2}-\\d{4}");
}
/**
* Method to read log file
*
* @param date
* @return
*/
public String readLogs(String userDate) {
File file = new File(LOGGER_BASE_PATH + LOGGER_FILE_NAME + "." + userDate);
StringBuilder builder = new StringBuilder();
String path;
if (file.exists()) {
path = LOGGER_BASE_PATH + LOGGER_FILE_NAME + "." + userDate;
} else {
path = LOGGER_BASE_PATH + LOGGER_FILE_NAME;
}
try (FileReader in = new FileReader(path); BufferedReader br = new BufferedReader(in);) {
String str;
while ((str = br.readLine()) != null) {
builder.append(str).append(System.getProperty("line.separator"));
}
} catch (FileNotFoundException e) {
CoefficientLogger.log(CoefficientLoggerLevel.ERROR, "File (logger) not found exception ", e,
LoggerUtil.class);
builder.setLength(0);
builder.append("Could not find log file");
} catch (IOException e) {
CoefficientLogger.log(CoefficientLoggerLevel.ERROR, "IOException for logger ", e, LoggerUtil.class);
builder.setLength(0);
builder.append("Exception occured while reading file");
}
return builder.toString();
}
/**
* List all files name in folder
*
* @param folderPath
* @return
*/
public static List<String> listOfAllFileInFolder(String folderPath) {
List<String> files = new ArrayList<String>();
File folder = new File(folderPath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
files.add(listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
return files;
}
/**
* Method to compare two dates
*
* @param userDate
* @param loggerDate
* @return
*/
public static boolean compareDates(Date userDate, Date loggerDate) {
return userDate.compareTo(loggerDate) == 0 ? true : false;
}
}
<file_sep>package com.coefficient.rest.generic.dao;
import java.util.List;
import org.hibernate.Session;
public interface GenericDao<E, I> {
public Session getCurrentSession();
public List<E> findAll();
public E find(I id);
public E create(E e);
public void update(E e);
public void saveOrUpdate(E e);
public void delete(E e);
public void flush();
}
<file_sep>package com.coefficient.rest.generic.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.coefficient.rest.user.dao.UserDao;
@Service("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
UserDao userDao;
@Override
@Transactional
public UserDetails loadUserByUsername(String email) {
/*
* UserDetails user = userDao.loadUserByUsername(email); if(user ==
* null){ throw new UsernameNotFoundException("The user " + email +
* " was not found"); } return user;
*/
return null;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cofficient.rest</groupId>
<artifactId>coefficientrest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>coefficientrest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.3</version>
<exclusions>
<exclusion>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<!-- Database -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>5.2.5.Final</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<!-- jpa -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- geo ip -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- Apache Commons Upload -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- Quartz Scheduler -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- Http post server calls -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
<!-- File Mime type -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.6</version>
</dependency>
<!--Java Mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<!-- Convert from graphml file to json format -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<dependency>
<groupId>com.tinkerpop.blueprints</groupId>
<artifactId>blueprints-core</artifactId>
<version>2.6.0</version>
</dependency>
<!-- <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-maven-plugin</artifactId>
<version>7.7.6</version> </dependency> -->
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-explorer</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-jsr94</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
<version>6.5.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>coefficientrest</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>ehubrest</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<file_sep>package com.coefficient.rest.generic.serviceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.coefficient.rest.generic.dao.GenericDao;
import com.coefficient.rest.generic.service.GenericService;
@Service("genericService")
public class GenericServiceImpl<E, I> implements GenericService<E, I> {
protected GenericDao<E, I> genericDao;
public GenericServiceImpl() {
}
public GenericServiceImpl(GenericDao<E, I> genericDao) {
super();
this.genericDao = genericDao;
}
@Override
@Transactional(readOnly = true)
public E find(I id) {
return genericDao.find(id);
}
@Override
@Transactional
public E save(E e) {
return genericDao.create(e);
}
@Override
@Transactional
public void saveOrUpdate(E e) {
genericDao.saveOrUpdate(e);
}
@Override
@Transactional
public void delete(E e) {
genericDao.delete(e);
}
@Override
@Transactional(readOnly = true)
public List<E> findAll() {
return genericDao.findAll();
}
@Override
@Transactional
public void update(E e) {
genericDao.update(e);
}
@Override
@Transactional
public void flush() {
genericDao.flush();
}
}
| 7af3d8813cb6887b9689a4fe468ae8b39355457f | [
"Java",
"Maven POM"
] | 5 | Java | PaulJalagari/Coefficient | b9f7812925faa1cf17b5674c968ddb19b379cd81 | 2cada56a5016669d6342a8f9689bacfead66c353 |
refs/heads/master | <repo_name>gbshakya/CE2018_40_41_BST<file_sep>/arrayBST.h
#ifndef ARRAYBST_H
#define ARRAYBST_H
#include "BST.h"
#define MAX_SIZE 1000
using namespace std;
class ArrayBST:public BST
{
private:
int data[MAX_SIZE];
public:
ArrayBST();
~ArrayBST();
void add(int val);
void preOrderTraversal();
bool isIn(int val);
};
ArrayBST::ArrayBST()
{
for (int i=0;i<MAX_SIZE;i++)
{
this->data[i]=-1;
}
}
ArrayBST::~ArrayBST(){}
void ArrayBST::add(int val)
{
if (this->data[1]==-1)
{
this->data[1]=val;
}
else
{
for(int i=1; i<=MAX_SIZE;)
{
//this is for changing value of i
if(val < this->data[i])
{
i = 2*i;
}
else
{
i = 2*i + 1;
}
//this is for inserting the value in the correct position
if(this->data[i]==-1)
{
this->data[i] = val;
cout<<val<<" inserted successfully."<<endl;
break;
}
}
}
}
void ArrayBST::preOrderTraversal()
{
int i=1;
int j=0;
int k=0;
int l=0;
while(i>0 && i<MAX_SIZE)
{
if(j!=1)
{
cout<<"["<<i<<"] "<<this->data[i]<<endl;
k=0;
l=0;
}
if(2*i<MAX_SIZE && this->data[2*i]!=-1 && k!=1)
{
i=2*i;
j=0;
l=0;
}
else if (2*i+1<MAX_SIZE && this->data[2*i+1]!=-1 && l!=1)
{
i=2*i+1;
j=0;
k=0;
}
else
{
if(i%2!=0)
{
l=1;
}
else
{
l=0;
}
i=int(i/2);
j=1;
k=1;
}
}
}
bool ArrayBST::isIn(int val)
{
for(int i=1;i<MAX_SIZE;)
{
if(this->data[i]==val)
{
return true;
}
else if (val<this->data[i])
{
i=2*i;
}
else
{
i=2*i+1;
}
}
return false;
}
#endif // ARRAYBST_H
<file_sep>/README.md
# CE2018_40_41_BST
lab
<file_sep>/BST.h
#ifndef BST_H
#define BST_H
class BST
{
public:
virtual void add (int val)=0;
virtual void preorderTraversal()=0;
virtual bool isIn (int val)=0;
};
#endif // BST_H
<file_sep>/linkedBST.h
#include "BST.h"
class Node{
public:
int data;
Node *left;
Node *right;
};
class LinkedBST:public BST{
public:
Node* root;
LinkedBST();
void preorderTraversal();
void add(int data);
void add(Node* &root,int data);
bool isIn(int data);
private:
bool find(Node* &root,int targetKey);
void insert(Node* &subtree, Node* newNode);
void traverse(Node* root);
};
<file_sep>/arrayBST.cpp
#include <iostream>
#include "arrayBST.h"
int main()
{
ArrayBST a;
a.add(5);
a.add(6);
a.add(4);
a.add(10);
a.add(40);
a.add(3);
a.add(2);
a.add(50);
a.add(32);
a.add(69);
a.add(30);
cout<<"-------------------"<<endl;
a.preOrderTraversal();
bool check=a.isIn(40);
if (check==true)
{
cout<<"Data found."<<endl;
}
else
{
cout<<"Data not found."<<endl;
}
return 0;
}
<file_sep>/main.cpp
#include<iostream>
#include"linkedBST.h"
int main(){
std::cout<<"***Binary Tree Linked List Implementation***"<<std::endl;
LinkedBST tree;
//adding datas
tree.add(17);
tree.add(11);
tree.add(41);
tree.add(122);
tree.add(5);
std::cout<<"Pre order traveral: "<<std::endl;
tree.preorderTraversal();
std::cout<<"\nAdding 101: "<<std::endl;
tree.add(101);
std::cout<<"Pre order traveral: "<<std::endl;
tree.preorderTraversal();
std::cout<<std::endl;
std::cout<<"\nIs 11 in data: "<<tree.isIn(11)<<"\n";
std::cout<<"\nIs 13 in data: "<<tree.isIn(13)<<"\n";
} | eccb7b2d7025354e61611d9953421c936f5f91ee | [
"Markdown",
"C++"
] | 6 | C++ | gbshakya/CE2018_40_41_BST | 169766104c100531f313e82656e5d62407299c21 | a7ded38dfda9aa587f7094246ac8a33602d30cff |
refs/heads/master | <file_sep>
import becker.robots.City;
import becker.robots.Direction;
import becker.robots.Robot;
import becker.robots.Thing;
import becker.robots.Wall;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author messr2578
*/
public class A1_q5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//created integers
int moves = 0;
//create a city for the robot
City kw = new City();
//create a robot facing east
Robot Karel = new Robot(kw,3,3,Direction.EAST);
Robot Maria = new Robot(kw,0,1,Direction.WEST);
//label the robots
Karel.setLabel("K");
Maria.setLabel("M");
// create walls
new Wall(kw,2,3,Direction.WEST);
new Wall(kw,2,3,Direction.NORTH);
new Wall(kw,2,3,Direction.EAST);
new Wall(kw,3,3,Direction.EAST);
new Wall(kw,3,3,Direction.SOUTH);
new Thing(kw,0,0);
new Thing(kw,1,0);
new Thing(kw,1,1);
new Thing(kw,1,2);
new Thing(kw,2,2);
//move both the robots to collect the dropped groceries
Karel.turnLeft();
Karel.turnLeft();
Karel.move();
Maria.move();
Maria.pickThing();
Karel.turnLeft();
Karel.turnLeft();
Karel.turnLeft();
Karel.move();
Karel.pickThing();
Maria.turnLeft();
Karel.move();
Maria.move();
Maria.pickThing();
Karel.pickThing();
Maria.turnLeft();
Karel.turnLeft();
Maria.move();
Maria.pickThing();
}
}
<file_sep>
import becker.robots.City;
import becker.robots.Direction;
import becker.robots.Robot;
import becker.robots.Wall;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author messr2578
*/
public class A1_q1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// CREATE INTEGERS
int Rotate = 0;
//create a city for the robot
City kw = new City();
//create a robot facing east
Robot Hans = new Robot(kw,0,2,Direction.WEST);
// create walls
new Wall(kw,1,1,Direction.NORTH);
new Wall(kw,1,2,Direction.NORTH);
new Wall(kw,2,1,Direction.WEST);
new Wall(kw,1,1,Direction.WEST);
new Wall(kw,2,2,Direction.EAST);
new Wall(kw,1,2,Direction.EAST);
new Wall(kw,2,2,Direction.SOUTH);
new Wall(kw,2,1,Direction.SOUTH);
//move robot
Hans.move();
Hans.move();
Hans.turnLeft();
while(Rotate < 3){
Hans.move();
Hans.move();
Hans.move();
Hans.turnLeft();
Rotate = Rotate + 1;
}
Hans.move();
}
}
| 10969dc81470e78811a16868c9c4389b4c4da7bc | [
"Java"
] | 2 | Java | Ryme28/3U-Assignment01 | 189a7b89d4901a0cc14ddad3829ccd39877b3f8c | df8f18cda65486024b8e1a666d580467cfcdf81c |
refs/heads/master | <repo_name>AninHuang/express-ws<file_sep>/server.js
const express = require('express')
const WebSocket = require('ws')
const port = 3000
const server = express().listen(port, () => console.log(`Listening on ${port}`))
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
console.log('Client connected')
ws.on('close', () => {
console.log('Close connected')
})
});<file_sep>/README.md
# express-ws
使用 Web 框架的 Express.js 和 ws(Node.js WebSocket library) 搭建 WebSocket 環境
## Pre-requisites
* [Node.js/npm](https://nodejs.org/en/)
* [express](https://www.npmjs.com/package/express)
* [ws](https://www.npmjs.com/package/ws)
## Example
1) `cd` into the project folder
2) Then run:
```bash
npm i
node server.js
```
| 7c0eedb2ed5aad0a99dbedb3da787c62b5c82dc9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | AninHuang/express-ws | 4ec82302678a06556d4f1acb5cb57b2efc40fd3e | 245f3740e12c33a81fd32514c09e445feda616e1 |
refs/heads/master | <file_sep>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vuee!'
},
methods:{
titleUpperCase(){
this.message=this.message.toUpperCase();
},
titleLowerCase(){
this.message=this.message.toLowerCase();
}
}
})
| 0daa6c09ee04c7a3aa45d1fb40ba2f76a9b56355 | [
"JavaScript"
] | 1 | JavaScript | puneetjyot/VUE_HELLO | 74654f3c3d996ed146660c09783e09be9da5478a | e0e4acf15ec51905c5822da8cb221f28c861a55d |
refs/heads/master | <file_sep>//
// SwiftLibTableViewCell.swift
// SemsterProject9
//
// Created by <NAME> on 5/6/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import UIKit
class SwiftLibTableViewCell: UITableViewCell {
@IBOutlet weak var titleOutlet: UILabel!
@IBOutlet weak var authorOutlet: UILabel!
@IBOutlet weak var scoreOutlet: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// CompletedLibController.swift
// SemsterProject9
//
// Created by <NAME> on 5/14/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class CompletedLibController : UIViewController {
@IBOutlet weak var storyOutlet: UILabel!
@IBOutlet weak var titleOutlet: UILabel!
@IBOutlet weak var scoreOutlet: UILabel!
@IBOutlet weak var voteController: UISegmentedControl!
@IBOutlet weak var authorOutlet: UILabel!
var lib: SwiftLibObj? = nil
var storyText = ""
let rootRef = Database.database().reference()
var selectedFlag = false
override func viewDidLoad() {
super.viewDidLoad()
self.titleOutlet.text = self.lib?.getTitle()
let story = mergeFunction(self.lib!.story, self.lib!.arguments)
for index in 0...story.count-1 {
self.storyText.append(contentsOf: story[index])
}
self.storyOutlet.text = self.storyText
self.storyOutlet.adjustsFontSizeToFitWidth = true
self.titleOutlet.adjustsFontSizeToFitWidth = true
self.scoreOutlet.text = String(self.lib!.getScore())
self.authorOutlet.text = "By: \(String(describing: self.lib!.author))"
}
@IBAction func votePressed(_ sender: Any) {
switch voteController.selectedSegmentIndex
{
case 0:
//adjustScore(direction: false)
self.scoreOutlet.text = String(self.lib!.getScore()-1)
case 1:
//adjustScore(direction: true)
self.scoreOutlet.text = String(self.lib!.getScore()+1)
default:
break
}
}
func adjustScore(direction: Bool) {
if(direction == true) {
let temp = SwiftLibObj(title: self.lib?.title ?? "", author: self.lib?.author ?? "", story: self.lib?.story ?? [], score: self.lib!.score+1, args: self.lib?.arguments ?? [])
saveToFirebase(lib: temp)
} else {
let temp = SwiftLibObj(title: self.lib?.title ?? "", author: self.lib?.author ?? "", story: self.lib?.story ?? [], score: self.lib!.score-1, args: self.lib?.arguments ?? [])
saveToFirebase(lib: temp)
}
}
func saveToFirebase(lib : SwiftLibObj) {
let usersRef = rootRef.child("Users")
let user = usersRef.child(lib.author).child("SwiftLibs")
let values = ["Title":lib.title, "Score": lib.score, "Arguments": lib.arguments, "Story": lib.story] as [String : Any]
user.childByAutoId().setValue(values)
}
func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
var merged = zip(one, two).flatMap { [$0, $1] }
if one.count > commonLength { merged.append(one[commonLength]) }
if two.count > commonLength { merged.append(two[commonLength]) }
return merged
}
}
<file_sep>//
// CompleteSwiftlibController.swift
// SemsterProject9
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class CompleteSwiftlibController : UIViewController {
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var titleOutlet: UITextField!
@IBOutlet weak var bodyOutlet: UILabel!
let rootRef = Database.database().reference()
var lib: SwiftLibObj? = nil
var inputArgs: [String] = []
var storyText = ""
override func viewDidLoad() {
super.viewDidLoad()
showInputDialog()
self.titleOutlet.text = self.lib?.getTitle()
self.bodyOutlet.adjustsFontSizeToFitWidth = true
self.titleOutlet.adjustsFontSizeToFitWidth = true
}
@IBAction func submitPressed(_ sender: Any) {
var username = usernameOutlet.text
if username == "" || username == nil {
username = "Anonymous"
}
let tempLib = SwiftLibObj(title: self.lib!.title, author: username ?? "Anonymous", story: self.lib!.story, score: 0, args: self.inputArgs)
saveToFirebase(lib: tempLib)
let viewController: UINavigationController = self.storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
func saveToFirebase(lib : SwiftLibObj) {
let usersRef = rootRef.child("Users")
let user = usersRef.child(lib.author).child("SwiftLibs")
let values = ["Title":lib.title, "Score": 0, "Arguments": lib.arguments, "Story": lib.story] as [String : Any]
user.childByAutoId().setValue(values)
}
func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
var merged = zip(one, two).flatMap { [$0, $1] }
if one.count > commonLength { merged.append(one[commonLength]) }
if two.count > commonLength { merged.append(two[commonLength]) }
return merged
}
func showInputDialog() {
//Creating UIAlertController and
//Setting title and message for the alert dialog
let alertController = UIAlertController(title: "Complete the blank fields.", message: "Please enter the part of speech for each blank.", preferredStyle: .alert)
//the confirm action taking the inputs
let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in
//getting the input values from user
let num = alertController.textFields?.capacity
for index in 0...num!-1 {
self.inputArgs.append(alertController.textFields![index].text ?? "")
}
let storyElements = self.lib?.getStory() ?? []
let story = self.mergeFunction(storyElements, self.inputArgs)
for index in 0...story.count-1 {
self.storyText.append(contentsOf: story[index])
}
self.bodyOutlet.text = self.storyText
}
//the cancel action doing nothing
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
let viewController: UINavigationController = self.storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
//adding textfields to our dialog box
for value in lib!.arguments {
alertController.addTextField { (textField) in
textField.placeholder = "Enter a \(value)"
}
}
//adding the action to dialogbox
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
//finally presenting the dialog box
self.present(alertController, animated: true, completion: nil)
}
}
<file_sep># SemesterProject9
Group repository for CMSC 436 Semester Project 9
Please remember to git status as it will tell you if there have been any recent changes.
Then, git stash your local changes.
Next, git pull in any changes that have been made since you've last pulled.
Next, git stash pop to retrieve your local changes.
Lastly, git push your changes to the repo.
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '12.2'
target 'SemsterProject9' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for SemsterProject9
pod 'Firebase'
pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Auth'
target 'SemsterProject9Tests' do
inherit! :search_paths
# Pods for testing
end
target 'SemsterProject9UITests' do
inherit! :search_paths
# Pods for testing
end
end
<file_sep>//
// AppImageView.swift
// SemsterProject9
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
import UIKit
class AppImageView: UIImageView {
}
<file_sep>//
// MySwiftLibsController.swift
// SemsterProject9
//
// Created by <NAME> on 5/13/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class MySwiftLibTableViewController: UITableViewController {
let rootRef = Database.database().reference()
var user: String = ""
var swiftLibs: [SwiftLibObj] = []
override func viewDidLoad() {
super.viewDidLoad()
showInputDialog()
print(self.user)
// Do any additional setup after loading the view, typically from a nib.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return swiftLibs.count
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CompletedLibSegue" ,
let nextScene = segue.destination as? CompletedLibController,
let indexPath = self.tableView.indexPathForSelectedRow {
let selectedLib = swiftLibs[indexPath.row]
nextScene.lib = selectedLib
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "SwiftLibTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SwiftLibTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
let lib = swiftLibs[indexPath.row]
cell.authorOutlet.text = "By \(lib.author)"
cell.scoreOutlet.text = String(lib.score)
cell.titleOutlet.text = String(lib.title)
return cell
}
func loadFromFireBase(completionHandler:@escaping (_ libArray: [SwiftLibObj]?)->()) {
if(self.user != "") {
let userRef = rootRef.child("Users").child(self.user).child("SwiftLibs")
var libs:[SwiftLibObj] = []
userRef.observe(.value, with: { (snapshot) in
//let values = snapshot.value as! [String: Any]
for value in snapshot.children {
let snap = value as! DataSnapshot
let values = snap.value as! [String: Any]
let lib = SwiftLibObj(title: values["Title"] as! String, author: self.user, story: values["Story"] as! [String], score: values["Score"] as! Int, args: values["Arguments"] as! [String])
libs.append(lib)
}
if libs.isEmpty {
completionHandler(nil)
}else {
completionHandler(libs)
}
})
}
}
func showInputDialog() {
//Creating UIAlertController and
//Setting title and message for the alert dialog
let alertController = UIAlertController(title: "What Username?", message: "Please enter the Username you would like to filter by.", preferredStyle: .alert)
//the confirm action taking the inputs
let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in
//getting the input values from user
self.user = alertController.textFields?[0].text ?? ""
self.loadFromFireBase { libArray in
let temp = libArray?.sorted(by: { (lib1: SwiftLibObj, lib2: SwiftLibObj) -> Bool in
lib1.getScore() > lib2.getScore()
})
self.swiftLibs = temp ?? []
self.tableView.reloadData()
}
}
//the cancel action doing nothing
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
let viewController: UINavigationController = self.storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
//adding textfields to our dialog box
alertController.addTextField { (textField) in
textField.placeholder = "Enter Username"
}
//adding the action to dialogbox
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
//finally presenting the dialog box
self.present(alertController, animated: true, completion: nil)
}
}
<file_sep>//
// SwiftLibObj.swift
// SemsterProject9
//
// Created by <NAME> on 4/21/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
class SwiftLibObj {
let title: String
let author: String
var score: Int
var arguments : [String]
let story : [String]
init(title: String, author: String, story: [String]) {
self.title = title
self.author = author
self.story = story
self.score = 0
self.arguments = []
}
init(title: String, author: String, story: [String], score: Int) {
self.title = title
self.author = author
self.story = story
self.score = score
self.arguments = []
}
init(title: String, author: String, story: [String], score: Int, args: [String]) {
self.title = title
self.author = author
self.story = story
self.score = score
self.arguments = args
}
//Function to return the title of the obj
func getTitle() -> String {
return self.title
}
//Function to return the author of the obj
func getAuthor() -> String {
return self.author
}
//Function to return the story collection of the obj
func getStory() -> [String] {
return self.story
}
//Function to return the arguments that are being stored in obj
func getArguments() -> [String] {
return self.arguments
}
//Function to add to the arguments that are being stored in obj
func addArguments(arg: [String]) {
self.arguments.append(contentsOf: arg)
}
//Function to add to the score of the obj
func addScore(score : Int) {
self.score += score
}
//Function to remove from the score of the obj
func subtractScore(score : Int) {
self.score -= score
}
//Function to get the score of the obj
func getScore() -> Int {
return self.score
}
//EOF
}
<file_sep>//
// SwiftLibTableViewController.swift
// SemsterProject9
//
// Created by <NAME> on 5/6/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import UIKit
import os.log
import Firebase
class SwiftLibTableViewController: UITableViewController {
var swiftLibs: [SwiftLibObj] = []
let rootRef = Database.database().reference()
var users = [String]()
typealias LibArrayClosure = (Array<SwiftLibObj>?) -> Void
func loadSwiftLibs(){
let lib1 = SwiftLibObj(title: "Long SwiftLib", author: "<NAME>", story: ["I wanted to make this a super long story to show that our project is really ", " and adjusts the text size based on the length of the story. My favorite thing to do is ", " because it is a great activity and makes me feel super great even when I have to wake up early!"], score: 0, args: ["awesome","program"])
let lib2 = SwiftLibObj(title: "Romeo and Juliet", author: "Shakespeare", story: ["There were once two ", " lovers. Their names were Romeo and Juliet. One day they saw ", " which made them ", ". But that is just the beginning of the story..."], score: 5, args: ["crazy", "Paris", "cry"])
let lib3 = SwiftLibObj(title: "My Typical Day", author: "<NAME>", story: ["I usually wake up feeling ", " at around 10 am. Then I go ", " for about 30 minutes before starting my day. Next I have breakfast, usually some ", " bananas. Then I head to my day of classes!"], score: 10, args: ["refreshed","swim", "moldy"])
let tempLibs = [lib1,lib2,lib3]
for lib in tempLibs {
saveToFirebase(lib: lib)
}
swiftLibs = tempLibs
}
func saveToFirebase(lib : SwiftLibObj) {
let usersRef = rootRef.child("Users")
let user = usersRef.child(lib.author).child("SwiftLibs")
let values = ["Title":lib.title, "Score": lib.score, "Arguments": lib.arguments, "Story": lib.story] as [String : Any]
user.childByAutoId().setValue(values)
}
func loadFromFireBase(completionHandler:@escaping (_ libArray: [SwiftLibObj]?)->()) {
let childRef = rootRef.child("Users")
var tempUsers = [String]()
childRef.observe(.value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
var libs: [SwiftLibObj] = []
for user in userDict.keys {
tempUsers.append(user)
}
for user in tempUsers {
let userSnaps = snapshot.childSnapshot(forPath: user).childSnapshot(forPath: "SwiftLibTemplates")
for userSnap in userSnaps.children {
let snap = userSnap as! DataSnapshot
let values = snap.value as! [String: Any]
let lib = SwiftLibObj(title: values["Title"] as! String, author: user, story: values["Story"] as! [String], score: values["Score"] as! Int, args: values["Arguments"] as! [String])
libs.append(lib)
}
}
if libs.isEmpty {
completionHandler(nil)
}else {
completionHandler(libs)
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CompleteSwiftlibSegue" ,
let nextScene = segue.destination as? CompleteSwiftlibController,
let indexPath = self.tableView.indexPathForSelectedRow {
let selectedLib = swiftLibs[indexPath.row]
nextScene.lib = selectedLib
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
//loadSwiftLibs()
loadFromFireBase { libArray in
let temp = libArray?.sorted(by: { (lib1: SwiftLibObj, lib2: SwiftLibObj) -> Bool in
lib1.getScore() > lib2.getScore()
})
self.swiftLibs = temp ?? []
self.tableView.reloadData()
}
tableView.dataSource = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return swiftLibs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "SwiftLibTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? SwiftLibTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
let lib = swiftLibs[indexPath.row]
cell.authorOutlet.text = "By \(lib.author)"
cell.scoreOutlet.text = String(lib.score)
cell.titleOutlet.text = String(lib.title)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
}
<file_sep>//
// CreateSwiftLibController.swift
// SemsterProject9
//
// Created by <NAME> on 5/11/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import Foundation
import UIKit
import Firebase
extension String {
func split(usingRegex pattern: String) -> [String] {
//### Crashes when you pass invalid `pattern`
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: self, range: NSRange(0..<utf16.count))
let ranges = [startIndex..<startIndex] + matches.map{Range($0.range, in: self)!} + [endIndex..<endIndex]
return (0...matches.count).map {String(self[ranges[$0].upperBound..<ranges[$0+1].lowerBound])}
}
}
class CreateSwiftLibController : UIViewController {
var args : [String] = []
@IBOutlet weak var TitleAction: UITextField!
@IBOutlet weak var AuthorAction: UITextField!
@IBOutlet var SwiftLibStory: UITextView!
@IBOutlet weak var ClearButtonOutlet: UIButton!
@IBOutlet weak var SubmitButtonOutlet: UIButton!
@IBOutlet var ActionButtons: [UIButton]!
@IBAction func AdjAction(_ sender: UIButton) {
self.SwiftLibStory.text = self.SwiftLibStory.text + " Adjective "
args.append("Adjective")
}
@IBAction func NounAction(_ sender: UIButton) {
self.SwiftLibStory.text = self.SwiftLibStory.text + " Noun "
args.append("Noun")
}
@IBAction func VerbAction(_ sender: UIButton) {
self.SwiftLibStory.text = self.SwiftLibStory.text + " Verb "
args.append("Verb")
}
let rootRef = Database.database().reference()
func splitStory(story: String) -> [String] {
let str = story
let separator = "(Adjective|Noun|Verb)"
let result = str.split(usingRegex: separator)
return result
}
@IBAction func SubmitSwiftLib(_ sender: Any) {
if let author = AuthorAction.text {
if let title = TitleAction.text {
let temp = SwiftLibObj(title: title, author: author, story: splitStory(story: SwiftLibStory.text), score: 0, args: args)
saveToFirebase(lib: temp)
let viewController: UINavigationController = self.storyboard?.instantiateViewController(withIdentifier: "MainViewController") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
}
}
@IBAction func ClearTextAction(_ sender: Any) {
self.SwiftLibStory.text = ""
}
func saveToFirebase(lib : SwiftLibObj) {
let usersRef = rootRef.child("Users")
let user = usersRef.child(lib.author).child("SwiftLibTemplates")
let values = ["Title":lib.title, "Score": 0, "Arguments": lib.arguments, "Story": lib.story] as [String : Any]
user.childByAutoId().setValue(values)
}
override func viewDidLoad() {
for button in ActionButtons{
button.layer.cornerRadius = 5
button.backgroundColor = UIColor.ThemeColors.OceanBlue
button.layer.borderWidth = 0.5
button.layer.borderColor = UIColor.white.cgColor
button.setTitleColor(UIColor.white, for: UIControl.State.normal)
}
}
}
<file_sep>//
// ViewController.swift
// SemsterProject9
//
// Created by <NAME> on 4/21/19.
// Copyright © 2019 SemesterProject9. All rights reserved.
//
import UIKit
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
class ViewController: UIViewController {
@IBOutlet weak var CreateSwiftButton: UIButton!
@IBOutlet weak var SearchSwiftButton: UIButton!
@IBOutlet weak var BrowseSwiftButton: UIButton!
@IBOutlet var ButtonCollection: [UIButton]!
@IBOutlet weak var AppTitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
CreateSwiftButton.backgroundColor = UIColor.ThemeColors.BlueGreen
SearchSwiftButton.backgroundColor = UIColor.ThemeColors.OceanBlue
BrowseSwiftButton.backgroundColor = UIColor.ThemeColors.PalerBlue
var duration = 0.7
for button in ButtonCollection {
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.white.cgColor
button.setTitleColor(UIColor.darkGray, for: UIControl.State.normal)
/* UIView.animate(withDuration: duration, animations: {
button.frame.size.width += 20
button.frame.size.height += 20
}) {
_ in
UIView.animate(withDuration: duration, delay: 0.10, options: [.curveEaseOut], animations:{ button.frame.origin.y -= 40})
}
duration += 0.3
*/
}
var imageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 80, height: 100))
var image = UIImage(named: "myImage.png")
imageView.image = image
self.view.addSubview(imageView)
self.AppTitleLabel.textColor = UIColor.ThemeColors.TitleColor
self.AppTitleLabel.font = self.AppTitleLabel.font.withSize(60.0)
UIView.animate(withDuration: 1.0, delay: 0.10, options: [.curveEaseIn], animations: {
self.AppTitleLabel.frame.origin.y -= 50
})
}
}
extension UIColor{
struct ThemeColors {
static let OceanBlue = UIColor(red: 177/255, green: 240/255, blue: 242/255, alpha: 1)
static let PalerBlue = UIColor(red: 179/255, green: 223/255, blue: 243/255, alpha: 1)
static let BlueGreen = UIColor(red: 185/255, green: 241/255, blue: 206/255, alpha: 1)
static let TitleColor = UIColor(red: 185/255, green: 170/255, blue: 255/255, alpha: 1)
}
}
| 244702fa57bb91914b9009cec572068aad0e72b1 | [
"Swift",
"Ruby",
"Markdown"
] | 11 | Swift | KeeganBlack/semesterProjectGroup09 | edcc0a1a069f92146d07bb1ea89fe6dfe81f8fcd | c1b4404396f190ca88893fc9e83b4e76bc57208b |
refs/heads/master | <file_sep># koa-example-project<file_sep>/**
* Created by Jacksun on 16/9/8.
*/
'use strict';
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const fs = require('fs');
const isProduction = process.env.NODE_ENV === 'production';
// 创建一个Koa对象表示web app本身:
const app = new Koa();
// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
var start = Date.now(),
execTime;
await next();
execTime = Date.now() - start;
ctx.response.set('X-Response-Time', `${execTime}ms`);
});
if (!isProduction) {
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
}
app.use(bodyParser());
const templating = require('./templating');
app.use(templating('views', {
noCache: !isProduction,
watch: !isProduction
}));
addControllers(router);
// add router middleware
app.use(router.routes());
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');
/**
* Created by Jacksun on 16/9/9.
*/
const model = require('./model');
let
Pet = model.Pet,
User = model.User;
(async () => {
var user = await User.create({
name: 'John',
gender: false,
email: 'john-' + Date.now() + '@garfield.pet',
passwd: '<PASSWORD>'
});
console.log('created: ' + JSON.stringify(user));
var cat = await Pet.create({
ownerId: user.id,
name: 'Garfield',
gender: false,
birth: '2007-07-07',
});
console.log('created: ' + JSON.stringify(cat));
var dog = await Pet.create({
ownerId: user.id,
name: 'Odie',
gender: false,
birth: '2008-08-08',
});
console.log('created: ' + JSON.stringify(dog));
})();
/**
* 添加路由控制器
* @param router
*/
function addControllers(router) {
var files = fs.readdirSync(__dirname + '/controllers');
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + '/controllers/' + f);
addMapping(router, mapping);
}
}
/**
* 添加路由映射
* @param router
* @param mapping
*/
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
| d387dd5596ec50a361eae0a2b88324d6e04c7119 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | yugasun/koa-example-project | 0c588f1e915edb07392f838498089bb4286b8095 | 264bfa5e7177b024e352cc91b9b2bfa502d6e292 |
refs/heads/master | <file_sep>spring.application.name=biblioc-mail
spring.mail.host=smtp.mailtrap.io
spring.mail.port=2525
spring.mail.username=6948fb787f0b08
spring.mail.password=<PASSWORD>
spring.cloud.config.uri=http://localhost:9101
<file_sep>spring.application.name=biblioc-authentification
spring.cloud.config.uri=http://localhost:9101
<file_sep>spring.application.name=biblioc-bibliotheque
spring.cloud.config.uri=http://localhost:9101<file_sep>package fr.biblioc.bibliocauthentification.web.controller;
import fr.biblioc.bibliocauthentification.dao.CompteDao;
import fr.biblioc.bibliocauthentification.dto.CompteDto;
import fr.biblioc.bibliocauthentification.mapper.CompteMapper;
import fr.biblioc.bibliocauthentification.model.Compte;
import fr.biblioc.bibliocauthentification.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocauthentification.web.exceptions.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link Compte}
*/
@RestController
public class CompteController implements HealthIndicator {
//------------------------- ATTRIBUTS -------------------------
@Autowired
CompteDao compteDao;
@Autowired
CompteMapper compteMapper;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Indique le status du microservice
* @return etat du microservice
*/
@Override
public Health health() {
List<Compte> comptes = compteDao.findAll();
if(comptes.isEmpty()) {
return Health.down().build();
}
return Health.up().build();
}
/**
* Affiche la liste de tous les comptes
* @return liste {@link Compte}
*/
@GetMapping(value = "/Comptes")
public List<CompteDto> listeDesComptes(){
List<Compte> comptes = compteDao.findAll();
List<CompteDto> comptesDto = new ArrayList<>();
for (Compte compte : comptes){
comptesDto.add(compteMapper.compteToCompteDto(compte));
}
if(comptes.isEmpty()){
throw new ObjectNotFoundException("Aucun compte n'a été trouvée");
}
log.info("Récupération de la liste des comptesDto");
return comptesDto;
}
/**
* Verifier l'existence un compte par son id
* @param id int
* @return bean {@link Compte}
*/
@GetMapping( value = "/Comptes/existe/{id}")
public boolean isCompte(@PathVariable int id) {
return compteDao.existsById_compte(id);
}
/**
* Récuperer un compte par son id
* @param id int
* @return bean {@link Compte}
*/
@GetMapping( value = "/Comptes/{id}")
public Optional<Compte> recupererUnCompte(@PathVariable int id) {
Optional<Compte> compte = compteDao.findById(id);
if(!compte.isPresent()) throw new ObjectNotFoundException("L'compte correspondant à l'id " + id + " n'existe pas");
return compte;
}
/**
* Récuperer un compte par son email
* @param email String
* @return bean {@link Compte}
*/
@GetMapping( value = "/Comptes_mail/{email}")
public Compte recupererUnCompte(@PathVariable String email) {
Compte compte = compteDao.findByEmail(email);
return compte;
}
/**
* Ajouter un compte
* @param compte bean {@link Compte}
* @return ResponseEntity Compte renvoi un http status.
*/
@PostMapping(value = "/Comptes")
public ResponseEntity<Compte> newCompte(@RequestBody Compte compte){
Compte newCompte = compteDao.save(compte);
if(newCompte == null) throw new ErrorAddException("Impossible d'ajouter ce compte");
return new ResponseEntity<Compte>(compte, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour un compte existant.
* @param compte bean {@link Compte}
**/
@PutMapping(value = "/Comptes")
public void updateCompte(@RequestBody Compte compte) {
System.out.println("compte" + compte);
compteDao.save(compte);
}
}<file_sep>package fr.biblioc.mail.mail;
import fr.biblioc.mail.model.PrereservationDispoData;
import freemarker.template.TemplateException;
import java.io.IOException;
/**
* Interface Generateur mail
*/
public interface MailContentGenerator {
String generate(PrereservationDispoData prereservationDispoData) throws TemplateException, IOException;
}
<file_sep>package fr.biblioc.bibliocreservation.dao;
import fr.biblioc.bibliocreservation.model.Reservation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ReservationDao extends JpaRepository<Reservation, Integer> {
@Query(value = "SELECT * FROM reservation WHERE id_compte = :id_compte", nativeQuery = true)
List<Reservation> findAllById_compte(@Param("id_compte") int id_compte);
List<Reservation> findAllByRenduFalse();
}
<file_sep>CREATE SEQUENCE public.liste_attente_id_liste_attente_seq_1;
CREATE TABLE public.liste_attente (
id_liste_attente INTEGER NOT NULL DEFAULT nextval('public.liste_attente_id_liste_attente_seq_1'),
id_biblio INTEGER NOT NULL,
id_livre INTEGER NOT NULL,
CONSTRAINT liste_attente_pk PRIMARY KEY (id_liste_attente)
);
ALTER SEQUENCE public.liste_attente_id_liste_attente_seq_1 OWNED BY public.liste_attente.id_liste_attente;
CREATE SEQUENCE public.prereservation_id_prereservation_seq;
CREATE TABLE public.prereservation (
id_prereservation INTEGER NOT NULL DEFAULT nextval('public.prereservation_id_prereservation_seq'),
id_compte INTEGER NOT NULL,
date DATE NOT NULL,
id_liste_attente INTEGER,
expire BOOLEAN NOT NULL,
CONSTRAINT prereservation_pk PRIMARY KEY (id_prereservation)
);
ALTER SEQUENCE public.prereservation_id_prereservation_seq OWNED BY public.prereservation.id_prereservation;
ALTER TABLE public.liste_attente ADD CONSTRAINT bibliotheque_liste_attente_fk
FOREIGN KEY (id_biblio)
REFERENCES public.bibliotheque (id_biblio)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE public.liste_attente ADD CONSTRAINT livre_liste_attente_fk
FOREIGN KEY (id_livre)
REFERENCES public.livre (id_livre)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE public.prereservation ADD CONSTRAINT liste_attente_prereservation_fk
FOREIGN KEY (id_liste_attente)
REFERENCES public.liste_attente (id_liste_attente)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE public.prereservation ADD CONSTRAINT compte_prereservation_fk
FOREIGN KEY (id_compte)
REFERENCES public.compte (id_compte)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;<file_sep>package fr.biblioc.bibliocclientUi.proxies;
import fr.biblioc.bibliocclientUi.beans.mail.PrereservationDispoDataBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/**
* Proxy du microservice reservation.
*/
@FeignClient(name = "biblioc-mail", url = "localhost:9007")
public interface BibliocMailProxy {
@PostMapping(value = "/sendMailPrereservation")
ResponseEntity sendMailPrereservation(@RequestBody PrereservationDispoDataBean prereservationDispoData);
}
<file_sep>package fr.biblioc.bibliocclientUi.controller;
import fr.biblioc.bibliocclientUi.beans.authentification.CompteBean;
import fr.biblioc.bibliocclientUi.beans.reservation.BibliothequeBean;
import fr.biblioc.bibliocclientUi.proxies.BibliocReservationProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Controller de la page d'accueil
*/
@Controller
public class ClientController {
//------------------------- PARAMETRE -------------------------
@Autowired
private BibliocReservationProxy reservationProxy;
//------------------------- METHODE -------------------------
/**
* Reuquete de la page d'accueil
* @param request
* @param redirectAttributes
* @return page d'accueil
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView accueilConnecte(HttpServletRequest request, RedirectAttributes redirectAttributes) {
ModelAndView modelAndView = new ModelAndView("accueil");
List<BibliothequeBean> bibliotheques = reservationProxy.listBibliotheques();
modelAndView.addObject("bibliotheques", bibliotheques);
CompteBean compte = (CompteBean)request.getSession().getAttribute("compte");
modelAndView.addObject("compte", compte);
return modelAndView;
}
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller;
import fr.biblioc.bibliocreservation.dao.ExemplaireDao;
import fr.biblioc.bibliocreservation.dto.ExemplaireDto;
import fr.biblioc.bibliocreservation.mapper.ExemplaireMapper;
import fr.biblioc.bibliocreservation.model.Exemplaire;
import fr.biblioc.bibliocreservation.web.exceptions.ErrorAddException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link Exemplaire}
*/
@RestController
public class ExemplaireController implements HealthIndicator {
//------------------------- ATTRIBUTS -------------------------
@Autowired
ExemplaireDao exemplaireDao;
@Autowired
ExemplaireMapper exemplaireMapper;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Indique le status du microservice
* @return etat du microservice
*/
@Override
public Health health() {
List<Exemplaire> exemplaires = exemplaireDao.findAll();
if(exemplaires.isEmpty()) {
return Health.down().build();
}
return Health.up().build();
}
/**
* Affiche la liste de tous les exemplaires
* @return liste de {@link Exemplaire}
*/
@GetMapping(value = "/Exemplaires")
public List<ExemplaireDto> listeDesExemplaires(){
List<Exemplaire> exemplaires = exemplaireDao.findAll();
return getExemplaireDtos(exemplaires);
}
/**
* Verifier l'existence un exemplaire par son id
* @param id int
* @return bean {@link Exemplaire}
*/
@GetMapping( value = "/Exemplaires/existe/{id}")
public boolean isExemplaire(@PathVariable int id) {
return exemplaireDao.existsById_exemplaire(id);
}
/**
* Retourne le nombre d'exemplaire présent du livre dans cette bibliothèque
* @param id_livre int
* @param id_biblio int
* @return int nbre exemplaire
*/
@GetMapping( value = "/Exemplaires/count/{id_livre}/{id_biblio}")
public int exemplaireCount(@PathVariable("id_livre") int id_livre,@PathVariable("id_biblio") int id_biblio){
return exemplaireDao.nbreExemplaire(id_livre, id_biblio);
}
@GetMapping(value = "/exemplaireDispo/{id_livre}/{id_bibliotheque}")
public List<Exemplaire> exemplaireDispo(@PathVariable("id_livre") int id_livre,@PathVariable("id_bibliotheque") int id_biblio) {
return exemplaireDao.exemplaireDispoByIdLivreAndIdBiblio(id_livre, id_biblio);
}
/**
* Récuperer un exemplaire par son id
* @param id int
* @return bean {@link Exemplaire}
*/
@GetMapping( value = "/Exemplaires/{id}")
public ExemplaireDto recupererUnExemplaire(@PathVariable int id) {
Optional<Exemplaire> exemplaire = exemplaireDao.findById(id);
return getExemplaireDto(exemplaire);
}
/**
* Récuperer un exemplaire par son id
* @param id int
* @return bean {@link Exemplaire}
*/
@GetMapping( value = "/Exemplaires-livre/{id}")
public List<ExemplaireDto> recupererExemplairesByIdLivre(@PathVariable int id) {
List<Exemplaire> exemplaires = exemplaireDao.findAllById_livre(id);
return getExemplaireDtos(exemplaires);
}
/**
* Récuperer un exemplaire par son id
* @param id int
* @return bean {@link Exemplaire}
*/
@GetMapping( value = "/Exemplaires-livre-dispo/{id}")
public List<ExemplaireDto> recupererExemplairesByIdLivreDispo(@PathVariable int id) {
List<Exemplaire> exemplaires = exemplaireDao.findAllById_livre(id);
List<Exemplaire> exemplairesDispo = new ArrayList<>();
for (Exemplaire exemplaire : exemplaires){
if(exemplaire.isDisponible()){
exemplairesDispo.add(exemplaire);
}
}
return getExemplaireDtos(exemplairesDispo);
}
@GetMapping( value = "/Exemplaires-livre")
public List<ExemplaireDto> multiCrit(String multicrit) {
log.info(multicrit);
Integer id_auteur = 0;
Integer id_genre = 0;
Integer id_biblio = 0;
List<String> output = Arrays.asList(multicrit.split("_"));
for (int i = 0; i < output.size(); i++) {
if (output.get(i).equals("idAuteur")) {
id_auteur = Integer.parseInt(output.get(i + 1));
log.info("id_auteur : " + id_auteur);
} else if (output.get(i).equals("idGenre")) {
id_genre = Integer.parseInt(output.get(i + 1));
log.info("id_genre : " + id_genre);
} else if (output.get(i).equals("idBiblio")) {
id_biblio = Integer.parseInt(output.get(i + 1));
log.info("id_biblio : " + id_biblio);
}
}
List<Exemplaire> exemplaires = exemplaireDao.multiCrit(id_auteur, id_genre, id_biblio);
return getExemplaireDtos(exemplaires);
}
/**
* Ajouter un exemplaire
* @param exemplaire bean {@link Exemplaire}
* @return ResponseEntity Exemplaire renvoi un http status.
*/
@PostMapping(value = "/Exemplaires")
public ResponseEntity<Exemplaire> addExemplaire(Exemplaire exemplaire){
Exemplaire newExemplaire = exemplaireDao.save(exemplaire);
if(newExemplaire == null) throw new ErrorAddException("Impossible d'ajouter cet exemplaire");
return new ResponseEntity<Exemplaire>(exemplaire, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour un exemplaire existant.
* @param exemplaire bean {@link Exemplaire}
**/
@PutMapping(value = "/Exemplaires")
public void updateExemplaire(@RequestBody Exemplaire exemplaire) {
exemplaireDao.save(exemplaire);
}
//------------------------- METHODE INTERNE-------------------------
/**
* transforme un objet exemplaire en exemplaireDto
* @param exemplaire ENTITY
* @return exemplaireDto DTO
*/
private ExemplaireDto getExemplaireDto(Optional<Exemplaire> exemplaire) {
ExemplaireDto exemplaireDto = null;
if(exemplaire.isPresent()) {
exemplaireDto = exemplaireMapper.exemplaireToExemplaireDto(exemplaire.get());
log.info("ExemplaireDto : " + exemplaireDto);
}
return exemplaireDto;
}
/**
* transforme un objet exemplaireDto en exemplaire
* @param exemplaireDto DTO
* @return exemplaire ENTITY
*/
public Exemplaire getExemplaireFromDto(ExemplaireDto exemplaireDto) {
Exemplaire exemplaire = exemplaireMapper.exemplaireDtoToExemplaire(exemplaireDto);
log.info("Exemplaire : " + exemplaire);
return exemplaire;
}
/**
* transforme une list d'objet exemplaire en exemplaireDto
* @param exemplaires ENTITY
* @return exemplairesDto DTO
*/
private List<ExemplaireDto> getExemplaireDtos(List<Exemplaire> exemplaires) {
List<ExemplaireDto> exemplairesDto = new ArrayList<>();
if(!exemplaires.isEmpty()){
for (Exemplaire exemplaire : exemplaires){
exemplairesDto.add(exemplaireMapper.exemplaireToExemplaireDto(exemplaire));
}
}
log.info("List<ExemplaireDto> : " + exemplairesDto);
return exemplairesDto;
}
}
<file_sep>spring.application.name=biblioc-batch
spring.cloud.config.uri=http://localhost:9101
<file_sep>package fr.biblioc.utilisateur.configurations;
public class SleuthConfig {
}
<file_sep>package fr.biblioc.bibliocclientUi.beans.reservation;
import fr.biblioc.bibliocclientUi.beans.utilisateur.UtilisateurBean;
import javax.validation.constraints.NotNull;
import java.sql.Date;
/**
* Bean Reservation coté client
*/
public class ReservationBean {
//------------------------- ATTRIBUTS -------------------------
private int id_reservation;
private String id_view_reservation;
@NotNull
private int id_utilisateur;
private UtilisateurBean utilisateur;
@NotNull
private Date date_emprunt;
private Date date_retour;
@NotNull
private Boolean extension;
@NotNull
private Boolean rendu;
/*
BUGFIX correction du bug de prolongation d'un prêt si la date de fin de prêt est dépassée.
*/
private boolean extension_possible;
@NotNull
private ExemplaireBean exemplaire;
private String id_view_exemplaire;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public ReservationBean() {
}
/**
* constructeur avec parametres
* @param id_utilisateur int
* @param date_emprunt Date
* @param exemplaire ExemplaireBean
*/
public ReservationBean(@NotNull int id_utilisateur, @NotNull Date date_emprunt, @NotNull ExemplaireBean exemplaire) {
this.id_utilisateur = id_utilisateur;
this.date_emprunt = date_emprunt;
this.extension = false;
this.exemplaire = exemplaire;
this.rendu = false;
}
//------------------------- METHODE -------------------------
public String formatId(int id){
String format = ("00000000" + id).substring(String.valueOf(id).length());
return format;
}
//------------------------- GETTER/SETTER -------------------------
public int getId_reservation() {
return id_reservation;
}
public void setId_reservation(int id_reservation) {
this.id_reservation = id_reservation;
}
public String getId_view_reservation() {
return id_view_reservation;
}
public void setId_view_reservation(String id_view_reservation) {
this.id_view_reservation = id_view_reservation;
}
public int getId_utilisateur() {
return id_utilisateur;
}
public void setId_utilisateur(int id_utilisateur) {
this.id_utilisateur = id_utilisateur;
}
public Date getDate_emprunt() {
return date_emprunt;
}
public void setDate_emprunt(Date date_emprunt) {
this.date_emprunt = date_emprunt;
}
public Date getDate_retour() {
return date_retour;
}
public void setDate_retour(Date date_retour) {
this.date_retour = date_retour;
}
public Boolean getExtension() {
return extension;
}
public void setExtension(Boolean extension) {
this.extension = extension;
}
public Boolean getRendu() {
return rendu;
}
public void setRendu(Boolean rendu) {
this.rendu = rendu;
}
public boolean isExtension_possible() {
return extension_possible;
}
public void setExtension_possible(boolean extension_possible) {
this.extension_possible = extension_possible;
}
public ExemplaireBean getExemplaire() {
return exemplaire;
}
public void setExemplaire(ExemplaireBean exemplaire) {
this.exemplaire = exemplaire;
}
public UtilisateurBean getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(UtilisateurBean utilisateur) {
this.utilisateur = utilisateur;
}
public String getId_view_exemplaire() {
return id_view_exemplaire;
}
public void setId_view_exemplaire(String id_view_exemplaire) {
this.id_view_exemplaire = id_view_exemplaire;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "ReservationBean{" +
", id_utilisateur=" + id_utilisateur +
", date_emprunt=" + date_emprunt +
", extension=" + extension +
", rendu=" + rendu +
", exemplaire=" + exemplaire +
'}';
}
}
<file_sep>spring.application.name=biblioc-reservation
spring.cloud.config.uri=http://localhost:9101
<file_sep>package fr.biblioc.bibliocclientUi.beans.reservation;
import fr.biblioc.bibliocclientUi.beans.utilities.ErrorAddException;
import fr.biblioc.bibliocclientUi.beans.utilities.ObjectNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class ListeAttenteBean {
//------------------------- ATTRIBUTS -------------------------
private int id_liste_attente;
private int nbreExemplaire;
private List<PreReservationBean> preReservationList;
private int id_livre;
private int id_bibliotheque;
//------------------------- CONSTRUCTEUR -------------------------
public ListeAttenteBean(){
preReservationList = new ArrayList<PreReservationBean>();
}
//------------------------- METHODES -------------------------
/**
* La liste de réservation ne peut comporter qu’un maximum de personnes correspondant à 2x le nombre d’exemplaires de l’ouvrage.
* @param preReservation
*/
public void addToList(PreReservationBean preReservation) throws ErrorAddException {
if(preReservationList.size() >= nbreExemplaire*2){
preReservationList.add(preReservation);
}
else {
throw new ErrorAddException("la liste de réservation est pleine");
}
}
public void delToList(PreReservationBean preReservation) throws ObjectNotFoundException {
if(preReservationList.contains(preReservation)){
preReservationList.remove(preReservation);
}
else{
throw new ObjectNotFoundException("la préreservation n'existe pas dans la liste");
}
}
public int getSizeListAttente(){
int sizeListAttente = 0;
if(nbreExemplaire != 0){
int nbrePreReserv = getPreReservationList().size();
sizeListAttente = nbreExemplaire * 2 - nbrePreReserv;
}
return sizeListAttente;
}
public int getnbrePrereservation(){
return preReservationList.size();
}
//------------------------- GETTER/SETTER -------------------------
public int getId_liste_attente() {
return id_liste_attente;
}
public void setId_liste_attente(int id_liste_attente) {
this.id_liste_attente = id_liste_attente;
}
public int getNbreExemplaire() {
return nbreExemplaire;
}
public void setNbreExemplaire(int nbreExemplaire) {
this.nbreExemplaire = nbreExemplaire;
}
public List<PreReservationBean> getPreReservationList() {
return preReservationList;
}
public void setPreReservationList(List<PreReservationBean> preReservationList) {
this.preReservationList = preReservationList;
}
public int getId_livre() {
return id_livre;
}
public void setId_livre(int id_livre) {
this.id_livre = id_livre;
}
public int getId_bibliotheque() {
return id_bibliotheque;
}
public void setId_bibliotheque(int id_bibliotheque) {
this.id_bibliotheque = id_bibliotheque;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "ListeAttente{" +
"id_liste_attente=" + id_liste_attente +
", nbreExemplaire=" + nbreExemplaire +
", preReservationList=" + preReservationList +
", id_livre='" + id_livre + '\'' +
", id_bibliotheque=" + id_bibliotheque +
'}';
}
}
<file_sep>package fr.biblioc.mail.mail;
import javax.mail.MessagingException;
/**
* Interface d'envoie de mail
*/
public interface MailSenderService {
void send(String mailDestination,String titre, String content) throws MessagingException;
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller;
import fr.biblioc.bibliocreservation.dao.BibliothequeDao;
import fr.biblioc.bibliocreservation.dto.BibliothequeDto;
import fr.biblioc.bibliocreservation.mapper.BibliothequeMapper;
import fr.biblioc.bibliocreservation.model.Bibliotheque;
import fr.biblioc.bibliocreservation.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocreservation.web.exceptions.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link Bibliotheque}
*/
@RestController
public class BibliothequeController implements HealthIndicator {
//------------------------- ATTRIBUTS -------------------------
@Autowired
BibliothequeDao bibliothequeDao;
@Autowired
BibliothequeMapper bibliothequeMapper;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Indique le status du microservice
* @return etat du microservice
*/
@Override
public Health health() {
List<Bibliotheque> bibliotheques = bibliothequeDao.findAll();
if(bibliotheques.isEmpty()) {
return Health.down().build();
}
return Health.up().build();
}
/**
* Affiche la liste de toutes les bibliotheques
* @return liste de {@link Bibliotheque}
*/
@GetMapping(value = "/Bibliotheques")
public List<BibliothequeDto> listeDesBibliotheques(){
List<Bibliotheque> bibliotheques = bibliothequeDao.findAll();
List<BibliothequeDto> bibliothequesDto = new ArrayList<>();
if(!bibliotheques.isEmpty()){
for(Bibliotheque bibliotheque : bibliotheques){
bibliothequesDto.add(bibliothequeMapper.bibliothequeToBibliothequeDto(bibliotheque));
}
}
log.info("Récupération de la liste des DTO bibliotheques");
return bibliothequesDto;
}
/**
* Récuperer une bibliotheque par son id
* @param id int
* @return bean {@link Bibliotheque}
*/
@GetMapping( value = "/Bibliotheques/{id}")
public BibliothequeDto recupererUneBibliotheque(@PathVariable int id) {
Optional<Bibliotheque> bibliotheque = bibliothequeDao.findById(id);
BibliothequeDto bibliothequeDto = null;
if(bibliotheque.isPresent()){
bibliothequeDto = bibliothequeMapper.bibliothequeToBibliothequeDto(bibliotheque.get());
log.info(bibliothequeDto.toString());
}
return bibliothequeDto;
}
/**
* Ajouter une bibliotheque
* @param bibliotheque bean {@link Bibliotheque}
* @return ResponseEntity Bibliotheque renvoi un http status.
*/
@PostMapping(value = "/Bibliotheques")
public ResponseEntity<Bibliotheque> addBibliotheque(Bibliotheque bibliotheque){
Bibliotheque newBibliotheque = bibliothequeDao.save(bibliotheque);
if(newBibliotheque == null) throw new ErrorAddException("Impossible d'ajouter ce bibliotheque");
return new ResponseEntity<Bibliotheque>(bibliotheque, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour un bibliotheque existant.
* @param bibliotheque bean {@link Bibliotheque}
**/
@PutMapping(value = "/Bibliotheques")
public void updateBibliotheque(@RequestBody Bibliotheque bibliotheque) {
bibliothequeDao.save(bibliotheque);
}
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller;
import fr.biblioc.bibliocreservation.dao.PreReservationDao;
import fr.biblioc.bibliocreservation.dto.PreReservationDto;
import fr.biblioc.bibliocreservation.mapper.PreReservationMapper;
import fr.biblioc.bibliocreservation.model.PreReservation;
import fr.biblioc.bibliocreservation.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocreservation.web.exceptions.FunctionalException;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link PreReservation}
*/
@RestController
public class PreReservationController {
//------------------------- ATTRIBUTS -------------------------
@Autowired
PreReservationDao preReservationDao;
@Autowired
PreReservationMapper preReservationMapper;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Affiche la liste de toutes les preReservations
* @return liste de {@link PreReservation}
*/
@GetMapping(value = "/PreReservations")
public List<PreReservationDto> listeDesPreReservations() {
List<PreReservationDto> preReservationDtoList = null;
List<PreReservation> preReservations = getPrereservationDao();
try {
preReservationDtoList = getPreReservationDtos(preReservations);
} catch (FunctionalException e) {
e.printStackTrace();
}
return preReservationDtoList;
}
@NotNull
protected List<PreReservation> getPrereservationDao() {
return preReservationDao.findAll();
}
/**
* Affiche la liste de toutes les preReservations d'un utilisateur
* @return liste de {@link PreReservation}
*/
@GetMapping(value = "/PreReservations/{id_compte}")
public List<PreReservationDto> listPreReservationsByIdUser(@PathVariable int id_compte){
List<PreReservationDto> preReservationDtoList = null;
List<PreReservation> preReservations = getPrereservationDaoById_compte(id_compte);
try {
preReservationDtoList = getPreReservationDtos(preReservations);
} catch (FunctionalException e) {
e.printStackTrace();
}
return preReservationDtoList;
}
@NotNull
protected List<PreReservation> getPrereservationDaoById_compte(int id_compte) {
return preReservationDao.findAllById_compte(id_compte);
}
/**
* Récuperer une preReservation par son id
* @param id_preReservation int
* @return bean {@link PreReservation}
*/
@GetMapping( value = "/PreReservation/{id_preReservation}")
public PreReservationDto preReservationbyId(@PathVariable int id_preReservation) {
Optional<PreReservation> preReservation = preReservationDao.findById(id_preReservation);
return getPreReservationDto(preReservation);
}
/**
* Ajouter une preReservation
* @param preReservation bean {@link PreReservation}
* @return ResponseEntity PreReservation renvoi un http status.
*/
@PostMapping(value = "/PreReservation")
public ResponseEntity<PreReservation> addPreReservation(@RequestBody PreReservation preReservation){
System.out.println(preReservation.toString());
if(preReservation == null) {
throw new ErrorAddException("Impossible d'ajouter cette preReservation");
} else {
preReservationDao.save(preReservation);
}
return new ResponseEntity<PreReservation>(preReservation, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour un preReservation existant.
* @param preReservation bean {@link PreReservation}
**/
@PutMapping(value = "/PreReservation")
public void updatePreReservation(@RequestBody PreReservation preReservation) {
preReservationDao.save(preReservation);
}
@PostMapping(value = "/Prereservation/checkAcceptationDuration")
public void checkAcceptationDuration(){
getExpiredMailSendPreReservation();
}
//------------------------- METHODE INTERNE-------------------------
public List<PreReservation> getExpiredMailSendPreReservation(){
List<PreReservation> preReservations = preReservationDao.findAllByNotExpired();
List<PreReservation> preReservationsChecked = new ArrayList<>();
for (PreReservation preReservation : preReservations){
if(expirationDateCheck((Date) preReservation.getDatePreReservation())){
preReservationsChecked.add(preReservation);
}
}
return preReservationsChecked;
}
public boolean expirationDateCheck(Date date){
LocalDate localDate = LocalDate.now().minusDays(2);
if(date.after(Date.valueOf(localDate))){
return false;
} else {
return true;
}
}
/**
* transforme un objet preReservation en preReservationDto
* @param preReservation ENTITY
* @return preReservationDto DTO
*/
protected PreReservationDto getPreReservationDto(Optional<PreReservation> preReservation) {
PreReservationDto preReservationDto = null;
if(preReservation.isPresent()) {
preReservationDto = preReservationMapper.preReservationToPreReservationDto(preReservation.get());
log.info("PreReservationDto : " + preReservationDto);
}
return preReservationDto;
}
/**
* transforme une list d'objet preReservation en preReservationDto
* @param preReservations ENTITY
* @return preReservationsDto DTO
*/
public List<PreReservationDto> getPreReservationDtos(List<PreReservation> preReservations) throws FunctionalException {
List<PreReservationDto> preReservationsDto = new ArrayList<>();
if ( preReservations.isEmpty() ) {
throw new FunctionalException("la liste est vide");
} else {
for (PreReservation preReservation : preReservations) {
preReservationsDto.add( preReservationMapper.preReservationToPreReservationDto(preReservation) );
}
}
log.info("List<PreReservationDto> : " + preReservationsDto);
return preReservationsDto;
}
//------------------------- SETTER -------------------------
public void setPreReservationDao(PreReservationDao preReservationDao) {
this.preReservationDao = preReservationDao;
}
public void setPreReservationMapper(PreReservationMapper preReservationMapper) {
this.preReservationMapper = preReservationMapper;
}
}
<file_sep>package fr.biblioc.bibliocbibliotheque.dto;
/**
* Dto editeur
*/
public class EditeurDto {
//------------------------- ATTRIBUTS -------------------------
private int id_editeur;
private String nom;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public EditeurDto() {
}
/**
* constructeur avec parametres
* @param nom string
*/
public EditeurDto(String nom) {
this.nom = nom;
}
//------------------------- GETTER/SETTER -------------------------
public int getid_editeur() {
return id_editeur;
}
public void setid_editeur(int id_editeur) {
this.id_editeur = id_editeur;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Editeur{" +
"id_editeur=" + id_editeur +
", nom='" + nom + '\'' +
'}';
}
}
<file_sep>package fr.biblioc.bibliocreservation.custom;
import javax.inject.Inject;
import javax.inject.Named;
/**
* Objet permettant l'injections des DAO
*/
@Named("daoFactory")
public class DaoFactoryImpl implements DaoFactory {
@Inject
ReservationExpireDao reservationExpireDaoImpl;
@Override
public ReservationExpireDao getReservationExpireDao() {
return reservationExpireDaoImpl;
}
@Override
public void setReservationExpireDao(ReservationExpireDao reservationExpireDao) {
this.reservationExpireDaoImpl = reservationExpireDao;
}
}
<file_sep>package fr.biblioc.bibliocreservation.mapper;
import fr.biblioc.bibliocreservation.custom.ReservationExpire;
import fr.biblioc.bibliocreservation.dto.ReservationExpireDto;
import org.mapstruct.Mapper;
/**
* Mapper mapstruct de l'Entity au DTO et l'inverse
*/
@Mapper(componentModel = "spring")
public interface ReservationExpireMapper {
ReservationExpireDto reservationExpireToReservationExpireDto(ReservationExpire reservationExpire);
ReservationExpire reservationExpireDtoToReservationExpire(ReservationExpireDto reservationExpireDto);
}<file_sep>package fr.biblioc.bibliocbatch.configurations;
import fr.biblioc.bibliocbatch.listener.JobCompletionNotificationListener;
import fr.biblioc.bibliocbatch.mail.MailContentGenerator;
import fr.biblioc.bibliocbatch.mail.MailContentGeneratorImpl;
import fr.biblioc.bibliocbatch.mail.ReservationExpireMailSenderService;
import fr.biblioc.bibliocbatch.mail.ReservationExpireMailSenderServiceImpl;
import fr.biblioc.bibliocbatch.model.ReservationExpire;
import fr.biblioc.bibliocbatch.processor.ReservationExpireItemProcessor;
import fr.biblioc.bibliocbatch.writer.ReservationExpireItemWriter;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.json.JacksonJsonObjectReader;
import org.springframework.batch.item.json.JsonItemReader;
import org.springframework.batch.item.json.builder.JsonItemReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.javamail.JavaMailSender;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Classe de configuration de spring batch avec les beans de job step reader et writer
*/
@Configuration
@EnableBatchProcessing
public class SpringBatchConfig {
//------------------------- ATTRIBUT -------------------------
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
JavaMailSender javaMailSender;
@Autowired
private freemarker.template.Configuration config;
private static final Logger log = LoggerFactory.getLogger(SpringBatchConfig.class);
//------------------------- BEAN -------------------------
/**
* Reader json
* @return JsonItemReaderBuilder de ReservationExpire
* @throws MalformedURLException
*/
@Bean
@StepScope
public JsonItemReader<ReservationExpire> reservationExpireItemReader() throws MalformedURLException {
URL resource = new URL("http://localhost:9003//Reservations/expire");
return new JsonItemReaderBuilder<ReservationExpire>()
.name("reservationItemReader")
.resource(new UrlResource(resource))
.jsonObjectReader(new JacksonJsonObjectReader<>(ReservationExpire.class))
.build();
}
@Bean
public ReservationExpireItemProcessor processor() {
return new ReservationExpireItemProcessor();
}
@Bean
public MailContentGenerator mailContentGenerator(final freemarker.template.Configuration conf)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
return new MailContentGeneratorImpl(conf);
}
@Bean
public ReservationExpireMailSenderService planningMailSenderService(final JavaMailSender javaMailSender) {
return new ReservationExpireMailSenderServiceImpl(javaMailSender);
}
@Bean
public ReservationExpireItemWriter reservationExpireItemWriter(final ReservationExpireMailSenderService reservationExpireService,
final MailContentGenerator mailContentGenerator) {
return new ReservationExpireItemWriter(reservationExpireService, mailContentGenerator);
}
@Bean
public Step step1(ItemWriter<ReservationExpire> reservationExpireItemWriter) throws MalformedURLException {
return stepBuilderFactory.get("step1")
.<ReservationExpire, ReservationExpire>chunk(10)
.reader(reservationExpireItemReader())
.processor(processor())
.writer(reservationExpireItemWriter)
.build();
}
@Bean
public Job importReservationExpireJob(JobCompletionNotificationListener listener, Step step1) {
return jobBuilderFactory.get("importReservationExpireJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
}
<file_sep>spring.application.name=biblioc-clientui
spring.cloud.config.uri=http://localhost:9101
<file_sep>package fr.biblioc.bibliocreservation.custom;
import java.util.List;
/**
* Dao de la classe ReservationExpire
*/
public interface ReservationExpireDao {
List<ReservationExpire> readAll();
}
<file_sep>package fr.biblioc.bibliocbatch.writer;
import fr.biblioc.bibliocbatch.mail.MailContentGenerator;
import fr.biblioc.bibliocbatch.mail.ReservationExpireMailSenderService;
import fr.biblioc.bibliocbatch.model.ReservationExpire;
import org.springframework.batch.item.ItemWriter;
import java.util.List;
/**
* ItemWriter permetant la génération de contenu et l'envoi de mail
*/
public class ReservationExpireItemWriter implements ItemWriter<ReservationExpire> {
private final ReservationExpireMailSenderService reservationExpireService;
private final MailContentGenerator mailContentGenerator;
public ReservationExpireItemWriter(final ReservationExpireMailSenderService reservationExpireService,
final MailContentGenerator mailContentGenerator) {
super();
this.reservationExpireService = reservationExpireService;
this.mailContentGenerator = mailContentGenerator;
}
@Override
public void write(List<? extends ReservationExpire> reservations) throws Exception {
for (ReservationExpire reservation : reservations) {
String content = mailContentGenerator.generate(reservation);
reservationExpireService.send(reservation.getEmail(), content);
}
}
}
<file_sep>package fr.biblioc.bibliocclientUi.proxies;
import fr.biblioc.bibliocclientUi.beans.utilisateur.AdresseBean;
import fr.biblioc.bibliocclientUi.beans.utilisateur.UtilisateurBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Proxy du microservice utilisateur.
*/
@FeignClient(name = "biblioc-utilisateur", url = "localhost:9004")
public interface BibliocUtilisateurProxy {
@GetMapping(value = "/Utilisateurs")
List<UtilisateurBean> listUtilisateurs();
@GetMapping( value = "/Utilisateurs-last")
int recupererLeDernierUtilisateur();
@GetMapping(value = "/Utilisateurs/{id}")
UtilisateurBean getUtilisateur(@PathVariable("id") int id);
@PostMapping(value = "/Utilisateurs")
UtilisateurBean newUtilisateur(@RequestBody UtilisateurBean utilisateur);
@PutMapping(value = "/Utilisateurs")
UtilisateurBean updateUtilisateur(@RequestBody UtilisateurBean utilisateur);
@GetMapping(value = "/Adresses/{id}")
AdresseBean getAdresse(@PathVariable("id") int id);
@PostMapping(value = "/Adresses")
AdresseBean newAdresse(@RequestBody AdresseBean adresse);
@PutMapping(value = "/Adresses")
AdresseBean updateAdresse(@RequestBody AdresseBean adresse);
}
<file_sep>package fr.biblioc.bibliocclientUi.controller;
import fr.biblioc.bibliocclientUi.beans.authentification.CompteBean;
import fr.biblioc.bibliocclientUi.beans.utilisateur.AdresseBean;
import fr.biblioc.bibliocclientUi.beans.utilisateur.UtilisateurBean;
import fr.biblioc.bibliocclientUi.beans.utilities.PasswordDigest;
import fr.biblioc.bibliocclientUi.proxies.BibliocAuthentificationProxy;
import fr.biblioc.bibliocclientUi.proxies.BibliocUtilisateurProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
/**
* Controller utilisant le proxy vers le microservice authentification
*/
@Controller
public class AuthentificationController {
@Autowired
private BibliocAuthentificationProxy authentificationProxy;
@Autowired
private BibliocUtilisateurProxy utilisateurProxy;
@RequestMapping(value= "/authentification/connexion", method = RequestMethod.GET)
public ModelAndView connexion(Model model){
return new ModelAndView("connexion");
}
@RequestMapping(value = "/authentification/connexion/erreur", method = RequestMethod.GET)
public ModelAndView connexionError(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("connexion");
Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request); // 1
if (!CollectionUtils.isEmpty(flashMap)) {
modelAndView.addObject("erreur", flashMap.get("erreur")); // 2
}
return modelAndView;
}
@PostMapping("/authentification/connexion")
public ModelAndView connexion(String email, String password, HttpServletRequest request, RedirectAttributes redirectAttributes){
if (email.length() != 0 && password.length() != 0) {
CompteBean compte = authentificationProxy.getCompte(email);
password = <PASSWORD>.hashAndSalt(password);
if (compte != null && compte.getPassword().equals(password)) {
request.getSession().setAttribute("compte",compte);
return new ModelAndView("redirect:/");
} else {
String erreur = "Erreur votre email ou votre mot de passe est incorrect !";
redirectAttributes.addFlashAttribute("erreur", erreur);
return new ModelAndView("redirect:/authentification/connexion/erreur");
}
} else {
String erreur = "Erreur votre email ou votre mot de passe est incorrect !";
redirectAttributes.addFlashAttribute("erreur", erreur);
return new ModelAndView("redirect:/authentification/connexion/erreur");
}
}
@PostMapping("/authentification/deconnexion")
public ModelAndView deconnexion(@ModelAttribute CompteBean compte, HttpServletRequest request, RedirectAttributes redirectAttributes){
request.getSession().removeAttribute("compte");
return new ModelAndView("redirect:/");
}
@RequestMapping(value= "/authentification/inscription", method = RequestMethod.GET)
public String inscription(Model model){
return "inscription";
}
@PostMapping("/authentification/inscription")
public String inscription(String email, String password, Model model){
CompteBean compteComparator = authentificationProxy.getCompte(email);
if(compteComparator != null){
String erreur = "cette adresse email est déjà utilisée !";
model.addAttribute("erreur", erreur);
return "inscription";
} else{
password = <PASSWORD>(password);
//attribution de l'utilisateur provisoire
CompteBean compte = new CompteBean(email, password, 1, 1);
authentificationProxy.newCompte(compte);
return "connexion";
}
}
@RequestMapping(value= "/authentification/profil", method = RequestMethod.GET)
public String profil(Model model, HttpServletRequest request){
CompteBean compte = (CompteBean)request.getSession().getAttribute("compte");
model.addAttribute("compte", compte);
UtilisateurBean utilisateur = utilisateurProxy.getUtilisateur(compte.getId_utilisateur());
AdresseBean adresse = utilisateurProxy.getAdresse(utilisateur.getId_adresse());
model.addAttribute("compte", compte);
model.addAttribute("utilisateur", utilisateur);
model.addAttribute("adresse", adresse);
return "profil";
}
@PostMapping("/authentification/profil")
public String profil(@ModelAttribute UtilisateurBean utilisateur,
@Valid @ModelAttribute AdresseBean adresse, BindingResult bindingResult, Model model, HttpServletRequest request){
CompteBean compte = (CompteBean)request.getSession().getAttribute("compte");
if(bindingResult.hasErrors()){
for (ObjectError error : bindingResult.getAllErrors()) {
System.out.println("erreurs : " + error.toString());
}
}
else {
if(compte.getId_utilisateur() != 1){
utilisateurProxy.updateUtilisateur(utilisateur);
} else {
utilisateurProxy.newUtilisateur(utilisateur);
int id_utilisateur = utilisateurProxy.recupererLeDernierUtilisateur();
compte.setId_utilisateur(id_utilisateur);
authentificationProxy.updateCompte(compte);
}
}
model.addAttribute("compte", compte);
model.addAttribute("utilisateur", utilisateur);
model.addAttribute("adresse", adresse);
return "profil";
}
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller.automation.proxies;
import fr.biblioc.bibliocreservation.model.PrereservationDispoDataBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
/**
* Proxy du microservice reservation.
*/
@FeignClient(name = "biblioc-mail", url = "localhost:9007")
public interface BibliocMailProxy {
@PostMapping(value = "/sendMailListPrereservation")
public ResponseEntity sendMailPrereservationList(@RequestBody List<PrereservationDispoDataBean> prereservationDispoDatas);
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller.automation.proxies;
import fr.biblioc.bibliocreservation.web.controller.automation.model.CompteBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Proxy du microservice authentification.
*/
@FeignClient(name = "biblioc-authentification", url = "localhost:9001")
public interface BibliocAuthentificationProxy {
@GetMapping(value = "/Comptes")
List<CompteBean> listComptes();
@GetMapping(value = "/Comptes/existe/{id}")
boolean isCompte(@PathVariable("id") int id);
@GetMapping(value = "/Comptes/{id}")
CompteBean getCompte(@PathVariable("id") int id);
@GetMapping( value = "/Comptes_mail/{email}")
CompteBean getCompte(@PathVariable("email") String email);
@PutMapping(value = "/Comptes")
CompteBean updateCompte(@RequestBody CompteBean compte);
@PostMapping(value = "/Comptes")
CompteBean newCompte(@RequestBody CompteBean compte);
}
<file_sep>package fr.biblioc.bibliocreservation.dao;
import fr.biblioc.bibliocreservation.model.PreReservation;
import fr.biblioc.bibliocreservation.model.Reservation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface PreReservationDao extends JpaRepository<PreReservation, Integer> {
@Query(value = "SELECT * FROM prereservation WHERE expire = false AND mail_send = true", nativeQuery = true)
List<PreReservation> findAllByNotExpired();
@Query(value = "SELECT * FROM prereservation WHERE id_compte = :id_compte AND expire = false", nativeQuery = true)
List<PreReservation> findAllById_compte(@Param("id_compte") int id_compte);
@Query(value = "INSERT INTO prereservation (id_prereservation, id_compte, date, id_liste_attente, expire, mail_send) VALUES (:id_prereservation, :id_compte, :date, :id_liste_attente, :expire, :mail_send)", nativeQuery = true)
void newPrereservation(@Param("id_prereservation") int id_prereservation,
@Param("id_compte") int id_compte,
@Param("date") Date date,
@Param("id_liste_attente") int id_liste_attente,
@Param("expire") boolean expire,
@Param("mail_send") boolean mail_send);
}
<file_sep>package fr.biblioc.bibliocclientUi.beans.reservation;
import java.util.Date;
public class PreReservationBean {
//------------------------- ATTRIBUTS -------------------------
private int id_prereservation;
private int id_compte;
private String titre;
private int numFileAttente;
private Date datePreReservation;
private int id_liste_attente;
private Integer id_exemplaire;
private boolean expire;
private Date dateMail;
private boolean mailSend;
private Date dateMailSend;
//------------------------- CONSTRUCTEUR -------------------------
public PreReservationBean() {
expire = false;
}
public PreReservationBean(int id_compte, Date datePreReservation, int id_liste_attente, boolean expire, Date dateMail, boolean mailSend) {
this.id_compte = id_compte;
this.datePreReservation = datePreReservation;
this.id_liste_attente = id_liste_attente;
this.expire = expire;
this.dateMail = dateMail;
this.mailSend = mailSend;
}
//------------------------- GETTER/SETTER -------------------------
public int getId_prereservation() {
return id_prereservation;
}
public void setId_prereservation(int id_prereservation) {
this.id_prereservation = id_prereservation;
}
public int getId_compte() {
return id_compte;
}
public void setId_compte(int id_compte) {
this.id_compte = id_compte;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public int getNumFileAttente() {
return numFileAttente;
}
public void setNumFileAttente(int numFileAttente) {
this.numFileAttente = numFileAttente;
}
public Date getDatePreReservation() {
return datePreReservation;
}
public void setDatePreReservation(Date datePreReservation) {
this.datePreReservation = datePreReservation;
}
public int getId_liste_attente() {
return id_liste_attente;
}
public void setId_liste_attente(int id_liste_attente) {
this.id_liste_attente = id_liste_attente;
}
public int getId_exemplaire() {
return id_exemplaire;
}
public void setId_exemplaire(Integer id_exemplaire) {
this.id_exemplaire = id_exemplaire;
}
public boolean isExpire() {
return expire;
}
public void setExpire(boolean expire) {
this.expire = expire;
}
public void setDateMail(Date date) {
this.dateMail = dateMail;
}
public Date getDateMail() {
return dateMail;
}
public boolean isMailSend() {
return mailSend;
}
public void setMailSend(boolean mailSend) {
this.mailSend = mailSend;
}
public Date getDateMailSend() {
return dateMailSend;
}
public void setDateMailSend(Date dateMailSend) {
this.dateMailSend = dateMailSend;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "PreReservationBean{" +
"id_prereservation=" + id_prereservation +
", id_compte=" + id_compte +
", id_exemplaire=" + id_exemplaire +
", titre='" + titre + '\'' +
", numFileAttente=" + numFileAttente +
", datePreReservation=" + datePreReservation +
", id_liste_attente=" + id_liste_attente +
", expire=" + expire +
", mailSend=" + mailSend +
'}';
}
}
<file_sep>package fr.biblioc.bibliocauthentification.utilities;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Classe de sécurisation des mots de passe
*/
public class PasswordDigest {
/**
* Méthode permettant de hash et saler un String
* @param password string
* @return string hash
*/
public static String hashAndSalt(String password){
String cle_salage = password.length()+"<PASSWORD>";
password += cle_salage;
MessageDigest vMessageDigest = null;
try {
vMessageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hashInBytes = vMessageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
// bytes to hex
StringBuilder vStringBuilder = new StringBuilder();
for (byte b : hashInBytes) {
vStringBuilder.append(String.format("%02x", b));
}
return vStringBuilder.toString();
}
}
<file_sep>package fr.biblioc.bibliocauthentification.web.controller;
import fr.biblioc.bibliocauthentification.dao.RoleDao;
import fr.biblioc.bibliocauthentification.model.Role;
import fr.biblioc.bibliocauthentification.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocauthentification.web.exceptions.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link Role}
*/
@RestController
public class RoleController implements HealthIndicator {
//------------------------- ATTRIBUTS -------------------------
@Autowired
RoleDao roleDao;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Indique le status du microservice
* @return etat du microservice
*/
@Override
public Health health() {
List<Role> roles = roleDao.findAll();
if(roles.isEmpty()) {
return Health.down().build();
}
return Health.up().build();
}
/**
* Affiche la liste de tous les roles
* @return liste de {@link Role}
*/
@GetMapping(value = "/Roles")
public List<Role> listeDesRoles(){
List<Role> roles = roleDao.findAll();
if(roles.isEmpty()){
throw new ObjectNotFoundException("Aucun role n'a été trouvée");
}
log.info("Récupération de la liste des roles");
return roles;
}
/**
* Récuperer un role par son id
* @param id int
* @return bean {@link Role}
*/
@GetMapping( value = "/Roles/{id}")
public Optional<Role> recupererUnRole(@PathVariable int id) {
Optional<Role> role = roleDao.findById(id);
if(!role.isPresent()) throw new ObjectNotFoundException("Le role correspondant à l'id " + id + " n'existe pas");
return role;
}
/**
* Ajouter un role
* @param role bean {@link Role}
* @return ResponseEntity Role renvoi un http status.
*/
@PostMapping(value = "/Roles")
public ResponseEntity<Role> addRole(Role role){
Role newRole = roleDao.save(role);
if(newRole == null) throw new ErrorAddException("Impossible d'ajouter ce role");
return new ResponseEntity<Role>(role, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour un role existant.
* @param role bean {@link Role}
**/
@PutMapping(value = "/Roles")
public void updateRole(@RequestBody Role role) {
roleDao.save(role);
}
}
<file_sep>package fr.biblioc.mail.model;
/**
* POJO des données du mail a envoyer
*/
public class PrereservationDispoData {
//------------------------- ATTRIBUTS -------------------------
private Integer id_exemplaire;
private String email;
private String prenom;
private String bibliotheque;
private String titre;
//------------------------- CONSTRUCTEUR -------------------------
/**
* Constructeur
*/
public PrereservationDispoData() {
}
/**
* Constructeur avec parametres
* @param id_exemplaire int
* @param email string
* @param prenom string
* @param bibliotheque string
* @param titre string
*/
public PrereservationDispoData(Integer id_exemplaire, String email, String prenom, String bibliotheque, String titre) {
this.id_exemplaire = id_exemplaire;
this.email = email;
this.prenom = prenom;
this.bibliotheque = bibliotheque;
this.titre = titre;
}
//------------------------- GETTER/SETTER -------------------------
public Integer getId_exemplaire() {
return id_exemplaire;
}
public void setId_exemplaire(Integer id_exemplaire) {
this.id_exemplaire = id_exemplaire;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getBibliotheque() {
return bibliotheque;
}
public void setBibliotheque(String bibliotheque) {
this.bibliotheque = bibliotheque;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "PrereservationDispoData{" +
", id_exemplaire=" + id_exemplaire +
", email='" + email + '\'' +
", prenom='" + prenom + '\'' +
", bibliotheque='" + bibliotheque + '\'' +
", titre='" + titre + '\'' +
'}';
}
}
<file_sep>package fr.biblioc.bibliocauthentification.dao;
import fr.biblioc.bibliocauthentification.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Interface Dao pour JPA Hibernate
*/
@Repository
public interface RoleDao extends JpaRepository<Role, Integer> {
}
<file_sep>package fr.biblioc.bibliocbatch.mail;
import fr.biblioc.bibliocbatch.model.ReservationExpire;
import freemarker.template.TemplateException;
import java.io.IOException;
/**
* Interface Generateur mail
*/
public interface MailContentGenerator {
String generate(ReservationExpire reservationExpire) throws TemplateException, IOException;
}
<file_sep># Projet_7
##BDD
**configuration des bases de données :**
les blobs de restoration sont dans le dossier \Projet_7\script_bdd
ils y a deux bases de données a créer :
<ul>La base de donnée principale : biblioc_bdd utiliser le fichier biblioc_db.sql</ul>
<ul>La base de donnée du batch : batch_db utiliser le fichier batch_db.sql</ul>
un role d'acces est a configurer, dans les configuration.properties sur github les modification sont a faire sur les lignes : <br>
spring.datasource.username= admin_biblioc<br>
spring.datasource.password= <PASSWORD><br>
<br>
Sinon créer les roles dans la base de donnée.
## SPRING CLOUD CONFIG
**configuration de cloud config :**
les fichiers .properties sont disponibles
<ul>sur <a href="https://github.com/benzouille/biblioc-config">github.com/benzouille/biblioc-config</a></ul>
Vous devez modifier la boite mail dans le fichier biblioc-batch.properties afin d'y mettre votre adresse email
##ordre de lancement des micro-services :
Lancer les micros -services dans l'ordre suivant :
<ul>ConfigServerApplication</ul>
<ul>EurekaServerApplication</ul>
<ul>BibliocAuthentificationApplication</ul>
<ul>BibliocBibliothequeApplication</ul>
<ul>BibliocReservationApplication</ul>
<ul>BibliocUtilisateurApplication</ul>
<ul>BibliocClientUiApplication</ul>
<ul>BibliocBatchApplication</ul>
## Lancement des micros services :
Aller dans chaques microservices : <br>
biblioc/biblioc-"MICROSERVICE"/src/main/java/fr.banane.biblioc"MICROSERVICE"/"MICROSERVICE"Application<br>
puis RUN.
Sous intellij onglet Service en bas et démarrer les micros-services dans l'ordre ci-dessus.<file_sep>package fr.biblioc.bibliocclientUi.beans.bibliotheque;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
/**
* Bean genre coté client
*/
public class GenreBean {
//------------------------- ATTRIBUTS -------------------------
private int id_genre;
@NotNull
private String genre;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public GenreBean() {
}
/**
* constructeur avec parametres
* @param id_genre int
* @param genre string
*/
public GenreBean(int id_genre, @NotNull String genre) {
this.id_genre = id_genre;
this.genre = genre;
}
//------------------------- GETTER/SETTER -------------------------
public int getid_genre() {
return id_genre;
}
public void setid_genre(int id_genre) {
this.id_genre = id_genre;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Genre{" +
"id_genre=" + id_genre +
", genre='" + genre + '\'' +
'}';
}
}
<file_sep>
INSERT INTO auteur (prenom, nom, date_naissance, date_deces) VALUES
('Victor', 'Hugo', '1802/02/26', '1885/05/22'),
('<NAME>', 'Tolkien ', '1892/01/03', '1973/09/02'),
('Isaac', 'Asimov', '1920/01/02', '1992/04/06'),
('Franck', 'Herbert', '1920/10/08', '1986/02/11'),
('Charle', 'Baudelaire', '1821/04/09', '1867/08/31');
INSERT INTO role (role) VALUES
('usagé'),
('bibliothecaire'),
('administrateur');
INSERT INTO genre (genre) VALUES
('historique'),
('science fiction'),
('fantaisie'),
('policier'),
('sociologie'),
('droit'),
('économie'),
('roman'),
('biographie'),
('sciences'),
('bande dessinée'),
('manga'),
('enfant'),
('médical'),
('informatique'),
('biologie'),
('géographie'),
('langues étrangères'),
('mathématiques'),
('physique'),
('chimie'),
('phylosophie'),
('géologie'),
('astronomie'),
('ésothérisme'),
('poésie');
INSERT INTO editeur (nom) VALUES
('Folio'),
('Pocket'),
('Gléna'),
('Hachette'),
(E'L\'Ecole des Loisirs'),
('Larousse');
INSERT INTO livre (isbn13, id_genre, titre, resume, image, annee_parution, id_editeur) VALUES
('978-2211238465', 8, 'Les misérables', E'Valjean, l\'ancien forçat devenu bourgeois et protecteur des faibles ; Fantine, l\'ouvrière écrasée par sa condition ; le couple Thénardier, figure du mal et de l\'opportunisme ; Marius, l\'étudiant idéaliste ; Gavroche, le gamin des rues impertinent qui meurt sur les barricades ; Javert, la fatalité imposée par la société sous les traits d\'un policier vengeur... Et, bien sûr, Cosette, l\'enfant victime. Voilà comment une oeuvre immense incarne son siècle en quelques destins exemplaires, figures devenues mythiques qui continuent de susciter une multitude d\'adaptations.',
'miserable.jpg', 2019, 5),
('978-2070360536', 2, 'Le cycle de Fondation, I : Fondation',E'En ce début de treizième millénaire, l\'Empire n\'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C\'est dans sa capitale, Trantor, que l\'éminent savant <NAME> invente la psychohistoire, une science nouvelle permettant de prédire l\'avenir. Grâce à elle, Seldon prévoit l\'effondrement de l\'Empire d\'ici cinq siècles, suivi d\'une ère de ténèbres de trente mille ans. Réduire cette période à mille ans est peut-être possible, à condition de mener à terme son projet : la Fondation, chargée de rassembler toutes les connaissances humaines. Une entreprise visionnaire qui rencontre de nombreux et puissants détracteurs...',
'fondation_tome_1.jpg', 2009, 1),
('978-2070360550', 2, 'Le cycle de Fondation, II : Fondation et Empire', E'Tandis que les crises qui secouent l\'Empire redoublent de violence et annoncent son effondrement définitif, la Fondation créée par le psychohistorien <NAME> pour sauvegarder la civilisation devient de plus en plus puissante, suscitant naturellement convoitise et visées annexionnistes. En tout premier lieu, celles de Bel Riose, jeune général qui voit dans les secrets détenus par la Fondation le moyen de monter sur le trône.C\'est alors qu\'apparaît un mystérieux et invincible conquérant, surnommé le Mulet, que le plan de Seldon n\'avait pas prévu...',
'fondation_tome_2.jpg', 2009, 1),
('978-2070360529', 2, 'Le cycle de Fondation, III : Seconde Fondation', E'Conçue par le psychohistorien <NAME> pour restreindre l\'ère de chaos résultant de la décadence de l\'Empire galactique, la Fondation est désormais aux mains du Mulet, un mutant imprévisible capable de manipuler les esprits et d\'imposer sa volonté à quiconque. Avec ses pouvoirs et les immenses ressources que lui procurent la Fondation, il s\'est donné pour objectif d\'étendre sa domination aux ultimes vestiges de l\'Empire défunt.Mais déjà une nouvelle légende prend forme : il existerait une seconde Fondation, consacrée aux sciences mentales, œuvrant de façon occulte pour garantir l\'accomplissement des desseins du légendaire <NAME>...',
'fondation_tome_3.jpg', 2009, 1),
('978-2070360529', 3, 'Intégrale Le Seigneur des Anneaux (Nouvelle traduction)', E'Une contrée paisible où vivent les Hobbits. Un anneau magique à la puissance infinie. Sauron, son créateur, prêt à dévaster le monde entier pour récupérer son bien. Frodon, jeune Hobbit, détenteur de l\'Anneau malgré lui. Gandalf, le Magicien, venu avertir Frodon du danger. Et voilà déjà les Cavaliers Noirs qui approchent...C\'est ainsi que tout commence en Terre du Milieu entre le Comté et Mordor. C\'est ainsi que la plus grande légende est née.',
'seignieur_des_anneaux.jpg', 2018, 2),
('978-2266121026', 3, '<NAME>', E'Les Premiers jours du Monde étaient à peine passés quand Fëanor, le plus doué des elfes, créa les trois Silmarils. Ces bijoux renfermaient la Lumière des Deux Arbres de Valinor. Morgoth, le premier Prince de la Nuit, était encore sur la Terre du Milieu, et il fut fâché d\'apprendre que la Lumière allait se perpétuer. Alors il enleva les Silmarils, les fit sertir dans son diadème et garder dans la forteresse d\'Angband. Les elfes prirent les armes pour reprendre les joyaux et ce fut la première de toutes les guerres. Longtemps, longtemps après, lors de la Guerre de l\'Anneau, Elrond et Galadriel en parlaient encore.',
'silmarillion.jpg', 2018, 2),
('978-2266233200', 3, '1. Dune', E'Il n\'y a pas, dans tout l\'Empire, de planète plus inhospitalière que Dune. Partout des sables à perte de vue. Une seule richesse : l\'épice de longue vie, née du désert, et que tout l\'univers convoite.Quand <NAME> reçoit Dune en fief, il flaire le piège. Il aura besoin des guerriers Fremen qui, réfugiés au fond du désert, se sont adaptés à une vie très dure en préservant leur liberté, leurs coutumes et leur foi. Ils rêvent du prophète qui proclamera la guerre sainte et changera le cours de l\'Histoire.Cependant les Révérendes Mères du <NAME> poursuivent leur programme millénaire de sélection génétique : elles veulent créer un homme qui réunira tous les dons latents de l\'espèce. Le Messie des Fremen est-il déjà né dans l\'Empire ?',
'dune_1.jpg', 2012, 2),
('978-2266235815', 3, '2. Le messie de dune', E'<NAME> a triomphé de ses ennemis. En douze ans de guerre sainte, ses Fremen ont conquis l\'univers. Il est devenu l\'empereur Muad\' Dib. Presque un dieu, puisqu\'il voit l\'avenir. Ses ennemis, il les connaît. Il sait quand et comment ils frapperont. Ils vont essayer de lui reprendre l\'épice qui donne la prescience et peut-être de percer le secret de son pouvoir. Il peut déjouer leurs plans, mais voit plus loin encore. Il sait que tous les futurs possibles mènent au désastre et est hanté par la vision de sa propre mort. Peut-être n\'y a-t-il pas d\'autre liberté pour le prescient que celle du sacrifice...',
'dune_2.jpg', 2012, 2),
('978-2266235822', 3, '3. Les enfants de Dune', E'Sur Dune, la planète des sables, les prophéties s\'accomplissent : le désert devient jardin. Mais les vers géants se font rares et l\'Épice de prescience vient à manquer. Tout ce qui reste de l\'épopée de Muad\'Did, c\'est un empire conquis, des guerriers déchus, des prêtres tentés par la théocratie. Et les jumeaux Leto et Ghanima, qui portent en eux les souvenirs d\'innombrables générations dont, peut-être, ceux de l\'antique Abomination, redoutée par les sœurs du B<NAME> et prête à revenir du passé génétique pour faire basculer l\'univers dans le cauchemar. Les morts dominent les vivants. Leto devra affronter les uns et les autres en un combat sans merci dont l\'enjeu est plus que la prescience, plus que la longévité : au moins la toute-puissance, et peut-être l\'immortalité.',
'dune_3.jpg', 2012, 2),
('978-2266235839', 3, E'4. L\'Empereur-dieu de Dune', E'Leto II Atréides, l\'Empereur-Dieu de Dune, est désormais un ver de sable à face humaine. À peu près invulnérable et immortel, il a entrevu dans l\'avenir l\'extinction de l\'espèce humaine. Pour la conjurer, il fait respecter son ordre, le Sentier d\'Or. L\'empire a connu trente-cinq siècles de paix. La Guilde et le <NAME> ont les mains liées : c\'est Leto qui contrôle sur Dune les dernières réserves de l\'indispensable épice. Les Ixiens lui envoient une femme parfaite, issue d\'une éprouvette et chargée à son insu de le séduire et de le détruire. Leto sait désormais qu\'il devra peut être se sacrifier et sacrifier la femme qu\'il aime et qui réveille d\'anciens souvenirs.',
'dune_4.jpg', 2012, 2),
('978-2266235846', 3, '5. Les hérétiques de Dune', E'Leto II, le Tyran, l\'Empereur-Dieu, est mort depuis des milliers d\'années, mais son souvenir est dans toutes les mémoires. Sa disparition a entraîné la Grande Famine et la Dispersion de l\'humanité à travers les univers. Pourtant ces désordres ont assuré la survie de l\'humanité conformément aux plans du Tyran ; et ses Prêtres en tirent argument pour justifer leurs ambitions. Mais la Révérende <NAME> sait bien que le pouvoir vient de l\'Épice, source de la prescience. La planète Dune, devenue Rakis, restera-t-elle le centre de toutes les intrigues alors que le Bene Tleilax a appris à produire l\'Épice sans le secours des vers géants ? Les forces qui se mesurent dans l\'ombre sont à l\'affût du moindre signe.',
'dune_5.jpg', 2012, 2),
('978-2266235853', 3, '6. La maison des mères', E'Dune est détruite, vitrifiée, atomisée. Sur tout l\'Empire déferlent les hordes furieuses des Honorées Matriarches, massacrant tout sur leur passage. Le Bene Gesserit reste la seule force organisée. Mais la solution n\'est peut-être pas dans le pouvoir des armes. <NAME>, la Mère Supérieure, propose de négocier. La Très Honorée Matriarche accepte : elle s\'attend à une capitulation sans conditions. Mais Darwi a un plan. Elle sait bien que l\'entreprise est des plus risquées. Si elle parvenait à ramener la paix, elle provoquerait des tensions insupportables et peut-être une nouvelle Dispersion. Rien de moins.',
'dune_6.jpg', 2012, 2),
('978-2035861566', 26, 'Les fleurs du mal', E'Pourquoi le recueil des Fleurs du mal a-t-il cette audience aujourd’hui ? Parce qu’il représente, depuis 1857, la naissance d’une poésie nouvelle. Baudelaire utilise les formes classiques – le sonnet, l’alexandrin – pour dire la modernité : la bizarrerie, les villes immenses, le malaise d’une existence douloureuse. Face à cette angoisse, il nous propose un moyen de vaincre le mal, le dégoût de soi et des autres, le « spleen » : l’idéal d’un langage qui nous montrerait un ailleurs rêvé, un monde enfin habitable.',
'les_fleur_du_mal.jpg', 2011, 6);
/*
('000-0000', id_genre, 'titre', E'resume',
'.jpg', 2012, id_editeur);
*/
INSERT INTO adresse (code_postal, rue, num, commune) VALUES
('57000','rue des cordonniers', 20, 'Metz'),
('57950','rue du général Patton', 45, 'Montigny-lès-Metz'),
('57950',E'place de l\'église', 18, 'Montigny-lès-Metz'),
('57950','rue des alliés', 7, 'Montigny-lès-Metz'),
('57950','rue du général Patton', 4, 'Montigny-lès-Metz');
INSERT INTO utilisateur (nom, prenom, telephone, id_adresse) VALUES
('admin', 'admin', '0123456789', 1),
('tata', 'manue', '9876543210', 2),
('simon', 'culçonet', '0000000000', 3);
INSERT INTO compte (email, password, id_role, id_utilisateur) VALUES
('<EMAIL>', 'admin', 3, 1),
('<EMAIL>', '1234', 1, 2),
('<EMAIL>', '2345', 1, 3);
INSERT INTO bibliotheque (nom, id_adresse) VALUES
('bibliothèque du centre', 4),
('bibliothèque <NAME>', 5);
INSERT INTO exemplaire (id_livre, id_biblio) VALUES
(1, 1),
(1, 1),
(1, 2),
(1, 2),
(1, 2),
(1, 2),
(2, 1),
(2, 1),
(2, 1),
(2, 1),
(2, 2),
(2, 2),
(2, 2),
(3, 1),
(3, 1),
(3, 1),
(3, 1),
(3, 1),
(3, 2),
(3, 2);
INSERT INTO livre_auteur (id_livre, id_auteur) VALUES
(1, 1),
(2, 3),
(3, 3);
INSERT INTO reservation (id_compte, date_emprunt, extension, id_exemplaire) VALUES
(2, '2019/11/5', false, 7),
(2, '2019/11/5', false, 14),
(3, '2019/9/11', true, 8);
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (1.8.0_141) on Mon Feb 17 09:50:22 CET 2020 -->
<title>B-Index</title>
<meta name="date" content="2020-02-17">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="B-Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li><a href="index-3.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">J</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">N</a> <a href="index-14.html">O</a> <a href="index-15.html">P</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">U</a> <a href="index-20.html">W</a> <a name="I:B">
<!-- -->
</a>
<h2 class="title">B</h2>
<dl>
<dt><a href="../fr/biblioc/bibliocauthentification/BibliocAuthentificationApplication.html" title="class in fr.biblioc.bibliocauthentification"><span class="typeNameLink">BibliocAuthentificationApplication</span></a> - Class in <a href="../fr/biblioc/bibliocauthentification/package-summary.html">fr.biblioc.bibliocauthentification</a></dt>
<dd>
<div class="block">Classe main du microservice authentification</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocauthentification/BibliocAuthentificationApplication.html#BibliocAuthentificationApplication--">BibliocAuthentificationApplication()</a></span> - Constructor for class fr.biblioc.bibliocauthentification.<a href="../fr/biblioc/bibliocauthentification/BibliocAuthentificationApplication.html" title="class in fr.biblioc.bibliocauthentification">BibliocAuthentificationApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocclientUi/proxies/BibliocAuthentificationProxy.html" title="interface in fr.biblioc.bibliocclientUi.proxies"><span class="typeNameLink">BibliocAuthentificationProxy</span></a> - Interface in <a href="../fr/biblioc/bibliocclientUi/proxies/package-summary.html">fr.biblioc.bibliocclientUi.proxies</a></dt>
<dd>
<div class="block">Proxy du microservice authentification.</div>
</dd>
<dt><a href="../fr/biblioc/bibliocbatch/BibliocBatchApplication.html" title="class in fr.biblioc.bibliocbatch"><span class="typeNameLink">BibliocBatchApplication</span></a> - Class in <a href="../fr/biblioc/bibliocbatch/package-summary.html">fr.biblioc.bibliocbatch</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocbatch/BibliocBatchApplication.html#BibliocBatchApplication--">BibliocBatchApplication()</a></span> - Constructor for class fr.biblioc.bibliocbatch.<a href="../fr/biblioc/bibliocbatch/BibliocBatchApplication.html" title="class in fr.biblioc.bibliocbatch">BibliocBatchApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocbibliotheque/BibliocBibliothequeApplication.html" title="class in fr.biblioc.bibliocbibliotheque"><span class="typeNameLink">BibliocBibliothequeApplication</span></a> - Class in <a href="../fr/biblioc/bibliocbibliotheque/package-summary.html">fr.biblioc.bibliocbibliotheque</a></dt>
<dd>
<div class="block">Classe main du microservice bibliotheque</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocbibliotheque/BibliocBibliothequeApplication.html#BibliocBibliothequeApplication--">BibliocBibliothequeApplication()</a></span> - Constructor for class fr.biblioc.bibliocbibliotheque.<a href="../fr/biblioc/bibliocbibliotheque/BibliocBibliothequeApplication.html" title="class in fr.biblioc.bibliocbibliotheque">BibliocBibliothequeApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocclientUi/proxies/BibliocBibliothequeProxy.html" title="interface in fr.biblioc.bibliocclientUi.proxies"><span class="typeNameLink">BibliocBibliothequeProxy</span></a> - Interface in <a href="../fr/biblioc/bibliocclientUi/proxies/package-summary.html">fr.biblioc.bibliocclientUi.proxies</a></dt>
<dd>
<div class="block">Proxy du microservice bibliotheque.</div>
</dd>
<dt><a href="../fr/biblioc/bibliocclientUi/BibliocClientUiApplication.html" title="class in fr.biblioc.bibliocclientUi"><span class="typeNameLink">BibliocClientUiApplication</span></a> - Class in <a href="../fr/biblioc/bibliocclientUi/package-summary.html">fr.biblioc.bibliocclientUi</a></dt>
<dd>
<div class="block">Classe Main du ClientUi</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocclientUi/BibliocClientUiApplication.html#BibliocClientUiApplication--">BibliocClientUiApplication()</a></span> - Constructor for class fr.biblioc.bibliocclientUi.<a href="../fr/biblioc/bibliocclientUi/BibliocClientUiApplication.html" title="class in fr.biblioc.bibliocclientUi">BibliocClientUiApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocreservation/BibliocReservationApplication.html" title="class in fr.biblioc.bibliocreservation"><span class="typeNameLink">BibliocReservationApplication</span></a> - Class in <a href="../fr/biblioc/bibliocreservation/package-summary.html">fr.biblioc.bibliocreservation</a></dt>
<dd>
<div class="block">Classe main du microservice reservation</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/BibliocReservationApplication.html#BibliocReservationApplication--">BibliocReservationApplication()</a></span> - Constructor for class fr.biblioc.bibliocreservation.<a href="../fr/biblioc/bibliocreservation/BibliocReservationApplication.html" title="class in fr.biblioc.bibliocreservation">BibliocReservationApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocclientUi/proxies/BibliocReservationProxy.html" title="interface in fr.biblioc.bibliocclientUi.proxies"><span class="typeNameLink">BibliocReservationProxy</span></a> - Interface in <a href="../fr/biblioc/bibliocclientUi/proxies/package-summary.html">fr.biblioc.bibliocclientUi.proxies</a></dt>
<dd>
<div class="block">Proxy du microservice reservation.</div>
</dd>
<dt><a href="../fr/biblioc/utilisateur/BibliocUtilisateurApplication.html" title="class in fr.biblioc.utilisateur"><span class="typeNameLink">BibliocUtilisateurApplication</span></a> - Class in <a href="../fr/biblioc/utilisateur/package-summary.html">fr.biblioc.utilisateur</a></dt>
<dd>
<div class="block">Classe main du microservice utilisateur</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/utilisateur/BibliocUtilisateurApplication.html#BibliocUtilisateurApplication--">BibliocUtilisateurApplication()</a></span> - Constructor for class fr.biblioc.utilisateur.<a href="../fr/biblioc/utilisateur/BibliocUtilisateurApplication.html" title="class in fr.biblioc.utilisateur">BibliocUtilisateurApplication</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocclientUi/proxies/BibliocUtilisateurProxy.html" title="interface in fr.biblioc.bibliocclientUi.proxies"><span class="typeNameLink">BibliocUtilisateurProxy</span></a> - Interface in <a href="../fr/biblioc/bibliocclientUi/proxies/package-summary.html">fr.biblioc.bibliocclientUi.proxies</a></dt>
<dd>
<div class="block">Proxy du microservice utilisateur.</div>
</dd>
<dt><a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html" title="class in fr.biblioc.bibliocreservation.model"><span class="typeNameLink">Bibliotheque</span></a> - Class in <a href="../fr/biblioc/bibliocreservation/model/package-summary.html">fr.biblioc.bibliocreservation.model</a></dt>
<dd>
<div class="block">Bean Bibliothèque representant la table bibliotheque de la bdd</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html#Bibliotheque--">Bibliotheque()</a></span> - Constructor for class fr.biblioc.bibliocreservation.model.<a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html" title="class in fr.biblioc.bibliocreservation.model">Bibliotheque</a></dt>
<dd>
<div class="block">constructeur</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html#Bibliotheque-java.lang.String-fr.biblioc.bibliocreservation.model.Adresse-">Bibliotheque(String, Adresse)</a></span> - Constructor for class fr.biblioc.bibliocreservation.model.<a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html" title="class in fr.biblioc.bibliocreservation.model">Bibliotheque</a></dt>
<dd>
<div class="block">Constructeur avec paramètres</div>
</dd>
<dt><a href="../fr/biblioc/bibliocclientUi/beans/reservation/BibliothequeBean.html" title="class in fr.biblioc.bibliocclientUi.beans.reservation"><span class="typeNameLink">BibliothequeBean</span></a> - Class in <a href="../fr/biblioc/bibliocclientUi/beans/reservation/package-summary.html">fr.biblioc.bibliocclientUi.beans.reservation</a></dt>
<dd>
<div class="block">Bean Bibliotheque coté client</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocclientUi/beans/reservation/BibliothequeBean.html#BibliothequeBean--">BibliothequeBean()</a></span> - Constructor for class fr.biblioc.bibliocclientUi.beans.reservation.<a href="../fr/biblioc/bibliocclientUi/beans/reservation/BibliothequeBean.html" title="class in fr.biblioc.bibliocclientUi.beans.reservation">BibliothequeBean</a></dt>
<dd>
<div class="block">constructeur</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocclientUi/beans/reservation/BibliothequeBean.html#BibliothequeBean-java.lang.String-fr.biblioc.bibliocclientUi.beans.reservation.AdresseBean-">BibliothequeBean(String, AdresseBean)</a></span> - Constructor for class fr.biblioc.bibliocclientUi.beans.reservation.<a href="../fr/biblioc/bibliocclientUi/beans/reservation/BibliothequeBean.html" title="class in fr.biblioc.bibliocclientUi.beans.reservation">BibliothequeBean</a></dt>
<dd>
<div class="block">Constructeur avec paramètres</div>
</dd>
<dt><a href="../fr/biblioc/bibliocclientUi/controller/BibliothequeController.html" title="class in fr.biblioc.bibliocclientUi.controller"><span class="typeNameLink">BibliothequeController</span></a> - Class in <a href="../fr/biblioc/bibliocclientUi/controller/package-summary.html">fr.biblioc.bibliocclientUi.controller</a></dt>
<dd>
<div class="block">Controller utilisant le proxy vers le microservice bibliotheque</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocclientUi/controller/BibliothequeController.html#BibliothequeController--">BibliothequeController()</a></span> - Constructor for class fr.biblioc.bibliocclientUi.controller.<a href="../fr/biblioc/bibliocclientUi/controller/BibliothequeController.html" title="class in fr.biblioc.bibliocclientUi.controller">BibliothequeController</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocreservation/web/controller/BibliothequeController.html" title="class in fr.biblioc.bibliocreservation.web.controller"><span class="typeNameLink">BibliothequeController</span></a> - Class in <a href="../fr/biblioc/bibliocreservation/web/controller/package-summary.html">fr.biblioc.bibliocreservation.web.controller</a></dt>
<dd>
<div class="block">Controller de la classe <a href="../fr/biblioc/bibliocreservation/model/Bibliotheque.html" title="class in fr.biblioc.bibliocreservation.model"><code>Bibliotheque</code></a></div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/web/controller/BibliothequeController.html#BibliothequeController--">BibliothequeController()</a></span> - Constructor for class fr.biblioc.bibliocreservation.web.controller.<a href="../fr/biblioc/bibliocreservation/web/controller/BibliothequeController.html" title="class in fr.biblioc.bibliocreservation.web.controller">BibliothequeController</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocreservation/dao/BibliothequeDao.html" title="interface in fr.biblioc.bibliocreservation.dao"><span class="typeNameLink">BibliothequeDao</span></a> - Interface in <a href="../fr/biblioc/bibliocreservation/dao/package-summary.html">fr.biblioc.bibliocreservation.dao</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocreservation/dto/BibliothequeDto.html" title="class in fr.biblioc.bibliocreservation.dto"><span class="typeNameLink">BibliothequeDto</span></a> - Class in <a href="../fr/biblioc/bibliocreservation/dto/package-summary.html">fr.biblioc.bibliocreservation.dto</a></dt>
<dd>
<div class="block">Dto de l'objet Bibliothèque</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/dto/BibliothequeDto.html#BibliothequeDto--">BibliothequeDto()</a></span> - Constructor for class fr.biblioc.bibliocreservation.dto.<a href="../fr/biblioc/bibliocreservation/dto/BibliothequeDto.html" title="class in fr.biblioc.bibliocreservation.dto">BibliothequeDto</a></dt>
<dd>
<div class="block">constructeur</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/dto/BibliothequeDto.html#BibliothequeDto-java.lang.String-fr.biblioc.bibliocreservation.model.Adresse-">BibliothequeDto(String, Adresse)</a></span> - Constructor for class fr.biblioc.bibliocreservation.dto.<a href="../fr/biblioc/bibliocreservation/dto/BibliothequeDto.html" title="class in fr.biblioc.bibliocreservation.dto">BibliothequeDto</a></dt>
<dd>
<div class="block">Constructeur avec paramètres</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/mapper/BibliothequeMapper.html#bibliothequeDtoToBibliotheque-fr.biblioc.bibliocreservation.dto.BibliothequeDto-">bibliothequeDtoToBibliotheque(BibliothequeDto)</a></span> - Method in interface fr.biblioc.bibliocreservation.mapper.<a href="../fr/biblioc/bibliocreservation/mapper/BibliothequeMapper.html" title="interface in fr.biblioc.bibliocreservation.mapper">BibliothequeMapper</a></dt>
<dd> </dd>
<dt><a href="../fr/biblioc/bibliocreservation/mapper/BibliothequeMapper.html" title="interface in fr.biblioc.bibliocreservation.mapper"><span class="typeNameLink">BibliothequeMapper</span></a> - Interface in <a href="../fr/biblioc/bibliocreservation/mapper/package-summary.html">fr.biblioc.bibliocreservation.mapper</a></dt>
<dd>
<div class="block">Mapper mapstruct de l'Entity au DTO et l'inverse</div>
</dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocreservation/mapper/BibliothequeMapper.html#bibliothequeToBibliothequeDto-fr.biblioc.bibliocreservation.model.Bibliotheque-">bibliothequeToBibliothequeDto(Bibliotheque)</a></span> - Method in interface fr.biblioc.bibliocreservation.mapper.<a href="../fr/biblioc/bibliocreservation/mapper/BibliothequeMapper.html" title="interface in fr.biblioc.bibliocreservation.mapper">BibliothequeMapper</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../fr/biblioc/bibliocclientUi/controller/GestionController.html#byUser-java.lang.String-org.springframework.web.servlet.mvc.support.RedirectAttributes-">byUser(String, RedirectAttributes)</a></span> - Method in class fr.biblioc.bibliocclientUi.controller.<a href="../fr/biblioc/bibliocclientUi/controller/GestionController.html" title="class in fr.biblioc.bibliocclientUi.controller">GestionController</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">J</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">N</a> <a href="index-14.html">O</a> <a href="index-15.html">P</a> <a href="index-16.html">R</a> <a href="index-17.html">S</a> <a href="index-18.html">T</a> <a href="index-19.html">U</a> <a href="index-20.html">W</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li><a href="index-3.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>package fr.biblioc.bibliocreservation.dao;
import fr.biblioc.bibliocreservation.model.Exemplaire;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ExemplaireDao extends JpaRepository<Exemplaire, Integer> {
@Query(value = "SELECT EXISTS(SELECT true from exemplaire where id_exemplaire=:id_exemplaire)", nativeQuery = true)
boolean existsById_exemplaire(@Param("id_exemplaire") int id_exemplaire);
@Query(value = "SELECT * FROM exemplaire WHERE id_livre = :id_livre", nativeQuery = true)
List<Exemplaire> findAllById_livre(@Param("id_livre") int id_livre);
@Query(value = "SELECT * FROM exemplaire inner join livre on livre.id_livre = exemplaire.id_livre inner join auteur_livre on auteur_livre.livre_id = livre.id_livre WHERE auteur_livre.auteur_id =:auteur_id AND livre.id_genre =:id_genre AND exemplaire.id_biblio =:id_biblio", nativeQuery = true)
List<Exemplaire> multiCrit(@Param("auteur_id") int auteur_id, @Param("id_genre") int id_genre, @Param("id_biblio") int id_biblio);
@Query(value = "SELECT COUNT(*) FROM exemplaire WHERE id_livre = :id_livre AND id_biblio = :id_biblio", nativeQuery = true)
int nbreExemplaire(@Param("id_livre") int id_livre, @Param("id_biblio") int id_biblio);
@Query(value = "SELECT * FROM exemplaire WHERE id_livre = :id_livre AND id_biblio = :id_biblio AND disponible = TRUE", nativeQuery = true)
List<Exemplaire> exemplaireDispoByIdLivreAndIdBiblio(@Param("id_livre") int id_livre, @Param("id_biblio") int id_biblio);
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller.automation.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* Bean Utilisateur coté client
*/
public class UtilisateurBean {
//------------------------- ATTRIBUTS -------------------------
private int id_utilisateur;
private String nom;
private String prenom;
private long telephone;
private int id_adresse;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public UtilisateurBean() {
}
/**
* constructeur avec parametres
* @param nom string
* @param prenom string
* @param telephone long
* @param id_adresse int
*/
public UtilisateurBean(String nom, String prenom, long telephone, int id_adresse) {
this.nom = nom;
this.prenom = prenom;
this.telephone = telephone;
this.id_adresse = id_adresse;
}
//------------------------- GETTER/SETTER -------------------------
public int getId_utilisateur() {
return id_utilisateur;
}
public void setId_utilisateur(int id_utilisateur) {
this.id_utilisateur = id_utilisateur;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public long getTelephone() {
return telephone;
}
public void setTelephone(long telephone) {
this.telephone = telephone;
}
public int getId_adresse() {
return id_adresse;
}
public void setId_adresse(int id_adresse) {
this.id_adresse = id_adresse;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Utilisateur{" +
"id_utilisateur=" + id_utilisateur +
", nom='" + nom + '\'' +
", prenom='" + prenom + '\'' +
", telephone=" + telephone +
", id_adresse=" + id_adresse +
'}';
}
}
<file_sep>package fr.biblioc.bibliocreservation;
import fr.biblioc.bibliocreservation.web.controller.automation.MailController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* Classe main du microservice reservation
*/
@EnableConfigurationProperties
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients("fr.biblioc")
@EnableScheduling
public class BibliocReservationApplication {
@Autowired
private MailController mailController;
public static void main(String[] args) {
SpringApplication.run(BibliocReservationApplication.class, args);
}
/**
* Automatisation journalier du job
* @throws Exception -
*/
//1 fois par jour a 1h01
//@Scheduled(cron = "0 1 1 * * ?")
//toutes les 120 secondes
@Scheduled(fixedRate = 120000)
public void perform() throws Exception
{
System.out.println("scheduled run");
mailController.inspectionDelais();
}
}
<file_sep>package fr.biblioc.bibliocclientUi.beans.utilities;
public class ObjectNotFoundException extends Throwable {
public ObjectNotFoundException(String s) {
}
}
<file_sep>package fr.biblioc.bibliocclientUi.controller;
import fr.biblioc.bibliocclientUi.beans.authentification.CompteBean;
import fr.biblioc.bibliocclientUi.beans.mail.PrereservationDispoDataBean;
import fr.biblioc.bibliocclientUi.beans.reservation.ExemplaireBean;
import fr.biblioc.bibliocclientUi.beans.reservation.ListeAttenteBean;
import fr.biblioc.bibliocclientUi.beans.reservation.PreReservationBean;
import fr.biblioc.bibliocclientUi.beans.reservation.ReservationBean;
import fr.biblioc.bibliocclientUi.beans.utilisateur.UtilisateurBean;
import fr.biblioc.bibliocclientUi.proxies.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
/**
* Controller utilisant le proxy vers le microservice reservation
*/
@Controller
public class GestionController {
//------------------------- PARAMETRE -------------------------
@Autowired
private BibliocUtilisateurProxy utilisateurProxy;
@Autowired
private BibliocBibliothequeProxy bibliothequeProxy;
@Autowired
private BibliocReservationProxy reservationProxy;
@Autowired
private BibliocAuthentificationProxy authentificationProxy;
@Autowired
private BibliocMailProxy mailProxy;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
@RequestMapping(value = "/mes_emprunts", method = RequestMethod.GET)
public ModelAndView empruntsUtilisateur(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("mes_emprunts");
CompteBean compte = (CompteBean) request.getSession().getAttribute("compte");
modelAndView.addObject("compte", compte);
UtilisateurBean utilisateur = utilisateurProxy.getUtilisateur(compte.getId_utilisateur());
List<ReservationBean> reservations = reservationProxy.getReservationById_compte(compte.getId_compte());
//ajout des objets livres dans les reservations
for (ReservationBean reservation : reservations) {
reservation.setUtilisateur(utilisateurProxy.getUtilisateur(reservation.getId_utilisateur()));
reservation.setDate_retour(dateDebutToFin(reservation.getDate_emprunt(), reservation.getExtension()));
reservation.getExemplaire().setLivre(bibliothequeProxy.getLivre(reservation.getExemplaire().getId_livre()));
/*
BUGFIX correction du bug de prolongation d'un prêt si la date de fin de prêt est dépassée.
*/
reservation.setExtension_possible(false);
if (!reservation.getRendu()) {
if (!reservation.getExtension()) {
if (reservation.getDate_retour().after(Date.from(Instant.now()))) {
reservation.setExtension_possible(true);
}
}
}
}
//les prereservations
List<PreReservationBean> userPreservationList = reservationProxy.listPreReservationByIdUser(compte.getId_compte());
for (PreReservationBean preReservation : userPreservationList) {
String titre = bibliothequeProxy.getLivre(reservationProxy.listAttenteById(preReservation.getId_liste_attente()).getId_livre()).getTitre();
preReservation.setTitre(titre);
if (preReservation != null)
System.out.println(preReservation);
else System.out.println("c'est null");
}
modelAndView.addObject("prereservations", userPreservationList);
modelAndView.addObject("utilisateur", utilisateur);
modelAndView.addObject("reservations", reservations);
return modelAndView;
}
@RequestMapping(value = "/gestion", method = RequestMethod.GET)
public ModelAndView gestion(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("gestion_reservation");
CompteBean compte = (CompteBean) request.getSession().getAttribute("compte");
modelAndView.addObject("compte", compte);
Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request); // 1
if (!CollectionUtils.isEmpty(flashMap)) {
List<ReservationBean> reservationByIdCompte = (List<ReservationBean>) flashMap.get("reservationByIdCompte");
String erreur = (String) flashMap.get("erreur");
modelAndView.addObject("erreur", erreur);
modelAndView.addObject("reservationByIdCompte", formatReservation(reservationByIdCompte)); // 2
}
List<ReservationBean> reservations;
if (!reservationProxy.listeReservationsEnCours().isEmpty()) {
reservations = reservationProxy.listeReservationsEnCours();
//ajout des objets livres et utilisateurs ainsi que la date de retour dans les reservations
modelAndView.addObject("reservations", formatReservation(reservations));
}
return modelAndView;
}
@PostMapping(value = "/gestion/ajout")
public ModelAndView ajout(String id_exemplaire, String id_utilisateur, RedirectAttributes redirectAttributes) {
int exemplaireId = Integer.parseInt(id_exemplaire);
int utilisateurId = Integer.parseInt(id_utilisateur);
ExemplaireBean exemplaire;
String erreur = "";
boolean isErreur = false;
if (authentificationProxy.isCompte(utilisateurId)) {
if (reservationProxy.isExemplaire(exemplaireId)) {
exemplaire = reservationProxy.getExemplaire(exemplaireId);
if (exemplaire.isDisponible()) {
exemplaire.setDisponible(false);
ReservationBean reservation = new ReservationBean(utilisateurId, newDate(), exemplaire);
reservationProxy.newReservation(reservation);
reservationProxy.updateExemplaire(exemplaire);
log.info("Ajout pret " + reservation.toString());
} else {
erreur = "L'exemplaire n'est pas disponible";
isErreur = true;
}
} else {
erreur = "L'identifiant exemplaire n'existe pas";
isErreur = true;
}
} else {
erreur = "L'identifiant utilisateur n'existe pas";
isErreur = true;
}
if (isErreur) {
redirectAttributes.addFlashAttribute("erreur", erreur);
}
return new ModelAndView("redirect:/gestion");
}
@PostMapping(value = "/gestion/addByUser")
public ModelAndView addByUser(String id_livre, String id_bibliotheque, RedirectAttributes redirectAttributes) {
int livreId = Integer.parseInt(id_livre);
int biblioId = Integer.parseInt(id_bibliotheque);
ExemplaireBean exemplaire;
//Recuperer un exemplaire libre avec l'id livre et l'id biblio
exemplaire = reservationProxy.exemplaireDispo(livreId, biblioId).get(0);
exemplaire.setDisponible(false);
ReservationBean reservation = new ReservationBean(biblioId, newDate(), exemplaire);
reservationProxy.newReservation(reservation);
reservationProxy.updateExemplaire(exemplaire);
log.info("Ajout pret " + reservation.toString());
return new ModelAndView("redirect:/mes_emprunts");
}
@PostMapping(value = "/gestion/userPrereservation")
public ModelAndView prereservation(String id_livre, String id_bibliotheque, HttpServletRequest request) {
CompteBean compte = (CompteBean) request.getSession().getAttribute("compte");
ListeAttenteBean listeAttente = reservationProxy.listAttente(Integer.parseInt(id_livre), Integer.parseInt(id_bibliotheque));
System.out.println(listeAttente);
PreReservationBean preReservation = new PreReservationBean(compte.getId_utilisateur(), newDate(), listeAttente.getId_liste_attente(), false, null, false);
preReservation.setId_exemplaire(-1);
System.out.println(preReservation.toString());
reservationProxy.newPrereservation(preReservation);
System.out.println("prereservation : id_livre :" + id_livre + " id_bibliotheque : " + id_bibliotheque + " id_utilisateur : " + compte.getId_utilisateur());
return new ModelAndView("redirect:/mes_emprunts");
}
/**
* Methode au retour de prêt
*
* @param id_reservation
* @return
*/
@PostMapping(value = "/gestion/retour")
public ModelAndView retour(String id_reservation) {
log.info("Retour pret, id reservation : " + id_reservation);
ReservationBean reservation = reservationProxy.getReservation(Integer.parseInt(id_reservation));
reservation.setRendu(true);
reservationProxy.updateReservation(reservation);
ListeAttenteBean listeAttente = reservationProxy.listAttente(
reservation.getExemplaire().getId_livre(),
reservation.getExemplaire().getBibliotheque().getid_biblio());
//Vérification de l'état de la liste d'attente
if (!listeAttente.getPreReservationList().isEmpty()) {
//suivant de la liste
PreReservationBean preReservation = listeAttente.getPreReservationList().get(0);
CompteBean compte = authentificationProxy.getCompte(preReservation.getId_compte());
UtilisateurBean utilisateur = utilisateurProxy.getUtilisateur(compte.getId_utilisateur());
//envoi de mail
PrereservationDispoDataBean prereservationDispoData = new PrereservationDispoDataBean(
reservation.getExemplaire().getid_exemplaire(),
compte.getEmail(),
utilisateur.getPrenom(),
reservation.getExemplaire().getBibliotheque().getNom(),
reservation.getExemplaire().getLivre().getTitre());
mailProxy.sendMailPrereservation(prereservationDispoData);
//mise a jour de la prereservation avec date envoi mail et l'id de l'exemplaire en plus
preReservation.setId_exemplaire(reservation.getExemplaire().getid_exemplaire());
preReservation.setDateMail(newDate());
reservationProxy.updatePreReservation(preReservation);
} else {
ExemplaireBean exemplaire = reservation.getExemplaire();
exemplaire.setDisponible(true);
reservationProxy.updateExemplaire(exemplaire);
}
return new ModelAndView("redirect:/gestion");
}
@PostMapping(value = "/gestion/reservation/acceptation")
public ModelAndView reservationStatus(int id_prereservation, String accepter_pret) {
PreReservationBean preReservation = reservationProxy.preReservationById(id_prereservation);
preReservation.setExpire(true);
reservationProxy.updatePreReservation(preReservation);
ExemplaireBean exemplaire = reservationProxy.getExemplaire(preReservation.getId_exemplaire());
//Acceptation
if(accepter_pret.equals("Accepter")){
ReservationBean reservation = new ReservationBean(preReservation.getId_compte(), newDate(), exemplaire);
reservationProxy.newReservation(reservation);
}
else {
ListeAttenteBean listeAttente = reservationProxy.listAttente(exemplaire.getId_livre(), exemplaire.getBibliotheque().getid_biblio());
//Vérification de l'état de la liste d'attente
if (!listeAttente.getPreReservationList().isEmpty()) {
//suivant de la liste
PreReservationBean nextPreReservation = listeAttente.getPreReservationList().get(0);
CompteBean compte = authentificationProxy.getCompte(nextPreReservation.getId_compte());
UtilisateurBean utilisateur = utilisateurProxy.getUtilisateur(compte.getId_utilisateur());
//envoi de mail
PrereservationDispoDataBean prereservationDispoData = new PrereservationDispoDataBean(
exemplaire.getid_exemplaire(),
compte.getEmail(),
utilisateur.getPrenom(),
exemplaire.getBibliotheque().getNom(),
exemplaire.getLivre().getTitre());
mailProxy.sendMailPrereservation(prereservationDispoData);
//mise a jour de la prereservation avec date envoi mail et l'id de l'exemplaire en plus
nextPreReservation.setId_exemplaire(exemplaire.getid_exemplaire());
nextPreReservation.setDateMail(newDate());
reservationProxy.updatePreReservation(nextPreReservation);
} else {
exemplaire.setDisponible(true);
reservationProxy.updateExemplaire(exemplaire);
}
}
return new ModelAndView("redirect:/mes_emprunts");
}
@PostMapping(value = "/gestion/extention")
public ModelAndView extention(String id_reservation) {
log.info("Extention pret, id reservtion : " + id_reservation);
ReservationBean reservation = reservationProxy.getReservation(Integer.parseInt(id_reservation));
reservation.setExtension(true);
reservationProxy.updateReservation(reservation);
return new ModelAndView("redirect:/gestion");
}
@PostMapping(value = "/user/extention")
public ModelAndView extentionUser(String id_reservation) {
log.info("Extention pret par l'utilisateur, id reservtion : " + id_reservation);
ReservationBean reservation = reservationProxy.getReservation(Integer.parseInt(id_reservation));
reservation.setExtension(true);
reservationProxy.updateReservation(reservation);
return new ModelAndView("redirect:/mes_emprunts");
}
@PostMapping(value = "/gestion/utilisateur")
public ModelAndView byUser(String id_utilisateur, RedirectAttributes redirectAttributes) {
log.info("Par compte, id compte : " + id_utilisateur);
List<ReservationBean> reservationByIdCompte = reservationProxy.getReservationById_compte(Integer.parseInt(id_utilisateur));
System.out.println("gestion/utilisateur : " + reservationByIdCompte);
//le retour
redirectAttributes.addFlashAttribute("reservationByIdCompte", reservationByIdCompte);
return new ModelAndView("redirect:/gestion");
}
//------------------------- METHODE INTERNE -------------------------
/**
* remplit les bean reservation d'une liste avec les données utilisteur, exemplaire et date retour.
*
* @param reservationByIdCompte List<ReservationBean>
* @return List<ReservationBean>
*/
private List<ReservationBean> formatReservation(List<ReservationBean> reservationByIdCompte) {
for (ReservationBean reservation : reservationByIdCompte) {
reservation.setUtilisateur(utilisateurProxy.getUtilisateur(reservation.getId_utilisateur()));
reservation.setDate_retour(dateDebutToFin(reservation.getDate_emprunt(), reservation.getExtension()));
reservation.getExemplaire().setLivre(bibliothequeProxy.getLivre(reservation.getExemplaire().getId_livre()));
//affichage
reservation.setId_view_reservation(reservation.formatId(reservation.getId_reservation()));
reservation.setId_view_exemplaire(reservation.formatId(reservation.getExemplaire().getid_exemplaire()));
}
return reservationByIdCompte;
}
/**
* Renvoie la date du jour
*
* @return java.sql.Date
*/
private Date newDate() {
LocalDate localDate = LocalDate.now();
return Date.valueOf(localDate);
}
/**
* Permet de calculer la date retour maximal en fonction de l'extention
*
* @param dateDebut Date
* @param extention Boolean
* @return java.sql.Date
*/
private Date dateDebutToFin(Date dateDebut, boolean extention) {
long dureePret = 28;
LocalDate dateFin;
if (!extention) {
dateFin = dateDebut.toLocalDate().plusDays(dureePret);
} else {
dateFin = dateDebut.toLocalDate().plusDays(dureePret * 2);
}
return Date.valueOf(dateFin);
}
}
<file_sep>package fr.biblioc.utilisateur.dao;
import fr.biblioc.utilisateur.model.Utilisateur;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Interface Dao pour JPA Hibernate
*/
@Repository
public interface UtilisateurDao extends JpaRepository<Utilisateur, Integer> {
@Query(value = " SELECT id_utilisateur FROM utilisateur ORDER BY id_utilisateur DESC LIMIT 1;", nativeQuery = true)
int findLastId_compte();
}
<file_sep>package fr.biblioc.bibliocreservation.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.sql.Date;
/**
* Bean Reservation representant la table reservation de la bdd
*/
@Entity
public class Reservation {
//------------------------- ATTRIBUTS -------------------------
@Id
@GeneratedValue
private int id_reservation;
@NotNull
private int id_compte;
@NotNull
private Date date_emprunt;
@NotNull
private Boolean extension;
@NotNull
private Boolean rendu;
@NotNull
@ManyToOne
@JoinColumn(name = "id_exemplaire")
private Exemplaire exemplaire;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public Reservation() {
}
/**
* constructeur avec parametres
* @param id_compte int
* @param date_emprunt Date
* @param extension boolean
* @param rendu boolean
* @param exemplaire Objet Exemplaire
*/
public Reservation(@NotNull int id_compte, @NotNull Date date_emprunt, @NotNull Boolean extension, @NotNull Boolean rendu, @NotNull Exemplaire exemplaire) {
this.id_compte = id_compte;
this.date_emprunt = date_emprunt;
this.extension = extension;
this.exemplaire = exemplaire;
this.rendu = rendu;
}
//------------------------- GETTER/SETTER -------------------------
public int getId_reservation() {
return id_reservation;
}
public void setId_reservation(int id_reservation) {
this.id_reservation = id_reservation;
}
public int getId_utilisateur() {
return id_compte;
}
public void setId_utilisateur(int id_utilisateur) {
this.id_compte = id_utilisateur;
}
public Date getDate_emprunt() {
return date_emprunt;
}
public void setDate_emprunt(Date date_emprunt) {
this.date_emprunt = date_emprunt;
}
public Boolean getExtension() {
return extension;
}
public void setExtension(Boolean extension) {
this.extension = extension;
}
public Boolean getRendu() {
return rendu;
}
public void setRendu(Boolean rendu) {
this.rendu = rendu;
}
public Exemplaire getExemplaire() {
return exemplaire;
}
public void setExemplaire(Exemplaire exemplaire) {
this.exemplaire = exemplaire;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Reservation{" +
"id_reservation=" + id_reservation +
", id_compte=" + id_compte +
", date_emprunt=" + date_emprunt +
", extension=" + extension +
", rendu=" + rendu +
", exemplaire=" + exemplaire +
'}';
}
}
<file_sep>package fr.biblioc.mail.mail;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* Implementation de ReservationExpireMailSenderService permetant l'envoi de mail
*/
public class MailSenderServiceImpl implements MailSenderService {
private final JavaMailSender javaMailSender;
private Boolean html = true;
public MailSenderServiceImpl(final JavaMailSender javaMailSender) {
super();
this.javaMailSender = javaMailSender;
}
public void setHtmlFormat(Boolean html){
this.html = html;
}
@Override
public void send(final String mailDestination, final String titre, final String content) throws MessagingException, MailSendException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setText(content, html);
helper.setFrom("<EMAIL>");
helper.setTo(mailDestination);
helper.setSubject(titre);
javaMailSender.send(message);
}
}
<file_sep>spring.application.name=biblioc-utilisateur
spring.cloud.config.uri=http://localhost:9101
<file_sep>package fr.biblioc.bibliocclientUi.beans.bibliotheque;
import java.util.Date;
import java.util.List;
/**
* Bean auteur côté client
*/
public class AuteurBean {
//------------------------- ATTRIBUTS -------------------------
private int id;
private String nom;
private String prenom;
private Date date_naissance;
private Date date_deces;
private List<LivreBean> bibliographie;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public AuteurBean() {
}
/**
* constructeur avec parametres
* @param id int
* @param nom string
* @param prenom string
* @param date_naissance Date
* @param date_deces Date
* @param bibliographie list de livre
*/
public AuteurBean(int id, String nom, String prenom, Date date_naissance, Date date_deces, List<LivreBean> bibliographie) {
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.date_naissance = date_naissance;
this.date_deces = date_deces;
this.bibliographie = bibliographie;
}
//------------------------- GETTER/SETTER -------------------------
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDate_naissance() {
return date_naissance;
}
public void setDate_naissance(Date date_naissance) {
this.date_naissance = date_naissance;
}
public Date getDate_deces() {
return date_deces;
}
public void setDate_deces(Date date_deces) {
this.date_deces = date_deces;
}
public List<LivreBean> getBibliographie() {
return bibliographie;
}
public void setBibliographie(List<LivreBean> bibliographie) {
this.bibliographie = bibliographie;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "AuteurBean{" +
"id=" + id +
", nom='" + nom + '\'' +
", prenom='" + prenom + '\'' +
", date_naissance=" + date_naissance +
", date_deces=" + date_deces +
", bibliographie=" + bibliographie +
'}';
}
}<file_sep>package fr.biblioc.bibliocclientUi.beans.bibliotheque;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
/**
* Bean editeur côté client
*/
public class EditeurBean {
//------------------------- ATTRIBUTS -------------------------
private int id_editeur;
@NotNull
private String nom;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public EditeurBean() {
}
/**
* constructeur avec parametres
* @param nom string
*/
public EditeurBean(@NotNull @Max(100) String nom) {
this.nom = nom;
}
//------------------------- GETTER/SETTER -------------------------
public int getid_editeur() {
return id_editeur;
}
public void setid_editeur(int id_editeur) {
this.id_editeur = id_editeur;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Editeur{" +
"id_editeur=" + id_editeur +
", nom='" + nom + '\'' +
'}';
}
}
<file_sep>package fr.biblioc.bibliocreservation.web.controller;
import fr.biblioc.bibliocreservation.custom.ReservationExpire;
import fr.biblioc.bibliocreservation.custom.ReservationExpireDaoImpl;
import fr.biblioc.bibliocreservation.dao.ReservationDao;
import fr.biblioc.bibliocreservation.dto.ReservationDto;
import fr.biblioc.bibliocreservation.dto.ReservationExpireDto;
import fr.biblioc.bibliocreservation.mapper.ReservationExpireMapper;
import fr.biblioc.bibliocreservation.mapper.ReservationMapper;
import fr.biblioc.bibliocreservation.model.Reservation;
import fr.biblioc.bibliocreservation.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocreservation.web.exceptions.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Controller de la classe {@link Reservation}
*/
@RestController
public class ReservationController implements HealthIndicator {
//------------------------- ATTRIBUTS -------------------------
@Autowired
private ReservationDao reservationDao;
@Autowired
private ReservationMapper reservationMapper;
@Autowired
private ReservationExpireDaoImpl reservationExpireDao;
@Autowired
private ReservationExpireMapper reservationExpireMapper;
Logger log = LoggerFactory.getLogger(this.getClass());
//------------------------- METHODE -------------------------
/**
* Indique le status du microservice
*
* @return etat du microservice
*/
@Override
public Health health() {
List<Reservation> reservations = reservationDao.findAll();
if (reservations.isEmpty()) {
return Health.down().build();
}
return Health.up().build();
}
/**
* Affiche la liste de toutes les reservations
*
* @return liste de {@link Reservation}
*/
@GetMapping(value = "/Reservations")
public List<Reservation> listeDesReservations() {
List<Reservation> reservations = reservationDao.findAll();
if (reservations.isEmpty()) {
throw new ObjectNotFoundException("Aucune reservation n'a été trouvée");
}
log.info("Récupération de la liste des reservations");
return reservations;
}
/**
* Affiche la liste de toutes les reservations en cours
*
* @return liste de {@link Reservation}
*/
@GetMapping(value = "/Reservations/en_cours")
public List<ReservationDto> listeDesReservationsEnCours() {
log.info("Récupération de la liste des reservationsRenduFalse");
List<Reservation> reservations = reservationDao.findAllByRenduFalse();
List<ReservationDto> reservationsDto = new ArrayList<>();
for (Reservation reservation : reservations) {
reservationsDto.add(reservationMapper.reservationToReservationDto(reservation));
}
return reservationsDto;
}
/**
* Affiche la liste de toutes les reservations expirés
*
* @return liste de {@link ReservationExpireDto}
*/
@GetMapping(value = "/Reservations/expire")
public List<ReservationExpireDto> listeDesReservationsExpire() {
log.info("Récupération de la liste des reservationsExpire");
List<ReservationExpire> reservationsExpire = reservationExpireDao.readAll();
List<ReservationExpireDto> reservationsExpireDto = new ArrayList<>();
for (ReservationExpire reservationExpire : reservationsExpire) {
reservationsExpireDto.add(reservationExpireMapper.reservationExpireToReservationExpireDto(reservationExpire));
}
return reservationsExpireDto;
}
/**
* Récuperer une reservation par son id
*
* @param id int
* @return bean {@link Reservation}
*/
@GetMapping(value = "/Reservations/{id}")
public Optional<Reservation> recupererUneReservation(@PathVariable int id) {
Optional<Reservation> reservation = reservationDao.findById(id);
if (!reservation.isPresent())
throw new ObjectNotFoundException("La reservation correspondant à l'id " + id + " n'existe pas");
return reservation;
}
/**
* Récuperer des reservations par l'id_compte
*
* @param id_compte int
* @return List {@link Reservation}
*/
@GetMapping(value = "/Reservations/compte/{id_compte}")
List<Reservation> getReservationById_compte(@PathVariable int id_compte) {
List<Reservation> reservations = reservationDao.findAllById_compte(id_compte);
List<ReservationDto> reservationsDto = new ArrayList<>();
return reservations;
}
/**
* Ajouter une reservation
*
* @param reservation bean {@link Reservation}
* @return ResponseEntity Reservation renvoi un http status.
*/
@PostMapping(value = "/Reservations")
public ResponseEntity<Reservation> addReservation(@RequestBody Reservation reservation) {
log.info("addReservation : " + reservation);
Reservation newReservation = reservationDao.save(reservation);
if (newReservation == null) throw new ErrorAddException("Impossible d'ajouter cette reservation");
return new ResponseEntity<Reservation>(reservation, HttpStatus.CREATED);
}
/**
* Permet de mettre à jour une reservation existante.
* @param reservation bean {@link Reservation}
**/
@PutMapping(value = "/Reservations")
public void updateReservation(@RequestBody Reservation reservation) {
reservationDao.save(reservation);
}
//------------------------- METHODE INTERNE -------------------------
/**
* Renvoie la date du jour
*
* @return java.sql.Date
*/
private Date newDate() {
LocalDate localDate = LocalDate.now();
return Date.valueOf(localDate);
}
/**
* Permet de calculer la date retour maximal en fonction de l'extention
*
* @param dateDebut Date
* @param extention Boolean
* @return java.sql.Date
*/
private Date dateDebutToFin(Date dateDebut, boolean extention) {
long dureePret = 28;
LocalDate dateFin;
if (!extention) {
dateFin = dateDebut.toLocalDate().plusDays(dureePret);
} else {
dateFin = dateDebut.toLocalDate().plusDays(dureePret * 2);
}
return Date.valueOf(dateFin);
}
}
<file_sep>package fr.biblioc.bibliocreservation.dao;
import fr.biblioc.bibliocreservation.model.Adresse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AdresseDao extends JpaRepository<Adresse, Integer> {
}
<file_sep>package fr.biblioc.mail.mail;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.ErrorCollector;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.junit.Rule;
import javax.mail.MessagingException;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MailSenderServiceImplTest {
Logger log = LoggerFactory.getLogger(this.getClass());
private static final String EMAIL = "<EMAIL>";
private static final String BODY = "Some contents.";
private static final String SUBJECT = "Some subject";
@Mock
private JavaMailSender javaMailSender;
//@Autowired
private MailSenderServiceImpl mailSender;
@Rule
public ErrorCollector collector = new ErrorCollector();
@BeforeEach
public void before() {
MockitoAnnotations.initMocks(this);
mailSender = new MailSenderServiceImpl(javaMailSender);
}
@Test
public void send_should_return_exception() throws MessagingException {
mailSender.setHtmlFormat(false);
mailSender.send(EMAIL, SUBJECT, BODY);
// Act
//Mailbox.get(email);
// Assert
ArgumentCaptor<SimpleMailMessage> emailCaptor =
ArgumentCaptor.forClass(SimpleMailMessage .class);
verify(javaMailSender, times(1)).send(emailCaptor.capture());
List<SimpleMailMessage> actualList = emailCaptor.getAllValues();
collector.checkThat(actualList.size(), equalTo(1));
collector.checkThat(actualList.get(0).getSubject(), equalTo(SUBJECT));
collector.checkThat(actualList.get(0).getText(), equalTo(BODY));
}
}
<file_sep>package fr.biblioc.bibliocreservation.mapper;
import fr.biblioc.bibliocreservation.dto.PreReservationDto;
import fr.biblioc.bibliocreservation.model.PreReservation;
import org.mapstruct.Mapper;
/**
* Mapper mapstruct de l'Entity au DTO et l'inverse
*/
@Mapper(componentModel = "spring")
public interface PreReservationMapper {
PreReservationDto preReservationToPreReservationDto(PreReservation preReservation);
PreReservation preReservationDtoToPreReservation(PreReservationDto preReservationDto);
}
<file_sep>package fr.biblioc.bibliocauthentification.dto;
/**
* dto Compte
*/
public class CompteDto {
//------------------------- ATTRIBUTS -------------------------
private int id_compte;
private String email;
private String password;
private int id_role;
private int id_utilisateur;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public CompteDto() {
}
/**
* Constructeur avec parametres
* @param email String
* @param password String
* @param id_role int
* @param id_utilisateur int
*/
public CompteDto(String email, String password, int id_role, int id_utilisateur) {
this.email = email;
this.password = <PASSWORD>;
this.id_role = id_role;
this.id_utilisateur = id_utilisateur;
}
//------------------------- GETTER/SETTER -------------------------
public int getId_compte() {
return id_compte;
}
public void setId_compte(int id_compte) {
this.id_compte = id_compte;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return <PASSWORD>;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public int getId_role() {
return id_role;
}
public void setId_role(int id_role) {
this.id_role = id_role;
}
public int getId_utilisateur() {
return id_utilisateur;
}
public void setId_utilisateur(int id_utilisateur) {
this.id_utilisateur = id_utilisateur;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Compte{" +
"id_compte=" + id_compte +
", email='" + email + '\'' +
", password='" + <PASSWORD> + '\'' +
", id_role=" + id_role +
", id_utilisateur=" + id_utilisateur +
'}';
}
}
<file_sep>package fr.biblioc.bibliocreservation.model;
import fr.biblioc.bibliocreservation.web.exceptions.ErrorAddException;
import fr.biblioc.bibliocreservation.web.exceptions.ObjectNotFoundException;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Entity(name = "liste_attente")
public class ListeAttente {
//------------------------- ATTRIBUTS -------------------------
@Id
private int id_liste_attente;
@Transient
private int nbreExemplaire;
@OneToMany(mappedBy = "id_liste_attente")
private List<PreReservation> preReservationList;
private int id_livre;
@Column(name = "id_biblio")
private int id_bibliotheque;
//------------------------- CONSTRUCTEUR -------------------------
public ListeAttente(){
preReservationList = new ArrayList<PreReservation>();
}
//------------------------- GETTER/SETTER -------------------------
public int getId_liste_attente() {
return id_liste_attente;
}
public void setId_liste_attente(int id_liste_attente) {
this.id_liste_attente = id_liste_attente;
}
public int getNbreExemplaire() {
return nbreExemplaire;
}
public void setNbreExemplaire(int nbreExemplaire) {
this.nbreExemplaire = nbreExemplaire;
}
public List<PreReservation> getPreReservationList() {
return preReservationList;
}
public void setPreReservationList(List<PreReservation> preReservationList) {
this.preReservationList = preReservationList;
}
public int getId_livre() {
return id_livre;
}
public void setId_livre(int id_livre) {
this.id_livre = id_livre;
}
public int getId_bibliotheque() {
return id_bibliotheque;
}
public void setId_bibliotheque(int id_bibliotheque) {
this.id_bibliotheque = id_bibliotheque;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "ListeAttente{" +
"id_liste_attente=" + id_liste_attente +
", nbreExemplaire=" + nbreExemplaire +
// ", preReservationList=" + preReservationList +
", id_livre='" + id_livre + '\'' +
", id_bibliotheque=" + id_bibliotheque +
'}';
}
}
<file_sep>package fr.biblioc.bibliocbibliotheque.dto;
import fr.biblioc.bibliocbibliotheque.model.Auteur;
import fr.biblioc.bibliocbibliotheque.model.Editeur;
import fr.biblioc.bibliocbibliotheque.model.Genre;
import java.util.List;
/**
* Dto Livre
*/
public class LivreDto {
//------------------------- ATTRIBUTS -------------------------
private int id_livre;
private String isbn13;
private Genre genre;
private String titre;
private List<Auteur> auteurs;
private String resume;
private String image;
private int annee_parution;
private Editeur editeur;
//------------------------- CONSTRUCTEUR -------------------------
/**
* constructeur
*/
public LivreDto() {
}
/**
* Constructeur avec ses parametres
*
* @param isbn13-
* @param genre-
* @param titre-
* @param auteurs List d'auteurs
* @param resume-
* @param image-
* @param annee_parution-
* @param editeur-
*/
public LivreDto(String isbn13, Genre genre, String titre, List<Auteur> auteurs, String resume, String image, int annee_parution,Editeur editeur) {
this.isbn13 = isbn13;
this.genre = genre;
this.titre = titre;
this.auteurs = auteurs;
this.resume = resume;
this.image = image;
this.annee_parution = annee_parution;
this.editeur = editeur;
}
//------------------------- GETTER/SETTER -------------------------
public int getid_livre() {
return id_livre;
}
public void setid_livre(int id_livre) {
this.id_livre = id_livre;
}
public String getIsbn13() {
return isbn13;
}
public void setIsbn13(String isbn13) {
this.isbn13 = isbn13;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public List<Auteur> getAuteurs() {
return auteurs;
}
public void setAuteurs(List<Auteur> auteurs) {
this.auteurs = auteurs;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getAnnee_parution() {
return annee_parution;
}
public void setAnnee_parution(int annee_parution) {
this.annee_parution = annee_parution;
}
public Editeur getEditeur() {
return editeur;
}
public void setEditeur(Editeur editeur) {
this.editeur = editeur;
}
//------------------------- TO_STRING -------------------------
@Override
public String toString() {
return "Livre{" +
"id_livre=" + id_livre +
", isbn13='" + isbn13 + '\'' +
", genre=" + genre +
", titre='" + titre + '\'' +
", auteurs=" + auteurs +
", resume='" + resume + '\'' +
", image='" + image + '\'' +
", annee_parution=" + annee_parution +
", editeur=" + editeur +
'}';
}
}
<file_sep>package fr.biblioc.bibliocbibliotheque.mapper;
import fr.biblioc.bibliocbibliotheque.dto.LivreDto;
import fr.biblioc.bibliocbibliotheque.model.Livre;
import org.mapstruct.Mapper;
/**
* Interface de mapping entre entity et Dto
*/
@Mapper(componentModel = "spring")
public interface LivreMapper {
LivreDto livreToLivreDto(Livre livre);
Livre livreDtoToLivre(LivreDto livreDto);
}
| 4ec98d3a7275bd2033be393cb7fbb70c82cb56b6 | [
"SQL",
"HTML",
"Markdown",
"INI",
"Java"
] | 59 | INI | benzouille/projet_10_R | 28dc9bcaa032fe64aaa49ceab0676a7e9ba4c6be | 73226bcceea7aa365cffa24e8b052a5c4d975f31 |
refs/heads/master | <repo_name>van4esco/fotick<file_sep>/WEB/DAL/Entities/ImageTag.cs
using System;
namespace DAL.Entities
{
public class ImageTag:BaseEntity
{
public Guid ImageId { get; set; }
public Guid TagId { get; set; }
}
}
<file_sep>/src/main/java/com/example/fotick/PostInterface.java
package com.example.fotick;
import org.json.JSONArray;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* Created by ПОДАРУНКОВИЙ on 14.05.2017.
*/
public interface PostInterface {
@POST("users")
Call<String> getStringScalar(@Body String body);
@POST("images/hateinsta2")
Call<String> getArray(@Body JSONArray body);
@POST("images/user/sale")
Call<String> getArraySale(@Body JSONArray body);
}
<file_sep>/WEB/DAL/Entities/BaseEntity.cs
using System;
namespace DAL.Entities
{
public abstract class BaseEntity
{
public Guid Id { get; set; }
public DateTime AddedDate { get; set; }
protected BaseEntity()
{
Id = Guid.NewGuid();
AddedDate = DateTime.UtcNow;
}
}
}
<file_sep>/WEB/BLL/TagsManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using BLL.Extensions;
using DAL.Entities;
using Newtonsoft.Json;
using BLL.Models;
using DAL;
namespace BLL
{
public class TagsManager:IDisposable
{
private string _accessToken;
private HttpClient _client;
public TagsManager()
{
InitializeClient();
}
private async void InitializeClient()
{
_client = new HttpClient()
{
BaseAddress = new Uri(ConfigurationManager.AppSettings["Clarifai:base_url"])
};
var content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>(){
new KeyValuePair<string,string>("client_id",ConfigurationManager.AppSettings["Clarifai:client_id"]),
new KeyValuePair<string,string>("client_secret",ConfigurationManager.AppSettings["Clarifai:client_secret"]),
new KeyValuePair<string,string>("grant_type",ConfigurationManager.AppSettings["Clarifai:grant_type"]),
});
var msgT = _client.PostAsync(ConfigurationManager.AppSettings["Clarifai:token_url"], content);
msgT.Wait();
var result = msgT.Result.Content.ReadAsStringAsync();
result.Wait();
_accessToken = result.Result.ToDictionary()["access_token"];
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken);
}
public async Task<IEnumerable<Tag>> GetTags(string url)
{
var obj = JsonConvert.SerializeObject(new TagManagerModel
{
Inputs = new List<Input>(){
new Input{
Data = new Data{
Image = new Models.Image{
Url = url
}
}
}
}
});
var curl = ConfigurationManager.AppSettings["Clarifai:url"];
var model = ConfigurationManager.AppSettings["Clarifai:model"];
curl = curl.Replace("{0}", model);
var msg = await _client.PostAsync(curl, new StringContent(obj, Encoding.UTF8, "application/json"));
var json = await msg.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Model>(json);
var list = new List<Tag>();
using (var db = FontickDbContext.Create())
{
foreach (var item in result.Outputs[0].Data.Concepts)
{
var tag = db.Tags.FirstOrDefault(p => p.Text == item.Name);
if (tag == null)
{
tag = new Tag
{
Text = item.Name
};
db.Tags.Add(tag);
}
list.Add(tag);
}
db.SaveChanges();
return list;
}
}
public void Dispose()
{
if (_client != null)
_client.Dispose();
}
}
}
<file_sep>/WEB/WEB/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Web.Mvc;
using DAL;
using System.Net;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Fotick.Api.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string tag)
{
using (var db = FontickDbContext.Create())
{
if (!string.IsNullOrWhiteSpace(tag))
{
return View(db.Images.Where(p => p.IsForSale && p.Tags != null && p.Tags.Any(pp => pp.Text.Intersect(tag).Count() > 0)).Select(p => p.Url));
}
return View();
}
}
public FileStreamResult DownloadItem(string url)
{
Stream stream = null;
stream = GetImageStreamFromUrl(url);
return File(stream, "image/jpeg", "ImageName");
}
public Stream GetImageStreamFromUrl(string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (Stream stream = httpWebReponse.GetResponseStream())
{
return stream;
}
}
}
}
}
<file_sep>/WEB/DAL/FontickDbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using DAL.Entities;
namespace DAL
{
public class FontickDbContext:DbContext
{
public FontickDbContext():base("DefaultConnection")
{
Database.CreateIfNotExists();
Database.SetInitializer(new DropCreateDatabaseAlways<FontickDbContext>());
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Image> Images { get; set; }
public virtual DbSet<Tag> Tags { get; set; }
public static FontickDbContext Create() => new FontickDbContext();
}
}
<file_sep>/WEB/BLL/Extensions/StringExtensions.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Extensions
{
public static class StringExtensions
{
public static Dictionary<string, string> ToDictionary(this string str)
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
}
}
}
<file_sep>/WEB/WEB/Controllers/Api/UsersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using BLL;
using DAL;
using System.Threading.Tasks;
using DAL.Entities;
using System.Web.Http;
using Newtonsoft.Json;
namespace Fotick.Api.Web.Controllers
{
[Route("api/Users")]
public class UsersController : ApiController
{
[HttpPost]
public System.Web.Mvc.ActionResult Post([FromBody]string userName)
{
try
{
if(string.IsNullOrWhiteSpace(userName))
{
return new System.Web.Mvc.HttpStatusCodeResult(400);
}
using (var db = FontickDbContext.Create())
{
var user = db.Users.FirstOrDefault(p => p.UserName == userName);
if (user != null)
{
return new System.Web.Mvc.HttpStatusCodeResult(200);
}
user = new User
{
Login = userName,
UserName = userName
};
db.Users.Add(user);
db.SaveChanges();
return new System.Web.Mvc.HttpStatusCodeResult(200);
}
}
catch (Exception e)
{
return new System.Web.Mvc.HttpStatusCodeResult(500);
}
}
}
}
<file_sep>/src/main/java/com/example/fotick/ImageAdapter.java
package com.example.fotick;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import com.example.fotick.POJO.Image;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.Holder> {
//private ImageClickListener mlistener;
private List<Image> mPictures;
private List<Image> currentPictures;
CustomItemClickListener listener;
public ImageAdapter(List<Image> pics, CustomItemClickListener listener){
mPictures = pics;
this.listener = listener;
}
@Override
public Holder onCreateViewHolder(ViewGroup viewGroup, final int i) {
View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_item, viewGroup, false);
final Holder mViewHolder = new Holder(row);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClick(v, i);
}
});
return new Holder(row);
}
@Override
public void onBindViewHolder(final Holder holder, int i) {
final Image currPic = mPictures.get(i);
Picasso.with(holder.itemView.getContext()).load(currPic.getURL()).into(holder.mPhoto1);
holder.mPhoto1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("AAAAAAAAAAAAAAAAAAAAAA","AAAAAAAAAAAAAAAAAAAA "+currPic.getURL());
currPic.setChoosed(!currPic.getChoosed());
Log.d("AAAAAAAAAAAAAAAAAAA",String.valueOf(currPic.getChoosed()));
if(currPic.getChoosed()){
v.setBackgroundResource(R.drawable.shape);
}else{
v.setBackgroundResource(R.drawable.none);
}
}
});
}
@Override
public int getItemCount() {
return mPictures.size();
}
public Image getSelectedPicture(int position) {
return mPictures.get(position);
}
// public void addImage(Picture picture) {
// mPictures.add(picture);
// }
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView mPhoto1, mPhoto2;
public Holder(View itemView) {
super(itemView);
mPhoto1 = (ImageView)itemView.findViewById(R.id.image1);
//mPhoto2 = (ImageView)itemView.findViewById(R.id.image2);
}
@Override
public void onClick(View v) {
Log.d("test pls",String.valueOf(v.getId())) ;
Log.d("test pls",v.toString());
Log.d("test pls",v.getTag().toString());
}
}
}<file_sep>/src/main/java/com/example/fotick/CustomItemClickListener.java
package com.example.fotick;
import android.view.View;
/**
* Created by ПОДАРУНКОВИЙ on 14.05.2017.
*/
public interface CustomItemClickListener {
public void onItemClick(View v, int position);
}<file_sep>/src/main/java/com/example/fotick/POJO/Image.java
package com.example.fotick.POJO;
/**
* Created by ПОДАРУНКОВИЙ on 13.05.2017.
*/
public class Image {
String URL;
Boolean choosed=false;
public Boolean getChoosed() {
return choosed;
}
public void setChoosed(Boolean choosed) {
this.choosed = choosed;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
}
<file_sep>/WEB/DAL/Entities/User.cs
using System.Collections.Generic;
namespace DAL.Entities
{
public class User:BaseEntity
{
public string UserName { get; set; }
public string Login { get; set; }
public ICollection<Image> Images { get; set; }
}
}
<file_sep>/src/main/java/com/example/fotick/POJO/TokenResponse.java
package com.example.fotick.POJO;
/**
* Created by ПОДАРУНКОВИЙ on 13.05.2017.
*/
public class TokenResponse {
User user;
String acsess_token;
@Override
public String toString() {
return "TokenResponse{" +
"user=" + user +
", acsess_token='" + acsess_token + '\'' +
'}';
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getAcsess_token() {
return acsess_token;
}
public void setAcsess_token(String acsess_token) {
this.acsess_token = acsess_token;
}
}
<file_sep>/WEB/DAL/Entities/Tag.cs
using System.Collections.Generic;
namespace DAL.Entities
{
public class Tag:BaseEntity
{
public string Text { get; set; }
public ICollection<Image> Images { get; set; }
}
}
<file_sep>/src/main/java/com/example/fotick/SplashActivity.java
package com.example.fotick;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class SplashActivity extends AppCompatActivity {
TextView logoTextView;
EditText login;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/sweetsensations.ttf");
logoTextView = (TextView)findViewById(R.id.fullscreen_content);
logoTextView.setTypeface(myTypeface);
Typeface myTypeface2 = Typeface.createFromAsset(getAssets(), "fonts/robotoregular.ttf");
login = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
button.setTypeface(myTypeface2);
}
public void onClick(View view) {
Intent intent = new Intent(SplashActivity.this, PhotosActivity.class);
intent.putExtra("login",login.getText().toString());
startActivity(intent);
}
}
<file_sep>/WEB/DAL/Entities/Image.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Entities
{
public class Image:BaseEntity
{
public string Url { get; set; }
public Guid UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public string AestheticsStatus { get; set; }
public string AestheticsPersent { get; set; }
public bool IsForSale { get; set; }
public ICollection<Tag> Tags { get; set; }
}
}
<file_sep>/WEB/DAL/Migrations/201705141302322_Initial.cs
namespace DAL.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Images",
c => new
{
Id = c.Guid(nullable: false),
Url = c.String(),
UserId = c.Guid(nullable: false),
AestheticsStatus = c.String(),
AestheticsPersent = c.String(),
IsForSale = c.Boolean(nullable: false),
AddedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.Tags",
c => new
{
Id = c.Guid(nullable: false),
Text = c.String(),
AddedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Users",
c => new
{
Id = c.Guid(nullable: false),
UserName = c.String(),
Login = c.String(),
AddedDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TagImages",
c => new
{
Tag_Id = c.Guid(nullable: false),
Image_Id = c.Guid(nullable: false),
})
.PrimaryKey(t => new { t.Tag_Id, t.Image_Id })
.ForeignKey("dbo.Tags", t => t.Tag_Id, cascadeDelete: true)
.ForeignKey("dbo.Images", t => t.Image_Id, cascadeDelete: true)
.Index(t => t.Tag_Id)
.Index(t => t.Image_Id);
}
public override void Down()
{
DropForeignKey("dbo.Images", "UserId", "dbo.Users");
DropForeignKey("dbo.TagImages", "Image_Id", "dbo.Images");
DropForeignKey("dbo.TagImages", "Tag_Id", "dbo.Tags");
DropIndex("dbo.TagImages", new[] { "Image_Id" });
DropIndex("dbo.TagImages", new[] { "Tag_Id" });
DropIndex("dbo.Images", new[] { "UserId" });
DropTable("dbo.TagImages");
DropTable("dbo.Users");
DropTable("dbo.Tags");
DropTable("dbo.Images");
}
}
}
<file_sep>/WEB/BLL/Models/TagManagersModel.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Models
{
public class TagManagerModel
{
[JsonProperty("inputs")]
public IEnumerable<Input> Inputs { get; set; }
}
public class Input
{
[JsonProperty("data")]
public Data Data { get; set; }
}
public class Data
{
[JsonProperty("image")]
public Image Image { get; set; }
}
public class Image
{
[JsonProperty("url")]
public string Url { get; set; }
}
public class Concept
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string value { get; set; }
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("app_id")]
public string app_id { get; set; }
}
public class DataResponse
{
[JsonProperty("concepts")]
public IEnumerable<Concept> Concepts { get; set; }
}
public class Output
{
[JsonProperty("data")]
public DataResponse Data { get; set; }
}
public class Model
{
[JsonProperty("outputs")]
public List<Output> Outputs { get; set; }
}
}
<file_sep>/README.md
Fotick
=======
Фотографируйте классные моменты, делитесь ими в Instagram и продавайте за реальные деньги!
Описание идеи:
--
Мобильное приложение-фотобанк, в котором пользователь может загружать красивые фото в Instagram и получать деньги
за их коммерческое использование дизайнерами, редакторами и другими специалистами.
Сегодня большинство камер на наших смартфонах способны делать снимки в разрешении, допустимым требованиям самых
известных фотобанков. А это значит, что абсолютно каждый обладатель такого смартфона может удовлетворять не только свои
социальные потребности, вылаживая их в Instagram, но и финансовые, продавая их с помощью нашего приложения Fotick.
По самым свежим данным, в Instagram уже загружено более 40 миллиардов фото и 2,4 миллиарда загружается ежемесячно.
Если предположить, что там только 1 фото из 500 достойного продажи, получается база из 80 миллионов фото, что в
полтора раза больше, чем на одном из самых больших фотобанков - Deposit photos.
С помощью готовых решений нейронных сетей мы сможем:
* автоматически подбирать ключевые слова для фото;
* эстетически оценивать каждое фото;
* соответственно ускорить процесс модерации и появления фото в общем каталоге;
* рекомендовать пользователям, какие фото из их Instagram стоит выложить на продажу.
Купить эти фото можно будет на вебсайте Fotick с релевантным поиском и приятными тарифами.
Состав команды:
--
1. <NAME> - Product manager, Designer;
2. <NAME> - Full stack dev;
3. <NAME> - Android dev.
Контактные данные представителя команды:
--
[ФЕЙСБУК](https://www.facebook.com/van4esco) или <EMAIL> - Иван.
<file_sep>/WEB/WEB/Controllers/Api/ImagesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using BLL;
using DAL;
using System.Threading.Tasks;
using DAL.Entities;
using System.Web.Http;
using Newtonsoft.Json;
using WEB.App_Start;
using System.Net.Http;
using System.Web.Hosting;
namespace Fotick.Api.Web.Controllers
{
[RoutePrefix("api/Images")]
public class ImagesController : ApiController
{
[Route("{userName}")]
[HttpPost()]
public System.Web.Mvc.ActionResult Load([FromUri]string userName,[FromBody]IEnumerable<string> images)
{
try
{
using (var db = FontickDbContext.Create())
{
var user = db.Users.FirstOrDefault(p => p.UserName == userName);
if (user == null)
return new System.Web.Mvc.HttpStatusCodeResult(500);
foreach (var item in images)
{
if (db.Images.FirstOrDefault(p => p.Url == item) == null)
{
var image = new Image()
{
Url = item,
UserId = user.Id
};
db.Images.Add(image);
}
}
db.SaveChanges();
return new System.Web.Mvc.HttpStatusCodeResult(200);
}
}
catch(Exception e)
{
return new System.Web.Mvc.HttpStatusCodeResult(500);
}
}
[Route("{userName}/sell")]
[HttpPost]
public async Task<System.Web.Mvc.ActionResult> SellAsync(string userName, [FromBody]IEnumerable<string> images)
{
using (var db = FontickDbContext.Create())
{
var tagsManager = new TagsManager();
var random = new Random();
var user = db.Users.FirstOrDefault(p => p.UserName == userName);
if (user == null)
return new System.Web.Mvc.HttpStatusCodeResult(400);
foreach (var item in images)
{
var image = db.Images.FirstOrDefault(p => p.Url == item);
var t = random.Next(0, 10001) % 2 == 0;
if (image == null)
{
image = new Image()
{
Url = item,
UserId = user.Id,
IsForSale = t
};
db.Images.Add(image);
}
else
{
image.IsForSale = t;
db.Entry(image).State = System.Data.Entity.EntityState.Modified;
}
var tags = await tagsManager.GetTags(item);
if (image.Tags == null)
image.Tags = new List<Tag>();
foreach (var i in tags)
{
image.Tags.Add(i);
}
db.SaveChanges();
}
return new System.Web.Mvc.HttpStatusCodeResult(200);
}
}
[Route("Tags")]
[HttpGet]
public string GetTags([FromUri]string url){
using (var db = FontickDbContext.Create())
{
return JsonConvert.SerializeObject(db.Images.FirstOrDefault(p => p.Url == url)?.Tags);
}
}
[Route("User")]
[HttpGet()]
public string GetUser([FromUri]string url)
{
using (var db = FontickDbContext.Create())
{
return db.Users.FirstOrDefault(p => p.Images != null && p.Images.Any(x => x.Url == url)).Login;
}
}
[Route("{userName}/files")]
[HttpPost]
public async Task<IHttpActionResult> UploadSingleFile([FromUri]string userName)
{
try
{
var path = HostingEnvironment.MapPath($"~/Content/Files/Images/{userName}");
var streamProvider = new MultipartFormDataStreamProvider(path);
await Request.Content.ReadAsMultipartAsync(streamProvider);
using (var db = FontickDbContext.Create())
{
var tagsManager = new TagsManager();
var user = db.Users.FirstOrDefault(p => p.UserName == userName);
var url = $"https://fotick-test.azurewebsites.net/Content/Files/Images/{userName}/{streamProvider.FileData.Select(entry => entry.LocalFileName)}";
var image = new Image()
{
Url = url,
UserId = user.Id,
IsForSale = true,
Tags = new List<Tag>()
};
db.Images.Add(image);
var tags = await tagsManager.GetTags(url);
foreach (var item in tags)
{
image.Tags.Add(item);
}
db.SaveChanges();
return Ok();
}
}
catch(Exception){
return BadRequest();
}
}
[Route("{userName}")]
[HttpGet]
public string Images([FromUri]string userName)
{
using (var db = FontickDbContext.Create())
{
return JsonConvert.SerializeObject(db.Images.Where(p =>p.IsForSale && p.User.UserName == userName).Select(p => p.Url));
}
}
}
}
| 04bc9a026667bfe8fc9d84fc1cd204c84f7238cd | [
"Java",
"C#",
"Markdown"
] | 20 | C# | van4esco/fotick | f809ae38f4124f75ffd1687e59228b0708b89b7b | d65f2ebd33156220632b6771668091c5ce448039 |
refs/heads/main | <file_sep><?php
namespace Surgems\EnvCondition\Modifiers;
use Statamic\Modifiers\Modifier;
class IfEnv extends Modifier
{
protected static $handle = 'if_env';
public function index($value, $params, $context)
{
$env = trim(strtolower(env('APP_ENV')));
foreach($params as $param)
{
if($param == $env) return $value;
}
return false;
}
}<file_sep><?php
namespace Surgems\EnvCondition;
use Statamic\Providers\AddonServiceProvider;
use Surgems\EnvCondition\Tags\IfEnv as IfEnvTag;
use Surgems\EnvCondition\Modifiers\IfEnv;
use Surgems\EnvCondition\Modifiers\IfEnvNot;
class ServiceProvider extends AddonServiceProvider
{
protected $modifiers = [
IfEnv::class,
IfEnvNot::class
];
protected $tags = [
IfEnvTag::class
];
public function bootAddon()
{
//
}
}
<file_sep><?php
namespace Surgems\EnvCondition\Tags;
use Exception;
use Statamic\Tags\Tags;
class IfEnv extends Tags
{
public function index()
{
$params = $this->params->explode("env");
if(isset($params))
{
$env = trim(strtolower(env('APP_ENV')));
foreach($params as $param)
{
if($param == $env) return [];
}
return false;
}
throw new Exception('No env parameters set on if_env tag.');
}
public function not()
{
$params = $this->params->explode("env");
if(isset($params))
{
$env = trim(strtolower(env('APP_ENV')));
foreach($params as $param)
{
if($param == $env) return false;
}
return [];
}
throw new Exception('No env parameters set on if_env:not tag.');
}
}
<file_sep># Change Log
All notable changes to this project will be documented in this file.
## [v2.0.0] - 12/07/2022
``` bash
composer require surgems/env-condition:2.0.0
```
### Added
- Tag for the if_env
### Changed
- README.md
### Fixed
## [Release] - 12/07/2022
``` bash
composer require surgems/env-condition:1.0.0
```
### Added
- Initial release of the Statamic addon
### Changed
### Fixed
<file_sep># Env Condition
> Env Condition is a Statamic Modifier that only displays it's content in a selected environment.
## Features
This addon does:
- Allows you to display content/fields based on the <code>APP_ENV</code>.
## How to Install
You can use this addon by running the following command from your project root:
``` bash
composer require surgems/env-condition
```
## How to Use
This addons uses 3 environments:
- local
- staging
- production
### Tag
You can display content inside the tag depending on the condition of the <code>APP_ENV</code>.
There are 2 tag Methods:
```antlers
{{ if_env env="local" }}
{{ content | widont }}
{{ /if_env }}
```
This would display the content inside the tags if the <code>APP_ENV</code> IS 'local'.
```antlers
{{ if_env:not env="local" }}
{{ content | widont }}
{{ /if_env:not }}
```
This would display the content inside the tags if the <code>APP_ENV</code> IS NOT 'local'.
You can also add multiple parameters:
```antlers
{{ if_env:not env="local|staging" }}
{{ content | widont }}
{{ /if_env:not }}
```
This would display the content inside the tags if the <code>APP_ENV</code> IS NOT 'local' OR 'staging'.
### Modifier
You can display a field whenever the <code>APP_ENV</code> is a certain environment.
There are 2 modifiers:
```antlers
{{ field | if_env:local }}
```
This would display the field content if the <code>APP_ENV</code> IS equal to 'local'.
```antlers
{{ field | if_env_not:local }}
```
This would display the field content if the <code>APP_ENV</code> IS NOT equal to 'local'.
You can also add multiple parameters:
```antlers
{{ field | if_env:local:staging }}
```
| 4d128e3f325f1e7481eb4824914a39b7a91529d4 | [
"Markdown",
"PHP"
] | 5 | PHP | JacobTinston/StatamicEnvCondition | 238a2346ef949bff45ef7ae0f83e9bfe1fe739e3 | 9b2f6142a3352346b05d6754652564a3c4628796 |
refs/heads/master | <file_sep>using System.Data;
using MySqlConnector.Core;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlBatchCommand : IMySqlCommand
{
public MySqlBatchCommand()
: this(null)
{
}
public MySqlBatchCommand(string? commandText)
{
CommandText = commandText;
CommandType = CommandType.Text;
}
public string? CommandText { get; set; }
public CommandType CommandType { get; set; }
public CommandBehavior CommandBehavior { get; set; }
public int RecordsAffected { get; set; }
public MySqlParameterCollection Parameters => m_parameterCollection ??= new MySqlParameterCollection();
bool IMySqlCommand.AllowUserVariables => false;
MySqlParameterCollection? IMySqlCommand.RawParameters => m_parameterCollection;
MySqlConnection? IMySqlCommand.Connection => Batch?.Connection;
long IMySqlCommand.LastInsertedId => m_lastInsertedId;
PreparedStatements? IMySqlCommand.TryGetPreparedStatements() => null;
void IMySqlCommand.SetLastInsertedId(long lastInsertedId) => m_lastInsertedId = lastInsertedId;
MySqlParameterCollection? IMySqlCommand.OutParameters { get; set; }
MySqlParameter? IMySqlCommand.ReturnParameter { get; set; }
ICancellableCommand IMySqlCommand.CancellableCommand => Batch!;
internal MySqlBatch? Batch { get; set; }
MySqlParameterCollection? m_parameterCollection;
long m_lastInsertedId;
}
}
<file_sep>#if !NETSTANDARD1_3
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using MySql.Data.MySqlClient;
namespace MySqlConnector.Core
{
internal sealed class SchemaProvider
{
public SchemaProvider(MySqlConnection connection)
{
m_connection = connection;
m_schemaCollections = new Dictionary<string, Action<DataTable>>
{
{ "DataSourceInformation", FillDataSourceInformation},
{ "MetaDataCollections", FillMetadataCollections },
{ "CharacterSets", FillCharacterSets },
{ "Collations", FillCollations },
{ "CollationCharacterSetApplicability", FillCollationCharacterSetApplicability },
{ "Columns", FillColumns },
{ "Databases", FillDatabases },
{ "DataTypes", FillDataTypes },
{ "Engines", FillEngines },
{ "KeyColumnUsage", FillKeyColumnUsage },
{ "KeyWords", FillKeyWords },
{ "Parameters", FillParameters },
{ "Partitions", FillPartitions },
{ "Plugins", FillPlugins },
{ "Procedures", FillProcedures },
{ "ProcessList", FillProcessList },
{ "Profiling", FillProfiling },
{ "ReferentialConstraints", FillReferentialConstraints },
{ "ReservedWords", FillReservedWords },
{ "ResourceGroups", FillResourceGroups },
{ "SchemaPrivileges", FillSchemaPrivileges },
{ "Tables", FillTables },
{ "TableConstraints", FillTableConstraints },
{ "TablePrivileges", FillTablePrivileges },
{ "TableSpaces", FillTableSpaces },
{ "Triggers", FillTriggers },
{ "UserPrivileges", FillUserPrivileges },
{ "Views", FillViews },
};
}
public DataTable GetSchema() => GetSchema("MetaDataCollections");
public DataTable GetSchema(string collectionName)
{
if (collectionName is null)
throw new ArgumentNullException(nameof(collectionName));
if (!m_schemaCollections.TryGetValue(collectionName, out var fillAction))
throw new ArgumentException("Invalid collection name.", nameof(collectionName));
var dataTable = new DataTable(collectionName);
fillAction(dataTable);
return dataTable;
}
private void FillDataSourceInformation(DataTable dataTable)
{
dataTable.Columns.AddRange(new [] {
new DataColumn("CompositeIdentifierSeparatorPattern", typeof(string)),
new DataColumn("DataSourceProductName", typeof(string)),
new DataColumn("DataSourceProductVersion", typeof(string)),
new DataColumn("DataSourceProductVersionNormalized", typeof(string)),
new DataColumn("GroupByBehavior", typeof(GroupByBehavior)),
new DataColumn("IdentifierPattern", typeof(string)),
new DataColumn("IdentifierCase", typeof(IdentifierCase)),
new DataColumn("OrderByColumnsInSelect", typeof(bool)),
new DataColumn("ParameterMarkerFormat", typeof(string)),
new DataColumn("ParameterMarkerPattern", typeof(string)),
new DataColumn("ParameterNameMaxLength", typeof(int)),
new DataColumn("QuotedIdentifierPattern", typeof(string)),
new DataColumn("QuotedIdentifierCase", typeof(IdentifierCase)),
new DataColumn("ParameterNamePattern", typeof(string)),
new DataColumn("StatementSeparatorPattern", typeof(string)),
new DataColumn("StringLiteralPattern", typeof(string)),
new DataColumn("SupportedJoinOperators", typeof(SupportedJoinOperators))
});
var row = dataTable.NewRow();
row["CompositeIdentifierSeparatorPattern"] = @"\.";
row["DataSourceProductName"] = "MySQL";
row["DataSourceProductVersion"] = m_connection.ServerVersion;
row["DataSourceProductVersionNormalized"] = GetVersion(m_connection.Session.ServerVersion.Version);
row["GroupByBehavior"] = GroupByBehavior.Unrelated;
row["IdentifierPattern"] = @"(^\[\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\[[^\]\0]|\]\]+\]$)|(^\""[^\""\0]|\""\""+\""$)";
row["IdentifierCase"] = IdentifierCase.Insensitive;
row["OrderByColumnsInSelect"] = false;
row["ParameterMarkerFormat"] = @"{0}";
row["ParameterMarkerPattern"] = @"(@[A-Za-z0-9_$#]*)";
row["ParameterNameMaxLength"] = 128; // For function out parameters
row["QuotedIdentifierPattern"] = @"(([^\`]|\`\`)*)";
row["QuotedIdentifierCase"] = IdentifierCase.Sensitive;
row["ParameterNamePattern"] = @"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
row["StatementSeparatorPattern"] = ";";
row["StringLiteralPattern"] = @"'(([^']|'')*)'";
row["SupportedJoinOperators"] =
SupportedJoinOperators.FullOuter |
SupportedJoinOperators.Inner |
SupportedJoinOperators.LeftOuter |
SupportedJoinOperators.RightOuter;
dataTable.Rows.Add(row);
}
private string GetVersion(Version v) => $"{v.Major:00}.{v.Minor:00}.{v.Build:0000}";
private void FillMetadataCollections(DataTable dataTable)
{
dataTable.Columns.AddRange(new[] {
new DataColumn("CollectionName", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("NumberOfRestrictions", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("NumberOfIdentifierParts", typeof(int)) // lgtm[cs/local-not-disposed]
});
foreach (var collectionName in m_schemaCollections.Keys)
dataTable.Rows.Add(collectionName, 0, 0);
}
private void FillCharacterSets(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFAULT_COLLATE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DESCRIPTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("MAXLEN", typeof(int)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "CHARACTER_SETS");
}
private void FillCollations(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("COLLATION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ID", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_DEFAULT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_COMPILED", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SORTLEN", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("PAD_ATTRIBUTE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "COLLATIONS");
}
private void FillCollationCharacterSetApplicability(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("COLLATION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "COLLATION_CHARACTER_SET_APPLICABILITY");
}
private void FillColumns(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ORDINAL_POSITION", typeof(uint)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_DEFAULT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_NULLABLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_MAXIMUM_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("NUMERIC_PRECISION", typeof(ulong)), // lgtm[cs/local-not-disposed]
new DataColumn("NUMERIC_SCALE", typeof(ulong)), // lgtm[cs/local-not-disposed]
new DataColumn("DATETIME_PRECISION", typeof(uint)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLLATION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_KEY", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EXTRA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PRIVILEGES", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
});
using (var command = new MySqlCommand("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'information_schema' AND table_name = 'COLUMNS' AND column_name = 'GENERATION_EXPRESSION';", m_connection))
{
if (command.ExecuteScalar() is object)
dataTable.Columns.Add(new DataColumn("GENERATION_EXPRESSION", typeof(string))); // lgtm[cs/local-not-disposed]
}
using (var command = new MySqlCommand("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'information_schema' AND table_name = 'COLUMNS' AND column_name = 'SRS_ID';", m_connection))
{
if (command.ExecuteScalar() is object)
dataTable.Columns.Add(new DataColumn("SRS_ID", typeof(uint))); // lgtm[cs/local-not-disposed]
}
FillDataTable(dataTable, "COLUMNS");
}
private void FillDatabases(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("CATALOG_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SCHEMA_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFAULT_CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFAULT_COLLATION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SQL_PATH", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "SCHEMATA");
}
private void FillDataTypes(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TypeName", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ProviderDbType", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("ColumnSize", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("CreateFormat", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CreateParameters", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DataType", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IsAutoIncrementable", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsBestMatch", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsCaseSensitive", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsFixedLength", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsFixedPrecisionScale", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsLong", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsNullable", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsSearchable", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsSearchableWithLike", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsUnsigned", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("MaximumScale", typeof(short)), // lgtm[cs/local-not-disposed]
new DataColumn("MinimumScale", typeof(short)), // lgtm[cs/local-not-disposed]
new DataColumn("IsConcurrencyType", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("IsLiteralSupported", typeof(bool)), // lgtm[cs/local-not-disposed]
new DataColumn("LiteralPrefix", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("LiteralSuffix", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("NativeDataType", typeof(string)), // lgtm[cs/local-not-disposed]
});
var clrTypes = new HashSet<string>();
foreach (var columnType in TypeMapper.Instance.GetColumnTypeMetadata())
{
// hard-code a few types to not appear in the schema table
var mySqlDbType = columnType.MySqlDbType;
if (mySqlDbType == MySqlDbType.Decimal || mySqlDbType == MySqlDbType.Newdate || mySqlDbType == MySqlDbType.Null || mySqlDbType == MySqlDbType.VarString)
continue;
if (mySqlDbType == MySqlDbType.Bool && columnType.IsUnsigned)
continue;
// set miscellaneous properties in code (rather than being data-driven)
var clrType = columnType.DbTypeMapping.ClrType;
var clrTypeName = clrType.ToString();
var dataTypeName = mySqlDbType == MySqlDbType.Guid ? "GUID" :
mySqlDbType == MySqlDbType.Bool ? "BOOL" : columnType.DataTypeName;
var isAutoIncrementable = mySqlDbType == MySqlDbType.Byte || mySqlDbType == MySqlDbType.Int16 || mySqlDbType == MySqlDbType.Int24 || mySqlDbType == MySqlDbType.Int32 || mySqlDbType == MySqlDbType.Int64 ||
mySqlDbType == MySqlDbType.UByte || mySqlDbType == MySqlDbType.UInt16 || mySqlDbType == MySqlDbType.UInt24 || mySqlDbType == MySqlDbType.UInt32 || mySqlDbType == MySqlDbType.UInt64;
var isBestMatch = clrTypes.Add(clrTypeName);
var isFixedLength = isAutoIncrementable ||
mySqlDbType == MySqlDbType.Date || mySqlDbType == MySqlDbType.DateTime || mySqlDbType == MySqlDbType.Time || mySqlDbType == MySqlDbType.Timestamp ||
mySqlDbType == MySqlDbType.Double || mySqlDbType == MySqlDbType.Float || mySqlDbType == MySqlDbType.Year || mySqlDbType == MySqlDbType.Guid || mySqlDbType == MySqlDbType.Bool;
var isFixedPrecisionScale = isFixedLength ||
mySqlDbType == MySqlDbType.Bit || mySqlDbType == MySqlDbType.NewDecimal;
var isLong = mySqlDbType == MySqlDbType.Blob || mySqlDbType == MySqlDbType.MediumBlob || mySqlDbType == MySqlDbType.LongBlob;
// map ColumnTypeMetadata to the row for this data type
var createFormatParts = columnType.CreateFormat.Split(';');
dataTable.Rows.Add(
dataTypeName,
(int)mySqlDbType,
columnType.ColumnSize,
createFormatParts[0],
createFormatParts.Length == 1 ? null : createFormatParts[1],
clrTypeName,
isAutoIncrementable,
isBestMatch,
false,
isFixedLength,
isFixedPrecisionScale,
isLong,
true,
clrType != typeof(byte[]),
clrType == typeof(string),
columnType.IsUnsigned,
DBNull.Value,
DBNull.Value,
DBNull.Value,
true,
DBNull.Value,
DBNull.Value,
null
);
}
}
private void FillEngines(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("ENGINE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SUPPORT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TRANSACTIONS", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("XA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SAVEPOINTS", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "ENGINES");
}
private void FillKeyColumnUsage(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("CONSTRAINT_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLUMN_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ORDINAL_POSITION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("POSITION_IN_UNIQUE_CONSTRAINT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("REFERENCED_TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("REFERENCED_TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("REFERENCED_COLUMN_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "KEY_COLUMN_USAGE");
}
private void FillKeyWords(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("WORD", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("RESERVED", typeof(int)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "KEYWORDS");
}
private void FillParameters(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("SPECIFIC_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SPECIFIC_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SPECIFIC_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ORDINAL_POSITION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("PARAMETER_MODE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARAMETER_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_MAXIMUM_LENGTH", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_OCTET_LENGTH", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("NUMERIC_PRECISION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("NUMERIC_SCALE", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("DATETIME_PRECISION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLLATION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DTD_IDENTIFIER", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "PARAMETERS");
}
private void FillPartitions(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SUBPARTITION_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_ORDINAL_POSITION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("SUBPARTITION_ORDINAL_POSITION", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_METHOD", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SUBPARTITION_METHOD", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_EXPRESSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SUBPARTITION_EXPRESSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_DESCRIPTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_ROWS", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("AVG_ROW_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("MAX_DATA_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("INDEX_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_FREE", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("CREATE_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("UPDATE_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("CHECK_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("CHECKSUM", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("PARTITION_COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("NODEGROUP", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLESPACE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "PARTITIONS");
}
private void FillPlugins(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("PLUGIN_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_VERSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_STATUS", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_TYPE_VERSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_LIBRARY", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_LIBRARY_VERSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_AUTHOR", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_DESCRIPTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PLUGIN_LICENSE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("LOAD_OPTION", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "PLUGINS");
}
private void FillProcedures(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("SPECIFIC_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DTD_IDENTIFIER", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_BODY", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_DEFINITION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EXTERNAL_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EXTERNAL_LANGUAGE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PARAMETER_STYLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_DETERMINISTIC", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SQL_DATA_ACCESS", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SQL_PATH", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SECURITY_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CREATED", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("LAST_ALTERED", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("SQL_MODE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROUTINE_COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFINER", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "ROUTINES");
}
private void FillProcessList(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("ID", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("USER", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("HOST", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DB", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COMMAND", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TIME", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("STATE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("INFO", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "PROCESSLIST");
}
private void FillProfiling(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("QUERY_ID", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("SEQ", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("STATE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DURATION", typeof(decimal)), // lgtm[cs/local-not-disposed]
new DataColumn("CPU_USER", typeof(decimal)), // lgtm[cs/local-not-disposed]
new DataColumn("CPU_SYSTEM", typeof(decimal)), // lgtm[cs/local-not-disposed]
new DataColumn("CONTEXT_VOLUNTARY", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("CONTEXT_INVOLUNTARY", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("BLOCK_OPS_IN", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("BLOCK_OPS_OUT", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("MESSAGES_SENT", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("MESSAGES_RECEIVED", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("PAGE_FAULTS_MAJOR", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("PAGE_FAULTS_MINOR", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("SWAPS", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("SOURCE_FUNCTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SOURCE_FILE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SOURCE_LINE", typeof(int)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "PROFILING");
}
private void FillReferentialConstraints(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("CONSTRAINT_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("UNIQUE_CONSTRAINT_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("UNIQUE_CONSTRAINT_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("UNIQUE_CONSTRAINT_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("MATCH_OPTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("UPDATE_RULE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DELETE_RULE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("REFERENCED_TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "REFERENTIAL_CONSTRAINTS");
}
private void FillReservedWords(DataTable dataTable)
{
dataTable.Columns.Add(new DataColumn("ReservedWord", typeof(string))); // lgtm[cs/local-not-disposed]
// Note:
// For MySQL 8.0, the INFORMATION_SCHEMA.KEYWORDS table could be used to load the list at runtime,
// unfortunately this bug https://bugs.mysql.com/bug.php?id=90160 makes it impratical to do it
// (the bug is marked as fixed in MySQL 8.0.13, not published yet at the time of writing this note).
//
// Note:
// Once the previously mentioned bug will be fixed, for versions >= 8.0.13 reserved words could be
// loaded at runtime form INFORMATION_SCHEMA.KEYWORDS, and for other versions the hard coded list
// could be used (notice the list could change with the release, adopting the 8.0.12 list is a
// suboptimal one-size-fits-it-all solution.
// To get the current MySQL version at runtime one could query SELECT VERSION(); which returns a
// version followed by a suffix. The problem is that MariaDB 10.0 is only compatible with MySQL 5.6
// (but has a higher version number)
// select word from information_schema.keywords where reserved = 1; on MySQL Server 8.0.18
var reservedWords = new[]
{
"ACCESSIBLE",
"ADD",
"ALL",
"ALTER",
"ANALYZE",
"AND",
"AS",
"ASC",
"ASENSITIVE",
"BEFORE",
"BETWEEN",
"BIGINT",
"BINARY",
"BLOB",
"BOTH",
"BY",
"CALL",
"CASCADE",
"CASE",
"CHANGE",
"CHAR",
"CHARACTER",
"CHECK",
"COLLATE",
"COLUMN",
"CONDITION",
"CONSTRAINT",
"CONTINUE",
"CONVERT",
"CREATE",
"CROSS",
"CUBE",
"CUME_DIST",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"CURSOR",
"DATABASE",
"DATABASES",
"DAY_HOUR",
"DAY_MICROSECOND",
"DAY_MINUTE",
"DAY_SECOND",
"DEC",
"DECIMAL",
"DECLARE",
"DEFAULT",
"DELAYED",
"DELETE",
"DENSE_RANK",
"DESC",
"DESCRIBE",
"DETERMINISTIC",
"DISTINCT",
"DISTINCTROW",
"DIV",
"DOUBLE",
"DROP",
"DUAL",
"EACH",
"ELSE",
"ELSEIF",
"EMPTY",
"ENCLOSED",
"ESCAPED",
"EXCEPT",
"EXISTS",
"EXIT",
"EXPLAIN",
"FALSE",
"FETCH",
"FIRST_VALUE",
"FLOAT",
"FLOAT4",
"FLOAT8",
"FOR",
"FORCE",
"FOREIGN",
"FROM",
"FULLTEXT",
"FUNCTION",
"GENERATED",
"GET",
"GRANT",
"GROUP",
"GROUPING",
"GROUPS",
"HAVING",
"HIGH_PRIORITY",
"HOUR_MICROSECOND",
"HOUR_MINUTE",
"HOUR_SECOND",
"IF",
"IGNORE",
"IN",
"INDEX",
"INFILE",
"INNER",
"INOUT",
"INSENSITIVE",
"INSERT",
"INT",
"INT1",
"INT2",
"INT3",
"INT4",
"INT8",
"INTEGER",
"INTERVAL",
"INTO",
"IO_AFTER_GTIDS",
"IO_BEFORE_GTIDS",
"IS",
"ITERATE",
"JOIN",
"JSON_TABLE",
"KEY",
"KEYS",
"KILL",
"LAG",
"LAST_VALUE",
"LATERAL",
"LEAD",
"LEADING",
"LEAVE",
"LEFT",
"LIKE",
"LIMIT",
"LINEAR",
"LINES",
"LOAD",
"LOCALTIME",
"LOCALTIMESTAMP",
"LOCK",
"LONG",
"LONGBLOB",
"LONGTEXT",
"LOOP",
"LOW_PRIORITY",
"MASTER_BIND",
"MASTER_SSL_VERIFY_SERVER_CERT",
"MATCH",
"MAXVALUE",
"MEDIUMBLOB",
"MEDIUMINT",
"MEDIUMTEXT",
"MEMBER",
"MIDDLEINT",
"MINUTE_MICROSECOND",
"MINUTE_SECOND",
"MOD",
"MODIFIES",
"NATURAL",
"NOT",
"NO_WRITE_TO_BINLOG",
"NTH_VALUE",
"NTILE",
"NULL",
"NUMERIC",
"OF",
"ON",
"OPTIMIZE",
"OPTIMIZER_COSTS",
"OPTION",
"OPTIONALLY",
"OR",
"ORDER",
"OUT",
"OUTER",
"OUTFILE",
"OVER",
"PARTITION",
"PERCENT_RANK",
"PRECISION",
"PRIMARY",
"PROCEDURE",
"PURGE",
"RANGE",
"RANK",
"READ",
"READS",
"READ_WRITE",
"REAL",
"RECURSIVE",
"REFERENCES",
"REGEXP",
"RELEASE",
"RENAME",
"REPEAT",
"REPLACE",
"REQUIRE",
"RESIGNAL",
"RESTRICT",
"RETURN",
"REVOKE",
"RIGHT",
"RLIKE",
"ROW",
"ROWS",
"ROW_NUMBER",
"SCHEMA",
"SCHEMAS",
"SECOND_MICROSECOND",
"SELECT",
"SENSITIVE",
"SEPARATOR",
"SET",
"SHOW",
"SIGNAL",
"SMALLINT",
"SPATIAL",
"SPECIFIC",
"SQL",
"SQLEXCEPTION",
"SQLSTATE",
"SQLWARNING",
"SQL_BIG_RESULT",
"SQL_CALC_FOUND_ROWS",
"SQL_SMALL_RESULT",
"SSL",
"STARTING",
"STORED",
"STRAIGHT_JOIN",
"SYSTEM",
"TABLE",
"TERMINATED",
"THEN",
"TINYBLOB",
"TINYINT",
"TINYTEXT",
"TO",
"TRAILING",
"TRIGGER",
"TRUE",
"UNDO",
"UNION",
"UNIQUE",
"UNLOCK",
"UNSIGNED",
"UPDATE",
"USAGE",
"USE",
"USING",
"UTC_DATE",
"UTC_TIME",
"UTC_TIMESTAMP",
"VALUES",
"VARBINARY",
"VARCHAR",
"VARCHARACTER",
"VARYING",
"VIRTUAL",
"WHEN",
"WHERE",
"WHILE",
"WINDOW",
"WITH",
"WRITE",
"XOR",
"YEAR_MONTH",
"ZEROFILL",
};
foreach (string word in reservedWords)
dataTable.Rows.Add(word);
}
private void FillResourceGroups(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("RESOURCE_GROUP_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("RESOURCE_GROUP_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("RESOURCE_GROUP_ENABLED", typeof(int)), // lgtm[cs/local-not-disposed]
new DataColumn("VCPU_IDS", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("THREAD_PRIORITY", typeof(int)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "RESOURCE_GROUPS");
}
private void FillSchemaPrivileges(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("GRANTEE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PRIVILEGE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_GRANTABLE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "SCHEMA_PRIVILEGES");
}
private void FillTables(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ENGINE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("VERSION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ROW_FORMAT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_ROWS", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("AVG_ROW_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("MAX_DATA_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("INDEX_LENGTH", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("DATA_FREE", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("AUTO_INCREMENT", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("CREATE_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("UPDATE_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("CHECK_TIME", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_COLLATION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHECKSUM", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CREATE_OPTIONS", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "TABLES");
}
private void FillTableConstraints(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("CONSTRAINT_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CONSTRAINT_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "TABLE_CONSTRAINTS");
}
private void FillTablePrivileges(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("GRANTEE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PRIVILEGE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_GRANTABLE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "TABLE_PRIVILEGES");
}
private void FillTableSpaces(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TABLESPACE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ENGINE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLESPACE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("LOGFILE_GROUP_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EXTENT_SIZE", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("AUTOEXTEND_SIZE", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("MAXIMUM_SIZE", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("NODEGROUP_ID", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLESPACE_COMMENT", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "TABLESPACES");
}
private void FillTriggers(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TRIGGER_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TRIGGER_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TRIGGER_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EVENT_MANIPULATION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EVENT_OBJECT_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EVENT_OBJECT_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("EVENT_OBJECT_TABLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_ORDER", typeof(long)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_CONDITION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_STATEMENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_ORIENTATION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_TIMING", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_REFERENCE_OLD_TABLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_REFERENCE_NEW_TABLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_REFERENCE_OLD_ROW", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("ACTION_REFERENCE_NEW_ROW", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CREATED", typeof(DateTime)), // lgtm[cs/local-not-disposed]
new DataColumn("SQL_MODE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFINER", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_CLIENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLLATION_CONNECTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DATABASE_COLLATION", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "TRIGGERS");
}
private void FillUserPrivileges(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("GRANTEE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("PRIVILEGE_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_GRANTABLE", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "USER_PRIVILEGES");
}
private void FillViews(DataTable dataTable)
{
dataTable.Columns.AddRange(new[]
{
new DataColumn("TABLE_CATALOG", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_SCHEMA", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("TABLE_NAME", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("VIEW_DEFINITION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHECK_OPTION", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("IS_UPDATABLE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("DEFINER", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("SECURITY_TYPE", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("CHARACTER_SET_CLIENT", typeof(string)), // lgtm[cs/local-not-disposed]
new DataColumn("COLLATION_CONNECTION", typeof(string)), // lgtm[cs/local-not-disposed]
});
FillDataTable(dataTable, "VIEWS");
}
private void FillDataTable(DataTable dataTable, string tableName)
{
Action? close = null;
if (m_connection.State != ConnectionState.Open)
{
m_connection.Open();
close = m_connection.Close;
}
using (var command = m_connection.CreateCommand())
{
#pragma warning disable CA2100
command.CommandText = "SELECT " + string.Join(", ", dataTable.Columns.Cast<DataColumn>().Select(x => x.ColumnName)) + " FROM INFORMATION_SCHEMA." + tableName + ";";
#pragma warning restore CA2100
using var reader = command.ExecuteReader();
while (reader.Read())
{
var rowValues = new object[dataTable.Columns.Count];
reader.GetValues(rowValues);
dataTable.Rows.Add(rowValues);
}
}
close?.Invoke();
}
readonly MySqlConnection m_connection;
readonly Dictionary<string, Action<DataTable>> m_schemaCollections;
}
}
#endif
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using MySqlConnector.Logging;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class SingleCommandPayloadCreator : ICommandPayloadCreator
{
public static ICommandPayloadCreator Instance { get; } = new SingleCommandPayloadCreator();
// This is chosen to be something very unlikely to appear as a column name in a user's query. If a result set is read
// with this as the first column name, the result set will be treated as 'out' parameters for the previous command.
public static string OutParameterSentinelColumnName => "\uE001\b\x0B";
public bool WriteQueryCommand(ref CommandListPosition commandListPosition, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer)
{
if (commandListPosition.CommandIndex == commandListPosition.Commands.Count)
return false;
var command = commandListPosition.Commands[commandListPosition.CommandIndex];
var preparedStatements = command.TryGetPreparedStatements();
if (preparedStatements is null)
{
if (Log.IsDebugEnabled())
Log.Debug("Session{0} Preparing command payload; CommandText: {1}", command.Connection!.Session.Id, command.CommandText);
writer.Write((byte) CommandKind.Query);
WriteQueryPayload(command, cachedProcedures, writer);
commandListPosition.CommandIndex++;
}
else
{
writer.Write((byte) CommandKind.StatementExecute);
WritePreparedStatement(command, preparedStatements.Statements[commandListPosition.PreparedStatementIndex], writer);
// advance to next prepared statement or next command
if (++commandListPosition.PreparedStatementIndex == preparedStatements.Statements.Count)
{
commandListPosition.CommandIndex++;
commandListPosition.PreparedStatementIndex = 0;
}
}
return true;
}
/// <summary>
/// Writes the text of <paramref name="command"/> to <paramref name="writer"/>, encoded in UTF-8.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="cachedProcedures">The cached procedures.</param>
/// <param name="writer">The output writer.</param>
/// <returns><c>true</c> if a complete command was written; otherwise, <c>false</c>.</returns>
public static bool WriteQueryPayload(IMySqlCommand command, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer) =>
(command.CommandType == CommandType.StoredProcedure) ? WriteStoredProcedure(command, cachedProcedures, writer) : WriteCommand(command, writer);
private static void WritePreparedStatement(IMySqlCommand command, PreparedStatement preparedStatement, ByteBufferWriter writer)
{
var parameterCollection = command.RawParameters;
if (Log.IsDebugEnabled())
Log.Debug("Session{0} Preparing command payload; CommandId: {1}; CommandText: {2}", command.Connection!.Session.Id, preparedStatement.StatementId, command.CommandText);
writer.Write(preparedStatement.StatementId);
writer.Write((byte) 0);
writer.Write(1);
if (preparedStatement.Parameters?.Length > 0)
{
// TODO: How to handle incorrect number of parameters?
// build subset of parameters for this statement
var parameters = new MySqlParameter[preparedStatement.Statement.ParameterNames.Count];
for (var i = 0; i < preparedStatement.Statement.ParameterNames.Count; i++)
{
var parameterName = preparedStatement.Statement.ParameterNames[i];
var parameterIndex = parameterName is object ? (parameterCollection?.NormalizedIndexOf(parameterName) ?? -1) : preparedStatement.Statement.ParameterIndexes[i];
if (parameterIndex == -1 && parameterName is object)
throw new MySqlException("Parameter '{0}' must be defined.".FormatInvariant(parameterName));
else if (parameterIndex < 0 || parameterIndex >= (parameterCollection?.Count ?? 0))
throw new MySqlException("Parameter index {0} is invalid when only {1} parameter{2} defined.".FormatInvariant(parameterIndex, parameterCollection?.Count ?? 0, parameterCollection?.Count == 1 ? " is" : "s are"));
parameters[i] = parameterCollection![parameterIndex];
}
// write null bitmap
byte nullBitmap = 0;
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
if (parameter.Value is null || parameter.Value == DBNull.Value)
nullBitmap |= (byte) (1 << (i % 8));
if (i % 8 == 7)
{
writer.Write(nullBitmap);
nullBitmap = 0;
}
}
if (parameters.Length % 8 != 0)
writer.Write(nullBitmap);
// write "new parameters bound" flag
writer.Write((byte) 1);
foreach (var parameter in parameters)
{
// override explicit MySqlDbType with inferred type from the Value
var mySqlDbType = parameter.MySqlDbType;
var typeMapping = (parameter.Value is null || parameter.Value == DBNull.Value) ? null : TypeMapper.Instance.GetDbTypeMapping(parameter.Value.GetType());
if (typeMapping is object)
{
var dbType = typeMapping.DbTypes[0];
mySqlDbType = TypeMapper.Instance.GetMySqlDbTypeForDbType(dbType);
}
writer.Write(TypeMapper.ConvertToColumnTypeAndFlags(mySqlDbType, command.Connection!.GuidFormat));
}
var options = command.CreateStatementPreparerOptions();
foreach (var parameter in parameters)
parameter.AppendBinary(writer, options);
}
}
private static bool WriteStoredProcedure(IMySqlCommand command, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer)
{
var parameterCollection = command.RawParameters;
var cachedProcedure = cachedProcedures[command.CommandText!];
if (cachedProcedure is object)
parameterCollection = cachedProcedure.AlignParamsWithDb(parameterCollection);
MySqlParameter? returnParameter = null;
var outParameters = new MySqlParameterCollection();
var outParameterNames = new List<string>();
var inParameters = new MySqlParameterCollection();
var argParameterNames = new List<string>();
var inOutSetParameters = "";
for (var i = 0; i < (parameterCollection?.Count ?? 0); i++)
{
var param = parameterCollection![i];
var inName = "@inParam" + i;
var outName = "@outParam" + i;
switch (param.Direction)
{
case ParameterDirection.Input:
case ParameterDirection.InputOutput:
var inParam = param.WithParameterName(inName);
inParameters.Add(inParam);
if (param.Direction == ParameterDirection.InputOutput)
{
inOutSetParameters += $"SET {outName}={inName}; "; // lgtm[cs/string-concatenation-in-loop]
goto case ParameterDirection.Output;
}
argParameterNames.Add(inName);
break;
case ParameterDirection.Output:
outParameters.Add(param);
outParameterNames.Add(outName);
argParameterNames.Add(outName);
break;
case ParameterDirection.ReturnValue:
returnParameter = param;
break;
}
}
// if a return param is set, assume it is a function; otherwise, assume stored procedure
var commandText = command.CommandText + "(" + string.Join(", ", argParameterNames) + ");";
if (returnParameter is null)
{
commandText = inOutSetParameters + "CALL " + commandText;
if (outParameters.Count > 0 && (command.CommandBehavior & CommandBehavior.SchemaOnly) == 0)
{
commandText += "SELECT '" + OutParameterSentinelColumnName + "' AS '" + OutParameterSentinelColumnName + "', " + string.Join(", ", outParameterNames);
}
}
else
{
commandText = "SELECT " + commandText;
}
command.OutParameters = outParameters;
command.ReturnParameter = returnParameter;
var preparer = new StatementPreparer(commandText, inParameters, command.CreateStatementPreparerOptions());
return preparer.ParseAndBindParameters(writer);
}
private static bool WriteCommand(IMySqlCommand command, ByteBufferWriter writer)
{
var isSchemaOnly = (command.CommandBehavior & CommandBehavior.SchemaOnly) != 0;
var isSingleRow = (command.CommandBehavior & CommandBehavior.SingleRow) != 0;
if (isSchemaOnly)
writer.Write(SetSqlSelectLimit0);
else if (isSingleRow)
writer.Write(SetSqlSelectLimit1);
var preparer = new StatementPreparer(command.CommandText!, command.RawParameters, command.CreateStatementPreparerOptions());
var isComplete = preparer.ParseAndBindParameters(writer);
if (isComplete && (isSchemaOnly || isSingleRow))
writer.Write(ClearSqlSelectLimit);
return isComplete;
}
static ReadOnlySpan<byte> SetSqlSelectLimit0 => new byte[] { 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 48, 59, 10 }; // SET sql_select_limit=0;\n
static ReadOnlySpan<byte> SetSqlSelectLimit1 => new byte[] { 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 49, 59, 10 }; // SET sql_select_limit=1;\n
static ReadOnlySpan<byte> ClearSqlSelectLimit => new byte[] { 10, 83, 69, 84, 32, 115, 113, 108, 95, 115, 101, 108, 101, 99, 116, 95, 108, 105, 109, 105, 116, 61, 100, 101, 102, 97, 117, 108, 116, 59 }; // \nSET sql_select_limit=default;
static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(SingleCommandPayloadCreator));
}
}
<file_sep>namespace MySql.Data.MySqlClient
{
public enum MySqlBulkLoaderConflictOption
{
None,
Replace,
Ignore
}
}
<file_sep># New Relic Agent Custom Instrumentation
## Installation
Copy `MySqlConnector.xml` from this folder to `%PROGRAMDATA%\New Relic\.NET Agent\Extensions`.
You must be running [New Relic .NET Agent](https://docs.newrelic.com/docs/agents/net-agent) [version 8.19.353.0](https://docs.newrelic.com/docs/release-notes/agent-release-notes/net-release-notes/net-agent-8193530) or later.
## Documentation
See the New Relic documentation for [.NET custom transactions](https://docs.newrelic.com/docs/agents/net-agent/instrumentation/net-custom-transactions)
and [.NET custom instrumentation](https://docs.newrelic.com/docs/agents/net-agent/instrumentation/net-custom-instrumentation).
## Discussion
For more information, see this [discussion on the New Relic forums](https://discuss.newrelic.com/t/integrate-custom-ado-net-provider-with-newrelic/39964).
## Credit
The instrumentation file was [posted by ppavlov](https://discuss.newrelic.com/t/feature-idea-support-mysqlconnector-driver-for-db-instrumentation/63414/8).
<file_sep>#if !NETSTANDARD1_3
using System;
using System.Data;
using System.Data.Common;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlDataAdapter : DbDataAdapter
{
public MySqlDataAdapter()
{
GC.SuppressFinalize(this);
}
public MySqlDataAdapter(MySqlCommand selectCommand)
: this()
{
SelectCommand = selectCommand;
}
public MySqlDataAdapter(string selectCommandText, MySqlConnection connection)
: this(new MySqlCommand(selectCommandText, connection))
{
}
public MySqlDataAdapter(string selectCommandText, string connectionString)
: this(new MySqlCommand(selectCommandText, new MySqlConnection(connectionString)))
{
}
public event MySqlRowUpdatingEventHandler? RowUpdating;
public event MySqlRowUpdatedEventHandler? RowUpdated;
public new MySqlCommand? DeleteCommand
{
get => (MySqlCommand?) base.DeleteCommand;
set => base.DeleteCommand = value;
}
public new MySqlCommand? InsertCommand
{
get => (MySqlCommand?) base.InsertCommand;
set => base.InsertCommand = value;
}
public new MySqlCommand? SelectCommand
{
get => (MySqlCommand?) base.SelectCommand;
set => base.SelectCommand = value;
}
public new MySqlCommand? UpdateCommand
{
get => (MySqlCommand?) base.UpdateCommand;
set => base.UpdateCommand = value;
}
protected override void OnRowUpdating(RowUpdatingEventArgs value) => RowUpdating?.Invoke(this, (MySqlRowUpdatingEventArgs) value);
protected override void OnRowUpdated(RowUpdatedEventArgs value) => RowUpdated?.Invoke(this, (MySqlRowUpdatedEventArgs) value);
protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) => new MySqlRowUpdatingEventArgs(dataRow, command, statementType, tableMapping);
protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) => new MySqlRowUpdatedEventArgs(dataRow, command, statementType, tableMapping);
public override int UpdateBatchSize { get; set; }
protected override void InitializeBatching() => m_batch = new MySqlBatch();
protected override void TerminateBatching()
{
m_batch?.Dispose();
m_batch = null;
}
protected override int AddToBatch(IDbCommand command)
{
var mySqlCommand = (MySqlCommand) command;
if (m_batch!.Connection is null)
{
m_batch.Connection = mySqlCommand.Connection;
m_batch.Transaction = mySqlCommand.Transaction;
}
var count = m_batch.BatchCommands.Count;
var batchCommand = new MySqlBatchCommand
{
CommandText = command.CommandText,
CommandType = command.CommandType,
};
if (mySqlCommand.CloneRawParameters() is MySqlParameterCollection clonedParameters)
{
foreach (var clonedParameter in clonedParameters)
batchCommand.Parameters.Add(clonedParameter!);
}
m_batch.BatchCommands.Add(batchCommand);
return count;
}
protected override void ClearBatch() => m_batch!.BatchCommands.Clear();
protected override int ExecuteBatch() => m_batch!.ExecuteNonQuery();
MySqlBatch? m_batch;
}
public delegate void MySqlRowUpdatingEventHandler(object sender, MySqlRowUpdatingEventArgs e);
public delegate void MySqlRowUpdatedEventHandler(object sender, MySqlRowUpdatedEventArgs e);
public sealed class MySqlRowUpdatingEventArgs : RowUpdatingEventArgs
{
public MySqlRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
: base(row, command, statementType, tableMapping)
{
}
public new MySqlCommand Command => (MySqlCommand) base.Command;
}
public sealed class MySqlRowUpdatedEventArgs : RowUpdatedEventArgs
{
public MySqlRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
: base(row, command, statementType, tableMapping)
{
}
public new MySqlCommand Command => (MySqlCommand) base.Command;
}
}
#endif
<file_sep>---
lastmod: 2017-11-06
date: 2016-10-16
menu:
main:
parent: getting started
title: Use with ORMs
weight: 60
---
Use with ORMs
=============
This library is compatible with popular .NET ORMs including:
* [Dapper](https://stackexchange.github.io/Dapper/) ([GitHub](https://github.com/StackExchange/dapper-dot-net), [NuGet](https://www.nuget.org/packages/Dapper))
* [LINQ to DB](https://linq2db.github.io) ([GitHub](https://github.com/linq2db/linq2db), [NuGet](https://www.nuget.org/packages/linq2db.MySqlConnector))
* [NReco.Data](https://www.nrecosite.com/dalc_net.aspx) ([GitHub](https://github.com/nreco/data), [NuGet](https://www.nuget.org/packages/NReco.Data))
* [Paradigm ORM](http://www.paradigm.net.co/) ([GitHub](https://github.com/MiracleDevs/Paradigm.ORM), [NuGet](https://www.nuget.org/packages/Paradigm.ORM.Data.MySql/))
* [ServiceStack.OrmLite](https://servicestack.net/ormlite) ([GitHub](https://github.com/ServiceStack/ServiceStack.OrmLite), [NuGet](https://www.nuget.org/packages/ServiceStack.OrmLite.MySqlConnector))
* SimpleStack.Orm ([GitHub](https://github.com/SimpleStack/simplestack.orm), [NuGet](https://www.nuget.org/packages/SimpleStack.Orm.MySQLConnector))
For Entity Framework support, use:
* Pomelo.EntityFrameworkCore.MySql ([GitHub](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql), [NuGet](https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql))
<file_sep>using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace MySqlConnector.Performance
{
public static class AppConfig
{
public static IConfigurationRoot Config => LazyConfig.Value;
private static readonly Lazy<IConfigurationRoot> LazyConfig = new Lazy<IConfigurationRoot>(() => new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.AddJsonFile("appsettings.json")
.AddJsonFile("config.json")
.Build());
}
}
<file_sep>#!/usr/bin/env bash
cd $(dirname $0)/config
display_usage() {
echo -e "\nUsage:\n$0 [config.json script] [host] [port] [features]\n"
}
# check whether user had supplied -h or --help . If yes display usage
if [[ ( $# == "--help") || $# == "-h" ]]
then
display_usage
exit 0
fi
# check number of arguments
if [ $# -eq 0 ]
then
display_usage
exit 1
fi
# check that directory exists
if [ ! -f $1 ]
then
echo -e "Config file does not exist: $1"
exit 1
fi
cp $1 ../../tests/SideBySide/config.json
if [ $# -ge 2 ]
then
sed -i "s/127.0.0.1/$2/g" ../../tests/SideBySide/config.json
fi
if [ $# -ge 3 ]
then
sed -i "s/3306/$3/g" ../../tests/SideBySide/config.json
fi
if [ $# -ge 4 ]
then
sed -i "s/\"UnsupportedFeatures\": \".*\"/\"UnsupportedFeatures\": \"$4\"/g" ../../tests/SideBySide/config.json
fi
<file_sep>using System.Collections.Generic;
using MySqlConnector.Logging;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
namespace MySqlConnector.Core
{
internal sealed class ConcatenatedCommandPayloadCreator : ICommandPayloadCreator
{
public static ICommandPayloadCreator Instance { get; } = new ConcatenatedCommandPayloadCreator();
public bool WriteQueryCommand(ref CommandListPosition commandListPosition, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer)
{
if (commandListPosition.CommandIndex == commandListPosition.Commands.Count)
return false;
writer.Write((byte) CommandKind.Query);
bool isComplete;
do
{
var command = commandListPosition.Commands[commandListPosition.CommandIndex];
if (Log.IsDebugEnabled())
Log.Debug("Session{0} Preparing command payload; CommandText: {1}", command.Connection!.Session.Id, command.CommandText);
isComplete = SingleCommandPayloadCreator.WriteQueryPayload(command, cachedProcedures, writer);
commandListPosition.CommandIndex++;
}
while (commandListPosition.CommandIndex < commandListPosition.Commands.Count && isComplete);
return true;
}
static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(ConcatenatedCommandPayloadCreator));
}
}
<file_sep>using System;
using System.Buffers.Text;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Payloads;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class TextRow : Row
{
public TextRow(ResultSet resultSet)
: base(resultSet)
{
}
protected override Row CloneCore() => new TextRow(ResultSet);
protected override void GetDataOffsets(ReadOnlySpan<byte> data, int[] dataOffsets, int[] dataLengths)
{
var reader = new ByteArrayReader(data);
for (var column = 0; column < dataOffsets.Length; column++)
{
var length = reader.ReadLengthEncodedIntegerOrNull();
dataLengths[column] = length == -1 ? 0 : length;
dataOffsets[column] = length == -1 ? -1 : reader.Offset;
reader.Offset += dataLengths[column];
}
}
protected override int GetInt32Core(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) =>
!Utf8Parser.TryParse(data, out int value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new OverflowException() : value;
protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition)
{
var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0;
switch (columnDefinition.ColumnType)
{
case ColumnType.Tiny:
var value = ParseInt32(data);
if (Connection.TreatTinyAsBoolean && columnDefinition.ColumnLength == 1 && !isUnsigned)
return value != 0;
return isUnsigned ? (object) (byte) value : (sbyte) value;
case ColumnType.Int24:
case ColumnType.Long:
return isUnsigned ? (object) ParseUInt32(data) : ParseInt32(data);
case ColumnType.Longlong:
return isUnsigned ? (object) ParseUInt64(data) : ParseInt64(data);
case ColumnType.Bit:
return ReadBit(data, columnDefinition);
case ColumnType.String:
if (Connection.GuidFormat == MySqlGuidFormat.Char36 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36)
return Utf8Parser.TryParse(data, out Guid guid, out int guid36BytesConsumed, 'D') && guid36BytesConsumed == 36 ? guid : throw new FormatException();
if (Connection.GuidFormat == MySqlGuidFormat.Char32 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 32)
return Utf8Parser.TryParse(data, out Guid guid, out int guid32BytesConsumed, 'N') && guid32BytesConsumed == 32 ? guid : throw new FormatException();
goto case ColumnType.VarString;
case ColumnType.VarString:
case ColumnType.VarChar:
case ColumnType.TinyBlob:
case ColumnType.Blob:
case ColumnType.MediumBlob:
case ColumnType.LongBlob:
if (columnDefinition.CharacterSet == CharacterSet.Binary)
{
var guidFormat = Connection.GuidFormat;
if ((guidFormat == MySqlGuidFormat.Binary16 || guidFormat == MySqlGuidFormat.TimeSwapBinary16 || guidFormat == MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
return CreateGuidFromBytes(guidFormat, data);
return data.ToArray();
}
return Encoding.UTF8.GetString(data);
case ColumnType.Json:
return Encoding.UTF8.GetString(data);
case ColumnType.Short:
return isUnsigned ? (object) ParseUInt16(data) : ParseInt16(data);
case ColumnType.Date:
case ColumnType.DateTime:
case ColumnType.Timestamp:
return ParseDateTime(data);
case ColumnType.Time:
return Utility.ParseTimeSpan(data);
case ColumnType.Year:
return ParseInt32(data);
case ColumnType.Float:
return !Utf8Parser.TryParse(data, out float floatValue, out var floatBytesConsumed) || floatBytesConsumed != data.Length ? throw new FormatException() : floatValue;
case ColumnType.Double:
return !Utf8Parser.TryParse(data, out double doubleValue, out var doubleBytesConsumed) || doubleBytesConsumed != data.Length ? throw new FormatException() : doubleValue;
case ColumnType.Decimal:
case ColumnType.NewDecimal:
return Utf8Parser.TryParse(data, out decimal decimalValue, out int bytesConsumed) && bytesConsumed == data.Length ? decimalValue : throw new FormatException();
case ColumnType.Geometry:
return data.ToArray();
default:
throw new NotImplementedException("Reading {0} not implemented".FormatInvariant(columnDefinition.ColumnType));
}
}
private static short ParseInt16(ReadOnlySpan<byte> data) =>
!Utf8Parser.TryParse(data, out short value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new FormatException() : value;
private static ushort ParseUInt16(ReadOnlySpan<byte> data) =>
!Utf8Parser.TryParse(data, out ushort value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new FormatException() : value;
private static int ParseInt32(ReadOnlySpan<byte> data) =>
!Utf8Parser.TryParse(data, out int value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new FormatException() : value;
private static uint ParseUInt32(ReadOnlySpan<byte> data) =>
!Utf8Parser.TryParse(data, out uint value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new FormatException() : value;
private static long ParseInt64(ReadOnlySpan<byte> data) =>
!Utf8Parser.TryParse(data, out long value, out var bytesConsumed) || bytesConsumed != data.Length ? throw new FormatException() : value;
private object ParseDateTime(ReadOnlySpan<byte> value)
{
Exception? exception = null;
if (!Utf8Parser.TryParse(value, out int year, out var bytesConsumed) || bytesConsumed != 4)
goto InvalidDateTime;
if (value.Length < 5 || value[4] != 45)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(5), out int month, out bytesConsumed) || bytesConsumed != 2)
goto InvalidDateTime;
if (value.Length < 8 || value[7] != 45)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(8), out int day, out bytesConsumed) || bytesConsumed != 2)
goto InvalidDateTime;
if (year == 0 && month == 0 && day == 0)
{
if (Connection.ConvertZeroDateTime)
return DateTime.MinValue;
if (Connection.AllowZeroDateTime)
return new MySqlDateTime();
throw new InvalidCastException("Unable to convert MySQL date/time to System.DateTime, set AllowZeroDateTime=True or ConvertZeroDateTime=True in the connection string. See https://mysqlconnector.net/connection-options/");
}
int hour, minute, second, microseconds;
if (value.Length == 10)
{
hour = 0;
minute = 0;
second = 0;
microseconds = 0;
}
else
{
if (value[10] != 32)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(11), out hour, out bytesConsumed) || bytesConsumed != 2)
goto InvalidDateTime;
if (value.Length < 14 || value[13] != 58)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(14), out minute, out bytesConsumed) || bytesConsumed != 2)
goto InvalidDateTime;
if (value.Length < 17 || value[16] != 58)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(17), out second, out bytesConsumed) || bytesConsumed != 2)
goto InvalidDateTime;
if (value.Length == 19)
{
microseconds = 0;
}
else
{
if (value[19] != 46)
goto InvalidDateTime;
if (!Utf8Parser.TryParse(value.Slice(20), out microseconds, out bytesConsumed) || bytesConsumed != value.Length - 20)
goto InvalidDateTime;
for (; bytesConsumed < 6; bytesConsumed++)
microseconds *= 10;
}
}
try
{
return Connection.AllowZeroDateTime ? (object) new MySqlDateTime(year, month, day, hour, minute, second, microseconds) :
new DateTime(year, month, day, hour, minute, second, microseconds / 1000, Connection.DateTimeKind).AddTicks(microseconds % 1000 * 10);
}
catch (Exception ex)
{
exception = ex;
}
InvalidDateTime:
throw new FormatException("Couldn't interpret '{0}' as a valid DateTime".FormatInvariant(Encoding.UTF8.GetString(value)), exception);
}
}
}
<file_sep>using System;
namespace MySqlConnector.Core
{
[Flags]
internal enum StatementPreparerOptions
{
None = 0,
AllowUserVariables = 0x1,
AllowOutputParameters = 0x4,
DateTimeUtc = 0x8,
DateTimeLocal = 0x10,
GuidFormatChar36 = 0x20,
GuidFormatChar32 = 0x40,
GuidFormatBinary16 = 0x60,
GuidFormatTimeSwapBinary16 = 0x80,
GuidFormatLittleEndianBinary16 = 0xA0,
GuidFormatMask = 0xE0,
NoBackslashEscapes = 0x100,
}
}
<file_sep>using System;
using System.Globalization;
using MySql.Data.Types;
using MySqlConnector.Core;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Payloads;
using MySqlConnector.Protocol.Serialization;
#if NET45
namespace System.Data.Common
{
public abstract class DbColumn
{
public bool? AllowDBNull { get; protected set; }
public string? BaseCatalogName { get; protected set; }
public string? BaseColumnName { get; protected set; }
public string? BaseSchemaName { get; protected set; }
public string? BaseServerName { get; protected set; }
public string? BaseTableName { get; protected set; }
public string ColumnName { get; protected set; } = "";
public int? ColumnOrdinal { get; protected set; }
public int? ColumnSize { get; protected set; }
public bool? IsAliased { get; protected set; }
public bool? IsAutoIncrement { get; protected set; }
public bool? IsExpression { get; protected set; }
public bool? IsHidden { get; protected set; }
public bool? IsIdentity { get; protected set; }
public bool? IsKey { get; protected set; }
public bool? IsLong { get; protected set; }
public bool? IsReadOnly { get; protected set; }
public bool? IsUnique { get; protected set; }
public int? NumericPrecision { get; protected set; }
public int? NumericScale { get; protected set; }
public string? UdtAssemblyQualifiedName { get; protected set; }
public Type? DataType { get; protected set; }
public string? DataTypeName { get; protected set; }
public virtual object? this[string property] => null;
}
}
#endif
namespace MySql.Data.MySqlClient
{
public sealed class MySqlDbColumn : System.Data.Common.DbColumn
{
internal MySqlDbColumn(int ordinal, ColumnDefinitionPayload column, bool allowZeroDateTime, MySqlDbType mySqlDbType)
{
var columnTypeMetadata = TypeMapper.Instance.GetColumnTypeMetadata(mySqlDbType);
var type = columnTypeMetadata.DbTypeMapping.ClrType;
var columnSize = type == typeof(string) || type == typeof(Guid) ?
column.ColumnLength / ProtocolUtility.GetBytesPerCharacter(column.CharacterSet) :
column.ColumnLength;
AllowDBNull = (column.ColumnFlags & ColumnFlags.NotNull) == 0;
BaseCatalogName = null;
BaseColumnName = column.PhysicalName;
BaseSchemaName = column.SchemaName;
BaseTableName = column.PhysicalTable;
ColumnName = column.Name;
ColumnOrdinal = ordinal;
ColumnSize = columnSize > int.MaxValue ? int.MaxValue : unchecked((int) columnSize);
DataType = (allowZeroDateTime && type == typeof(DateTime)) ? typeof(MySqlDateTime) : type;
DataTypeName = columnTypeMetadata.SimpleDataTypeName;
if (mySqlDbType == MySqlDbType.String)
DataTypeName += string.Format(CultureInfo.InvariantCulture, "({0})", columnSize);
IsAliased = column.PhysicalName != column.Name;
IsAutoIncrement = (column.ColumnFlags & ColumnFlags.AutoIncrement) != 0;
IsExpression = false;
IsHidden = false;
IsKey = (column.ColumnFlags & ColumnFlags.PrimaryKey) != 0;
IsLong = column.ColumnLength > 255 &&
((column.ColumnFlags & ColumnFlags.Blob) != 0 || column.ColumnType == ColumnType.TinyBlob || column.ColumnType == ColumnType.Blob || column.ColumnType == ColumnType.MediumBlob || column.ColumnType == ColumnType.LongBlob);
IsReadOnly = false;
IsUnique = (column.ColumnFlags & ColumnFlags.UniqueKey) != 0;
if (column.ColumnType == ColumnType.Decimal || column.ColumnType == ColumnType.NewDecimal)
{
NumericPrecision = (int) column.ColumnLength;
if ((column.ColumnFlags & ColumnFlags.Unsigned) == 0)
NumericPrecision--;
if (column.Decimals > 0)
NumericPrecision--;
}
NumericScale = column.Decimals;
ProviderType = mySqlDbType;
}
public MySqlDbType ProviderType { get; }
}
}
<file_sep>using System;
using System.Globalization;
using Microsoft.Extensions.Logging;
namespace MySqlConnector.Logging
{
public sealed class MicrosoftExtensionsLoggingLoggerProvider : IMySqlConnectorLoggerProvider
{
public MicrosoftExtensionsLoggingLoggerProvider(ILoggerFactory loggerFactory) => m_loggerFactory = loggerFactory;
public IMySqlConnectorLogger CreateLogger(string name) => new MicrosoftExtensionsLoggingLogger(m_loggerFactory.CreateLogger(name));
private class MicrosoftExtensionsLoggingLogger : IMySqlConnectorLogger
{
public MicrosoftExtensionsLoggingLogger(ILogger logger) => m_logger = logger;
public bool IsEnabled(MySqlConnectorLogLevel level) => m_logger.IsEnabled(GetLevel(level));
public void Log(MySqlConnectorLogLevel level, string message, object[] args = null, Exception exception = null)
{
if (args is null || args.Length == 0)
m_logger.Log(GetLevel(level), 0, message, exception, s_getMessage);
else
m_logger.Log(GetLevel(level), 0, (message, args), exception, s_messageFormatter);
}
private static LogLevel GetLevel(MySqlConnectorLogLevel level) => level switch
{
MySqlConnectorLogLevel.Trace => LogLevel.Trace,
MySqlConnectorLogLevel.Debug => LogLevel.Debug,
MySqlConnectorLogLevel.Info => LogLevel.Information,
MySqlConnectorLogLevel.Warn => LogLevel.Warning,
MySqlConnectorLogLevel.Error => LogLevel.Error,
MySqlConnectorLogLevel.Fatal => LogLevel.Critical,
_ => throw new ArgumentOutOfRangeException(nameof(level), level, "Invalid value for 'level'.")
};
static readonly Func<string, Exception, string> s_getMessage = (s, e) => s;
static readonly Func<(string Message, object[] Args), Exception, string> s_messageFormatter = (s, e) => string.Format(CultureInfo.InvariantCulture, s.Message, s.Args);
readonly ILogger m_logger;
}
readonly ILoggerFactory m_loggerFactory;
}
}
<file_sep>using System;
namespace MySql.Data.MySqlClient
{
/// <summary>
/// <see cref="MySqlBulkCopyColumnMapping"/> specifies how to map columns in the source data to
/// destination columns when using <see cref="MySqlBulkCopy"/>.
/// </summary>
public sealed class MySqlBulkCopyColumnMapping
{
/// <summary>
/// Initializes <see cref="MySqlBulkCopyColumnMapping"/> with the default values.
/// </summary>
public MySqlBulkCopyColumnMapping()
{
DestinationColumn = "";
}
/// <summary>
/// Initializes <see cref="MySqlBulkCopyColumnMapping"/> to the specified values.
/// </summary>
/// <param name="sourceOrdinal">The ordinal position of the source column.</param>
/// <param name="destinationColumn">The name of the destination column.</param>
/// <param name="expression">The optional expression to be used to set the destination column.</param>
public MySqlBulkCopyColumnMapping(int sourceOrdinal, string destinationColumn, string? expression = null)
{
SourceOrdinal = sourceOrdinal;
DestinationColumn = destinationColumn ?? throw new ArgumentNullException(nameof(destinationColumn));
Expression = expression;
}
/// <summary>
/// The ordinal position of the source column to map from.
/// </summary>
public int SourceOrdinal { get; set; }
/// <summary>
/// The name of the destination column to copy to. To use an expression, this should be the name of a unique user-defined variable.
/// </summary>
public string DestinationColumn { get; set; }
/// <summary>
/// An optional expression for setting a destination column. To use an expression, the <see cref="DestinationColumn"/> should
/// be set to the name of a user-defined variable and this expression should set a column using that variable.
/// </summary>
/// <remarks>To populate a binary column, you must set <see cref="DestinationColumn"/> to a variable name, and <see cref="Expression"/> to an
/// expression that uses <code>UNHEX</code> to set the column value, e.g., <code>`destColumn` = UNHEX(@variableName)</code>.</remarks>
public string? Expression { get; set; }
}
}
<file_sep>using System;
using System.Collections;
using System.Data.Common;
#if !NETSTANDARD1_3
using System.Runtime.Serialization;
#endif
namespace MySql.Data.MySqlClient
{
#if !NETSTANDARD1_3
[Serializable]
#endif
public sealed class MySqlException : DbException
{
public int Number { get; }
public string? SqlState { get; }
#if !NETSTANDARD1_3
private MySqlException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Number = info.GetInt32("Number");
SqlState = info.GetString("SqlState");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Number", Number);
info.AddValue("SqlState", SqlState);
}
#endif
public override IDictionary Data
{
get
{
if (m_data is null)
{
m_data = base.Data;
m_data["Server Error Code"] = Number;
m_data["SqlState"] = SqlState;
}
return m_data;
}
}
internal MySqlException(string message)
: this(message, null)
{
}
internal MySqlException(string message, Exception? innerException)
: this(0, null, message, innerException)
{
}
internal MySqlException(MySqlErrorCode errorCode, string message)
: this((int) errorCode, null, message, null)
{
}
internal MySqlException(MySqlErrorCode errorCode, string message, Exception? innerException)
: this((int) errorCode, null, message, innerException)
{
}
internal MySqlException(int errorNumber, string sqlState, string message)
: this(errorNumber, sqlState, message, null)
{
}
internal MySqlException(int errorNumber, string? sqlState, string message, Exception? innerException)
: base(message, innerException)
{
Number = errorNumber;
SqlState = sqlState;
}
internal static MySqlException CreateForTimeout() => CreateForTimeout(null);
internal static MySqlException CreateForTimeout(Exception? innerException) =>
new MySqlException(MySqlErrorCode.CommandTimeoutExpired, "The Command Timeout expired before the operation completed.", innerException);
IDictionary? m_data;
}
}
<file_sep>using Dapper;
namespace SideBySide
{
public class TransactionFixture : DatabaseFixture
{
public TransactionFixture()
{
Connection.Open();
Connection.Execute(@"
drop table if exists transactions_test;
create table transactions_test(value integer null);
");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Payloads;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class TypeMapper
{
public static TypeMapper Instance = new TypeMapper();
private TypeMapper()
{
m_columnTypeMetadata = new List<ColumnTypeMetadata>();
m_dbTypeMappingsByClrType = new Dictionary<Type, DbTypeMapping>();
m_dbTypeMappingsByDbType = new Dictionary<DbType, DbTypeMapping>();
m_columnTypeMetadataLookup = new Dictionary<string, ColumnTypeMetadata>(StringComparer.OrdinalIgnoreCase);
m_mySqlDbTypeToColumnTypeMetadata = new Dictionary<MySqlDbType, ColumnTypeMetadata>();
// boolean
var typeBoolean = AddDbTypeMapping(new DbTypeMapping(typeof(bool), new[] { DbType.Boolean }, convert: o => Convert.ToBoolean(o)));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYINT", typeBoolean, MySqlDbType.Bool, isUnsigned: false, length: 1, columnSize: 1, simpleDataTypeName: "BOOL", createFormat: "BOOL"));
// integers
var typeSbyte = AddDbTypeMapping(new DbTypeMapping(typeof(sbyte), new[] { DbType.SByte }, convert: o => Convert.ToSByte(o)));
var typeByte = AddDbTypeMapping(new DbTypeMapping(typeof(byte), new[] { DbType.Byte }, convert: o => Convert.ToByte(o)));
var typeShort = AddDbTypeMapping(new DbTypeMapping(typeof(short), new[] { DbType.Int16 }, convert: o => Convert.ToInt16(o)));
var typeUshort = AddDbTypeMapping(new DbTypeMapping(typeof(ushort), new[] { DbType.UInt16 }, convert: o => Convert.ToUInt16(o)));
var typeInt = AddDbTypeMapping(new DbTypeMapping(typeof(int), new[] { DbType.Int32 }, convert: o => Convert.ToInt32(o)));
var typeUint = AddDbTypeMapping(new DbTypeMapping(typeof(uint), new[] { DbType.UInt32 }, convert: o => Convert.ToUInt32(o)));
var typeLong = AddDbTypeMapping(new DbTypeMapping(typeof(long), new[] { DbType.Int64 }, convert: o => Convert.ToInt64(o)));
var typeUlong = AddDbTypeMapping(new DbTypeMapping(typeof(ulong), new[] { DbType.UInt64 }, convert: o => Convert.ToUInt64(o)));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYINT", typeSbyte, MySqlDbType.Byte, isUnsigned: false));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYINT", typeByte, MySqlDbType.UByte, isUnsigned: true, length: 1));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYINT", typeByte, MySqlDbType.UByte, isUnsigned: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("SMALLINT", typeShort, MySqlDbType.Int16, isUnsigned: false));
AddColumnTypeMetadata(new ColumnTypeMetadata("SMALLINT", typeUshort, MySqlDbType.UInt16, isUnsigned: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("INT", typeInt, MySqlDbType.Int32, isUnsigned: false));
AddColumnTypeMetadata(new ColumnTypeMetadata("INT", typeUint, MySqlDbType.UInt32, isUnsigned: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("MEDIUMINT", typeInt, MySqlDbType.Int24, isUnsigned: false));
AddColumnTypeMetadata(new ColumnTypeMetadata("MEDIUMINT", typeUint, MySqlDbType.UInt24, isUnsigned: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("BIGINT", typeLong, MySqlDbType.Int64, isUnsigned: false));
AddColumnTypeMetadata(new ColumnTypeMetadata("BIGINT", typeUlong, MySqlDbType.UInt64, isUnsigned: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("BIT", typeUlong, MySqlDbType.Bit));
// decimals
var typeDecimal = AddDbTypeMapping(new DbTypeMapping(typeof(decimal), new[] { DbType.Decimal, DbType.Currency, DbType.VarNumeric }, convert: o => Convert.ToDecimal(o)));
var typeDouble = AddDbTypeMapping(new DbTypeMapping(typeof(double), new[] { DbType.Double }, convert: o => Convert.ToDouble(o)));
var typeFloat = AddDbTypeMapping(new DbTypeMapping(typeof(float), new[] { DbType.Single }, convert: o => Convert.ToSingle(o)));
AddColumnTypeMetadata(new ColumnTypeMetadata("DECIMAL", typeDecimal, MySqlDbType.NewDecimal, createFormat: "DECIMAL({0},{1});precision,scale"));
AddColumnTypeMetadata(new ColumnTypeMetadata("DECIMAL", typeDecimal, MySqlDbType.Decimal));
AddColumnTypeMetadata(new ColumnTypeMetadata("DOUBLE", typeDouble, MySqlDbType.Double));
AddColumnTypeMetadata(new ColumnTypeMetadata("FLOAT", typeFloat, MySqlDbType.Float));
// string
var typeFixedString = AddDbTypeMapping(new DbTypeMapping(typeof(string), new[] { DbType.StringFixedLength, DbType.AnsiStringFixedLength }, convert: Convert.ToString!));
var typeString = AddDbTypeMapping(new DbTypeMapping(typeof(string), new[] { DbType.String, DbType.AnsiString, DbType.Xml }, convert: Convert.ToString!));
AddColumnTypeMetadata(new ColumnTypeMetadata("VARCHAR", typeString, MySqlDbType.VarChar, createFormat: "VARCHAR({0});size"));
AddColumnTypeMetadata(new ColumnTypeMetadata("VARCHAR", typeString, MySqlDbType.VarString));
AddColumnTypeMetadata(new ColumnTypeMetadata("CHAR", typeFixedString, MySqlDbType.String, createFormat: "CHAR({0});size"));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYTEXT", typeString, MySqlDbType.TinyText, columnSize: byte.MaxValue, simpleDataTypeName: "VARCHAR"));
AddColumnTypeMetadata(new ColumnTypeMetadata("TEXT", typeString, MySqlDbType.Text, columnSize: ushort.MaxValue, simpleDataTypeName: "VARCHAR"));
AddColumnTypeMetadata(new ColumnTypeMetadata("MEDIUMTEXT", typeString, MySqlDbType.MediumText, columnSize: 16777215, simpleDataTypeName: "VARCHAR"));
AddColumnTypeMetadata(new ColumnTypeMetadata("LONGTEXT", typeString, MySqlDbType.LongText, columnSize: uint.MaxValue, simpleDataTypeName: "VARCHAR"));
AddColumnTypeMetadata(new ColumnTypeMetadata("ENUM", typeString, MySqlDbType.Enum));
AddColumnTypeMetadata(new ColumnTypeMetadata("SET", typeString, MySqlDbType.Set));
AddColumnTypeMetadata(new ColumnTypeMetadata("JSON", typeString, MySqlDbType.JSON));
// binary
var typeBinary = AddDbTypeMapping(new DbTypeMapping(typeof(byte[]), new[] { DbType.Binary }));
AddColumnTypeMetadata(new ColumnTypeMetadata("BLOB", typeBinary, MySqlDbType.Blob, binary: true, columnSize: ushort.MaxValue, simpleDataTypeName: "BLOB"));
AddColumnTypeMetadata(new ColumnTypeMetadata("BINARY", typeBinary, MySqlDbType.Binary, binary: true, simpleDataTypeName: "BLOB", createFormat: "BINARY({0});length"));
AddColumnTypeMetadata(new ColumnTypeMetadata("VARBINARY", typeBinary, MySqlDbType.VarBinary, binary: true, simpleDataTypeName: "BLOB", createFormat: "VARBINARY({0});length"));
AddColumnTypeMetadata(new ColumnTypeMetadata("TINYBLOB", typeBinary, MySqlDbType.TinyBlob, binary: true, columnSize: byte.MaxValue, simpleDataTypeName: "BLOB"));
AddColumnTypeMetadata(new ColumnTypeMetadata("MEDIUMBLOB", typeBinary, MySqlDbType.MediumBlob, binary: true, columnSize: 16777215, simpleDataTypeName: "BLOB"));
AddColumnTypeMetadata(new ColumnTypeMetadata("LONGBLOB", typeBinary, MySqlDbType.LongBlob, binary: true, columnSize: uint.MaxValue, simpleDataTypeName: "BLOB"));
// spatial
AddColumnTypeMetadata(new ColumnTypeMetadata("GEOMETRY", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("POINT", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("LINESTRING", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("POLYGON", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("MULTIPOINT", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("MULTILINESTRING", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("MULTIPOLYGON", typeBinary, MySqlDbType.Geometry, binary: true));
AddColumnTypeMetadata(new ColumnTypeMetadata("GEOMETRYCOLLECTION", typeBinary, MySqlDbType.Geometry, binary: true));
// date/time
var typeDate = AddDbTypeMapping(new DbTypeMapping(typeof(DateTime), new[] { DbType.Date }));
var typeDateTime = AddDbTypeMapping(new DbTypeMapping(typeof(DateTime), new[] { DbType.DateTime, DbType.DateTime2, DbType.DateTimeOffset }));
AddDbTypeMapping(new DbTypeMapping(typeof(DateTimeOffset), new[] { DbType.DateTimeOffset }));
var typeTime = AddDbTypeMapping(new DbTypeMapping(typeof(TimeSpan), new[] { DbType.Time }, convert: o => o is string s ? Utility.ParseTimeSpan(Encoding.UTF8.GetBytes(s)) : Convert.ChangeType(o, typeof(TimeSpan))));
AddColumnTypeMetadata(new ColumnTypeMetadata("DATETIME", typeDateTime, MySqlDbType.DateTime));
AddColumnTypeMetadata(new ColumnTypeMetadata("DATE", typeDate, MySqlDbType.Date));
AddColumnTypeMetadata(new ColumnTypeMetadata("DATE", typeDate, MySqlDbType.Newdate));
AddColumnTypeMetadata(new ColumnTypeMetadata("TIME", typeTime, MySqlDbType.Time));
AddColumnTypeMetadata(new ColumnTypeMetadata("TIMESTAMP", typeDateTime, MySqlDbType.Timestamp));
AddColumnTypeMetadata(new ColumnTypeMetadata("YEAR", typeInt, MySqlDbType.Year));
// guid
var typeGuid = AddDbTypeMapping(new DbTypeMapping(typeof(Guid), new[] { DbType.Guid }, convert: o => Guid.Parse(Convert.ToString(o)!)));
AddColumnTypeMetadata(new ColumnTypeMetadata("CHAR", typeGuid, MySqlDbType.Guid, length: 36, simpleDataTypeName: "CHAR(36)", createFormat: "CHAR(36)"));
// null
var typeNull = AddDbTypeMapping(new DbTypeMapping(typeof(object), new[] { DbType.Object }));
AddColumnTypeMetadata(new ColumnTypeMetadata("NULL", typeNull, MySqlDbType.Null));
}
public IReadOnlyList<ColumnTypeMetadata> GetColumnTypeMetadata() => m_columnTypeMetadata.AsReadOnly();
public ColumnTypeMetadata GetColumnTypeMetadata(MySqlDbType mySqlDbType) => m_mySqlDbTypeToColumnTypeMetadata[mySqlDbType];
public DbType GetDbTypeForMySqlDbType(MySqlDbType mySqlDbType) => m_mySqlDbTypeToColumnTypeMetadata[mySqlDbType].DbTypeMapping.DbTypes[0];
public MySqlDbType GetMySqlDbTypeForDbType(DbType dbType)
{
foreach (var pair in m_mySqlDbTypeToColumnTypeMetadata)
{
if (pair.Value.DbTypeMapping.DbTypes.Contains(dbType))
return pair.Key;
}
return MySqlDbType.VarChar;
}
private DbTypeMapping AddDbTypeMapping(DbTypeMapping dbTypeMapping)
{
m_dbTypeMappingsByClrType[dbTypeMapping.ClrType] = dbTypeMapping;
if (dbTypeMapping.DbTypes is object)
foreach (var dbType in dbTypeMapping.DbTypes)
m_dbTypeMappingsByDbType[dbType] = dbTypeMapping;
return dbTypeMapping;
}
private void AddColumnTypeMetadata(ColumnTypeMetadata columnTypeMetadata)
{
m_columnTypeMetadata.Add(columnTypeMetadata);
var lookupKey = columnTypeMetadata.CreateLookupKey();
if (!m_columnTypeMetadataLookup.ContainsKey(lookupKey))
m_columnTypeMetadataLookup.Add(lookupKey, columnTypeMetadata);
if (!m_mySqlDbTypeToColumnTypeMetadata.ContainsKey(columnTypeMetadata.MySqlDbType))
m_mySqlDbTypeToColumnTypeMetadata.Add(columnTypeMetadata.MySqlDbType, columnTypeMetadata);
}
internal DbTypeMapping? GetDbTypeMapping(Type clrType)
{
m_dbTypeMappingsByClrType.TryGetValue(clrType, out var dbTypeMapping);
return dbTypeMapping;
}
internal DbTypeMapping? GetDbTypeMapping(DbType dbType)
{
m_dbTypeMappingsByDbType.TryGetValue(dbType, out var dbTypeMapping);
return dbTypeMapping;
}
public DbTypeMapping? GetDbTypeMapping(string columnTypeName, bool unsigned = false, int length = 0)
{
return GetColumnTypeMetadata(columnTypeName, unsigned, length)?.DbTypeMapping;
}
public MySqlDbType GetMySqlDbType(string typeName, bool unsigned, int length) => GetColumnTypeMetadata(typeName, unsigned, length)!.MySqlDbType;
private ColumnTypeMetadata? GetColumnTypeMetadata(string columnTypeName, bool unsigned, int length)
{
if (!m_columnTypeMetadataLookup.TryGetValue(ColumnTypeMetadata.CreateLookupKey(columnTypeName, unsigned, length), out var columnTypeMetadata) && length != 0)
m_columnTypeMetadataLookup.TryGetValue(ColumnTypeMetadata.CreateLookupKey(columnTypeName, unsigned, 0), out columnTypeMetadata);
return columnTypeMetadata;
}
public static MySqlDbType ConvertToMySqlDbType(ColumnDefinitionPayload columnDefinition, bool treatTinyAsBoolean, MySqlGuidFormat guidFormat)
{
var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0;
switch (columnDefinition.ColumnType)
{
case ColumnType.Tiny:
return treatTinyAsBoolean && columnDefinition.ColumnLength == 1 && !isUnsigned ? MySqlDbType.Bool :
isUnsigned ? MySqlDbType.UByte : MySqlDbType.Byte;
case ColumnType.Int24:
return isUnsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24;
case ColumnType.Long:
return isUnsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32;
case ColumnType.Longlong:
return isUnsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64;
case ColumnType.Bit:
return MySqlDbType.Bit;
case ColumnType.String:
if (guidFormat == MySqlGuidFormat.Char36 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36)
return MySqlDbType.Guid;
if (guidFormat == MySqlGuidFormat.Char32 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 32)
return MySqlDbType.Guid;
if ((columnDefinition.ColumnFlags & ColumnFlags.Enum) != 0)
return MySqlDbType.Enum;
if ((columnDefinition.ColumnFlags & ColumnFlags.Set) != 0)
return MySqlDbType.Set;
goto case ColumnType.VarString;
case ColumnType.VarString:
case ColumnType.TinyBlob:
case ColumnType.Blob:
case ColumnType.MediumBlob:
case ColumnType.LongBlob:
var type = columnDefinition.ColumnType;
if (columnDefinition.CharacterSet == CharacterSet.Binary)
{
if ((guidFormat == MySqlGuidFormat.Binary16 || guidFormat == MySqlGuidFormat.TimeSwapBinary16 || guidFormat == MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
return MySqlDbType.Guid;
return type == ColumnType.String ? MySqlDbType.Binary :
type == ColumnType.VarString ? MySqlDbType.VarBinary :
type == ColumnType.TinyBlob ? MySqlDbType.TinyBlob :
type == ColumnType.Blob ? MySqlDbType.Blob :
type == ColumnType.MediumBlob ? MySqlDbType.MediumBlob :
MySqlDbType.LongBlob;
}
return type == ColumnType.String ? MySqlDbType.String :
type == ColumnType.VarString ? MySqlDbType.VarChar :
type == ColumnType.TinyBlob ? MySqlDbType.TinyText :
type == ColumnType.Blob ? MySqlDbType.Text :
type == ColumnType.MediumBlob ? MySqlDbType.MediumText :
MySqlDbType.LongText;
case ColumnType.Json:
return MySqlDbType.JSON;
case ColumnType.Short:
return isUnsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16;
case ColumnType.Date:
return MySqlDbType.Date;
case ColumnType.DateTime:
return MySqlDbType.DateTime;
case ColumnType.Timestamp:
return MySqlDbType.Timestamp;
case ColumnType.Time:
return MySqlDbType.Time;
case ColumnType.Year:
return MySqlDbType.Year;
case ColumnType.Float:
return MySqlDbType.Float;
case ColumnType.Double:
return MySqlDbType.Double;
case ColumnType.Decimal:
return MySqlDbType.Decimal;
case ColumnType.NewDecimal:
return MySqlDbType.NewDecimal;
case ColumnType.Geometry:
return MySqlDbType.Geometry;
case ColumnType.Null:
return MySqlDbType.Null;
default:
throw new NotImplementedException("ConvertToMySqlDbType for {0} is not implemented".FormatInvariant(columnDefinition.ColumnType));
}
}
public static ushort ConvertToColumnTypeAndFlags(MySqlDbType dbType, MySqlGuidFormat guidFormat)
{
var isUnsigned = false;
ColumnType columnType;
switch (dbType)
{
case MySqlDbType.Bool:
case MySqlDbType.Byte:
columnType = ColumnType.Tiny;
break;
case MySqlDbType.UByte:
columnType = ColumnType.Tiny;
isUnsigned = true;
break;
case MySqlDbType.Int16:
columnType = ColumnType.Short;
break;
case MySqlDbType.UInt16:
columnType = ColumnType.Short;
isUnsigned = true;
break;
case MySqlDbType.Int24:
columnType = ColumnType.Int24;
break;
case MySqlDbType.UInt24:
columnType = ColumnType.Int24;
isUnsigned = true;
break;
case MySqlDbType.Int32:
columnType = ColumnType.Long;
break;
case MySqlDbType.UInt32:
columnType = ColumnType.Long;
isUnsigned = true;
break;
case MySqlDbType.Int64:
columnType = ColumnType.Longlong;
break;
case MySqlDbType.UInt64:
columnType = ColumnType.Longlong;
isUnsigned = true;
break;
case MySqlDbType.Bit:
columnType = ColumnType.Bit;
break;
case MySqlDbType.Guid:
if (guidFormat == MySqlGuidFormat.Char36 || guidFormat == MySqlGuidFormat.Char32)
columnType = ColumnType.String;
else
columnType = ColumnType.Blob;
break;
case MySqlDbType.Enum:
case MySqlDbType.Set:
columnType = ColumnType.String;
break;
case MySqlDbType.Binary:
case MySqlDbType.String:
columnType = ColumnType.String;
break;
case MySqlDbType.VarBinary:
case MySqlDbType.VarChar:
case MySqlDbType.VarString:
columnType = ColumnType.VarString;
break;
case MySqlDbType.TinyBlob:
case MySqlDbType.TinyText:
columnType = ColumnType.TinyBlob;
break;
case MySqlDbType.Blob:
case MySqlDbType.Text:
columnType = ColumnType.Blob;
break;
case MySqlDbType.MediumBlob:
case MySqlDbType.MediumText:
columnType = ColumnType.MediumBlob;
break;
case MySqlDbType.LongBlob:
case MySqlDbType.LongText:
columnType = ColumnType.LongBlob;
break;
case MySqlDbType.JSON:
columnType = ColumnType.Json; // TODO: test
break;
case MySqlDbType.Date:
case MySqlDbType.Newdate:
columnType = ColumnType.Date;
break;
case MySqlDbType.DateTime:
columnType = ColumnType.DateTime;
break;
case MySqlDbType.Timestamp:
columnType = ColumnType.Timestamp;
break;
case MySqlDbType.Time:
columnType = ColumnType.Time;
break;
case MySqlDbType.Year:
columnType = ColumnType.Year;
break;
case MySqlDbType.Float:
columnType = ColumnType.Float;
break;
case MySqlDbType.Double:
columnType = ColumnType.Double;
break;
case MySqlDbType.Decimal:
columnType = ColumnType.Decimal;
break;
case MySqlDbType.NewDecimal:
columnType = ColumnType.NewDecimal;
break;
case MySqlDbType.Geometry:
columnType = ColumnType.Geometry;
break;
case MySqlDbType.Null:
columnType = ColumnType.Null;
break;
default:
throw new NotImplementedException("ConvertToColumnTypeAndFlags for {0} is not implemented".FormatInvariant(dbType));
}
return (ushort) ((byte) columnType | (isUnsigned ? 0x8000 : 0));
}
internal IEnumerable<ColumnTypeMetadata> GetColumnMappings()
{
return m_columnTypeMetadataLookup.Values.AsEnumerable();
}
readonly List<ColumnTypeMetadata> m_columnTypeMetadata;
readonly Dictionary<Type, DbTypeMapping> m_dbTypeMappingsByClrType;
readonly Dictionary<DbType, DbTypeMapping> m_dbTypeMappingsByDbType;
readonly Dictionary<string, ColumnTypeMetadata> m_columnTypeMetadataLookup;
readonly Dictionary<MySqlDbType, ColumnTypeMetadata> m_mySqlDbTypeToColumnTypeMetadata;
}
}
<file_sep>using MySql.Data.MySqlClient;
using Xunit;
namespace MySqlConnector.Tests
{
public class DbProviderFactoryTests
{
[Fact]
public void CreatesExpectedTypes()
{
Assert.IsType<MySqlConnection>(MySqlClientFactory.Instance.CreateConnection());
Assert.IsType<MySqlConnectionStringBuilder>(MySqlClientFactory.Instance.CreateConnectionStringBuilder());
Assert.IsType<MySqlCommand>(MySqlClientFactory.Instance.CreateCommand());
Assert.IsType<MySqlParameter>(MySqlClientFactory.Instance.CreateParameter());
}
[Fact]
public void Singleton()
{
var factory1 = MySqlClientFactory.Instance;
var factory2 = MySqlClientFactory.Instance;
Assert.True(object.ReferenceEquals(factory1, factory2));
}
}
}
<file_sep>using System;
using MySql.Data.MySqlClient;
namespace MySqlConnector.Performance
{
public class AppDb : IDisposable
{
public static void Initialize()
{
using (var db = new AppDb())
{
db.Connection.Open();
var cmd = db.Connection.CreateCommand();
cmd.CommandText = @"
DROP TABLE IF EXISTS `BlogPost`;
CREATE TABLE IF NOT EXISTS `BlogPost` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Content` longtext,
`Title` longtext,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB;
";
cmd.ExecuteNonQuery();
}
}
public MySqlConnection Connection;
public AppDb()
{
Connection = new MySqlConnection(AppConfig.Config["Data:ConnectionString"]);
}
public void Dispose()
{
Connection.Close();
}
}
}
<file_sep>using System;
namespace SideBySide
{
[Flags]
public enum ServerFeatures
{
None = 0,
Json = 0x1,
StoredProcedures = 0x2,
Sha256Password = 0x4,
RsaEncryption = 0x8,
LargePackets = 0x10,
CachingSha2Password = 0x20,
SessionTrack = 0x40,
Timeout = 0x80,
ErrorCodes = 0x100,
KnownCertificateAuthority = 0x200,
Tls11 = 0x400,
Tls12 = 0x800,
RoundDateTime = 0x1000,
UuidToBin = 0x2000,
Ed25519 = 0x4000,
UnixDomainSocket = 0x8000,
Tls13 = 0x1_0000,
}
}
<file_sep>title = "High-Performance Async MySQL Driver for .NET"
baseurl = "https://mysqlconnector.net/"
MetaDataFormat = "yaml"
pluralizeListTitles = false
pygmentsCodeFences = true
pygmentsStyle = "friendly"
[blackfriday]
plainIDAnchors = true
[params]
description = "Documentation for MySqlConnector: an Async MySQL Driver for .NET and .NET Core"
author = "MySqlConnector Authors"
[taxonomies]
tag = "tags"
group = "groups"
[[menu.main]]
name = "Getting Started"
identifier = "getting started"
pre = "<i class='fa fa-road'></i>"
weight = 20
[[menu.main]]
name = "Tutorials"
identifier = "tutorials"
pre = "<i class='fa fa-lightbulb-o'></i>"
weight = 40
[[menu.main]]
name = "API"
identifier = "api"
pre = "<i class='fa fa-file-text'></i>"
weight = 50
[[menu.main]]
name = "Troubleshooting"
identifier = "troubleshooting"
pre = "<i class='fa fa-lightbulb-o'></i>"
weight = 60
<file_sep>using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using MySqlConnector.Core;
using MySqlConnector.Diagnostics;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlBatch : ICancellableCommand, IDisposable
{
public MySqlBatch()
: this(null, null)
{
}
public MySqlBatch(MySqlConnection? connection = null, MySqlTransaction? transaction = null)
{
Connection = connection;
Transaction = transaction;
BatchCommands = new MySqlBatchCommandCollection();
m_commandId = ICancellableCommandExtensions.GetNextId();
}
public MySqlConnection? Connection { get; set; }
public MySqlTransaction? Transaction { get; set; }
public MySqlBatchCommandCollection BatchCommands { get; }
public DbDataReader ExecuteReader() => ExecuteDbDataReader();
public Task<DbDataReader> ExecuteReaderAsync(CancellationToken cancellationToken = default) => ExecuteDbDataReaderAsync(cancellationToken);
private DbDataReader ExecuteDbDataReader()
{
((ICancellableCommand) this).ResetCommandTimeout();
return ExecuteReaderAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
}
private Task<DbDataReader> ExecuteDbDataReaderAsync(CancellationToken cancellationToken)
{
((ICancellableCommand) this).ResetCommandTimeout();
return ExecuteReaderAsync(AsyncIOBehavior, cancellationToken);
}
private Task<DbDataReader> ExecuteReaderAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
if (!IsValid(out var exception))
return Utility.TaskFromException<DbDataReader>(exception);
foreach (var batchCommand in BatchCommands)
batchCommand.Batch = this;
var payloadCreator = Connection!.Session.SupportsComMulti ? BatchedCommandPayloadCreator.Instance :
IsPrepared ? SingleCommandPayloadCreator.Instance :
ConcatenatedCommandPayloadCreator.Instance;
Exception? e = null;
var sqlDiagnosticsCommands = BatchCommands.ToDiagnosticsCommands();
var operationId = _diagnosticListener.WriteCommandBefore(sqlDiagnosticsCommands);
try
{
return CommandExecutor.ExecuteReaderAsync(BatchCommands!, payloadCreator, CommandBehavior.Default, ioBehavior, cancellationToken);
}
catch (Exception ex)
{
e = ex;
throw;
}
finally
{
if (e != null)
{
_diagnosticListener.WriteCommandError(operationId, sqlDiagnosticsCommands, e);
}
else
{
_diagnosticListener.WriteCommandAfter(operationId, sqlDiagnosticsCommands);
}
}
}
public int ExecuteNonQuery() => ExecuteNonQueryAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
public object ExecuteScalar() => ExecuteScalarAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
public Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken = default) => ExecuteNonQueryAsync(AsyncIOBehavior, cancellationToken);
public Task<object> ExecuteScalarAsync(CancellationToken cancellationToken = default) => ExecuteScalarAsync(AsyncIOBehavior, cancellationToken);
public int Timeout { get; set; }
public void Prepare()
{
if (!NeedsPrepare(out var exception))
{
if (exception is object)
throw exception;
return;
}
DoPrepareAsync(IOBehavior.Synchronous, default).GetAwaiter().GetResult();
}
public Task PrepareAsync(CancellationToken cancellationToken = default) => PrepareAsync(AsyncIOBehavior, cancellationToken);
public void Cancel() => Connection?.Cancel(this);
public void Dispose()
{
m_isDisposed = true;
}
int ICancellableCommand.CommandId => m_commandId;
int ICancellableCommand.CommandTimeout => Timeout;
int ICancellableCommand.CancelAttemptCount { get; set; }
IDisposable? ICancellableCommand.RegisterCancel(CancellationToken token)
{
if (!token.CanBeCanceled)
return null;
m_cancelAction ??= Cancel;
return token.Register(m_cancelAction);
}
private async Task<int> ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
((ICancellableCommand) this).ResetCommandTimeout();
using var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
do
{
while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false))
{
}
} while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false));
return reader.RecordsAffected;
}
private async Task<object> ExecuteScalarAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
((ICancellableCommand) this).ResetCommandTimeout();
var hasSetResult = false;
object? result = null;
using var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
do
{
var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
if (!hasSetResult)
{
if (hasResult)
result = reader.GetValue(0);
hasSetResult = true;
}
} while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false));
return result!;
}
private bool IsValid([NotNullWhen(false)] out Exception? exception)
{
exception = null;
if (m_isDisposed)
exception = new ObjectDisposedException(GetType().Name);
else if (Connection is null)
exception = new InvalidOperationException("Connection property must be non-null.");
else if (Connection.State != ConnectionState.Open && Connection.State != ConnectionState.Connecting)
exception = new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(Connection.State));
else if (!Connection.IgnoreCommandTransaction && Transaction != Connection.CurrentTransaction)
exception = new InvalidOperationException("The transaction associated with this batch is not the connection's active transaction; see https://fl.vu/mysql-trans");
else if (BatchCommands.Count == 0)
exception = new InvalidOperationException("BatchCommands must contain a command");
else
exception = GetExceptionForInvalidCommands();
return exception is null;
}
private bool NeedsPrepare(out Exception? exception)
{
exception = null;
if (m_isDisposed)
exception = new ObjectDisposedException(GetType().Name);
else if (Connection is null)
exception = new InvalidOperationException("Connection property must be non-null.");
else if (Connection.State != ConnectionState.Open)
exception = new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(Connection.State));
else if (BatchCommands.Count == 0)
exception = new InvalidOperationException("BatchCommands must contain a command");
else if (Connection?.HasActiveReader ?? false)
exception = new InvalidOperationException("Cannot call Prepare when there is an open DataReader for this command; it must be closed first.");
else
exception = GetExceptionForInvalidCommands();
return exception is null && !Connection!.IgnorePrepare;
}
private Exception? GetExceptionForInvalidCommands()
{
foreach (var command in BatchCommands)
{
if (command is null)
return new InvalidOperationException("BatchCommands must not contain null");
if ((command.CommandBehavior & CommandBehavior.CloseConnection) != 0)
return new NotSupportedException("CommandBehavior.CloseConnection is not supported by MySqlBatch");
if (string.IsNullOrWhiteSpace(command.CommandText))
return new InvalidOperationException("CommandText must be specified on each batch command");
}
return null;
}
private Task PrepareAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
if (!NeedsPrepare(out var exception))
return exception is null ? Utility.CompletedTask : Utility.TaskFromException(exception);
return DoPrepareAsync(ioBehavior, cancellationToken);
}
private async Task DoPrepareAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
foreach (IMySqlCommand batchCommand in BatchCommands)
{
if (batchCommand.CommandType != CommandType.Text)
throw new NotSupportedException("Only CommandType.Text is currently supported by MySqlBatch.Prepare");
((MySqlBatchCommand) batchCommand).Batch = this;
// don't prepare the same SQL twice
if (Connection!.Session.TryGetPreparedStatement(batchCommand.CommandText!) is null)
await Connection.Session.PrepareAsync(batchCommand, ioBehavior, cancellationToken).ConfigureAwait(false);
}
}
private bool IsPrepared
{
get
{
foreach (var command in BatchCommands)
{
if (Connection!.Session.TryGetPreparedStatement(command!.CommandText!) is null)
return false;
}
return true;
}
}
private IOBehavior AsyncIOBehavior => Connection?.AsyncIOBehavior ?? IOBehavior.Asynchronous;
readonly int m_commandId;
bool m_isDisposed;
Action? m_cancelAction;
static readonly DiagnosticListener _diagnosticListener = new DiagnosticListener(MySqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
}
}
<file_sep>using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MySqlConnector.Performance.Models;
namespace MySqlConnector.Performance.Controllers
{
[Route("api/[controller]")]
public class AsyncController : Controller
{
// GET api/async
[HttpGet]
public async Task<IActionResult> GetLatest()
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
var result = await query.LatestPostsAsync();
return new OkObjectResult(result);
}
}
// GET api/async/5
[HttpGet("{id}")]
public async Task<IActionResult> GetOne(int id)
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
var result = await query.FindOneAsync(id);
if (result == null)
return new NotFoundResult();
return new OkObjectResult(result);
}
}
// POST api/async
[HttpPost]
public async Task<IActionResult> Post([FromBody]BlogPost body)
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
body.Db = db;
await body.InsertAsync();
return new OkObjectResult(body);
}
}
// PUT api/async/5
[HttpPut("{id}")]
public async Task<IActionResult> PutOne(int id, [FromBody]BlogPost body)
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
var result = await query.FindOneAsync(id);
if (result == null)
return new NotFoundResult();
result.Title = body.Title;
result.Content = body.Content;
await result.UpdateAsync();
return new OkObjectResult(result);
}
}
// DELETE api/async/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteOne(int id)
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
var result = await query.FindOneAsync(id);
if (result == null)
return new NotFoundResult();
await result.DeleteAsync();
return new OkResult();
}
}
// DELETE api/async
[HttpDelete]
public async Task<IActionResult> DeleteAll()
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
await query.DeleteAllAsync();
return new OkResult();
}
}
// GET api/async/bulkinsert/10000
[HttpGet("bulkinsert/{num}")]
public async Task<IActionResult> BulkInsert(int num)
{
using (var db = new AppDb())
{
var time = DateTime.Now;
await db.Connection.OpenAsync();
var txn = await db.Connection.BeginTransactionAsync();
try
{
for (var i = 0; i < num; i++)
{
var blogPost = new BlogPost
{
Db = db,
Title = "bulk",
Content = "bulk " + num
};
await blogPost.InsertAsync();
}
#if BASELINE
txn.Commit();
#else
await txn.CommitAsync();
#endif
}
catch (Exception)
{
#if BASELINE
txn.Rollback();
#else
await txn.RollbackAsync();
#endif
throw;
}
var timing = $"Async: Inserted {num} records in " + (DateTime.Now - time);
Console.WriteLine(timing);
return new OkObjectResult(timing);
}
}
// GET api/async/bulkselect
[HttpGet("bulkselect/{num}")]
public async Task<IActionResult> BulkSelect(int num)
{
using (var db = new AppDb())
{
var time = DateTime.Now;
await db.Connection.OpenAsync();
var query = new BlogPostQuery(db);
var reader = await query.LatestPostsCmd(num).ExecuteReaderAsync();
var numRead = 0;
while (await reader.ReadAsync())
{
var post = new BlogPost(db)
{
Id = await reader.GetFieldValueAsync<int>(0),
Title = await reader.GetFieldValueAsync<string>(1),
Content = await reader.GetFieldValueAsync<string>(2)
};
numRead++;
}
var timing = $"Async: Read {numRead} records in " + (DateTime.Now - time);
Console.WriteLine(timing);
return new OkObjectResult(timing);
}
}
}
}
<file_sep>---
lastmod: 2019-06-23
date: 2016-10-16
menu:
main:
parent: api
title: MySqlConnection
weight: 30
---
MySqlConnection
=================
MySqlConnection implements the [ADO.NET DbConnection class](https://docs.microsoft.com/en-us/dotnet/core/api/system.data.common.dbconnection);
please refer to its documentation.
Additionally, MySqlConnection provides the following public properties and methods that may be used:
### Constructors
`MySqlConnection()`
Parameterless constructor.
***
`MySqlConnection(string connectionString)`
Constructor that sets the `ConnectionString` property.
### Additional Properties
`int ServerThread`
Connection ID from MySQL Server.
***
`bool CanCreateBatch`
Returns `true`.
### Additional Instance Methods
`ValueTask<MySqlTransaction> BeginTransactionAsync()`
`ValueTask<MySqlTransaction> BeginTransactionAsync(CancellationToken cancellationToken)`
Async version of `BeginTransaction`.
***
`ValueTask<MySqlTransaction> BeginTransactionAsync(IsolationLevel isolationLevel)`
`ValueTask<MySqlTransaction> BeginTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)`
Async version of `BeginTransaction` that supports setting Isolation Level.
***
`MySqlBatch CreateBatch()`
Creates a `MySqlBatch` object for executing batched commands.
***
`MySqlBatchCommand CreateBatchCommand()`
Creates a `MySqlBatchCommand` object (that can be used with `MySqlBatch.BatchCommands`).
### Additional Static Methods
`static void ClearPool(MySqlConnection connection)`
Clears the connection pool that the connection belongs to.
***
`static Task ClearPoolAsync(MySqlConnection connection)`
Async version of `ClearPool`.
***
`static Task ClearPoolAsync(MySqlConnection connection, CancellationToken cancellationToken)`
Async version of `ClearPool` with cancellation token support.
***
`static void ClearAllPools()`
Clears all connection pools in the entire application.
***
`static Task ClearAllPoolsAsync()`
Async version of `ClearAllPoolsAsync`.
***
`static Task ClearAllPoolsAsync(CancellationToken cancellationToken)`
Async version of `ClearAllPoolsAsync` with cancellation token support.
<file_sep>namespace MySqlConnector.Tests
{
internal enum DummyEnum
{
FirstValue,
SecondValue
}
}
<file_sep>Performance Tests
=================
## Concurrency Testing
To run concurrency tests, execute the following command
```
dotnet run concurrency [iterations] [concurrency] [operations]
```
For example, the following command will run 3 iterations using 100 concurrent connections and 10 operations in each concurrency test:
```
dotnet run concurrency 3 100 10
```
## HTTP Load Testing
The `MySqlConnector.Performance` project runs a .NET Core MVC API application that is intended to be used to load test asynchronous and synchronous MySqlConnector methods.
You first must configure your MySql Database. Open the `config.json.example` file, configure the connection string, and save it as `config.json`. Now you can run the application with `dotnet run`.
The application runs on http://localhost:5000 by default. It drops and creates a table called `BlogPosts` in the test database when it is started.
`GET /api/async` and `GET /api/sync` return the most recent 10 posts.
`POST /api/async` and `POST /api/sync` create a new post. The request body should be `Content-Type: application/json` in the form:
{
"Title": "Post Title",
"Content": "Post Content"
}
`GET /api/async/bulkinsert/<num>` and `GET /api/sync/bulkinsert/<num>` Insert <num> blog posts serially in a transaction
`GET /api/async/bulkselect/<num>` and `GET /api/sync/bulkselect/<num>` Selects <num> blog posts and exhausts the datareader (make sure you have inserted <num> posts first with the bulkinsert endpoint)
The `scripts` directory contains load testing scripts. These scripts require that the [Vegeta](https://github.com/tsenart/vegeta/releases) binary is installed and accessible in your PATH. Here are examples of how to call the load testing scripts:
# by default, runs 50 async queries per second for 5 seconds
./stress.sh # bash for linux
./stress.ps1 # powershell for windows
# runs 100 async queries per second for 10 seconds on linux
./stress.sh 100 10s async
# run 50 sync queries per second for 1 minute on windows
./stress.ps1 50 1m sync
## Baseline Tests
To run the Baseline tests against MySql.Data, first restore the project to include MySql.Data:
```
dotnet restore /p:Configuration=Baseline
```
Next, run use `dotnet -c Baseline` when running any dotnet commands. Example:
```
dotnet run -c Baseline concurrency 3 100 10
```
<file_sep>using System.Data;
using MySql.Data.MySqlClient;
namespace MySqlConnector.Diagnostics
{
public class MySqlDiagnosticsCommand
{
public int CommandId { get; set; }
public int CommandTimeout { get; set; }
public string? CommandText { get; set; }
public CommandType CommandType { get; set; }
public bool AllowUserVariables { get; set; }
public CommandBehavior CommandBehavior { get; set; }
public MySqlParameterCollection? RawParameters { get; set; }
public MySqlConnection? Connection { get; set; }
}
}
<file_sep>---
lastmod: 2020-01-07
date: 2016-10-16
menu:
main:
parent: getting started
title: Installing
weight: 10
---
Installing
==========
The recommended way of installing MySqlConnector is through [NuGet](https://www.nuget.org/packages/MySqlConnector/).
Note that if you are using the `MySql.Data` NuGet package, it must be uninstalled first.
### Automatically
If using the new project system, run: `dotnet add package MySqlConnector`
Or, in Visual Studio, use the _NuGet Package Manager_ to browse for and install `MySqlConnector`.
### Manually
**Step 1:** Add MySqlConnector to the dependencies in your `csproj` file:
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyTitle>My Application</AssemblyTitle>
<Description>A great application</Description>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MySqlConnector" Version="0.61.0" />
</ItemGroup>
</Project>
```
**Step 2:** Run the command `dotnet restore`
<file_sep>using System;
using MySqlConnector.Utilities;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlProtocolException : InvalidOperationException
{
internal static MySqlProtocolException CreateForPacketOutOfOrder(int expectedSequenceNumber, int packetSequenceNumber)
{
return new MySqlProtocolException("Packet received out-of-order. Expected {0}; got {1}.".FormatInvariant(expectedSequenceNumber, packetSequenceNumber));
}
private MySqlProtocolException(string message)
: base(message)
{
}
}
}
<file_sep>[build]
base = "docs/"
publish = "docs/public/"
command = "hugo --gc --minify -v"
[[redirects]]
from = "/home/"
to = "/"
force = true
[[redirects]]
from = "/index.html"
to = "/"
force = true
[[redirects]]
from = "/:category/index.html"
to = "/:category/"
force = true
[[redirects]]
from = "/:category/:page/index.html"
to = "/:category/:page/"
force = true
[[redirects]]
from = "/api/"
to = "/"
status = 302
force = true
[[redirects]]
from = "/groups/"
to = "/"
status = 302
force = true
[[redirects]]
from = "/overview/"
to = "/"
status = 302
force = true
[[redirects]]
from = "/tags/"
to = "/"
status = 302
force = true
[[redirects]]
from = "/troubleshooting/"
to = "/"
status = 302
force = true
[[redirects]]
from = "/tutorials/"
to = "/"
status = 302
force = true
<file_sep>using System;
using System.Threading.Tasks;
namespace MySqlConnector.Utilities
{
internal static class ValueTaskExtensions
{
public static async ValueTask<TResult> ContinueWith<T, TResult>(this ValueTask<T> valueTask, Func<T, ValueTask<TResult>> continuation) => await continuation(await valueTask.ConfigureAwait(false)).ConfigureAwait(false);
public static ValueTask<T> FromException<T>(Exception exception) => new ValueTask<T>(Utility.TaskFromException<T>(exception));
}
}
<file_sep>using System;
namespace MySql.Data.MySqlClient
{
public enum MySqlDbType
{
Bool = -1,
Decimal,
Byte,
Int16,
Int32,
Float,
Double,
Null,
Timestamp,
Int64,
Int24,
Date,
Time,
DateTime,
[Obsolete("The Datetime enum value is obsolete. Please use DateTime.")]
Datetime = 12,
Year,
Newdate,
VarString,
Bit,
JSON = 245,
NewDecimal,
Enum,
Set,
TinyBlob,
MediumBlob,
LongBlob,
Blob,
VarChar,
String,
Geometry,
UByte = 501,
UInt16,
UInt32,
UInt64 = 508,
UInt24,
Binary = 600,
VarBinary,
TinyText = 749,
MediumText,
LongText,
Text,
Guid = 800
}
}
<file_sep>#if !NETCOREAPP1_1_2
using System;
using System.Data;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class DataAdapterTests : IClassFixture<DatabaseFixture>, IDisposable
{
public DataAdapterTests(DatabaseFixture database)
{
m_connection = database.Connection;
m_connection.Open();
#if BASELINE
// not sure why this is necessary
m_connection.Execute("drop table if exists data_adapter;");
#endif
m_connection.Execute(@"
create temporary table data_adapter(
id bigint not null primary key auto_increment,
int_value int null,
text_value text null
);
insert into data_adapter(int_value, text_value) values
(null, null),
(0, ''),
(1, 'one');
");
}
public void Dispose()
{
m_connection.Close();
}
[Fact]
public void UseDataAdapter()
{
using var command = new MySqlCommand("SELECT 1", m_connection);
using var da = new MySqlDataAdapter();
using var ds = new DataSet();
da.SelectCommand = command;
da.Fill(ds);
Assert.Single(ds.Tables);
Assert.Single(ds.Tables[0].Rows);
Assert.Single(ds.Tables[0].Rows[0].ItemArray);
TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]);
}
[Fact]
public void UseDataAdapterMySqlConnectionConstructor()
{
using var command = new MySqlCommand("SELECT 1", m_connection);
using var da = new MySqlDataAdapter(command);
using var ds = new DataSet();
da.Fill(ds);
TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]);
}
[Fact]
public void UseDataAdapterStringMySqlConnectionConstructor()
{
using var da = new MySqlDataAdapter("SELECT 1", m_connection);
using var ds = new DataSet();
da.Fill(ds);
TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]);
}
[Fact]
public void UseDataAdapterStringStringConstructor()
{
using var da = new MySqlDataAdapter("SELECT 1", AppConfig.ConnectionString);
using var ds = new DataSet();
da.Fill(ds);
TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]);
}
[Fact]
public void Fill()
{
using var da = new MySqlDataAdapter("select * from data_adapter", m_connection);
using var ds = new DataSet();
da.Fill(ds, "data_adapter");
Assert.Single(ds.Tables);
Assert.Equal(3, ds.Tables[0].Rows.Count);
Assert.Equal(1L, ds.Tables[0].Rows[0]["id"]);
Assert.Equal(2L, ds.Tables[0].Rows[1]["id"]);
Assert.Equal(3L, ds.Tables[0].Rows[2]["id"]);
Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["int_value"]);
Assert.Equal(0, ds.Tables[0].Rows[1]["int_value"]);
Assert.Equal(1, ds.Tables[0].Rows[2]["int_value"]);
Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["text_value"]);
Assert.Equal("", ds.Tables[0].Rows[1]["text_value"]);
Assert.Equal("one", ds.Tables[0].Rows[2]["text_value"]);
}
[Fact]
public void LoadDataTable()
{
using var command = new MySqlCommand("SELECT * FROM data_adapter", m_connection);
using var dr = command.ExecuteReader();
var dt = new DataTable();
dt.Load(dr);
dr.Close();
Assert.Equal(3, dt.Rows.Count);
Assert.Equal(1L, dt.Rows[0]["id"]);
Assert.Equal(2L, dt.Rows[1]["id"]);
Assert.Equal(3L, dt.Rows[2]["id"]);
Assert.Equal(DBNull.Value, dt.Rows[0]["int_value"]);
Assert.Equal(0, dt.Rows[1]["int_value"]);
Assert.Equal(1, dt.Rows[2]["int_value"]);
Assert.Equal(DBNull.Value, dt.Rows[0]["text_value"]);
Assert.Equal("", dt.Rows[1]["text_value"]);
Assert.Equal("one", dt.Rows[2]["text_value"]);
}
[SkippableFact(Baseline = "Throws FormatException: Input string was not in a correct format")]
public void InsertWithDataSet()
{
using (var ds = new DataSet())
using (var da = new MySqlDataAdapter("SELECT * FROM data_adapter", m_connection))
{
da.Fill(ds);
da.InsertCommand = new MySqlCommand("INSERT INTO data_adapter (int_value, text_value) VALUES (@int, @text)", m_connection);
da.InsertCommand.Parameters.Add(new MySqlParameter("@int", DbType.Int32));
da.InsertCommand.Parameters.Add(new MySqlParameter("@text", DbType.String));
da.InsertCommand.Parameters[0].Direction = ParameterDirection.Input;
da.InsertCommand.Parameters[1].Direction = ParameterDirection.Input;
da.InsertCommand.Parameters[0].SourceColumn = "int_value";
da.InsertCommand.Parameters[1].SourceColumn = "text_value";
var dt = ds.Tables[0];
var dr = dt.NewRow();
dr["int_value"] = 4;
dr["text_value"] = "four";
dt.Rows.Add(dr);
using var ds2 = ds.GetChanges();
da.Update(ds2);
ds.Merge(ds2);
ds.AcceptChanges();
}
using var cmd2 = new MySqlCommand("SELECT id, int_value, text_value FROM data_adapter", m_connection);
using var dr2 = cmd2.ExecuteReader();
Assert.True(dr2.Read());
Assert.Equal(1L, dr2[0]);
Assert.True(dr2.Read());
Assert.Equal(2L, dr2[0]);
Assert.True(dr2.Read());
Assert.Equal(3L, dr2[0]);
Assert.True(dr2.Read());
Assert.Equal(4L, dr2[0]);
Assert.Equal(4, dr2[1]);
Assert.Equal("four", dr2[2]);
}
[Fact]
public void BatchUpdate()
{
using (var ds = new DataSet())
using (var da = new MySqlDataAdapter("SELECT * FROM data_adapter", m_connection))
{
da.Fill(ds);
da.UpdateCommand = new MySqlCommand("UPDATE data_adapter SET int_value=@int, text_value=@text WHERE id=@id", m_connection)
{
Parameters =
{
new MySqlParameter("@int", MySqlDbType.Int32) { Direction = ParameterDirection.Input, SourceColumn = "int_value" },
new MySqlParameter("@text", MySqlDbType.String) { Direction = ParameterDirection.Input, SourceColumn = "text_value" },
new MySqlParameter("@id", MySqlDbType.Int64) { Direction = ParameterDirection.Input, SourceColumn = "id" },
},
UpdatedRowSource = UpdateRowSource.None,
};
da.UpdateBatchSize = 10;
var dt = ds.Tables[0];
dt.Rows[0][1] = 2;
dt.Rows[0][2] = "two";
dt.Rows[1][1] = 3;
dt.Rows[1][2] = "three";
dt.Rows[2][1] = 4;
dt.Rows[2][2] = "four";
da.Update(ds);
}
Assert.Equal(new[] { "two", "three", "four" }, m_connection.Query<string>("SELECT text_value FROM data_adapter ORDER BY id"));
}
[Fact]
public void BatchInsert()
{
using (var ds = new DataSet())
using (var da = new MySqlDataAdapter("SELECT * FROM data_adapter", m_connection))
{
da.Fill(ds);
da.InsertCommand = new MySqlCommand("INSERT INTO data_adapter(int_value, text_value) VALUES(@int, @text);", m_connection)
{
Parameters =
{
new MySqlParameter("@int", MySqlDbType.Int32) { Direction = ParameterDirection.Input, SourceColumn = "int_value" },
new MySqlParameter("@text", MySqlDbType.String) { Direction = ParameterDirection.Input, SourceColumn = "text_value" },
},
UpdatedRowSource = UpdateRowSource.None,
};
da.UpdateBatchSize = 10;
var dt = ds.Tables[0];
dt.Rows.Add(0, 2, "two");
dt.Rows.Add(0, 3, "three");
dt.Rows.Add(0, 4, "four");
da.Update(ds);
}
Assert.Equal(new[] { null, "", "one", "two", "three", "four" }, m_connection.Query<string>("SELECT text_value FROM data_adapter ORDER BY id"));
}
readonly MySqlConnection m_connection;
}
}
#endif
<file_sep>using System;
using System.Buffers.Text;
using System.Text;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class ServerVersion
{
public ServerVersion(ReadOnlySpan<byte> versionString)
{
OriginalString = Encoding.ASCII.GetString(versionString);
if (!Utf8Parser.TryParse(versionString, out int major, out var bytesConsumed) || versionString[bytesConsumed] != 0x2E)
throw new InvalidOperationException("Error parsing " + OriginalString);
versionString = versionString.Slice(bytesConsumed + 1);
if (!Utf8Parser.TryParse(versionString, out int minor, out bytesConsumed) || versionString[bytesConsumed] != 0x2E)
throw new InvalidOperationException("Error parsing " + OriginalString);
versionString = versionString.Slice(bytesConsumed + 1);
if (!Utf8Parser.TryParse(versionString, out int build, out bytesConsumed))
throw new InvalidOperationException("Error parsing " + OriginalString);
versionString = versionString.Slice(bytesConsumed);
Version = new Version(major, minor, build);
// check for MariaDB version appended to a fake MySQL version
if (versionString.Length != 0 && versionString[0] == 0x2D)
{
versionString = versionString.Slice(1);
var mariaDbIndex = versionString.IndexOf(MariaDb);
if (mariaDbIndex != -1)
{
var totalBytesRead = 0;
if (Utf8Parser.TryParse(versionString, out major, out bytesConsumed) && versionString[bytesConsumed] == 0x2E)
{
versionString = versionString.Slice(bytesConsumed + 1);
totalBytesRead += bytesConsumed + 1;
if (Utf8Parser.TryParse(versionString, out minor, out bytesConsumed) && versionString[bytesConsumed] == 0x2E)
{
versionString = versionString.Slice(bytesConsumed + 1);
totalBytesRead += bytesConsumed + 1;
if (Utf8Parser.TryParse(versionString, out build, out bytesConsumed) && versionString[bytesConsumed] == 0x2D)
{
totalBytesRead += bytesConsumed;
if (totalBytesRead == mariaDbIndex)
MariaDbVersion = new Version(major, minor, build);
}
}
}
}
}
}
public string OriginalString { get; }
public Version Version { get; }
public Version? MariaDbVersion { get; }
public static ServerVersion Empty { get; } = new ServerVersion();
private ServerVersion()
{
OriginalString = "";
Version = new Version(0, 0);
}
static ReadOnlySpan<byte> MariaDb => new byte[] { 0x2D, 0x4D, 0x61, 0x72, 0x69, 0x61, 0x44, 0x42 }; // -MariaDB
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlInfoMessageEventArgs : EventArgs
{
internal MySqlInfoMessageEventArgs(MySqlError[] errors) => this.errors = errors;
public MySqlError[] errors { get; }
public IReadOnlyList<MySqlError> Errors => errors;
}
public delegate void MySqlInfoMessageEventHandler(object sender, MySqlInfoMessageEventArgs args);
}
<file_sep>using System;
namespace SideBySide
{
[Flags]
public enum ConfigSettings
{
None = 0,
RequiresSsl = 0x1,
TrustedHost = 0x2,
UntrustedHost = 0x4,
PasswordlessUser = 0x8,
CsvFile = 0x10,
LocalCsvFile = 0x20,
TsvFile = 0x40,
LocalTsvFile = 0x80,
TcpConnection = 0x200,
SecondaryDatabase = 0x400,
KnownClientCertificate = 0x800,
GSSAPIUser = 0x1000,
HasKerberos = 0x2000
}
}
<file_sep>---
lastmod: 2016-10-16
date: 2016-10-16
menu:
main:
parent: getting started
title: Configuration
weight: 40
---
Configuration
============
MySqlConnector uses a connection string in order to connect to your database.
To connect to a database on `localhost` port `3306` with a user `mysqltest`, password `<PASSWORD>`, and default schema `mysqldb`, the connection string would be:
`host=127.0.0.1;port=3306;user id=mysqltest;password=<PASSWORD>;database=mysqldb;`
For all connection string options, view the [Connection Options Reference](connection-options/)
### Application Database Object Example
It's a good idea to use an IDisposable object that configures the connection string globally, and closes the connection automatically:
```csharp
public class AppDb : IDisposable
{
public readonly MySqlConnection Connection;
public AppDb()
{
Connection = new MySqlConnection("host=127.0.0.1;port=3306;user id=mysqltest;password=<PASSWORD>;database=mysqldb;");
}
public void Dispose()
{
Connection.Close();
}
}
```
Callers can use the Application Database Object object like so:
```csharp
public async Task AsyncMethod()
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
// db.Connection is open and ready to use
}
// db.Connection was closed by AppDb.Dispose
}
public void SyncMethod()
{
using (var db = new AppDb())
{
db.Connection.Open();
// db.Connection is open and ready to use
}
// db.Connection was closed by AppDb.Dispose
}
```
<file_sep>using System;
using System.Threading;
using MySql.Data.MySqlClient;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
/// <summary>
/// <see cref="IMySqlCommand"/> provides an internal abstraction over operations that can be cancelled: <see cref="MySqlCommand"/> and <see cref="MySqlBatch"/>.
/// </summary>
internal interface ICancellableCommand
{
int CommandId { get; }
int CommandTimeout { get; }
int CancelAttemptCount { get; set; }
MySqlConnection? Connection { get; }
IDisposable? RegisterCancel(CancellationToken cancellationToken);
}
internal static class ICancellableCommandExtensions
{
/// <summary>
/// Returns a unique ID for all implementations of <see cref="ICancellableCommand"/>.
/// </summary>
/// <returns></returns>
public static int GetNextId() => Interlocked.Increment(ref s_id);
/// <summary>
/// Causes the effective command timeout to be reset back to the value specified by <see cref="ICancellableCommand.CommandTimeout"/>.
/// </summary>
/// <remarks>As per the <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx">MSDN documentation</a>,
/// "This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command
/// execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network
/// read time. For example, with a 30 second time out, if Read requires two network packets, then it has 30 seconds to read both network packets. If you call
/// Read again, it will have another 30 seconds to read any data that it requires."
/// The <see cref="ResetCommandTimeout"/> method is called by public ADO.NET API methods to reset the effective time remaining at the beginning of a new
/// method call.</remarks>
public static void ResetCommandTimeout(this ICancellableCommand command)
{
var commandTimeout = command.CommandTimeout;
command.Connection?.Session?.SetTimeout(commandTimeout == 0 ? Constants.InfiniteTimeout : commandTimeout * 1000);
}
static int s_id = 1;
}
}
<file_sep>using System;
using Microsoft.AspNetCore.Mvc;
using MySqlConnector.Performance.Models;
namespace MySqlConnector.Performance.Controllers
{
[Route("api/[controller]")]
public class SyncController : Controller
{
// GET api/sync
[HttpGet]
public IActionResult GetLatest()
{
using (var db = new AppDb())
{
db.Connection.Open();
var query = new BlogPostQuery(db);
var result = query.LatestPosts();
return new OkObjectResult(result);
}
}
// GET api/sync/5
[HttpGet("{id}")]
public IActionResult GetOne(int id)
{
using (var db = new AppDb())
{
db.Connection.Open();
var query = new BlogPostQuery(db);
var result = query.FindOne(id);
if (result == null)
return new NotFoundResult();
return new OkObjectResult(result);
}
}
// POST api/sync
[HttpPost]
public IActionResult Post([FromBody]BlogPost body)
{
using (var db = new AppDb())
{
db.Connection.Open();
body.Db = db;
body.Insert();
return new OkObjectResult(body);
}
}
// PUT api/sync/5
[HttpPut("{id}")]
public IActionResult PutOne(int id, [FromBody]BlogPost body)
{
using (var db = new AppDb())
{
db.Connection.Open();
var query = new BlogPostQuery(db);
var result = query.FindOne(id);
if (result == null)
return new NotFoundResult();
result.Title = body.Title;
result.Content = body.Content;
result.Update();
return new OkObjectResult(result);
}
}
// DELETE api/sync/5
[HttpDelete("{id}")]
public IActionResult DeleteOne(int id)
{
using (var db = new AppDb())
{
db.Connection.Open();
var query = new BlogPostQuery(db);
var result = query.FindOne(id);
if (result == null)
return new NotFoundResult();
result.Delete();
return new OkResult();
}
}
// DELETE api/sync
[HttpDelete]
public IActionResult DeleteAll()
{
using (var db = new AppDb())
{
db.Connection.Open();
var query = new BlogPostQuery(db);
query.DeleteAll();
return new OkResult();
}
}
// GET api/sync/hello
// This method is used to establish baseline web server performance
// i.e. how many base RPS can the server handle
[HttpGet("hello")]
public IActionResult Hello()
{
return new OkObjectResult("hello world");
}
// GET api/sync/bulkinsert/10000
[HttpGet("bulkinsert/{num}")]
public IActionResult BulkInsert(int num)
{
using (var db = new AppDb())
{
var time = DateTime.Now;
db.Connection.Open();
var txn = db.Connection.BeginTransaction();
try
{
for (var i = 0; i < num; i++)
{
var blogPost = new BlogPost
{
Db = db,
Title = "bulk",
Content = "bulk " + num
};
blogPost.Insert();
}
}
catch (Exception)
{
txn.Rollback();
throw;
}
txn.Commit();
var timing = $"Sync: Inserted {num} records in " + (DateTime.Now - time);
Console.WriteLine(timing);
return new OkObjectResult(timing);
}
}
// GET api/sync/bulkselect
[HttpGet("bulkselect/{num}")]
public IActionResult BulkSelect(int num)
{
using (var db = new AppDb())
{
var time = DateTime.Now;
db.Connection.Open();
var query = new BlogPostQuery(db);
var reader = query.LatestPostsCmd(num).ExecuteReader();
var numRead = 0;
while (reader.Read())
{
var post = new BlogPost(db)
{
Id = reader.GetFieldValue<int>(0),
Title = reader.GetFieldValue<string>(1),
Content = reader.GetFieldValue<string>(2)
};
numRead++;
}
var timing = $"Sync: Read {numRead} records in " + (DateTime.Now - time);
Console.WriteLine(timing);
return new OkObjectResult(timing);
}
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class UpdateTests : IClassFixture<DatabaseFixture>, IDisposable
{
public UpdateTests(DatabaseFixture database)
{
m_database = database;
m_database.Connection.Open();
}
public void Dispose()
{
m_database.Connection.Close();
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 1)]
public async Task UpdateRowsExecuteReader(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_reader;
create table update_rows_reader(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_reader (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"update update_rows_reader set value = @newValue where value = @oldValue";
var p = cmd.CreateParameter();
p.ParameterName = "@oldValue";
p.Value = oldValue;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@newValue";
p.Value = 4;
cmd.Parameters.Add(p);
using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
Assert.False(await reader.ReadAsync().ConfigureAwait(false));
Assert.Equal(expectedRowsUpdated, reader.RecordsAffected);
Assert.False(await reader.NextResultAsync().ConfigureAwait(false));
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 1)]
public async Task UpdateRowsExecuteNonQuery(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_non_query;
create table update_rows_non_query(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_non_query (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"update update_rows_non_query set value = @newValue where value = @oldValue";
var p = cmd.CreateParameter();
p.ParameterName = "@oldValue";
p.Value = oldValue;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@newValue";
p.Value = 4;
cmd.Parameters.Add(p);
var rowsAffected = await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 1)]
public void UpdateRowsDapper(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_dapper;
create table update_rows_dapper(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_dapper (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
var rowsAffected = m_database.Connection.Execute(@"update update_rows_dapper set value = @newValue where value = @oldValue",
new { oldValue, newValue = 4 });
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
[Theory]
[InlineData(true, 1, 2)]
[InlineData(true, 2, 1)]
[InlineData(true, 3, 0)]
[InlineData(true, 4, 0)]
[InlineData(false, 1, 2)]
[InlineData(false, 2, 1)]
[InlineData(false, 3, 0)]
[InlineData(false, 4, 1)]
public async Task UpdateRowsDapperAsync(bool useAffectedRows, int oldValue, int expectedRowsUpdated)
{
var csb = AppConfig.CreateConnectionStringBuilder();
csb.UseAffectedRows = useAffectedRows;
using (var connection = new MySqlConnection(csb.ConnectionString))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_dapper_async;
create table update_rows_dapper_async(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_dapper_async (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
var rowsAffected = await connection.ExecuteAsync(@"update update_rows_dapper_async set value = @newValue where value = @oldValue",
new { oldValue, newValue = 4 }).ConfigureAwait(false);
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
}
[Fact]
public async Task UpdateDapperNoColumnsWereSelected()
{
await m_database.Connection.ExecuteAsync(@"drop table if exists update_station;
create table update_station (
SID bigint unsigned,
name text,
stationType_SID bigint unsigned not null,
geoPosition_SID bigint unsigned,
service_start datetime,
service_end datetime,
deleted boolean,
created_on datetime not null,
externalWebsite text,
externalTitle text
);
insert into update_station values(1, 'name', 2, null, null, null, false, '2016-09-07 06:28:00', 'https://github.com/mysql-net/MySqlConnector/issues/44', 'Issue #44');
").ConfigureAwait(false);
var queryString = @"UPDATE update_station SET name=@name,stationType_SID=@stationType_SID,geoPosition_SID=@geoPosition_SID,service_start=@service_start,service_end=@service_end,deleted=@deleted,created_on=@created_on,externalWebsite=@externalWebsite,externalTitle=@externalTitle WHERE SID=@SID";
var station = new Station
{
SID = 1,
name = "<NAME>",
stationType_SID = 3,
geoPosition_SID = null,
service_start = new DateTime(2016, 1, 1),
service_end = new DateTime(2017, 12, 31),
deleted = true,
created_on = new DateTime(2000, 1, 1),
externalWebsite = null,
externalTitle = null,
};
try
{
await m_database.Connection.QueryAsync<Station>(queryString, station).ConfigureAwait(false);
Assert.True(false, "Should throw InvalidOperationException");
}
catch (InvalidOperationException ex)
{
Assert.Equal("No columns were selected", ex.Message);
}
}
public class Station
{
public ulong? SID { get; set; }
public string name { get; set; }
public ulong stationType_SID { get; set; }
public ulong? geoPosition_SID { get; set; }
public DateTime? service_start { get; set; }
public DateTime? service_end { get; set; }
public bool? deleted { get; set; }
public DateTime created_on { get; set; }
public string externalWebsite { get; set; }
public string externalTitle { get; set; }
}
readonly DatabaseFixture m_database;
}
}
<file_sep>---
lastmod: 2016-10-16
date: 2016-10-16
menu:
main:
parent: api
title: MySqlTransaction
weight: 50
---
MySqlTransaction
==================
MySqlTransaction implements the [ADO.NET DbTransaction class](https://docs.microsoft.com/en-us/dotnet/core/api/system.data.common.dbtransaction),
please refer to its documentation.
Additionally, MySqlTransaction provides the following public properties and methods that may be used:
### Additional Instance Methods
`public Task CommitAsync()`
`public Task CommitAsync(CancellationToken cancellationToken)`
Async version of Commit
***
`public Task RollbackAsync()`
`public Task RollbackAsync(CancellationToken cancellationToken)`
Async version of Rollback
***
`public Task Save(string savepointName)`
`public Task SaveAsync(string savepointName, CancellationToken cancellationToken = default)`
Sets a named transaction savepoint with the specified `savepointName`. If the current transaction already has
a savepoint with the same name, the old savepoint is deleted and a new one is set.
***
`public Task Release(string savepointName)`
`public Task ReleaseAsync(string savepointName, CancellationToken cancellationToken = default)`
Removes the named transaction savepoint with the specified `savepointName`. No commit or rollback occurs.
***
***
`public Task Rollback(string savepointName)`
`public Task RollbackAsync(string savepointName, CancellationToken cancellationToken = default)`
Rolls back the current transaction to the savepoint with the specified `savepointName` without aborting the transaction.
The name must have been created with `Save`, but not released by calling `Release`.
***
<file_sep>---
lastmod: 2019-10-12
date: 2017-03-27
menu:
main:
parent: getting started
title: Known Issues
weight: 20
---
Known Issues
============
* Some `MySql.Data` connection string settings are not supported by this library. See [Connection Options](connection-options/) for a list of supported options.
<file_sep>using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using MySqlConnector.Performance.Commands;
namespace MySqlConnector.Performance
{
public class Program
{
public static void Main(string[] args)
{
AppDb.Initialize();
if (args.Length == 0)
{
BuildWebHost(args).Run();
}
else
{
Environment.Exit(CommandRunner.Run(args));
}
}
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:5000")
.UseStartup<Startup>()
.Build();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using MySql.Data.MySqlClient;
namespace MySqlConnector.Diagnostics
{
internal static class MySqlClientDiagnosticListenerExtensions
{
public const string DiagnosticListenerName = "MySqlClientDiagnosticListener";
private const string MySqlClientPrefix = "MySql.Data.MySqlClient.";
public const string MySqlBeforeExecuteCommand = MySqlClientPrefix + nameof(WriteCommandBefore);
public const string MySqlAfterExecuteCommand = MySqlClientPrefix + nameof(WriteCommandAfter);
public const string MySqlErrorExecuteCommand = MySqlClientPrefix + nameof(WriteCommandError);
public const string MySqlBeforeOpenConnection = MySqlClientPrefix + nameof(WriteConnectionOpenBefore);
public const string MySqlAfterOpenConnection = MySqlClientPrefix + nameof(WriteConnectionOpenAfter);
public const string MySqlErrorOpenConnection = MySqlClientPrefix + nameof(WriteConnectionOpenError);
public const string MySqlBeforeCloseConnection = MySqlClientPrefix + nameof(WriteConnectionCloseBefore);
public const string MySqlAfterCloseConnection = MySqlClientPrefix + nameof(WriteConnectionCloseAfter);
public const string MySqlErrorCloseConnection = MySqlClientPrefix + nameof(WriteConnectionCloseError);
public const string MySqlBeforeCommitTransaction = MySqlClientPrefix + nameof(WriteTransactionCommitBefore);
public const string MySqlAfterCommitTransaction = MySqlClientPrefix + nameof(WriteTransactionCommitAfter);
public const string MySqlErrorCommitTransaction = MySqlClientPrefix + nameof(WriteTransactionCommitError);
public const string MySqlBeforeRollbackTransaction = MySqlClientPrefix + nameof(WriteTransactionRollbackBefore);
public const string MySqlAfterRollbackTransaction = MySqlClientPrefix + nameof(WriteTransactionRollbackAfter);
public const string MySqlErrorRollbackTransaction = MySqlClientPrefix + nameof(WriteTransactionRollbackError);
#region Command
public static Guid WriteCommandBefore(this DiagnosticListener @this,
IReadOnlyList<MySqlDiagnosticsCommand> sqlDiagnosticsCommands, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlBeforeExecuteCommand))
{
Guid operationId = Guid.NewGuid();
@this.Write(
MySqlBeforeExecuteCommand,
new
{
OperationId = operationId,
Operation = operation,
Commands = sqlDiagnosticsCommands,
Timestamp = Stopwatch.GetTimestamp()
});
return operationId;
}
else
return Guid.Empty;
}
public static void WriteCommandAfter(this DiagnosticListener @this, Guid operationId,
IReadOnlyList<MySqlDiagnosticsCommand> sqlDiagnosticsCommands, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlAfterExecuteCommand))
{
@this.Write(
MySqlAfterExecuteCommand,
new
{
OperationId = operationId,
Operation = operation,
Commands = sqlDiagnosticsCommands,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static void WriteCommandError(this DiagnosticListener @this, Guid operationId,
IReadOnlyList<MySqlDiagnosticsCommand> sqlDiagnosticsCommands, Exception ex, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlErrorExecuteCommand))
{
@this.Write(
MySqlErrorExecuteCommand,
new
{
OperationId = operationId,
Operation = operation,
Commands = sqlDiagnosticsCommands,
Exception = ex,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
#endregion
#region Connection
public static Guid WriteConnectionOpenBefore(this DiagnosticListener @this,
MySqlConnection sqlConnection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlBeforeOpenConnection))
{
Guid operationId = Guid.NewGuid();
@this.Write(
MySqlBeforeOpenConnection,
new
{
OperationId = operationId,
Operation = operation,
Connection = sqlConnection,
Timestamp = Stopwatch.GetTimestamp()
});
return operationId;
}
else
return Guid.Empty;
}
public static void WriteConnectionOpenAfter(this DiagnosticListener @this, Guid operationId,
MySqlConnection sqlConnection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlAfterOpenConnection))
{
@this.Write(
MySqlAfterOpenConnection,
new
{
OperationId = operationId,
Operation = operation,
Connection = sqlConnection,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static void WriteConnectionOpenError(this DiagnosticListener @this, Guid operationId,
MySqlConnection sqlConnection, Exception ex, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlErrorOpenConnection))
{
@this.Write(
MySqlErrorOpenConnection,
new
{
OperationId = operationId,
Operation = operation,
Connection = sqlConnection,
Exception = ex,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static Guid WriteConnectionCloseBefore(this DiagnosticListener @this,
MySqlConnection sqlConnection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlBeforeCloseConnection))
{
Guid operationId = Guid.NewGuid();
@this.Write(
MySqlBeforeCloseConnection,
new
{
OperationId = operationId,
Operation = operation,
Connection = sqlConnection,
Timestamp = Stopwatch.GetTimestamp()
});
return operationId;
}
else
return Guid.Empty;
}
public static void WriteConnectionCloseAfter(this DiagnosticListener @this, Guid operationId,
string clientConnectionId, MySqlConnection sqlConnection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlAfterCloseConnection))
{
@this.Write(
MySqlAfterCloseConnection,
new
{
OperationId = operationId,
Operation = operation,
ConnectionId = clientConnectionId,
Connection = sqlConnection,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static void WriteConnectionCloseError(this DiagnosticListener @this, Guid operationId,
string clientConnectionId, MySqlConnection sqlConnection, Exception ex, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlErrorCloseConnection))
{
@this.Write(
MySqlErrorCloseConnection,
new
{
OperationId = operationId,
Operation = operation,
ConnectionId = clientConnectionId,
Connection = sqlConnection,
Exception = ex,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
#endregion
#region Transaction
public static Guid WriteTransactionCommitBefore(this DiagnosticListener @this,
IsolationLevel isolationLevel, MySqlConnection connection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlBeforeCommitTransaction))
{
Guid operationId = Guid.NewGuid();
@this.Write(
MySqlBeforeCommitTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Timestamp = Stopwatch.GetTimestamp()
});
return operationId;
}
else
return Guid.Empty;
}
public static void WriteTransactionCommitAfter(this DiagnosticListener @this, Guid operationId,
IsolationLevel isolationLevel, MySqlConnection connection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlAfterCommitTransaction))
{
@this.Write(
MySqlAfterCommitTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static void WriteTransactionCommitError(this DiagnosticListener @this, Guid operationId,
IsolationLevel isolationLevel, MySqlConnection connection, Exception ex, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlErrorCommitTransaction))
{
@this.Write(
MySqlErrorCommitTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Exception = ex,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static Guid WriteTransactionRollbackBefore(this DiagnosticListener @this,
IsolationLevel isolationLevel, MySqlConnection connection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlBeforeRollbackTransaction))
{
Guid operationId = Guid.NewGuid();
@this.Write(
MySqlBeforeRollbackTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Timestamp = Stopwatch.GetTimestamp()
});
return operationId;
}
else
return Guid.Empty;
}
public static void WriteTransactionRollbackAfter(this DiagnosticListener @this, Guid operationId,
IsolationLevel isolationLevel, MySqlConnection connection, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlAfterRollbackTransaction))
{
@this.Write(
MySqlAfterRollbackTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
public static void WriteTransactionRollbackError(this DiagnosticListener @this, Guid operationId,
IsolationLevel isolationLevel, MySqlConnection connection, Exception ex, [CallerMemberName] string operation = "")
{
if (@this.IsEnabled(MySqlErrorRollbackTransaction))
{
@this.Write(
MySqlErrorRollbackTransaction,
new
{
OperationId = operationId,
Operation = operation,
IsolationLevel = isolationLevel,
Connection = connection,
Exception = ex,
Timestamp = Stopwatch.GetTimestamp()
});
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using MySqlConnector.Core;
namespace MySqlConnector.Diagnostics
{
internal static class MySqlCommandExtensions
{
internal static MySqlDiagnosticsCommand ToDiagnosticsCommand(this IMySqlCommand sqlCommand)
{
if (sqlCommand == null)
throw new ArgumentNullException(nameof(sqlCommand));
return new MySqlDiagnosticsCommand
{
CommandId = sqlCommand.CancellableCommand.CommandId,
CommandTimeout = sqlCommand.CancellableCommand.CommandTimeout,
CommandText = sqlCommand.CommandText,
CommandType = sqlCommand.CommandType,
AllowUserVariables = sqlCommand.AllowUserVariables,
CommandBehavior = sqlCommand.CommandBehavior,
RawParameters = sqlCommand.RawParameters,
Connection = sqlCommand.Connection
};
}
internal static IReadOnlyList<MySqlDiagnosticsCommand> ToDiagnosticsCommands(this IEnumerable<IMySqlCommand> sqlCommands)
{
if (sqlCommands == null || !sqlCommands.Any())
throw new ArgumentNullException(nameof(sqlCommands));
return sqlCommands.Select(c => c.ToDiagnosticsCommand()).ToArray();
}
}
}
<file_sep>---
lastmod: 2017-11-06
date: 2016-10-16
menu:
main:
parent: api
title: MySqlDataReader
weight: 40
---
MySqlDataReader
=================
MySqlDataReader implements the [ADO.NET DbDataReader class](https://docs.microsoft.com/en-us/dotnet/core/api/system.data.common.dbdatareader);
please refer to its documentation.
Additionally, MySqlDataReader provides the following public properties and methods that may be used:
### Additional Instance Methods
`public sbyte GetSByte(int ordinal)`
Gets the value of the specified column as an sbyte
***
`public DateTimeOffset GetDateTimeOffset(int ordinal)`
Gets the value of the specified column as a DateTimeOffset with an offset of 0
***
`public ReadOnlyCollection<DbColumn> GetColumnSchema()`
Implements the new [`IDbColumnSchemaGenerator.GetColumnSchema`](https://docs.microsoft.com/en-us/dotnet/api/system.data.common.idbcolumnschemagenerator.getcolumnschema) interface that returns metadata about the columns in the result set.
<file_sep>---
lastmod: 2017-11-06
date: 2016-10-16
menu:
main:
parent: api
title: MySqlCommand
weight: 20
---
MySqlCommand
==============
`MySqlCommand` implements the [ADO.NET DbCommand class](https://docs.microsoft.com/en-us/dotnet/core/api/system.data.common.dbcommand);
please refer to its documentation.
Additionally, `MySqlCommand` provides the following public properties and methods that may be used:
### Constructors
`public MySqlCommand()`
Parameterless constructor
***
`public MySqlCommand(string commandText)`
constructor accepting command SQL
***
`public MySqlCommand(MySqlConnection connection, MySqlTransaction transaction)`
constructor accepting connection object and transaction object
***
`public MySqlCommand(string commandText, MySqlConnection connection)`
constructor accepting command SQL and connection object
***
`public MySqlCommand(string commandText, MySqlConnection connection, MySqlTransaction transaction)`
constructor accepting command SQL, connection object, and transaction object
***
### Additional Properties
`public long LastInsertedId`
Holds the first automatically-generated ID for a value inserted in an `AUTO_INCREMENT` column in the last statement.
See [`LAST_INSERT_ID()`](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id) for more information.
***
<file_sep>using System;
using System.Data.Common;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.CsProj;
using BenchmarkDotNet.Validators;
using MySql.Data.MySqlClient;
namespace Benchmark
{
class Program
{
static void Main()
{
var customConfig = ManualConfig
.Create(DefaultConfig.Instance)
.With(JitOptimizationsValidator.FailOnError)
.With(MemoryDiagnoser.Default)
.With(StatisticColumn.AllStatistics)
.With(Job.Default.With(Runtime.Clr).With(Jit.RyuJit).With(Platform.X64).With(CsProjClassicNetToolchain.Net472).WithNuGet("MySqlConnector", "0.56.0").WithId("net472 0.56.0"))
.With(Job.Default.With(Runtime.Clr).With(Jit.RyuJit).With(Platform.X64).With(CsProjClassicNetToolchain.Net472).WithNuGet("MySqlConnector", "0.57.0-beta2").WithId("net472 0.57.0"))
.With(Job.Default.With(Runtime.Core).With(CsProjCoreToolchain.NetCoreApp21).WithNuGet("MySqlConnector", "0.56.0").WithId("netcore21 0.56.0"))
.With(Job.Default.With(Runtime.Core).With(CsProjCoreToolchain.NetCoreApp21).WithNuGet("MySqlConnector", "0.57.0-beta2").WithId("netcore21 0.57.0"))
.With(DefaultExporters.Csv);
var summary = BenchmarkRunner.Run<MySqlClient>(customConfig);
Console.WriteLine(summary);
}
}
public class MySqlClient
{
[GlobalSetup]
public void GlobalSetup()
{
using (var connection = new MySqlConnection(s_connectionString))
{
connection.Open();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"
create schema if not exists benchmark;
drop table if exists benchmark.integers;
create table benchmark.integers (value int not null primary key);
insert into benchmark.integers(value) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
drop table if exists benchmark.blobs;
create table benchmark.blobs(
rowid integer not null primary key auto_increment,
`Blob` longblob null
);
insert into benchmark.blobs(`Blob`) values(null), (@Blob1), (@Blob2);";
// larger blobs make the tests run much slower
AddBlobParameter(cmd, "@Blob1", 75000);
AddBlobParameter(cmd, "@Blob2", 150000);
cmd.ExecuteNonQuery();
}
}
s_connectionString += ";database=benchmark";
m_connection = new MySqlConnection(s_connectionString);
m_connection.Open();
}
[GlobalCleanup]
public void GlobalCleanup()
{
m_connection.Dispose();
m_connection = null;
MySqlConnection.ClearAllPools();
}
private static void AddBlobParameter(DbCommand command, string name, int size)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
var random = new Random(size);
var value = new byte[size];
random.NextBytes(value);
parameter.Value = value;
command.Parameters.Add(parameter);
}
[Benchmark]
public async Task OpenFromPoolAsync()
{
m_connection.Close();
await m_connection.OpenAsync();
}
[Benchmark]
public void OpenFromPoolSync()
{
m_connection.Close();
m_connection.Open();
}
[Benchmark]
public async Task ExecuteScalarAsync()
{
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = c_executeScalarSql;
await cmd.ExecuteScalarAsync();
}
}
[Benchmark]
public void ExecuteScalarSync()
{
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = c_executeScalarSql;
cmd.ExecuteScalar();
}
}
private const string c_executeScalarSql = "select max(value) from integers;";
[Benchmark] public Task ReadBlobsAsync() => ReadAllRowsAsync(c_readBlobsSql);
[Benchmark] public void ReadBlobsSync() => ReadAllRowsSync(c_readBlobsSql);
private const string c_readBlobsSql = "select `Blob` from blobs;";
[Benchmark] public Task ManyRowsAsync() => ReadAllRowsAsync(c_manyRowsSql);
[Benchmark] public void ManyRowsSync() => ReadAllRowsSync(c_manyRowsSql);
private const string c_manyRowsSql = "select * from integers a join integers b join integers c;";
private async Task<int> ReadAllRowsAsync(string sql)
{
int total = 0;
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql;
using (var reader = await cmd.ExecuteReaderAsync())
{
do
{
while (await reader.ReadAsync())
{
if (reader.FieldCount > 1)
total += reader.GetInt32(1);
}
} while (await reader.NextResultAsync());
}
}
return total;
}
private int ReadAllRowsSync(string sql)
{
int total = 0;
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql;
using (var reader = cmd.ExecuteReader())
{
do
{
while (reader.Read())
{
if (reader.FieldCount > 1)
total += reader.GetInt32(1);
}
} while (reader.NextResult());
}
}
return total;
}
// TODO: move to config file
static string s_connectionString = "server=127.0.0.1;user id=mysqltest;password=<PASSWORD>;port=3306;ssl mode=none;Use Affected Rows=true;Connection Reset=false;Default Command Timeout=0;AutoEnlist=false;";
MySqlConnection m_connection;
}
}
<file_sep>---
lastmod: 2018-09-29
date: 2018-09-29
title: Connection Reuse
weight: 10
menu:
main:
parent: troubleshooting
---
# Connection Reuse
A `MySqlConnection` object may only be used for one operation at a time. It may not be shared
across multiple threads and used simultaneously, nor reused on the same thread while there is
an open `MySqlDataReader`.
## Examples of Prohibited Use
### Multiple Threads
You may not execute multiple operations in parallel, for example:
```csharp
using (var connection = new MySqlConnection("..."))
{
await connection.OpenAsync();
await Task.WhenAll( // don't do this
connection.ExecuteAsync("SELECT 1;"),
connection.ExecuteAsync("SELECT 2;"),
connection.ExecuteAsync("SELECT 3;"));
}
```
### Nested Access on Single Thread
You may not reuse the connection when there is an open `MySqlDataReader:`
```csharp
using (var connection = CreateOpenConnection())
using (var command = new MySqlCommand("SELECT id FROM ...", connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var idToUpdate = reader.GetValue(0);
connection.Execute("UPDATE ... SET ..."); // don't do this
}
}
```
## How to Fix
For the multithreaded scenario, if concurrent access to the database is truly necessary,
create and open a new `MySqlConnection` on each thread. But in most cases, you should
just write code that sequentially `await`s each asychronous operation (without performing
them in parallel).
For the nested access, read all the values from the `MySqlDataReader` into memory, close
the reader, then process the values. (If the data set is large, you may need to use a batching
approach where you read a limited number of rows in each batch.)<file_sep>## How to Use
To integrate MySqlConnector with Microsoft.Extensions.Logging, add the following line of code to your `Startup.Configure` method (before any `MySqlConnector` objects have been used):
```
MySqlConnectorLogManager.Provider = new MicrosoftExtensionsLoggingLoggerProvider(loggerFactory);
```
<file_sep>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MySqlConnector.Performance.Models;
namespace MySqlConnector.Performance.Commands
{
public static class ConcurrencyCommand
{
public static void Run(int iterations, int concurrency, int ops)
{
var recordNum = 0;
async Task InsertOne(AppDb db)
{
var blog = new BlogPost(db)
{
Title = "Title " + Interlocked.Increment(ref recordNum),
Content = "content"
};
await blog.InsertAsync();
}
var selected = new ConcurrentQueue<string>();
async Task SelectTen(AppDb db)
{
var blogPosts = await (new BlogPostQuery(db)).LatestPostsAsync();
selected.Enqueue(blogPosts.FirstOrDefault().Title);
}
var sleepNum = 0;
async Task SleepMillisecond(AppDb db)
{
using (var cmd = db.Connection.CreateCommand())
{
cmd.CommandText = "SELECT SLEEP(0.001)";
await cmd.ExecuteNonQueryAsync();
}
Interlocked.Increment(ref sleepNum);
}
using (var db = new AppDb())
{
db.Connection.Open();
using (var cmd = db.Connection.CreateCommand())
{
cmd.CommandText = "DELETE FROM `BlogPost`";
cmd.ExecuteNonQuery();
}
}
PerfTest(InsertOne, "Insert One", iterations, concurrency, ops).GetAwaiter().GetResult();
using (var db = new AppDb())
{
db.Connection.Open();
using (var cmd = db.Connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(*) FROM `BlogPost`";
Console.WriteLine("Records Inserted: " + cmd.ExecuteScalar());
Console.WriteLine();
}
}
PerfTest(SelectTen, "Select Ten", iterations, concurrency, ops).GetAwaiter().GetResult();
Console.WriteLine("Records Selected: " + selected.Count * 10);
string firstRecord;
if (selected.TryDequeue(out firstRecord))
Console.WriteLine("First Record: " + firstRecord);
Console.WriteLine();
PerfTest(SleepMillisecond, "Sleep 1ms", iterations, concurrency, ops).GetAwaiter().GetResult();
Console.WriteLine("Total Sleep Commands: " + sleepNum);
Console.WriteLine();
}
public static async Task PerfTest(Func<AppDb, Task> test, string testName, int iterations, int concurrency, int ops)
{
var timers = new List<TimeSpan>();
for (var iteration = 0; iteration < iterations; iteration++)
{
var tasks = new List<Task>();
var start = DateTime.UtcNow;
for (var connection = 0; connection < concurrency; connection++)
{
tasks.Add(ConnectionTask(test, ops));
}
await Task.WhenAll(tasks);
timers.Add(DateTime.UtcNow - start);
}
Console.WriteLine("Test " + testName);
Console.WriteLine("Iterations: " + iterations);
Console.WriteLine("Concurrency: " + concurrency);
Console.WriteLine("Operations: " + ops);
Console.WriteLine("Times (Min, Average, Max) "
+ timers.Min() + ", "
+ TimeSpan.FromTicks(timers.Sum(timer => timer.Ticks) / timers.Count) + ", "
+ timers.Max());
Console.WriteLine();
}
private static async Task ConnectionTask(Func<AppDb, Task> cb, int ops)
{
using (var db = new AppDb())
{
await db.Connection.OpenAsync();
for (var op = 0; op < ops; op++)
{
await cb(db);
}
}
}
}
}
<file_sep>namespace MySql.Data.MySqlClient
{
public sealed class MySqlError
{
internal MySqlError(string level, int code, string message)
{
Level = level;
Code = code;
Message = message;
}
public string Level { get; }
public int Code { get; }
public string Message { get; }
};
}
<file_sep>---
date: 2019-06-23
menu:
main:
parent: api
title: MySqlBatch
weight: 10
---
# MySqlBatch
`MySqlBatch` implements the new [ADO.NET batching API](https://github.com/dotnet/corefx/issues/35135).
**It is currently experimental** and may change in the future.
When using MariaDB (10.2 or later), the commands will be sent in a single batch, reducing network
round-trip time. With other MySQL Servers, this may be no more efficient than executing the commands
individually.
## Example Code
```csharp
using (var connection = new MySqlConnection("...connection string..."))
{
await connection.OpenAsync();
using (var batch = new MySqlBatch(connection)
{
BatchCommands =
{
new MySqlBatchCommand("INSERT INTO departments(name) VALUES(@name);")
{
Parameters =
{
new MySqlParameter("@name", "Sales"),
},
},
new MySqlBatchCommand("SET @dept_id = last_insert_id()"),
new MySqlBatchCommand("INSERT INTO employees(name, department_id) VALUES(@name, @dept_id);")
{
Parameters =
{
new MySqlParameter("@name", "<NAME>"),
},
},
new MySqlBatchCommand("INSERT INTO employees(name, department_id) VALUES(@name, @dept_id);")
{
Parameters =
{
new MySqlParameter("@name", "<NAME>"),
},
},
},
})
{
await batch.ExecuteNonQueryAsync();
}
}
```
## API Reference
### Constructors
`public MySqlBatch()`
Parameterless constructor.
***
`public MySqlBatch(MySqlConnection connection)`
Constructor that accepts a `MySqlConnection` and sets the `Connection` property.
### Properties
`public MySqlBatchCommandCollection BatchCommands { get; }`
The collection of commands that will be executed in the batch.
### Methods
`public void ExecuteNonQuery();`
`public Task ExecuteNonQueryAsync();`
Executes all the commands in the batch, returning nothing.
***
`public object ExecuteScalar();`
`public Task<object> ExecuteScalarAsync();`
Executes all the commands in the batch, returning the value from the first column in the first row of the first resultset.
***
`public MySqlDataReader ExecuteReader();`
`public Task<DbDataReader> ExecuteReaderAsync();`
Executes all the commands in the batch, return a `DbDataReader` that can iterate over the result sets. If multiple
resultsets are returned, use `DbDataReader.NextResult` (or `NextResultAsync`) to access them.
<file_sep>using MySqlConnector.Utilities;
namespace MySqlConnector.Protocol.Payloads
{
internal static class EmptyPayload
{
public static PayloadData Instance { get; } = new PayloadData(Utility.EmptyByteArray);
}
}
<file_sep>using System.Collections.Generic;
using System.Collections.ObjectModel;
using MySqlConnector.Core;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlBatchCommandCollection : Collection<MySqlBatchCommand>, IReadOnlyList<IMySqlCommand>
{
public new MySqlBatchCommand this[int index]
{
get => base[index];
set => base[index] = value;
}
IMySqlCommand IReadOnlyList<IMySqlCommand>.this[int index] => this[index];
IEnumerator<IMySqlCommand> IEnumerable<IMySqlCommand>.GetEnumerator()
{
foreach (var command in this)
yield return command;
}
}
}
<file_sep>namespace MySql.Data.MySqlClient
{
public enum MySqlBulkLoaderPriority
{
None,
Low,
Concurrent
}
}
<file_sep>INSTALL SONAME 'auth_ed25519';
CREATE USER 'ed25519user'@'%' IDENTIFIED VIA ed25519 USING PASSWORD('<PASSWORD>');
GRANT ALL PRIVILEGES ON *.* TO 'ed25519user'@'%';<file_sep>namespace MySqlConnector.Core
{
internal enum ResultSetState
{
None,
ReadResultSetHeader,
ReadingRows,
HasMoreData,
NoMoreData,
}
}
<file_sep>using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using MySql.Data.MySqlClient;
using Xunit;
namespace MySqlConnector.Tests
{
public class MySqlExceptionTests
{
[Fact]
public void IsSerializable()
{
var exception = new MySqlException(1, "two", "three");
MySqlException copy;
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, exception);
stream.Position = 0;
copy = (MySqlException) formatter.Deserialize(stream);
}
Assert.Equal(exception.Number, copy.Number);
Assert.Equal(exception.SqlState, copy.SqlState);
Assert.Equal(exception.Message, copy.Message);
}
[Fact]
public void Data()
{
var exception = new MySqlException(1, "two", "three");
Assert.Equal(1, exception.Data["Server Error Code"]);
Assert.Equal("two", exception.Data["SqlState"]);
}
}
}
<file_sep>using System.Data.Common;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlClientFactory : DbProviderFactory
{
public static readonly MySqlClientFactory Instance = new MySqlClientFactory();
public override DbCommand CreateCommand() => new MySqlCommand();
public override DbConnection CreateConnection() => new MySqlConnection();
public override DbConnectionStringBuilder CreateConnectionStringBuilder() => new MySqlConnectionStringBuilder();
public override DbParameter CreateParameter() => new MySqlParameter();
#if !NETSTANDARD1_3
public override DbCommandBuilder CreateCommandBuilder() => new MySqlCommandBuilder();
public override DbDataAdapter CreateDataAdapter() => new MySqlDataAdapter();
#endif
public MySqlBatch CreateBatch() => new MySqlBatch();
public MySqlBatchCommand CreateBatchCommand() => new MySqlBatchCommand();
public bool CanCreateBatch => true;
private MySqlClientFactory()
{
}
}
}
<file_sep>using System;
namespace MySql.Data.Types
{
public struct MySqlDateTime : IComparable, IConvertible
{
public MySqlDateTime(int year, int month, int day, int hour, int minute, int second, int microsecond)
{
Year = year;
Month = month;
Day = day;
Hour = hour;
Minute = minute;
Second = second;
Microsecond = microsecond;
}
public MySqlDateTime(DateTime dt)
: this(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, (int) (dt.Ticks % 10_000_000) / 10)
{
}
public MySqlDateTime(MySqlDateTime other)
{
Year = other.Year;
Month = other.Month;
Day = other.Day;
Hour = other.Hour;
Minute = other.Minute;
Second = other.Second;
Microsecond = other.Microsecond;
}
public readonly bool IsValidDateTime => Year != 0 && Month != 0 && Day != 0;
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public int Second { get; set; }
public int Microsecond { get; set; }
public int Millisecond
{
readonly get => Microsecond / 1000;
set => Microsecond = value * 1000;
}
public readonly DateTime GetDateTime() =>
!IsValidDateTime ? throw new MySqlConversionException("Cannot convert MySqlDateTime to DateTime when IsValidDateTime is false.") :
new DateTime(Year, Month, Day, Hour, Minute, Second, DateTimeKind.Unspecified).AddTicks(Microsecond * 10);
public readonly override string ToString() => IsValidDateTime ? GetDateTime().ToString() : "0000-00-00";
public static explicit operator DateTime(MySqlDateTime val) => !val.IsValidDateTime ? DateTime.MinValue : val.GetDateTime();
readonly int IComparable.CompareTo(object? obj)
{
if (!(obj is MySqlDateTime other))
throw new ArgumentException("CompareTo can only be called with another MySqlDateTime", nameof(obj));
if (Year < other.Year)
return -1;
if (Year > other.Year)
return 1;
if (Month < other.Month)
return -1;
if (Month > other.Month)
return 1;
if (Day < other.Day)
return -1;
if (Day > other.Day)
return 1;
if (Hour < other.Hour)
return -1;
if (Hour > other.Hour)
return 1;
if (Minute < other.Minute)
return -1;
if (Minute > other.Minute)
return 1;
if (Second < other.Second)
return -1;
if (Second > other.Second)
return 1;
return Microsecond.CompareTo(other.Microsecond);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider) => IsValidDateTime ? GetDateTime() : throw new InvalidCastException();
string IConvertible.ToString(IFormatProvider? provider) => IsValidDateTime ? GetDateTime().ToString(provider) : "0000-00-00";
object IConvertible.ToType(Type conversionType, IFormatProvider? provider) =>
conversionType == typeof(DateTime) ? (object) GetDateTime() :
conversionType == typeof(string) ? ((IConvertible) this).ToString(provider) :
throw new InvalidCastException();
TypeCode IConvertible.GetTypeCode() => TypeCode.Object;
bool IConvertible.ToBoolean(IFormatProvider? provider) => throw new InvalidCastException();
char IConvertible.ToChar(IFormatProvider? provider) => throw new InvalidCastException();
sbyte IConvertible.ToSByte(IFormatProvider? provider) => throw new InvalidCastException();
byte IConvertible.ToByte(IFormatProvider? provider) => throw new InvalidCastException();
short IConvertible.ToInt16(IFormatProvider? provider) => throw new InvalidCastException();
ushort IConvertible.ToUInt16(IFormatProvider? provider) => throw new InvalidCastException();
int IConvertible.ToInt32(IFormatProvider? provider) => throw new InvalidCastException();
uint IConvertible.ToUInt32(IFormatProvider? provider) => throw new InvalidCastException();
long IConvertible.ToInt64(IFormatProvider? provider) => throw new InvalidCastException();
ulong IConvertible.ToUInt64(IFormatProvider? provider) => throw new InvalidCastException();
float IConvertible.ToSingle(IFormatProvider? provider) => throw new InvalidCastException();
double IConvertible.ToDouble(IFormatProvider? provider) => throw new InvalidCastException();
decimal IConvertible.ToDecimal(IFormatProvider? provider) => throw new InvalidCastException();
}
}
<file_sep>using System;
namespace MySqlConnector.Performance.Commands
{
public static class CommandRunner
{
public static void Help()
{
Console.Error.WriteLine(@"dotnet run
concurrency [iterations] [concurrency] [operations]
-h, --help show this message
");
}
public static int Run(string[] args)
{
var cmd = args[0];
try
{
switch (cmd)
{
case "concurrency":
if (args.Length != 4)
goto default;
ConcurrencyCommand.Run(int.Parse(args[1]), int.Parse(args[2]), int.Parse(args[3]));
break;
case "-h":
case "--help":
Help();
break;
default:
Help();
return 1;
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
return 1;
}
return 0;
}
}
}
<file_sep>using System;
using System.Globalization;
using MySql.Data.Types;
using Xunit;
namespace MySqlConnector.Tests
{
public class MySqlDateTimeTests
{
[Fact]
public void NewMySqlDateTimeIsNotValidDateTime()
{
var msdt = new MySqlDateTime();
Assert.False(msdt.IsValidDateTime);
}
[Fact]
public void ZeroMySqlDateTimeIsNotValidDateTime()
{
var msdt = new MySqlDateTime(0, 0, 0, 0, 0, 0, 0);
Assert.False(msdt.IsValidDateTime);
}
[Fact]
public void NonZeroMySqlDateTimeIsValidDateTime()
{
var msdt = new MySqlDateTime(2018, 6, 9, 0, 0, 0, 0);
Assert.True(msdt.IsValidDateTime);
}
[Fact]
public void CreateFromDateTime()
{
var msdt = new MySqlDateTime(s_dateTime);
Assert.True(msdt.IsValidDateTime);
Assert.Equal(2018, msdt.Year);
Assert.Equal(6, msdt.Month);
Assert.Equal(9, msdt.Day);
Assert.Equal(12, msdt.Hour);
Assert.Equal(34, msdt.Minute);
Assert.Equal(56, msdt.Second);
Assert.Equal(123, msdt.Millisecond);
Assert.Equal(123456, msdt.Microsecond);
}
[Fact]
public void GetDateTime()
{
var msdt = s_mySqlDateTime;
Assert.True(msdt.IsValidDateTime);
var dt = msdt.GetDateTime();
Assert.Equal(s_dateTime, dt);
}
[Fact]
public void GetDateTimeForInvalidDate()
{
var msdt = new MySqlDateTime();
Assert.False(msdt.IsValidDateTime);
Assert.Throws<MySqlConversionException>(() => msdt.GetDateTime());
}
[Fact]
public void SetMicrosecond()
{
var msdt = new MySqlDateTime();
Assert.Equal(0, msdt.Microsecond);
msdt.Microsecond = 123456;
Assert.Equal(123, msdt.Millisecond);
}
[Fact]
public void ConvertibleToDateTime()
{
IConvertible convertible = s_mySqlDateTime;
var dt = convertible.ToDateTime(CultureInfo.InvariantCulture);
Assert.Equal(s_dateTime, dt);
}
[Fact]
public void ConvertToDateTime()
{
object obj = s_mySqlDateTime;
var dt = Convert.ToDateTime(obj);
Assert.Equal(s_dateTime, dt);
}
[Fact]
public void ChangeTypeToDateTime()
{
object obj = s_mySqlDateTime;
var dt = Convert.ChangeType(obj, TypeCode.DateTime);
Assert.Equal(s_dateTime, dt);
}
[Fact]
public void NotConvertibleToDateTime()
{
IConvertible convertible = new MySqlDateTime();
#if !BASELINE
Assert.Throws<InvalidCastException>(() => convertible.ToDateTime(CultureInfo.InvariantCulture));
#else
Assert.Throws<MySqlConversionException>(() => convertible.ToDateTime(CultureInfo.InvariantCulture));
#endif
}
[Fact]
public void NotConvertToDateTime()
{
object obj = new MySqlDateTime();
#if !BASELINE
Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(obj));
#else
Assert.Throws<MySqlConversionException>(() => Convert.ToDateTime(obj));
#endif
}
[Fact]
public void NotChangeTypeToDateTime()
{
object obj = new MySqlDateTime();
#if !BASELINE
Assert.Throws<InvalidCastException>(() => Convert.ChangeType(obj, TypeCode.DateTime));
#else
Assert.Throws<MySqlConversionException>(() => Convert.ChangeType(obj, TypeCode.DateTime));
#endif
}
#if !BASELINE
[Fact]
public void ValidDateTimeConvertibleToString()
{
IConvertible convertible = s_mySqlDateTime;
Assert.Equal("06/09/2018 12:34:56", convertible.ToString(CultureInfo.InvariantCulture));
}
[Fact]
public void InvalidDateTimeConvertibleToString()
{
IConvertible convertible = new MySqlDateTime();
Assert.Equal("0000-00-00", convertible.ToString(CultureInfo.InvariantCulture));
}
#endif
static readonly MySqlDateTime s_mySqlDateTime = new MySqlDateTime(2018, 6, 9, 12, 34, 56, 123456);
static readonly DateTime s_dateTime = new DateTime(2018, 6, 9, 12, 34, 56, 123).AddTicks(4560);
}
}
<file_sep>using System.Text;
namespace MySqlConnector.Protocol.Payloads
{
internal static class QueryPayload
{
public static PayloadData Create(string query)
{
var length = Encoding.UTF8.GetByteCount(query);
var payload = new byte[length + 1];
payload[0] = (byte) CommandKind.Query;
Encoding.UTF8.GetBytes(query, 0, query.Length, payload, 1);
return new PayloadData(payload);
}
}
}
<file_sep>---
lastmod: 2020-05-02
date: 2019-11-11
menu:
main:
parent: api
title: MySqlBulkCopy
weight: 15
---
# MySqlBulkCopy
`MySqlBulkCopy` lets you efficiently load a MySQL Server Table with data from another source.
It is similar to the [`SqlBulkCopy`](https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlbulkcopy) class
for SQL Server.
Due to [security features](../troubleshooting/load-data-local-infile/) in MySQL Server, the connection string
**must** have `AllowLoadLocalInfile=true` in order to use this class.
For data that is in CSV or TSV format, use [`MySqlBulkLoader`](api/mysql-bulk-loader/) to bulk load the file.
**Note:** This API is a unique feature of MySqlConnector; you must [switch to MySqlConnector](../../overview/installing/)
in order to use it. It is supported in version 0.62.0 and later.
## Example Code
```csharp
// NOTE: to copy data between tables in the same database, use INSERT ... SELECT
// https://dev.mysql.com/doc/refman/8.0/en/insert-select.html
var dataTable = GetDataTableFromExternalSource();
using (var connection = new MySqlConnection("...;AllowLoadLocalInfile=True"))
{
await connection.OpenAsync();
var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "some_table_name";
await bulkCopy.WriteToServerAsync(dataTable);
}
```
## API Reference
### Constructors
`public MySqlBulkCopy(MySqlConnection connection, MySqlTransaction transaction = null)`
Initializes a `MySqlBulkCopy` with the specified connection, and optionally the active transaction.
### Properties
`public int BulkCopyTimeout { get; set; }`
The number of seconds for the operation to complete before it times out, or `0` for no timeout.
`public string DestinationTableName { get; set; }`
Name of the destination table on the server. (This name shouldn't be quoted or escaped.)
`public int NotifyAfter { get; set; }`
If non-zero, this defines the number of rows to be processed before generating a notification event.
`public List<MySqlBulkCopyColumnMapping> ColumnMappings { get; }`
A collection of `MySqlBulkCopyColumnMapping` objects. If the columns being copied from the
data source line up one-to-one with the columns in the destination table then populating this collection is
unnecessary. Otherwise, this should be filled with a collection of `MySqlBulkCopyColumnMapping` objects
specifying how source columns are to be mapped onto destination columns. If one column mapping is specified,
then all must be specified.
### Methods
`public void WriteToServer(DataTable dataTable);`
`public Task WriteToServerAsync(DataTable dataTable, CancellationToken cancellationToken = default);`
Copies all rows in the supplied `DataTable` to the destination table specified by the `DestinationTableName` property of the `MySqlBulkCopy` object.
(This method is not available on `netstandard1.3`.)
***
`public void WriteToServer(IEnumerable<DataRow> dataRows, int columnCount)`
`public async Task WriteToServerAsync(IEnumerable<DataRow> dataRows, int columnCount, CancellationToken cancellationToken = default)`
Copies all rows in the supplied sequence of `DataRow` objects to the destination table specified by the `DestinationTableName` property of the `MySqlBulkCopy` object. The number of columns to be read from the `DataRow` objects must be specified in advance.
(This method is not available on `netstandard1.3`.)
***
`public void WriteToServer(IDataReader dataReader);`
`public Task WriteToServerAsync(IDataReader dataReader, CancellationToken cancellationToken = default);`
Copies all rows in the supplied `IDataReader` to the destination table specified by the `DestinationTableName` property of the `MySqlBulkCopy` object.
### Events
`public event MySqlRowsCopiedEventHandler RowsCopied;`
If `NotifyAfter` is non-zero, this event will be raised every time the number of rows specified by
`NotifyAfter` have been processed, and once after all rows have been copied (but duplicate events
will not be raised).
Receipt of a `RowsCopied` event does not imply that any rows have been sent to the server or committed.
The `MySqlRowsCopiedEventArgs.Abort` property can be set to `true` by the event handler to abort
the copy.
## MySqlBulkCopyColumnMapping
Use `MySqlBulkCopyColumnMapping` to specify how to map columns in the source data to
columns in the destination table.
Set `SourceOrdinal` to the index of the source column to map. Set `DestinationColumn` to
either the name of a column in the destination table, or the name of a user-defined variable.
If a user-defined variable, you can use `Expression` to specify a MySQL expression that sets
a destination column.
Source columns that don't have an entry in `MySqlBulkCopy.ColumnMappings` will be ignored
(unless the `ColumnMappings` collection is empty, in which case all columns will be mapped
one-to-one).
Columns containing binary data must be mapped using an expression that uses the `UNHEX` function.
### Examples
```csharp
new MySqlBulkCopyColumnMapping
{
SourceOrdinal = 2,
DestinationColumn = "user_name",
},
new MySqlBulkCopyColumnMapping
{
SourceOrdinal = 0,
DestinationColumn = "@tmp",
Expression = "SET column_value = @tmp * 2",
},
new MySqlBulkCopyColumnMapping
{
SourceOrdinal = 1,
DestinationColumn = "@tmp2",
Expression = "SET binary_column = UNHEX(@tmp2)",
},
```
<file_sep>using System;
namespace MySqlConnector.Logging
{
/// <summary>
/// Controls logging for MySqlConnector.
/// </summary>
public static class MySqlConnectorLogManager
{
/// <summary>
/// Allows the <see cref="IMySqlConnectorLoggerProvider"/> to be set for this library. <see cref="Provider"/> can
/// be set once, and must be set before any other library methods are used.
/// </summary>
public static IMySqlConnectorLoggerProvider Provider
{
internal get
{
s_providerRetrieved = true;
return s_provider;
}
set
{
if (s_providerRetrieved)
throw new InvalidOperationException("The logging provider must be set before any MySqlConnector methods are called.");
s_provider = value;
}
}
internal static IMySqlConnectorLogger CreateLogger(string name) => Provider.CreateLogger(name);
static IMySqlConnectorLoggerProvider s_provider = new NoOpLoggerProvider();
static bool s_providerRetrieved;
}
}
<file_sep>---
date: 2020-04-04
menu:
main:
parent: api
title: MySqlBulkLoader
weight: 18
---
# MySqlBulkLoader
`MySqlBulkLoader` lets you efficiently load a MySQL Server Table with data from a CSV or TSV file or `Stream`.
Due to [security features](../troubleshooting/load-data-local-infile/) in MySQL Server, the connection string
**must** have `AllowLoadLocalInfile=true` in order to use a local source.
## Example Code
```csharp
using (var connection = new MySqlConnection("...;AllowLoadLocalInfile=True"))
{
await connection.OpenAsync();
var bulkLoader = new MySqlBulkLoader(connection)
{
FileName = @"C:\Path\To\file.csv",
TableName = "destination",
CharacterSet = "UTF8",
NumberOfLinesToSkip = 1,
FieldTerminator = ",",
FieldQuotationCharacter = '"',
FieldQuotationOptional = true,
Local = true,
}
var rowCount = await bulkLoader.LoadAsync();
}
```
## API Reference
### Constructors
`public MySqlBulkLoader(MySqlConnection connection)`
Initializes a `MySqlBulkLoader` with the specified connection.
### Properties
`public string? CharacterSet { get; set; }`
(Optional) The character set of the source data. By default, the database's character set is used.
`public List<string> Columns { get; }`
(Optional) A list of the column names in the destination table that should be filled with data from the input file.
`public MySqlBulkLoaderConflictOption ConflictOption { get; set; }`
A `MySqlBulkLoaderConflictOption` value that specifies how conflicts are resolved (default `None`).
`public MySqlConnection Connection { get; set; }`
The `MySqlConnection` to use.
`public char EscapeCharacter { get; set; }`
(Optional) The character used to escape instances of `FieldQuotationCharacter` within field values.
`public List<string> Expressions { get; }`
(Optional) A list of expressions used to set field values from the columns in the source data.
`public char FieldQuotationCharacter { get; set; }`
(Optional) The character used to enclose fields in the source data.
`public bool FieldQuotationOptional { get; set; }`
Whether quoting fields is optional (default `false`).
`public string? FieldTerminator { get; set; }`
(Optional) The string fields are terminated with.
`public string? FileName { get; set; }`
The name of the local (if `Local` is `true`) or remote (otherwise) file to load. Either this or `SourceStream` must be set.
`public string? LinePrefix { get; set; }`
(Optional) A prefix in each line that should be skipped when loading.
`public string? LineTerminator { get; set; }`
(Optional) The string lines are terminated with.
`public bool Local { get; set; }`
Whether a local file is being used (default `true`).
`public int NumberOfLinesToSkip { get; set; }`
The number of lines to skip at the beginning of the file (default `0`).
`public MySqlBulkLoaderPriority Priority { get; set; }`
A `MySqlBulkLoaderPriority` giving the priority to load with (default `None`).
`public Stream? SourceStream { get; set; }`
A `Stream` containing the data to load. Either this or `FileName` must be set. The `Local` property must be `true` if this is set.
`public string? TableName { get; set; }`
The name of the table to load into. If this is a reserved word or contains spaces, it must be quoted.
`public int Timeout { get; set; }`
The timeout (in milliseconds) to use.
### Methods
`public int Load();`
`public Task<int> LoadAsync();`
`public Task<int> LoadAsync(CancellationToken cancellationToken);`
Loads all data in the source file or `Stream` into the destination table. Returns the number of rows inserted.
| 2219c2dc9bc6baee862826d397ff747300d5cccd | [
"SQL",
"Markdown",
"TOML",
"C#",
"Shell"
] | 68 | C# | HEF-Sharp/MySqlConnector | 74351bfb453917af2e49f0c88570ce30c1e398f8 | 529550f9a9bf2e420107bb9e85813f4322fc710a |
refs/heads/master | <file_sep>import java.io.PrintStream;
import java.util.*;
public class SortedLinkedListMultiset<T> extends Multiset<T>
{
// Parameters of SortedLinkedListMultiset (Sorted Doubly Linked List), same as non-sorted
protected Node nHead;
protected Node nTail;
protected int nCount;
// Node class, nodes present in the linked list, same as non-sorted
private class Node {
private T nValue;
private Node nPrev;
private Node nNext;
private int count;
// Node constructor
public Node(T value) {
nValue = value;
nPrev = null;
nNext = null;
count = 1;
}
// Node Getters and Setters
public T getValue() { return nValue; }
public Node getPrev() { return nPrev; }
public Node getNext() { return nNext; }
public int getCount() { return count; }
public void setValue(T value) { nValue = value; }
public void setPrev(Node prev) { nPrev = prev; }
public void setNext(Node next) { nNext = next; }
public void addCount() { count++; }
public void reduceCount() { count--; }
}
public SortedLinkedListMultiset() {
// Initialize same parameters as empty doubly linked list
nHead = null;
nTail = null;
nCount = 0;
} // end of SortedLinkedListMultiset()
// Extra function added: Retrieve node through index
public Node getNode(int index) {
// Throw an exception if index requested is too high or too low
if (index >= nCount || index < 0) {
throw new IndexOutOfBoundsException("Supplied index is invalid.");
}
// Request first node (return head node)
if (index == 0)
return nHead;
// Request last node (return tail node)
else if (index == nCount-1)
return nTail;
// Request any other node in between, iterate until node reached
Node currNode = nHead.getNext();
for(int i = 1; i < index; ++i)
currNode = currNode.getNext();
// Node should be reached once loop above has ended, return reached node
return currNode;
}
public void sortList(){
/* NOTE: Sorted using selection sort method following pseudocode in lecture notes
* A strange thing i found, was that the lecture notes had:
* i loop has: i = 0; i to n - 2
* j loop has: j = i + 1; to n - 1
* However implementing this did not work, so i found simply going through the
* entirety of both loops fixed the problem as the first element would be skipped */
int min = 0;
int comparison = 0;
// Nodes to store and swap values
Node temp = null;
Node n1 = null;
Node n2 = null;
// String values to compare if one is less than the other
String value1 = "";
String value2 = "";
for (int i = 0; i < nCount; i++) {
min = i;
for (int j = i; j < nCount; j++) {
value1 = (String) (getNode(j).getValue());
value2 = (String) (getNode(min).getValue());
comparison = value1.compareTo(value2);
if(comparison < 0)
min = j;
}
// SWAP A[i] and A[min] here
n1 = getNode(i);
n2 = getNode(min);
temp = new Node(n1.getValue());
n1.setValue(n2.getValue());
n2.setValue(temp.getValue());
}
}
public void add(T item) {
/* NOTE: Same functionality as linkedListMultiset's add(), so no commenting
* has been done to old sections */
Node newNode = new Node(item);
Node currNode = nHead;
if (nHead == null) {
nHead = newNode;
nTail = newNode;
}
else {
while (currNode != null) {
if (currNode.getValue().equals(item)) {
currNode.addCount();
return;
}
currNode = currNode.getNext();
}
newNode.setNext(nHead);
nHead.setPrev(newNode);
nHead = newNode;
}
nCount += 1;
sortList(); // [NEW] - sorting done after adding the node
} // end of add()
public int search(T item) {
/* NOTE: Same functionality as linkedListMultiset's search(), so no commenting
* has been done to old sections*/
Node currNode = nHead;
int count = 0;
while (currNode != null) {
if (currNode.getValue().equals(item)) {
count = currNode.getCount();
break;
}
currNode = currNode.getNext();
}
return count;
} // end of add()
public void removeOne(T item) {
/* NOTE: Same functionality as linkedListMultiset's removeOne(), so no commenting
* has been done to old sections*/
Node currNode = nHead;
while (currNode != null) {
if (currNode.getValue().equals(item)) {
if (currNode.getCount() > 1) {
currNode.reduceCount();
return;
} else {
removeAll(item);
return;
}
}
currNode = currNode.getNext();
}
} // end of removeOne()
public void removeAll(T item) {
/* NOTE: Same functionality as linkedListMultiset's removeAll(), so no commenting
* has been done to old sections*/
Node currNode = nHead;
Node prevNode = null;
Node nextNode = null;
if (currNode.getValue().equals(item)) {
if (nCount == 1) {
nHead = null;
nTail = null;
}
else {
nHead = currNode.getNext();
nHead.setPrev(null);
}
nCount--;
return;
}
else {
currNode = currNode.getNext();
while (currNode != null) {
if (currNode.getValue().equals(item)) {
prevNode = currNode.getPrev();
prevNode.setNext(currNode.getNext());
if (currNode.getNext() == null)
nTail = prevNode;
else {
nextNode = currNode.getNext();
nextNode.setPrev(prevNode);
}
nCount--;
return;
}
currNode = currNode.getNext();
}
}
} // end of removeAll()
public void print(PrintStream out) {
/* NOTE: Same functionality as linkedListMultiset's print(), so no commenting
* has been done to old sections*/
Node currNode = nHead;
while (currNode != null) {
out.println(currNode.getValue() + printDelim + currNode.getCount());
currNode = currNode.getNext();
}
} // end of print()
} // end of class SortedLinkedListMultiset
| 5ba69e8ae7ed0f72cb628090b044e9c4b373a48d | [
"Java"
] | 1 | Java | rmit-s3607050-rei-ito/Algorithms_A1 | 58c6f8159b4bd4638213b5f564d35fc3421679b5 | 8519da75d0fc1c7272bba69e24d36e4b3aa0dd25 |
refs/heads/master | <file_sep>#include <stdio.h>
//Find the first 50 Fibonacci Sequence numbers
//where the first two integers are 0,1
void Fibsequence(unsigned long int a[], int size);
int main(int argc, char **argv)
{
unsigned long int x[50]; //I can use this since
Fibsequence(x,50);
return 0;
}
void Fibsequence(unsigned long int a[], int size)
{
int i;
a[0] = 0;
a[1] = 1;
for(i=2; i<size; i++)
{
a[i] = a[i-1] + a[i-2];
}
for(i=0; i<size; i++)
{
printf("F%i: ",i);
printf("%lu\n",a[i]);
}
}
| 76881e208203e7d03bce9050379d9259b58ee992 | [
"C"
] | 1 | C | eggarcia408/FibonacciSequence | 4d17f3b978f20669eebaa424193b991c1fa2d353 | d411545d6eff376b15847c0f9bf91b1e28224218 |
refs/heads/main | <repo_name>dreamsxin/cocos-GeometryWar<file_sep>/assets/Script/Manager/UIMgr.ts
/*
* @Autor: Rao
* @Date: 2021-04-05 14:32:02
* @LastEditors: Rao
* @LastEditTime: 2021-05-22 22:39:36
* @Description:
*/
import ResMgr from "./ResMgr";
const { ccclass, property } = cc._decorator;
@ccclass
export default class UIMgr {
lastScene: string = '';
haveDialog: boolean = false; // 弹窗的数量。同一界面只能有一个弹窗
static instance: UIMgr = null;
static getInstance() {
if (!UIMgr.instance) {
UIMgr.instance = new UIMgr();
}
return UIMgr.instance;
}
openUINode(parentNode, uiName, uiType) {
if (!this.haveDialog) {
let pfbName = ResMgr.getInstance().getPrefab(uiName);
let pfbNode = cc.instantiate(pfbName);
parentNode.addChild(pfbNode);
pfbNode.addComponent(uiName);
if (uiType==='dialog') {
this.haveDialog = true;
}
}
}
closeUINode(curNode, uiType?) {
this.lastScene = curNode.name;
if (uiType==='dialog') {
this.haveDialog = false;
}
curNode.destroy();
}
setIsHaveDialog(rst:boolean) {
this.haveDialog = rst;
}
getLastScene() {
return this.lastScene;
}
addBtnClickEvent(btnNode: cc.Node, target, callFunc) {
let botton = btnNode.getComponent(cc.Button);
if (!botton) {
return;
}
btnNode.on('click', callFunc, target);
}
private _isAudioPlaying: boolean = true;
set isAudioPlaying(rst:boolean) {
this._isAudioPlaying = rst;
}
get isAudioPlaying() {
return this._isAudioPlaying;
}
}
<file_sep>/assets/Script/Entity/Item.ts
/*
* @Autor: Rao
* @Date: 2021-04-07 10:19:54
* @LastEditors: Rao
* @LastEditTime: 2021-05-17 11:27:00
* @Description:
*/
import GameComponent from "../GameComponent";
import ItemPool from "../NodePool/ItemPool";
import ResMgr from "../Manager/ResMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Item extends GameComponent {
private isRelaxScene: boolean;
private _id: number;
private _type: number;
private _buff: number;
props = {
id: this._id,
type: this._type,
lifeBuff: this._buff,
ackBuff: this._buff,
expBuff: this._buff,
timeBuff: this._buff,
}
buffMap = {
1: 'lifeBuff',
2: 'ackBuff',
3: 'expBuff',
4: 'timeBuff',
}
initWithData() {
let itemConfigs = ResMgr.getInstance().getConfig('ItemDt');
let index = this.node.name.substr(4);
let itemConfig = itemConfigs[parseInt(index)];
for (const key in this.props) {
this.props[key] = itemConfig[key];
}
}
get id() {
return this.props['id'];
}
get type() {
return this.props['type'];
}
get buff() {
let rst = this.props[this.buffMap[this.type]];
return rst ? rst:0;
}
moveVel:number = -160;
listEvent(){
return ['removeItem'];
}
onEvent(event) {
if (event === 'removeItem') {
this.removeItem();
}
}
onLoad () {
// GameComponent.prototype.onLoad.call(this);
this.isRelaxScene = this.node.parent.name === 'RelaxScene';
if (this.isRelaxScene) {
let ground = cc.find('Canvas/Game/RelaxScene/ground');
this.node.x = cc.winSize.width;
let minY = ground && ground.height/2+this.node.height/2;
let maxY = minY + 120;
let posY = Math.floor(Math.random()*(maxY-minY)+minY);
this.node.y = posY;
this.node.scale = 1.5;
}
this.initWithData();
}
update (dt) {
if (this.isRelaxScene) {
this.node.x += this.moveVel*dt;
if (this.node.x < -this.node.width) {
this.removeItem();
}
}
}
onCollisionEnter(other) {
let colliName = other.node.group;
if (colliName === 'hero') {
this.removeItem();
}
}
removeItem() {
ItemPool.getInstance().putItem(this.props['type'], this.node);
}
}
<file_sep>/assets/Script/Entity/Monster.ts
/*
* @Autor: Rao
* @Date: 2021-05-02 15:58:40
* @LastEditors: Rao
* @LastEditTime: 2021-05-19 14:25:49
* @Description:
*/
import ResMgr from "../Manager/ResMgr";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Monster extends cc.Component {
private _Dir: cc.Vec2;
private _velX: number;
private _velY: number;
private _aclY: number;
private _walkLen: number;
private _edgeLeft: number; // 怪物可以行走的左边界
private _edgeRight: number;
private _life: number;
private _hp: number;
private _ack: number;
private _exp: number;
private _score:number;
props = {
life: this._life,
hp: this._hp,
ack: this._ack,
exp: this._exp,
score: this._score,
}
onLoad () {
let monsterConfigs = ResMgr.getInstance().getConfig('monsterDt');
let index = this.node.name.substr(7);
let monsterConfig = monsterConfigs[parseInt(index)];
this.init(monsterConfig);
}
init(monsterConfig) {
for (const key in this.props) {
this.props[key] = monsterConfig[key];
}
this._Dir = cc.v2(-1,-1);
this._aclY = 980;
this._velY = 0;
this._velX = 83;
this._edgeLeft = 0;
this._edgeRight = 0;
}
get dirX() {
return this._Dir.x;
}
set dirX(num:number) {
this._Dir.x = num;
}
get dirY() {
return this._Dir.y;
}
set dirY(num:number) {
this._Dir.y = num;
}
get aclY() {
return this._aclY;
}
get life() {
return this.props['life'];
}
set life(num: number) {
this.props['life'] = num;
}
get hp() {
return this.props['hp'];
}
set hp(num: number) {
this.props['hp'] = num;
}
get ack() {
return this.props['ack'];
}
set ack(num: number) {
this.props['ack'] = num;
}
get score() {
return this.props['score'];
}
set score(num: number) {
this.props['score'] = num;
}
get velY() {
return this._velY;
}
set velY(num: number) {
this._velY = num;
}
get velX() {
return this._velX;
}
set velX(num: number) {
this._velX = num;
}
get exp() {
return this.props['exp'];
}
set walkLen(num: number) {
this._walkLen = num;
}
get walkLen() {
return this._walkLen;
}
onCollisionEnter(other) {
let colliName = other.node.group;
if(colliName === 'ground' || colliName === 'rail') {
this.velY = 0;
this.dirY = 0;
this._edgeLeft = other.node.x - other.node.width/2;
this._edgeRight = other.node.x + other.node.width/2;
if (this.node.y - other.node.y <= this.node.height/2 + other.node.height/2) {
this.node.y = other.node.y + other.node.height/2+this.node.height/2 - 2;
}
}
if (colliName === 'bullet') {
let bulletTs = other.node.getComponent('Bullet');
let bulletAck = bulletTs.ack;
console.log(bulletAck + "," +this.life);
this.life -= bulletAck;
if (this.life <= 0) {
EventMgr.getInstance().EventDispatcher('killMonster', {'exp':this.exp, 'score': this.score});
this.node.destroy();
}
}
}
onCollisionStay(other) {
let colliName = other.node.group;
if(colliName === 'ground' || colliName === 'rail') {
this.dirY=0;
this.node.y = other.node.y + other.node.height/2+this.node.height/2 - 2;
}
}
update (dt) {
this.updateVel(dt);
this.updatePosition(dt);
}
updateVel(dt) {
this.velY += dt*this.aclY*this.dirY;
}
updatePosition(dt) {
this.node.y += this.velY*dt;
this.node.x += this.velX*dt*this.dirX;
if (this.node.x <= this._edgeLeft+this.node.width/2 || this.node.x >= this._edgeRight-this.node.width/2) {
this.dirX *= -1;
}
}
}
<file_sep>/assets/Script/Entity/Money.ts
/*
* @Autor: Rao
* @Date: 2021-04-21 22:42:31
* @LastEditors: Rao
* @LastEditTime: 2021-05-17 09:46:08
* @Description:
*/
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import GameComponent from "../GameComponent";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Money extends GameComponent {
vel: number=350;
isRelaxScene: boolean;
existTime: number; // 存在时间
leftTime:number;
onLoad () {
this.isRelaxScene = this.node.parent.name === 'RelaxScene';
if(this.isRelaxScene) {
let posX = Math.ceil(Math.random()*680)+100;
this.node.x = posX;
this.node.y = 650;
this.existTime = 5;
this.leftTime = this.existTime;
}
}
start () {
}
update (dt) {
if(this.isRelaxScene) {
this.node.y -= dt*this.vel;
this.leftTime -= dt;
if(this.leftTime <= 0) {
this.node.destroy();
}
}
}
onCollisionEnter(other) {
let colliName = other.node.group;
if(colliName === 'ground') {
this.node.destroy();
}
if (colliName === 'hero') {
this.node.destroy();
}
if(colliName === 'rail') {
this.vel=0;
this.node.removeFromParent();
other.node.addChild(this.node);
this.node.x = this.node.x - other.node.x;
this.node.y = other.node.height/2+this.node.height/2;
}
}
}
<file_sep>/assets/Script/Layer/HeroInfoScene.ts
/*
* @Autor: Rao
* @Date: 2021-05-16 23:22:16
* @LastEditors: Rao
* @LastEditTime: 2021-05-26 00:25:12
* @Description:
*/
import GameComponent from "../GameComponent";
import EventMgr from "../Manager/EventMgr";
import UIMgr from "../Manager/UIMgr";
import Global from "../Global";
const {ccclass, property} = cc._decorator;
@ccclass
export default class HeroInfoScene extends GameComponent {
callCloseInfoFunc:boolean = false;
onLoad () {
GameComponent.prototype.onLoad.call(this);
cc.director.pause();
this.uiNodes['_btnReturn'].on('click', this.closeInfo, this);
let heroInfo = JSON.parse(cc.sys.localStorage.getItem('heroInfo'));
if (heroInfo) {
let attrs = ['_level', '_exp', '_life', '_ack'];
for(let attr of attrs) {
let attrLab = this.uiNodes[attr].getComponent(cc.Label);
if (attrLab && attr !== '_exp') {
attrLab.string = heroInfo[attr.substr(1)];
}
else if (attrLab && attr === '_exp') {
attrLab.string = heroInfo['curExp']+"/"+heroInfo['needExp'];
}
}
}
this.node.y -= this.node.parent.y;
}
closeInfo () {
this.callCloseInfoFunc = true;
cc.director.resume();
UIMgr.getInstance().closeUINode(this.node, 'dialog');
}
onDisable() {
// 如果没有关闭info界面就直接按了退出键,则不会执行closeInfo里的方法。导致UIMgr里面的haveDialog值为true。
// 同时,onDestroy方法也不会执行。但onDisabled会执行。
cc.director.resume();
!this.callCloseInfoFunc && UIMgr.getInstance().setIsHaveDialog(false);
}
}
<file_sep>/assets/Script/Layer/AdventureMenu.ts
/*
* @Autor: Rao
* @Date: 2021-05-01 12:10:32
* @LastEditors: Rao
* @LastEditTime: 2021-05-24 10:55:40
* @Description:
*/
import GameComponent from "../GameComponent";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class AdventureMenu extends GameComponent {
// LIFE-CYCLE CALLBACKS:
onLoad () {
GameComponent.prototype.onLoad.call(this);
this.uiNodes['_btnStart'].on('click', this.enterAdventureGameScene, this);
this.uiNodes['_btnSetting'].on('click', this.enterGameSettingScene, this);
this.uiNodes['_btnReturn'].on('click', this.exitAdventureGameScene, this);
}
enterAdventureGameScene () {
cc.sys.localStorage.setItem('curMapIndex', 1);
EventMgr.getInstance().EventDispatcher('openAdventureScene', {'curNode': this.node});
}
exitAdventureGameScene () {
EventMgr.getInstance().EventDispatcher('openGameMenu', {'curNode': this.node});
}
enterGameSettingScene() {
EventMgr.getInstance().EventDispatcher('openGameSetting', {'curNode': this.node});
}
onDestroy () {
this.uiNodes['_btnStart'].off('click', this.enterAdventureGameScene, this);
this.uiNodes['_btnReturn'].off('click', this.exitAdventureGameScene, this);
this.uiNodes['_btnSetting'].off('click', this.enterGameSettingScene, this);
}
}
<file_sep>/assets/Script/Manager/EventMgr.ts
/*
* @Autor: Rao
* @Date: 2021-04-04 21:58:48
* @LastEditors: Rao
* @LastEditTime: 2021-05-22 23:03:05
* @Description:
*/
const { ccclass, property } = cc._decorator;
@ccclass
export default class EventMgr {
static instance: EventMgr = null;
static getInstance() {
if (!EventMgr.instance) {
EventMgr.instance = new EventMgr();
}
return EventMgr.instance;
}
_events = new Map();
addEventListener(event, callFunc, target) {
if(typeof event !== 'string' || typeof callFunc !== 'function' || !target) {
cc.error('Error of Null');
return;
}
if(!this._events.has(event)) {
this._events.set(event, []);
}
let listener = this._events.get(event);
let len = listener.length;
listener[len] = {
target: target,
callFunc: callFunc
}
}
EventDispatcher(event, params ?){
if (!event || typeof event !== 'string' || !this._events.has(event)) {
return;
}
let listeners = this._events.get(event);
listeners.forEach( function(listener) {
listener && listener.callFunc.call(listener.target, event, params);
}.bind(this));
}
removeEventListener(event, target?) {
if (!event || typeof event !== 'string' || !this._events.has(event)) {
return;
}
let len = arguments.length;
if (len === 1) {
this._events.delete(event);
}
else if (len === 2) {
let targets = this._events.get(event);
for(let i=targets.length-1; i>=0; --i) {
if (targets[i].target === target) {
targets.splice(i, 1);
break;
}
}
}
}
}
// let EventMgr = {
// _events: new Map(),
// addEventListener(event, callFunc, target) {
// if (typeof event !== 'string' || typeof callFunc !== 'function' || !target) {
// cc.error('Error of Null');
// return;
// }
// if (!this._events.has(event)) {
// this._events.set(event, []);
// }
// let listener = this._events.get(event);
// let len = listener.length;
// listener[len] = {
// target: target,
// callFunc: callFunc
// }
// },
// EventDispatcher(event, params?) {
// if (!event || typeof event !== 'string' || !this._events.has(event)) {
// return;
// }
// let listeners = this._events.get(event);
// listeners.forEach(function (listener) {
// listener && listener.callFunc.call(listener.target, event, params);
// }.bind(this));
// },
// removeEventListener(event, callFunc, target) {
// if (!event || typeof event !== 'string' || !this._events.has(event)) {
// return;
// }
// }
// }
// export default EventMgr; <file_sep>/assets/Script/Layer/AdventureScene.ts
/*
* @Autor: Rao
* @Date: 2021-05-01 16:43:00
* @LastEditors: Rao
* @LastEditTime: 2021-05-26 00:30:54
* @Description:
*/
import GameComponent from "../GameComponent";
import ResMgr from "../Manager/ResMgr";
import EventMgr from "../Manager/EventMgr";
import UIMgr from "../Manager/UIMgr";
const { ccclass, property } = cc._decorator;
@ccclass
export default class AdventureScene extends GameComponent {
// LIFE-CYCLE CALLBACKS:
private _tileMap: cc.TiledMap;
private _moneyObjs: any;
private _railObjs: any;
private _itemObjs: any;
private _monsterObjs: any;
private _heroNode: cc.Node;
private _cameraMaxY: number = 0;
private _mainCamera: cc.Node;
private _mapIndex: number = 1;
private _mapSize: cc.Size;
private _tileSize: cc.Size;
private _mapHeight: number = 0;
listEvent() {
return ['closeAdventureScene', 'gameover'];
}
onEvent(event, params) {
if (event === 'closeAdventureScene') {
this.node.destroy();
}
else if (event === 'gameover') {
EventMgr.getInstance().EventDispatcher('openGameOverScene', { curNode: this.node });
}
}
onLoad() {
GameComponent.prototype.onLoad.call(this);
// cc.sys.localStorage.setItem('curGameScene', this.node.name);
this._tileMap = this.node.getComponent(cc.TiledMap);
this._mapIndex = cc.sys.localStorage.getItem('curMapIndex');
this._tileMap.tmxAsset = ResMgr.getInstance().getTileMap('map' + this._mapIndex);
this._mapSize = this._tileMap.getMapSize();
this._tileSize = this._tileMap.getTileSize();
let mapWidth = this._mapSize.width * this._tileSize.width;
this._mapHeight = this._mapSize.height * this._tileSize.height;
this._cameraMaxY = this._mapHeight / 2 - cc.winSize.height / 2;
this._mainCamera = cc.find('Canvas/Main Camera');
this.createMoney();
this.createRail();
this.createItem();
this.createHero();
this.createMonster();
let follow = cc.follow(this._heroNode, cc.rect(0, 0, mapWidth, this._mapHeight));
this.node.runAction(follow);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
}
changeMap() {
this._mapIndex++;
cc.sys.localStorage.setItem('curMapIndex', this._mapIndex);
EventMgr.getInstance().EventDispatcher('openAdventureScene', { curNode: this.node });
EventMgr.getInstance().EventDispatcher('saveInfo');
}
createMoney() {
this._moneyObjs = this._tileMap.getObjectGroup('money').getObjects();
let moneyPfb = ResMgr.getInstance().getPrefab('Money');
for (let money of this._moneyObjs) {
let moneyN = cc.instantiate(moneyPfb);
moneyN.addComponent('Money');
this.node.addChild(moneyN);
moneyN.x = money['x'];
moneyN.y = money['y'];
}
}
createRail() {
this._railObjs = this._tileMap.getObjectGroup('rail').getObjects();
let railPfb = ResMgr.getInstance().getPrefab('Rail');
for (let rail of this._railObjs) {
let railN = cc.instantiate(railPfb);
this.node.addChild(railN);
railN.x = rail['x'];
railN.y = rail['y'];
}
}
createItem() {
this._itemObjs = this._tileMap.getObjectGroup('item').getObjects();
for (let item of this._itemObjs) {
let itemName = 'Item' + item.name.substr(4);
let itemPfb = ResMgr.getInstance().getPrefab(itemName);
let itemN = cc.instantiate(itemPfb);
itemN.addComponent('Item');
this.node.addChild(itemN);
itemN.x = item['x'];
itemN.y = item['y'];
itemN.scale = 2;
}
}
createHero() {
let pfbName = ResMgr.getInstance().getPrefab('Hero');
this._heroNode = cc.instantiate(pfbName);
this.node.addChild(this._heroNode);
this._heroNode.addComponent('Hero');
}
createMonster() {
this._monsterObjs = this._tileMap.getObjectGroup('monster').getObjects();
for (let monster of this._monsterObjs) {
let monsterPfb = ResMgr.getInstance().getPrefab('Monster1');
let monsterN = cc.instantiate(monsterPfb);
monsterN.addComponent('Monster');
this.node.addChild(monsterN);
monsterN.x = monster['x'];
monsterN.y = monster['y'];
}
}
start() {
var colliMgr = cc.director.getCollisionManager();
if (!colliMgr.enabled) {
colliMgr.enabled = true;
//colliMgr.enabledDebugDraw = true;
// colliMgr.enabledDrawBoundingBox = true;
}
}
updateCameraPos() {
// let target = this._heroNode.position;
// if (target.y > 320) {
// target.y = this._cameraMaxY;
// this._mainCamera.y = target.y;
// }
// else {
// }
}
update(dt) {
this.updateCameraPos();
if (this._heroNode.y >= this._mapHeight) {
this.changeMap();
}
}
onKeyDown(event) {
switch (event.keyCode) {
case cc.macro.KEY.escape:
// if(cc.game.isPaused()) {
// cc.game.resume();
// }
EventMgr.getInstance().EventDispatcher('openAdventureMenu', { 'curNode': this.node });
//let pfbName = ResMgr.getInstance().getPrefab('PauseScene');
//let pfbNode = cc.instantiate(pfbName);
//this.node.addChild(pfbNode);
//pfbNode.y = this._heroNode.y;
//pfbNode.addComponent('PauseScene');
break;
case cc.macro.KEY.p:
// let isPause = cc.game.isPaused();
// if (isPause) {
// cc.game.resume();
// }
// else {
// cc.game.pause();
// }
EventMgr.getInstance().EventDispatcher('openPauseScene', { 'curNode': this.node, 'parentNode': this.node, 'uiType': 'dialog' });
break;
}
}
onDestroy() {
GameComponent.prototype.removeEvent.call(this);
}
}
<file_sep>/assets/Script/NodePool/ObstaclePool.ts
/*
* @Autor: Rao
* @Date: 2021-04-09 16:24:30
* @LastEditors: Rao
* @LastEditTime: 2021-04-09 21:01:25
* @Description:
*/
import GameComponent from "../GameComponent";
import ResMgr from "../Manager/ResMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class ObstaclePool extends GameComponent {
obstacleNodes = new Map();
constructor() {
super();
this.init();
}
/**
* @description:
* @for-i {节点池预制体个数}
* @for-j {预制体类型}
* @author: Rao
*/
init() {
for (let i = 1; i <= 2; i++) {
let obsNodePool: cc.NodePool = new cc.NodePool();
for (let j = 0; j < 15; j++) {
let obsPrefab = ResMgr.getInstance().getPrefab('Obstacle'+i); // Obstacle2
let obsNode = cc.instantiate(obsPrefab);
obsNodePool.put(obsNode);
}
this.obstacleNodes.set('obstacle'+i, obsNodePool);
}
}
getObstacle(type:number) {
if (this.obstacleNodes.has('obstacle'+type) && this.obstacleNodes.get('obstacle'+type)) {
let obsNodePool = this.obstacleNodes.get('obstacle'+type);
if (obsNodePool.size() > 0) {
return obsNodePool.get();
}
else {
let obsPrefab = ResMgr.getInstance().getPrefab('Obstacle'+type);
let obsNode = cc.instantiate(obsPrefab);
obsNodePool.put(obsNode);
}
}
}
putObstacle(type:number, obsNode:cc.Node) {
if (this.obstacleNodes.has('obstacle'+type) && this.obstacleNodes.get('obstacle'+type)) {
let obsNodePool = this.obstacleNodes.get('obstacle'+type);
obsNodePool && obsNodePool.put();
}
}
}
<file_sep>/assets/Script/Layer/GameMenu.ts
/*
* @Autor: Rao
* @Date: 2021-04-04 12:44:23
* @LastEditors: Rao
* @LastEditTime: 2021-05-19 14:32:26
* @Description:
*/
import ResMgr from "../Manager/ResMgr";
import GameComponent from "../GameComponent";
import EventMgr from "../Manager/EventMgr";
import UIMgr from "../Manager/UIMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameMenu extends GameComponent {
GameMenuNode: cc.Node;
onLoad () {
GameComponent.prototype.onLoad.call(this);
}
start() {
// UIMgr.getInstance().addBtnClickEvent(this.uiNodes['_btnRelax'], this, this.enterRelaxMode);
this.uiNodes['_btnRelax'].on('click', this.enterRelaxMode, this);
this.uiNodes['_btnAdventure'].on('click', this.enterAdventureMode, this);
this.uiNodes['_btnExit'].on('click', this.exitGame, this);
}
listEvent() {
return ['print'];
}
onEvent(event, params?) {
if(event === 'print') {
console.log('print'+params);
}
}
enterRelaxMode() {
// UIMgr.getInstance().openUINode(this.node.parent, 'RelaxMenu');
EventMgr.getInstance().EventDispatcher('openRelaxMenu', {'curNode': this.node});
//UIMgr.getInstance().closeUINode(this.node);
}
enterAdventureMode() {
EventMgr.getInstance().EventDispatcher('openAdventureMenu', {'curNode': this.node});
//UIMgr.getInstance().closeUINode(this.node);
}
exitGame() {
cc.game.end();
}
}
<file_sep>/assets/Script/Layer/GameOverScene.ts
/*
* @Autor: Rao
* @Date: 2021-05-16 10:24:27
* @LastEditors: Rao
* @LastEditTime: 2021-05-16 15:49:04
* @Description:
*/
import GameComponent from "../GameComponent";
import UIMgr from "../Manager/UIMgr";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameOver extends GameComponent {
heroData:any;
lastScene:string = '';
onLoad () {
GameComponent.prototype.onLoad.call(this);
this.uiNodes['_btnTrayAgain'].on('click', this.trayAgain, this);
this.uiNodes['_btnReturnMenu'].on('click', this.ReturnMenu, this);
}
start () {
this.lastScene = UIMgr.getInstance().getLastScene();
let heroData = JSON.parse(cc.sys.localStorage.getItem('heroData'));
console.log(heroData);
if (heroData) {
let score = this.uiNodes['_score'].getComponent(cc.Label);
let moneyCount = this.uiNodes['_moneyCount'].getComponent(cc.Label);
let killCountTitle = this.uiNodes['_killCountTitle'].getComponent(cc.Label);
let killCount = this.uiNodes['_killCount'].getComponent(cc.Label);
score.string = heroData.score;
moneyCount.string = heroData.moneyCount;
if(this.lastScene === 'RelaxScene') {
killCountTitle.string = '消灭障碍'
killCount.string = heroData.obstacleCount;
}
else {
killCountTitle.string = '杀灭怪物'
killCount.string = heroData.monsterCount;
}
}
}
trayAgain() {
EventMgr.getInstance().EventDispatcher('open'+this.lastScene, {curNode: this.node});
}
ReturnMenu() {
EventMgr.getInstance().EventDispatcher('openGameMenu', {curNode: this.node});
}
}
<file_sep>/assets/Script/Entity/Obstacle.ts
/*
* @Autor: Rao
* @Date: 2021-04-09 16:05:38
* @LastEditors: Rao
* @LastEditTime: 2021-05-17 11:21:35
* @Description:
*/
import GameComponent from "../GameComponent";
import ObstaclePool from "../NodePool/ObstaclePool";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Obstacle extends GameComponent {
// moveVel:number = -350;
moveDst:number = 6;
obsNodePool: any = new ObstaclePool();
type: any;
isCrashed:boolean = false;
funcMap = new Map();
getFuncByName(funcName) {
if (!funcName) {
return;
}
return this.funcMap.get(funcName);
}
onLoad () {
let ground = cc.find('Canvas/Game/RelaxScene/ground');
let obsScale = Math.round(Math.random()*1.5)+0.5;
this.node.scale = obsScale;
this.node.x = cc.winSize.width;
this.node.y = ground && ground.height/2+(this.node.height/2)*obsScale;
this.type = this.node.name.charAt(this.node.name.length - 1);
this.funcMap.set('rotateSelf', this.rotateSelf);
}
update (dt) {
// this.node.x += this.moveVel*dt;
if(!this.isCrashed) {
this.node.x -= this.moveDst;
}
if (this.node.x < -this.node.width || this.node.x > cc.winSize.width + 10) {
this.isCrashed = false;
this.node.destroy();
}
}
rotateSelf(heroPos?) {
this.isCrashed = true;
let dir = heroPos.x < this.node.x ? 1:-1; // 1--向右,-1向左
let dstPoint = dir ? cc.winSize.width+50 : 0-50;
let dstTime = Math.abs(dstPoint - this.node.x)/350;
cc.tween(this.node)
.to(0.5, {angle: 320})
.to(dstTime, {position: cc.v3(dstPoint, 260, 0)})
.start();
}
}
<file_sep>/assets/Script/Manager/GameMgr.ts
/*
* @Autor: Rao
* @Date: 2021-04-06 13:29:22
* @LastEditors: Rao
* @LastEditTime: 2021-05-19 21:58:36
* @Description:'
*/
import GameComponent from "../GameComponent";
import UIMgr from "./UIMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameMgr extends GameComponent {
onLoad () {
GameComponent.prototype.onLoad.call(this);
UIMgr.getInstance().openUINode(this.node, 'GameMenu', 'layer');
}
listEvent() {
return ['openRelaxMenu','openAdventureMenu', 'openRelaxScene', 'openAdventureScene',
'openPauseScene','callFuncObstacle','openGameMenu', 'openGameOverScene','openHeroInfoScene','openGameSetting'];
}
onEvent(event:string, params) {
if(event.startsWith('open')) {
let parentNode = params.parentNode ? params.parentNode : this.node;
!params.uiType && UIMgr.getInstance().closeUINode(params.curNode);
UIMgr.getInstance().openUINode(parentNode, event.substr(4), params.uiType);
//!params.isRetain && UIMgr.getInstance().closeUINode(params.curNode);
}
else if (event.startsWith('callFunc')) {
let path = 'Canvas/Game/'+params.scene+'/'+params.nodeName;
let node = cc.find(path);
let ts:any = node.getComponent(params.tsName);
let funcName = params.funcName;
let func = ts.getFuncByName(funcName);
func.call(ts, params.args);
}
}
onDestroy () {
GameComponent.prototype.removeEvent.call(this);
}
}
<file_sep>/README.md
# GeometryWar
基于Creator的几何大战游戏
<file_sep>/assets/Script/NodePool/BulletPool.ts
/*
* @Autor: Rao
* @Date: 2021-05-06 18:23:16
* @LastEditors: Rao
* @LastEditTime: 2021-05-13 11:52:22
* @Description:
*/
import ResMgr from "../Manager/ResMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class BulletPool extends cc.Component {
bulletNodes = new Map();
static instance: BulletPool = null;
static getInstance() {
if (!BulletPool.instance) {
BulletPool.instance = new BulletPool();
}
return BulletPool.instance;
}
private constructor() {
super();
this.init();
}
/**
* @description:
* @for-i {节点池预制体个数}
* @for-j {预制体类型}
* @author: Rao
*/
init() {
for (let i = 1; i <= 3; i++) {
let bulletNodePool: cc.NodePool = new cc.NodePool();
for (let j = 0; j < 15; j++) {
let bulletPrefab = ResMgr.getInstance().getPrefab('Bullet'+i); // bullet2
let bulletNode = cc.instantiate(bulletPrefab);
bulletNode.addComponent('Bullet');
bulletNodePool.put(bulletNode);
}
this.bulletNodes.set('bullet'+i, bulletNodePool);
}
}
getBullet(type:number) {
if (this.bulletNodes.has('bullet'+type) && this.bulletNodes.get('bullet'+type)) {
let bulletNodePool = this.bulletNodes.get('bullet'+type);
if (bulletNodePool.size() > 0) {
return bulletNodePool.get();
}
else {
let bulletPrefab = ResMgr.getInstance().getPrefab('bullet'+type);
let bulletNode = cc.instantiate(bulletPrefab);
bulletNodePool.put(bulletNode);
}
}
}
putBullet(type:number, bulletNode:cc.Node) {
if (this.bulletNodes.has('bullet'+type) && this.bulletNodes.get('bullet'+type)) {
let bulletNodePool = this.bulletNodes.get('bullet'+type);
bulletNodePool && bulletNodePool.put(bulletNode);
}
}
}
<file_sep>/assets/Script/Layer/PauseScene.ts
/*
* @Autor: Rao
* @Date: 2021-04-12 17:06:36
* @LastEditors: Rao
* @LastEditTime: 2021-05-25 17:20:50
* @Description:
*/
import GameComponent from "../GameComponent";
import EventMgr from "../Manager/EventMgr";
import UIMgr from "../Manager/UIMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class PauseScene extends GameComponent {
onLoad () {
GameComponent.prototype.onLoad.call(this);
cc.director.pause();
this.uiNodes['_btnContinue'].on('click', this.continueGame, this);
this.uiNodes['_btnReturn'].on('click', this.exitGame, this);
this.node.y -= this.node.parent.y;
}
continueGame() {
cc.director.resume();
UIMgr.getInstance().closeUINode(this.node, 'dialog');
}
exitGame() {
cc.director.resume();
let sceneName = this.node.parent.name;
let scenePrefix = sceneName.substr(0, sceneName.length-5);
UIMgr.getInstance().closeUINode(this.node, 'dialog');
EventMgr.getInstance().EventDispatcher('close'+sceneName);
EventMgr.getInstance().EventDispatcher('open'+scenePrefix+'Menu', {'curNode': this.node});
console.log(sceneName+scenePrefix);
}
}
<file_sep>/assets/Script/GameComponent.ts
/*
* @Autor: Rao
* @Date: 2021-04-04 13:40:17
* @LastEditors: Rao
* @LastEditTime: 2021-05-16 11:29:43
* @Description:
*/
import EventMgr from "./Manager/EventMgr";
import ResMgr from "./Manager/ResMgr";
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameComponent extends cc.Component {
uiNodes = {};
onLoad() {
this.bindUINodes(this.node, '');
this.addEventListner();
}
bindUINodes(root: cc.Node, path: string) {
let nodes = root.children;
for (let i = 0; i < nodes.length; ++i) {
this.bindUINodes(nodes[i], path + nodes[i].name + "/");
if (nodes[i].name.startsWith('_')) {
this.uiNodes[path + nodes[i].name] = nodes[i];
}
}
}
getRootNode() {
let root = this.node.getChildByName('Game');
if (root) {
return root;
}
}
bindBtnEvent(btnNode:cc.Node, caller, callFunc) {
if (!btnNode || !caller || !callFunc || typeof callFunc !== 'function') {
return;
}
let btn = btnNode.getComponent(cc.Button);
if(!btn) {
return;
}
btnNode.on('click', callFunc, caller);
}
listEvent():any {
return;
}
onEvent(event, params) {
return;
}
addEventListner() {
if (this.listEvent && this.onEvent) {
let events = this.listEvent();
if (events) {
for (let i=0; i<events.length; ++i) {
EventMgr.getInstance().addEventListener(events[i], this.onEvent, this);
}
}
}
}
removeEvent() {
let events = this.listEvent();
if(!events) {
return;
}
for (let i = 0; i < events.length; i++) {
EventMgr.getInstance().removeEventListener(events[i], this);
}
}
}
<file_sep>/assets/Script/Loading.ts
/*
* @Autor: Rao
* @Date: 2021-04-03 14:44:31
* @LastEditors: Rao
* @LastEditTime: 2021-05-18 11:52:12
* @Description:
*/
const {ccclass, property} = cc._decorator;
import ResMgr from './Manager/ResMgr';
@ccclass
export default class Loading extends cc.Component {
@property(cc.ProgressBar)
progressBar: cc.ProgressBar=null;
onLoad () {
let progressCountN = this.node.getChildByName('progressCount');
let progressCountLab = progressCountN.getComponent(cc.Label);
cc.resources.loadDir('./', (finishCount: number, totalCount: number, item):void=>{
this.progressBar.progress = finishCount/totalCount;
progressCountLab.string = finishCount+'/'+totalCount;
},
(err, assets)=>{
if(err) {
return;
}
for(let i = 0; i < assets.length; i++) {
let asset = assets[i];
if(asset instanceof cc.JsonAsset) {
ResMgr.getInstance().addData('config', asset.name, asset.json);
}
else if (asset instanceof cc.TiledMapAsset) {
ResMgr.getInstance().addData('tileMap', asset.name, asset);
}
else if(asset instanceof cc.SpriteFrame) {
ResMgr.getInstance().addData('spriteFrame', asset.name, asset);
}
else if(asset instanceof cc.Prefab) {
ResMgr.getInstance().addData('prefab', asset.name, asset);
}
}
cc.director.loadScene('GameScene');
});
}
}
<file_sep>/assets/Script/NodePool/ItemPool.ts
/*
* @Autor: Rao
* @Date: 2021-04-10 09:18:32
* @LastEditors: Rao
* @LastEditTime: 2021-05-22 23:29:52
* @Description:
*/
const {ccclass, property} = cc._decorator;
import GameComponent from "../GameComponent";
import ResMgr from "../Manager/ResMgr";
@ccclass
export default class ItemPool extends cc.Component {
itemNodes = new Map();
static instance: ItemPool = null;
static getInstance() {
if (!ItemPool.instance) {
ItemPool.instance = new ItemPool();
}
return ItemPool.instance;
}
private constructor() {
super();
this.init();
}
/**
* @description:
* @for-i {节点池预制体个数}
* @for-j {预制体类型}
* @author: Rao
*/
init() {
for (let i = 1; i <= 3; i++) {
let itemNodePool: cc.NodePool = new cc.NodePool();
for (let j = 0; j < 15; j++) {
let itemPrefab = ResMgr.getInstance().getPrefab('Item'+i); // item2
let itemNode = cc.instantiate(itemPrefab);
itemNode.addComponent('Item');
itemNodePool.put(itemNode);
}
this.itemNodes.set('item'+i, itemNodePool);
}
}
getItem(type:number) {
if (this.itemNodes.has('item'+type) && this.itemNodes.get('item'+type)) {
let itemNodePool = this.itemNodes.get('item'+type);
if (itemNodePool.size() > 0) {
return itemNodePool.get();
}
else {
let itemPrefab = ResMgr.getInstance().getPrefab('item'+type);
let itemNode = cc.instantiate(itemPrefab);
itemNodePool.put(itemNode);
}
}
}
putItem(type:number, itemNode:cc.Node) {
if (this.itemNodes.has('item'+type) && this.itemNodes.get('item'+type)) {
let itemNodePool = this.itemNodes.get('item'+type);
itemNodePool && itemNodePool.put(itemNode);
}
}
}
<file_sep>/assets/Script/Entity/Rail.ts
/*
* @Autor: Rao
* @Date: 2021-04-15 17:06:17
* @LastEditors: Rao
* @LastEditTime: 2021-05-17 11:34:21
* @Description: 能够承载hero栏杆
*/
const { ccclass, property } = cc._decorator;
@ccclass
export default class Rail extends cc.Component {
dir: number = -1;
vel: number = 206;
onLoad() {
let [minX, maxX, minY, maxY] = [100, 540, 280, 450];
// this.node.x = Math.floor(Math.random()*(maxX - minX) + minX);
// this.node.y = Math.floor(Math.random()*(maxY - minY) + minY);
this.node.x = 480;
this.node.y = 320;
}
start() {
// this.scheduleOnce(function () {
// this.node.destory();
// }, 3);
}
getVel() {
return this.vel;
}
update(dt) {
this.node.x += this.vel * dt * this.dir;
if (this.node.x + this.node.width / 2 > cc.winSize.width || this.node.x - this.node.width / 2 < 0) {
this.dir *= -1;
}
}
}
<file_sep>/assets/Script/Layer/RelaxMenu.ts
/*
* @Autor: Rao
* @Date: 2021-04-06 15:13:42
* @LastEditors: Rao
* @LastEditTime: 2021-05-19 14:36:50
* @Description:
*/
import GameComponent from "../GameComponent";
import UIMgr from "../Manager/UIMgr";
import EventMgr from "../Manager/EventMgr";
const {ccclass, property} = cc._decorator;
@ccclass
export default class RelaxMenu extends GameComponent {
onLoad () {
GameComponent.prototype.onLoad.call(this);
this.uiNodes['_btnStart'].on('click', this.enterRelaxGameScene, this);
this.uiNodes['_btnReturn'].on('click', this.exitRelaxGameScene, this);
this.uiNodes['_btnSetting'].on('click', this.enterGameSettingScene, this);
}
start () {
console.log('RelaxMenu:onDestroy:start');
// let btn = cc.find('Canvas/Game/RelaxMenu/_btnStart');
// btn.on('click', this.enterRelaxGameScene, this);
// this.uiNodes['_btnStart'].on('click', this.enterRelaxGameScene, this);
}
enterRelaxGameScene() {
//UIMgr.getInstance().closeUINode(this.node);
EventMgr.getInstance().EventDispatcher('openRelaxScene', {'curNode': this.node});
}
exitRelaxGameScene () {
//UIMgr.getInstance().closeUINode(this.node);
EventMgr.getInstance().EventDispatcher('openGameMenu', {'curNode': this.node});
}
enterGameSettingScene() {
EventMgr.getInstance().EventDispatcher('openGameSetting', {'curNode': this.node});
}
onDestroy() {
this.uiNodes['_btnStart'].off('click', this.enterRelaxGameScene, this);
this.uiNodes['_btnReturn'].off('click', this.exitRelaxGameScene, this);
this.uiNodes['_btnSetting'].off('click', this.enterGameSettingScene, this);
}
}
<file_sep>/assets/Script/Layer/GameSetting.ts
import GameComponent from "../GameComponent";
import UIMgr from "../Manager/UIMgr";
import EventMgr from "../Manager/EventMgr";
/*
* @Autor: Rao
* @Date: 2021-05-19 14:12:27
* @LastEditors: Rao
* @LastEditTime: 2021-05-19 15:40:12
* @Description:
*/
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameSetting extends GameComponent {
isBtnClicked: boolean = false;
labChoose:any = null;
onLoad () {
GameComponent.prototype.onLoad.call(this);
this.uiNodes['_btnChoose'].on('click', this.onBtnChoose, this);
this.uiNodes['_btnExit'].on('click', this.onBtnExit, this);
this.labChoose = this.uiNodes['_btnChoose/Background/_labChoose'].getComponent(cc.Label);
this.isBtnClicked = !UIMgr.getInstance().isAudioPlaying;
if (!UIMgr.getInstance().isAudioPlaying) {
this.labChoose.string = '否';
}
}
onBtnChoose () {
if (!this.isBtnClicked) {
this.labChoose.string = '否';
cc.audioEngine.pauseMusic();
// cc.audioEngine.stopMusic();
// cc.audioEngine.stopAllEffects();
}
else {
this.labChoose.string = '是';
cc.audioEngine.resumeMusic();
}
this.isBtnClicked = !this.isBtnClicked;
UIMgr.getInstance().isAudioPlaying = !UIMgr.getInstance().isAudioPlaying;
}
onBtnExit() {
EventMgr.getInstance().EventDispatcher('open'+UIMgr.getInstance().getLastScene(), {curNode:this.node});
}
// update (dt) {}
}
<file_sep>/assets/Script/Entity/Hero.ts
/*
* @Autor: Rao
* @Date: 2021-04-06 21:36:44
* @LastEditors: Rao
* @LastEditTime: 2021-05-26 00:39:55
* @Description:
*/
import GameComponent from "../GameComponent";
import ResMgr from "../Manager/ResMgr";
import EventMgr from "../Manager/EventMgr";
import BulletPool from "../NodePool/BulletPool";
import UIMgr from "../Manager/UIMgr";
import AudioMgr from "../Manager/AudioMgr";
import Global from "../Global";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Hero extends GameComponent {
private _Dir: cc.Vec2;
private _velX: number;
private _velY: number;
private _aclY: number;
private _life: number;
private _hp: number;
private _ack: number;
private _score: number;
private _isUltra: boolean = false;
private _curExp: number;
private _needExp: number;
private _level: number;
private _maxHp: number;
private _anim: cc.Animation;
private _scale: number;
private _isRailColli: boolean;
private _railNode: cc.Node = null;
private _bulletType: number;
private _isRight: boolean = true;
private _moneyCount: number = 0;
private _obstacleCount: number = 0;
private _monsterCount: number = 0;
// curSceneNode: cc.Node = null;
props = {
life: this._life,
ack: this._ack,
curExp: this._curExp,
needExp: this._needExp,
level: this._level,
score: this._score,
}
listEvent() {
return ['killMonster', 'reduceLife', 'saveInfo'];
}
onEvent(event, params) {
if (event === 'killMonster') {
this.killMonster(params);
}
else if (event === 'reduceLife') {
this.life--;
this.checkLife();
}
else if (event === 'saveInfo') {
this.saveInfo();
}
}
addScore(score: number) {
this.score += score;
if (this.score >= 200 && this.score <= 400) {
this.bulletType = 2;
}
else if (this.score > 400) {
this.bulletType = 3;
}
}
killMonster(rewards) {
this.monsterCount++;
this.addScore(rewards.score);
this.checkLevel(rewards.exp);
}
// reduceHp(mAck) {
// this.hp -= mAck;
// if (this.hp <= 0) {
// this.life--;
// this.checkLife();
// }
// }
checkLevel(exp) {
this.curExp += exp;
if (this.curExp >= this.needExp) {
this.level++;
this.curExp -= this.needExp;
this.needExp *= 1.6;
this.ack *= 1.2;
}
}
checkLife() {
if (this.life <= 0) {
EventMgr.getInstance().EventDispatcher('playDiesAudio');
let herodata = {
'score': this.score,
'moneyCount': this.moneyCount,
'obstacleCount': this.obstacleCount,
'monsterCount': this.monsterCount
}
cc.sys.localStorage.setItem('heroData', JSON.stringify(herodata));
EventMgr.getInstance().EventDispatcher('gameover');
}
}
saveInfo() {
let heroInfo = {
'level': this.level,
'curExp': this.curExp,
'needExp': this.needExp,
'ack': this.ack,
'life': this.life,
'score': this.score,
}
cc.sys.localStorage.setItem('heroInfo', JSON.stringify(heroInfo));
}
onLoad() {
GameComponent.prototype.onLoad.call(this);
this.init();
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
// let curGameScene = cc.sys.localStorage.getItem('curGameScene');
// this.curSceneNode = this.node.parent.getChildByName(curGameScene);
}
init() {
let mapIndex = cc.sys.localStorage.getItem('curMapIndex');
let heroConfig = null;
if (mapIndex <= 1) {
heroConfig = ResMgr.getInstance().getConfig('heroDt')[0];
}
else {
heroConfig = JSON.parse(cc.sys.localStorage.getItem('heroInfo'));
}
for (const key in this.props) {
this.props[key] = heroConfig[key];
}
this.node.x = 200;
this.node.y = 200;
this._velX = 0;
this._velY = 0;
this._aclY = -1280;
this._Dir = cc.v2(0, -1);
this._anim = this.getComponent(cc.Animation);
this._anim.play('HeroNormal');
this._scale = 1;
this._isRailColli = false;
this._maxHp = this.hp;
this._bulletType = 1;
}
get dirX() {
return this._Dir.x;
}
set dirX(num: number) {
this._Dir.x = num;
}
get dirY() {
return this._Dir.y;
}
set dirY(num: number) {
this._Dir.y = num;
}
get life() {
return this.props['life'];
}
set life(num: number) {
this.props['life'] = num;
}
get hp() {
return this.props['hp'];
}
set hp(num: number) {
this.props['hp'] = num;
}
get ack() {
return this.props['ack'];
}
set ack(num: number) {
this.props['ack'] = num;
}
get bulletType() {
return this._bulletType;
}
set bulletType(num: number) {
this._bulletType = num;
}
get score() {
return this.props['score'];
}
set score(num: number) {
this.props['score'] = num;
}
get moneyCount() {
return this._moneyCount;
}
set moneyCount(num: number) {
this._moneyCount = num;
}
get obstacleCount() {
return this._obstacleCount;
}
set obstacleCount(num: number) {
this._obstacleCount = num;
}
get monsterCount() {
return this._monsterCount;
}
set monsterCount(num: number) {
this._monsterCount = num;
}
get aclY() {
return this._aclY;
}
get velY() {
return this._velY;
}
set velY(num: number) {
this._velY = num;
}
get velX() {
return this._velX;
}
set velX(num: number) {
this._velX = num;
}
get needExp() {
return this.props['needExp'];
}
set needExp(num: number) {
this.props['needExp'] = num;
}
get curExp() {
return this.props['curExp'];
}
set curExp(num: number) {
this.props['curExp'] = num;
}
get level() {
return this.props['level'];
}
set level(num: number) {
this.props['level'] = num;
}
set isRight(rst: boolean) {
this._isRight = rst;
}
get isRight() {
return this._isRight;
}
update(dt) {
this.updateVel(dt);
this.updatePosition(dt);
this.checkRailColli();
}
checkRailColli() {
if (this._isRailColli) {
let isLeave = Math.abs(this._railNode.x - this.node.x) > this._railNode.width / 2 + this.node.width * this._scale / 2;
if (isLeave) {
this.dirY = -1;
this._isRailColli = false;
}
}
}
updateVel(dt) {
this.velY += dt * this.aclY * this.dirY;
if (this.velY < 0) {
this.dirY = -1;
}
}
updatePosition(dt) {
this.node.y += this.velY * dt * this.dirY;
this.node.x += this.velX * dt * this.dirX;
// console.log(this.curSceneNode.y);
}
onCollisionEnter(other) {
let colliName = other.node.group;
if (colliName === 'ground') {
this.velY = 0;
this.dirY = 0;
if (this.node.y - other.node.y <= this.node.height * this._scale / 2 + other.node.height / 2) {
this.node.y = other.node.height / 2 + this.node.height * this._scale / 2 - 2;
}
}
if (colliName === 'rail') {
this.colliRail(other);
}
if (colliName === 'item') {
this.colliItem(other);
}
if (colliName === 'obstacle') {
this.colliObstacle(other);
}
if (colliName === 'money') {
EventMgr.getInstance().EventDispatcher('playItemAudio');
this.score += 30;
this.moneyCount++;
EventMgr.getInstance().EventDispatcher('updateScore', this.score);
}
if (colliName === 'monster') {
this.life--;
this.checkLife();
}
}
onCollisionStay(other) {
let colliName = other.node.group;
if (colliName === 'ground') {
this.dirY = 0;
this.node.y = other.node.height / 2 + this.node.height * this.node.getScale(cc.v2()).x / 2 - 2;
}
}
colliRail(other) {
if (this.dirY === 1) {
this.dirY = -1;
this.dirX = 0;
}
else if (this.dirY === -1) {
// Math.abs(other.node.x - this.node.x) < other.node.width/2+this.node.width*this._scale/2 - 2
// 主角陷入rail中
if (this.node.y <= other.node.y + (other.node.height / 2 + this.node.height * this._scale / 2)) {
this.node.y = other.node.y + other.node.height / 2 + this.node.height * this._scale / 2 - 2;
this.dirY = 0;
this._railNode = other.node;
this._isRailColli = true;
}
else {
this.dirX = 0;
}
}
}
colliItem(other) {
this.score += 30;
EventMgr.getInstance().EventDispatcher('updateScore', this.score);
EventMgr.getInstance().EventDispatcher('playItemAudio');
let isRelaxScene = this.name === 'RelaxScene';
if (isRelaxScene) {
let type = other.node.name.substr(4);
if (type === '1') {
this.life++;
EventMgr.getInstance().EventDispatcher('updateHeroLife');
}
else {
this.node.scale = 1.8;
this._scale = 1.8;
this._isUltra = true;
this.scheduleOnce(function () {
this.node.scale = 1;
this._scale = 1;
this._isUltra = false;
this.dirY = -1;
}, 5);
}
}
else {
let itemTS = other.node.getComponent('Item');
let type = other.node.name.substr(4);
if (type === '1') {
// life
this.life += itemTS.buff;
}
else if (type === '2') {
// ack
this.ack += itemTS.buff;
}
else if (type === '3') {
// exp
this.checkLevel(itemTS.buff);
}
}
}
colliObstacle(other) {
if (this._isUltra) {
this.obstacleCount++;
this.score += 35;
EventMgr.getInstance().EventDispatcher('updateScore', this.score);
// EventMgr.getInstance().EventDispatcher('rotateObstacle', this.node.getPosition());
EventMgr.getInstance().EventDispatcher('callFuncObstacle', {
scene: 'RelaxScene', nodeName: other.node.name,
tsName: 'Obstacle', funcName: 'rotateSelf', args: this.node.getPosition()
});
return;
}
this.life--;
EventMgr.getInstance().EventDispatcher('updateHeroLife');
this.checkLife();
}
jump() {
if (this.dirY === 0) {
this.velY = 800;
this.dirY = 1;
}
}
createBullet() {
// let isRelaxScene = this.curSceneNode.name === 'RelaxScene';
let isRelaxScene = this.node.parent.name === 'RelaxScene';
if (isRelaxScene) {
return;
}
let bulletN = BulletPool.getInstance().getBullet(this.bulletType);
if (bulletN) {
// this.curSceneNode.addChild(bulletN);
this.node.parent.addChild(bulletN);
bulletN.addComponent('Bullet');
let bulletDir = this.isRight ? 1 : -1;
bulletN.x = this.node.x + this.node.width / 2 * bulletDir;
bulletN.y = this.node.y;
}
}
changeAniamtion(isRight) {
this.isRight = isRight;
!this.isRight && this._anim.play('HeroTurnLeft');
this.isRight && this._anim.play('HeroNormal');
}
showInfo() {
let isRelaxScene = this.node.parent.name === 'RelaxScene';
//let isRelaxScene = this.curSceneNode.name === 'RelaxScene';
if (isRelaxScene) {
return;
}
if (!cc.game.isPaused()) {
this.saveInfo();
EventMgr.getInstance().EventDispatcher('playPauseAudio');
EventMgr.getInstance().EventDispatcher('openHeroInfoScene', { parentNode: this.node.parent, uiType: 'dialog' });
}
}
onKeyDown(event) {
switch (event.keyCode) {
case cc.macro.KEY.d:
this.velX = 200;
this.dirX = 1;
this.changeAniamtion(true);
break;
case cc.macro.KEY.a:
this.velX = 250;
this.dirX = -1;
this.changeAniamtion(false);
break;
case cc.macro.KEY.j:
this.createBullet();
break;
case cc.macro.KEY.space:
this.jump();
break;
case cc.macro.KEY.i:
this.showInfo();
break;
}
}
onKeyUp(event) {
switch (event.keyCode) {
case cc.macro.KEY.d:
this.velX = 0;
this.dirX = 0;
break;
case cc.macro.KEY.a:
this._velX = 0;
this.dirX = 0;
break;
}
}
onDestroy() {
GameComponent.prototype.removeEvent.call(this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
}
}
<file_sep>/assets/Script/Manager/ResMgr.ts
/*
* @Autor: Rao
* @Date: 2021-04-04 09:31:17
* @LastEditors: Rao
* @LastEditTime: 2021-04-09 13:52:56
* @Description:
*/
export default class ResMgr{
static instance: ResMgr = null;
static getInstance() {
if (!ResMgr.instance) {
ResMgr.instance = new ResMgr();
}
return ResMgr.instance;
}
private constructor(){}
allCache = {
spriteFrame: new Map(),
prefab: new Map(),
config: new Map(),
tileMap: new Map(),
}
addData(type, key, data) {
if (!type || typeof(type)!=='string' || !key || typeof(key) !== 'string' || !data) {
return;
}
this.allCache[type].set(key, data);
}
getData(type, key){
if (!type || typeof(type)!=='string' || !key || typeof(key) !== 'string') {
return;
}
this.allCache[type].get(key);
}
getSpriteFrame(key) {
return this.allCache['spriteFrame'].get(key);
}
getConfig(key) {
return this.allCache['config'].get(key);
}
getPrefab(key) {
return this.allCache['prefab'].get(key);
}
getTileMap(key) {
return this.allCache['tileMap'].get(key);
}
}
<file_sep>/assets/Script/Layer/RelaxScene.ts
/*
* @Autor: Rao
* @Date: 2021-04-06 21:41:57
* @LastEditors: Rao
* @LastEditTime: 2021-05-26 00:40:44
* @Description:
*/
import GameComponent from "../GameComponent";
import ResMgr from "../Manager/ResMgr";
import ItemPool from "../NodePool/ItemPool";
import EventMgr from "../Manager/EventMgr";
const { ccclass, property } = cc._decorator;
@ccclass
export default class RelaxScene extends GameComponent {
heroNode: cc.Node;
heroMgr: any;
heroLife: cc.RichText;
runTime: cc.RichText;
time: number;
score: any;
obsCreateIntervel: number = 75;
obsCreateTime: number = 0;
obsNode: cc.Node;
obsPrefabs: {};
obsTypes: number[];
obsTypesLen: number = 0;
itemNodePool: any = ItemPool.getInstance();
itemCreateIntervel: number = 450;
itemCreateTime: number = 0;
moneyPrefab: any;
moneyCreateIntervel: number = 120;
moneyCreateTime: number = 0;
railPrefab: any;
listEvent() {
return ['updateHeroLife', "closeRelaxScene", 'updateScore', 'gameover'];
}
onEvent(event, params) {
if (event === 'updateHeroLife') {
this.updateHeroLife();
}
else if (event === 'closeRelaxScene') {
this.node.destroy();
}
else if (event === 'updateScore') {
this.updateScore(params);
}
else if (event === 'gameover') {
EventMgr.getInstance().EventDispatcher('openGameOverScene', { curNode: this.node });
}
}
onLoad() {
GameComponent.prototype.onLoad.call(this);
// cc.sys.localStorage.setItem('curGameScene', this.node.name);
var colliMgr = cc.director.getCollisionManager();
if (!colliMgr.enabled) {
colliMgr.enabled = true;
//colliMgr.enabledDebugDraw = true;
// colliMgr.enabledDrawBoundingBox = true;
}
this.time = 0;
this.obsPrefabs = {};
this.obsTypes = [];
this.heroLife = this.uiNodes['topBar/hero/_heroLife'].getComponent(cc.RichText);
this.runTime = this.uiNodes['topBar/time/_restTime'].getComponent(cc.RichText);
this.score = this.uiNodes['topBar/_score'].getComponent(cc.Label);
this.pushObsTypes();
}
start() {
let pfbName = ResMgr.getInstance().getPrefab('Hero');
this.heroNode = cc.instantiate(pfbName);
this.node.addChild(this.heroNode);
this.heroNode.addComponent('Hero');
this.heroMgr = this.heroNode.getComponent('Hero');
this.heroLife.string = '<color=#DCDCDC>' + this.heroMgr.life + '</color>';
this.node.on(cc.Node.EventType.TOUCH_START, this.onClick, this);
this.createObstacle();
this.createRail();
this.uiNodes['topBar/_btnReturn'].on('click', function () { // 'parentNode': this.node,
EventMgr.getInstance().EventDispatcher('openPauseScene', { 'curNode': this.node, 'parentNode': this.node, 'uiType': 'dialog' });
EventMgr.getInstance().EventDispatcher('playPauseAudio');
}, this);
this.score.string = 'Score:0';
}
onClick() {
this.heroMgr.jump();
}
update(dt) {
//this.heroMgr.update(dt);
this.time += dt;
this.runTime.string = '<color=#696969>' + this.time.toFixed(2) + '</color>';
this.obsCreateTime++;
if (this.obsCreateTime > this.obsCreateIntervel) {
this.obsCreateTime = 0;
this.createObstacle();
}
this.itemCreateTime++;
if (this.itemCreateTime > this.itemCreateIntervel) {
this.itemCreateTime = 0;
this.createItem();
}
this.moneyCreateTime++;
if (this.moneyCreateTime > this.moneyCreateIntervel) {
this.moneyCreateTime = 0;
this.createMoney();
}
}
updateHeroLife() {
this.heroLife.string = '<color=#DCDCDC>' + this.heroMgr.life + '</color>';
}
createObstacle() {
let type = this.obsTypes[this.obsTypesLen++];
if (this.obsTypesLen === 5) {
//this.shuffleObsTypes();
this.obsTypesLen = 0;
}
// 生成1-5的随机
//let type = Math.ceil(Math.random()*5);
if (!this.obsPrefabs.hasOwnProperty(type)) {
let obsPrefab = ResMgr.getInstance().getPrefab('Obstacle' + type);
this.obsPrefabs[type] = obsPrefab;
}
this.obsNode = cc.instantiate(this.obsPrefabs[type]); //this.obsNodePool.getObstacle(type);
this.obsNode && this.node.addChild(this.obsNode);
this.obsNode && this.obsNode.addComponent('Obstacle');
}
createItem() {
let type = Math.ceil(Math.random() * 3);
let itemNode = this.itemNodePool.getItem(type);
itemNode && this.node.addChild(itemNode);
itemNode && itemNode.addComponent('Item');
}
createRail() {
if (!this.railPrefab) {
this.railPrefab = ResMgr.getInstance().getPrefab('Rail');
}
let railNode = cc.instantiate(this.railPrefab);
this.node.addChild(railNode);
railNode.addComponent('Rail');
}
createMoney() {
if (!this.moneyPrefab) {
this.moneyPrefab = ResMgr.getInstance().getPrefab('Money');
}
let moneyNode = cc.instantiate(this.moneyPrefab);
this.node.addChild(moneyNode);
moneyNode.addComponent('Money');
}
pushObsTypes() {
for (let i = 1; i <= 5; i++) {
this.obsTypes.push(i);
}
}
shuffleObsTypes() {
for (let i = this.obsTypes.length - 1; i >= 0; i--) {
let index = Math.floor(Math.random() * i);
[this.obsTypes[i], this.obsTypes[index]] = [this.obsTypes[index], this.obsTypes[i]];
}
}
updateScore(score) {
this.score.string = 'Score:' + score;
}
onDestroy() {
// EventMgr.getInstance().removeEventListener('updateHeroLife');
// EventMgr.getInstance().removeEventListener('closeRelaxScene');
GameComponent.prototype.removeEvent.call(this);
}
}
<file_sep>/assets/Script/Global.ts
/*
* @Autor: Rao
* @Date: 2021-05-25 14:17:41
* @LastEditors: Rao
* @LastEditTime: 2021-05-25 14:24:08
* @Description:
*/
const {ccclass, property} = cc._decorator;
@ccclass
export default class Global {
static shiftY: number = 0; // hero的Y轴偏移量
static mapCount: number = 1; // 地图(关卡)数量
}
<file_sep>/assets/Script/Manager/AudioMgr.ts
/*
* @Autor: Rao
* @Date: 2021-05-19 12:59:45
* @LastEditors: Rao
* @LastEditTime: 2021-05-25 21:19:10
* @Description:
*/
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import GameComponent from "../GameComponent";
import UIMgr from "./UIMgr";
const { ccclass, property } = cc._decorator;
@ccclass
export default class AudioMgr extends GameComponent {
@property(cc.AudioClip)
bgAudio: cc.AudioClip = null;
@property(cc.AudioClip)
deiesAudio: cc.AudioClip = null;
@property({ 'type': cc.AudioClip })
itemAudio: cc.AudioClip = null;
@property(cc.AudioClip)
pauseAudio: cc.AudioClip = null;
bg: any;
item: any;
dies: any;
pause: any;
listEvent() {
return ['playItemAudio', 'playBgAudio', 'playPauseAudio', 'playDiesAudio', 'closeBgAudio']
}
onEvent(event, params) {
if (UIMgr.getInstance().isAudioPlaying) {
if (event === 'playItemAudio') {
this.playItemAudio();
}
else if (event === 'playBgAudio') {
this.playBgAudio();
}
else if (event === 'playPause') {
this.playPauseAudio();
}
else if (event === 'playDiesAudio') {
this.playDiesAudio();
}
else if (event === 'closeBgAudio') {
this.closeBgAudio();
}
}
}
onLoad() {
GameComponent.prototype.onLoad.call(this);
cc.audioEngine.playMusic(this.bgAudio, true);
cc.audioEngine.setMusicVolume(0.2);
}
playBgAudio() {
}
playItemAudio() {
// this.item = this.node.getComponent(cc.AudioSource);
// this.item.play();
this.item = cc.audioEngine.play(this.itemAudio, false, 0.3);
}
playPauseAudio() {
this.pause = cc.audioEngine.play(this.pauseAudio, false, 0.3);
}
playDiesAudio() {
this.dies = cc.audioEngine.play(this.deiesAudio, false, 0.6);
}
closeBgAudio() {
cc.audioEngine.stop(this.bg);
}
start() {
}
// update (dt) {}
}
<file_sep>/assets/Script/Entity/Bullet.ts
/*
* @Autor: Rao
* @Date: 2021-04-06 21:37:08
* @LastEditors: Rao
* @LastEditTime: 2021-05-25 23:27:14
* @Description:
*/
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import ResMgr from "../Manager/ResMgr";
import BulletPool from "../NodePool/BulletPool";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Bullet extends cc.Component {
private _id: number;
private _type: number;
private _buff: number;
private _dir: number = 0;
private _ack: number = 0;
props = {
id: this._id,
type: this._type,
ackBuff: this._buff
}
initWithData() {
let bulletConfigs = ResMgr.getInstance().getConfig('bulletDt');
let index = this.node.name.substr(6);
let bulletConfig = bulletConfigs[parseInt(index)];
for (const key in this.props) {
this.props[key] = bulletConfig[key];
}
}
get id() {
return this.props['id'];
}
get type() {
return this.props['type'];
}
get buff() {
return this.props['ackBuff'];
}
set dir(num:number) {
this._dir = num;
}
get dir() {
return this._dir;
}
set ack(num:number) {
this._ack = num;
}
get ack() {
return this._ack;
}
moveVel:number = 250;
onLoad () {
this.initWithData();
}
update (dt) {
this.node.x += this.moveVel*this.dir*dt;
if (this.node.x >= cc.winSize.width || this.node.x <= 0) {
console.log('bullet remove');
this.removeSelf();
}
}
onCollisionEnter (other) {
let colliName = other.node.group;
if (colliName==='hero') {
let heroN = this.node.parent.getChildByName('Hero');
// let heroN = this.node;.parent.parent.getChildByName('Hero');
if (heroN) {
let heroTs = heroN.getComponent('Hero');
this.dir = heroTs.isRight ? 1:-1;
this.ack = heroTs.ack + this.buff;
}
}
else if (colliName === 'monster') {
this.removeSelf();
}
}
removeSelf () {
BulletPool.getInstance().putBullet(this.type, this.node);
}
}
| f5d58bad82df28f38d7c68556d019515955baf60 | [
"Markdown",
"TypeScript"
] | 28 | TypeScript | dreamsxin/cocos-GeometryWar | 77d15713c882c72f53d738b5a0731d41aa12fe74 | ba994bb137f3c60b78457849bdd5e72366fa0f18 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xam.Plugin.TabView;
using Xamarin.Forms;
namespace TabViewSample
{
public partial class MainPage : ContentPage
{
TabViewControl tabView;
public MainPage()
{
InitializeComponent();
tabView = new TabViewControl(new List<TabItem>()
{
new TabItem("Tab 1", new Label{Text = "Tab 1", HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Red}),
new TabItem("Tab 2", new Label{Text = "Tab 2", HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Green}),
new TabItem("Tab 3", new Label{Text = "Tab 3", HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Blue}),
});
tabView.VerticalOptions = LayoutOptions.FillAndExpand;
theSl.Children.Add(tabView);
tabView.PositionChanged += TabView_PositionChanged;
tabView.PositionChanging += TabView_PositionChanging; ;
}
private void TabView_PositionChanging(object sender, PositionChangingEventArgs e)
{
}
private void TabView_PositionChanged(object sender, PositionChangedEventArgs e)
{
}
private void Button_Next(object sender, EventArgs e)
{
tabView.SelectNext();
}
private void Button_First(object sender, EventArgs e)
{
tabView.SelectFirst();
}
private void Button_Previous(object sender, EventArgs e)
{
tabView.SelectPrevious();
}
private void Button_Last(object sender, EventArgs e)
{
tabView.SelectLast();
}
private void Button_AddTab(object sender, EventArgs e)
{
tabView.AddTab(new TabItem("New", new Label { Text = "New", HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Red }));
}
private void Button_RemoveLastTab(object sender, EventArgs e)
{
tabView.RemoveTab(tabView.ItemSource.Count - 1);
}
private void Button_ChangeTextColor(object sender, EventArgs e)
{
tabView.HeaderTabTextColor = tabView.HeaderTabTextColor == Color.LightGreen ? Color.White : Color.LightGreen;
}
private void Button_ChangeSelectionUnderlineColor(object sender, EventArgs e)
{
tabView.HeaderSelectionUnderlineColor = tabView.HeaderSelectionUnderlineColor == Color.Yellow ? Color.White : Color.Yellow;
}
private void Button_ChangeSelectionUnderlineThickness(object sender, EventArgs e)
{
tabView.HeaderSelectionUnderlineThickness = tabView.HeaderSelectionUnderlineThickness + 5;
}
private void Button_ChangeSelectionUnderlineWidth(object sender, EventArgs e)
{
tabView.HeaderSelectionUnderlineWidth = tabView.HeaderSelectionUnderlineWidth + 10;
}
private void Button_ChangeTabTextFontSize(object sender, EventArgs e)
{
tabView.HeaderTabTextFontSize = tabView.HeaderTabTextFontSize + 1;
}
private void Button_ChangeTabTextFontAttributes(object sender, EventArgs e)
{
tabView.HeaderTabTextFontAttributes = tabView.HeaderTabTextFontAttributes == FontAttributes.Bold ? FontAttributes.Italic : FontAttributes.Bold;
}
private void Button_ChangeTabTextFontFamily(object sender, EventArgs e)
{
tabView.HeaderTabTextFontFamily = tabView.HeaderTabTextFontFamily == "Droid Sans Mono" ? "Comic Sans MS" : "Droid Sans Mono";
}
private async void GoToXamlSample(object sender, EventArgs e)
{
await Navigation.PushAsync(new XamlSamplePage());
}
}
} | c1f1deafab367f2c53f03ac0394b0c3f98482c39 | [
"C#"
] | 1 | C# | fperez2511/TabView | 5a9581458f89969a0449eecfb38c6216d7d794a2 | 83d27d63157046d77c9fdc88b6e8053dbd17aa18 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayHitInfo {
public GameObject gameObject;
public Vector3 point;
}
public class CameraManager : MonoBehaviour {
public static CameraManager instance = null;
[HideInInspector]
public Camera worldCamera;
private void Awake() {
if (instance == null) {
instance = this;
} else {
Destroy(this.gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
worldCamera = GetComponentInChildren<Camera>();
}
void Start(){
}
void Update(){
/*if (Input.GetMouseButtonDown(0)) {
RayHitInfo info = GetRayHitInfo();
if (info != null) {
Debug.Log("Hit " + info.gameObject + " at point " + info.point);
}
}*/
}
public RayHitInfo GetRayHitInfo() {
RayHitInfo hitInfo = null;
Ray ray = worldCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000)) {
if (hit.transform == null)
return null;
hitInfo = new RayHitInfo();
hitInfo.gameObject = hit.transform.gameObject;
hitInfo.point = hit.point;
return hitInfo;
}
return null;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PawnHealthBar : MonoBehaviour {
[HideInInspector]
public Pawn pawn;
[HideInInspector]
public Transform lookatObject;
public Transform mask;
private void FixedUpdate() {
if (lookatObject == null) {
lookatObject = CameraManager.instance.worldCamera.transform;
}
transform.LookAt(lookatObject);
SetHealth();
}
void SetHealth() {
float health = 100;
float baseHealth = 100;
if (pawn != null) {
health = pawn.Health;
baseHealth = pawn.BaseHealth;
}
float normalizedHealth = health / baseHealth;
normalizedHealth = Mathf.Clamp(normalizedHealth, 0, 1);
Vector3 scale = mask.transform.localScale;
scale.x = normalizedHealth;
mask.transform.localScale = scale;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PawnManager : MonoBehaviour {
public static WaitForSeconds spawnDelay = new WaitForSeconds(0.3f);
public static PawnManager instance = null;
private void Awake() {
if (instance == null) {
instance = this;
} else {
Destroy(this.gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
}
public Transform pawnsContainer;
public Pawn gruntObject;
public Pawn tankObject;
public Pawn sprintlingObject;
public List<Pawn> alivePawns = new List<Pawn>();
public void SpawnGrunt() {
Pawn pawn = InstantiatePawn(gruntObject);
pawn.StartMoving();
alivePawns.Add(pawn);
}
public void SpawnTank() {
Pawn pawn = InstantiatePawn(tankObject);
pawn.StartMoving();
alivePawns.Add(pawn);
}
public void SpawnSprintling() {
Pawn pawn = InstantiatePawn(sprintlingObject);
pawn.StartMoving();
alivePawns.Add(pawn);
}
public void ClearPawns() {
foreach (Pawn p in pawnsContainer.GetComponentsInChildren<Pawn>()) {
if (p != null) {
Destroy(p.gameObject);
}
}
alivePawns.Clear();
}
public Pawn InstantiatePawn(Pawn pawn) {
Pawn p = Instantiate(pawn, pawnsContainer);
p.Init();
p.agent.Warp(LevelManager.instance.currentLevel.StartPoint.position);
p.gameObject.SetActive(true);
p.moveTarget = LevelManager.instance.currentLevel.EndPoint;
return p;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Pawn", menuName = "Pawns/Pawn", order = 1)]
public class PawnInfo : ScriptableObject {
public int Health = 100;
public int ScoreAmount = 50;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class GameManager : MonoBehaviour {
public static GameManager instance = null;
private void Awake() {
if (instance == null) {
instance = this;
} else {
Destroy(this.gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
#if UNITY_STANDALONE
quitButton.gameObject.SetActive(true);
#endif
}
private void Start() {
OpenPlay();
}
[SerializeField]
private TextMeshProUGUI LivesAmountText;
[SerializeField]
private Button GruntButton;
[SerializeField]
private Button TankButton;
[SerializeField]
private Button SprintlingButton;
public GameObject MenuScene;
public RectTransform BG;
public RectTransform Play;
public RectTransform BuyUI;
public RectTransform Levels;
public RectTransform LevelResult;
public RectTransform quitButton;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI bestScoreText;
public TextMeshProUGUI levelIndexText;
public int GruntCost = 2;
public int TankCost = 5;
public int SprintlingCost = 1;
private int lives = 0;
public void OpenBuyUI() {
BG.gameObject.SetActive(false);
Play.gameObject.SetActive(false);
BuyUI.gameObject.SetActive(true);
Levels.gameObject.SetActive(false);
LevelResult.gameObject.SetActive(false);
}
public void OpenLevels() {
BG.gameObject.SetActive(true);
Play.gameObject.SetActive(false);
BuyUI.gameObject.SetActive(false);
Levels.gameObject.SetActive(true);
LevelResult.gameObject.SetActive(false);
}
public void OpenPlay() {
Level[] levels = FindObjectsOfType<Level>();
for (int i = 0; i < levels.Length; i++) {
levels[i].RemoveLevel();
}
BG.gameObject.SetActive(true);
Play.gameObject.SetActive(true);
BuyUI.gameObject.SetActive(false);
Levels.gameObject.SetActive(false);
LevelResult.gameObject.SetActive(false);
MenuScene.SetActive(true);
}
public void OpenLevelResults(int score, int bestScore) {
levelIndexText.text = "Completed Level " + LevelManager.instance.currentLevel.LevelIndex;
scoreText.text = "Score: " + score;
bestScoreText.text = "Best: " + bestScore;
BG.gameObject.SetActive(true);
Play.gameObject.SetActive(false);
BuyUI.gameObject.SetActive(false);
Levels.gameObject.SetActive(false);
LevelResult.gameObject.SetActive(true);
PawnManager.instance.ClearPawns();
}
public void PressedQuit() {
#if UNITY_WEBGL || UNITY_ANDROID || UNITY_IOS
return;
#endif
Application.Quit();
}
public void OpenLevel(int levelIndex) {
BG.gameObject.SetActive(false);
Play.gameObject.SetActive(false);
BuyUI.gameObject.SetActive(false);
Levels.gameObject.SetActive(false);
LevelResult.gameObject.SetActive(false);
CameraManager.instance.transform.localPosition = Vector3.zero;
LevelManager.instance.LoadLevel(levelIndex);
MenuScene.SetActive(false);
}
public void PressedGruntButton() {
TakeLives(GruntCost);
PawnManager.instance.SpawnGrunt();
}
public void PressedTankButton() {
TakeLives(TankCost);
PawnManager.instance.SpawnTank();
}
public void PressedSprintlingButton() {
TakeLives(SprintlingCost);
PawnManager.instance.SpawnSprintling();
}
public void CheckIfLost() {
if (Lives > 0)
return;
if (PawnManager.instance.alivePawns.Count > 0)
return;
OpenPlay();
}
public void TakeLives(int amount) {
Lives -= amount;
}
public int Lives {
get {
return lives;
}
set {
lives = value;
lives = Mathf.Clamp(lives, 0, LevelManager.instance.currentLevel.StartLives);
LivesAmountText.text = "" + lives;
GruntButton.interactable = lives >= GruntCost;
GruntButton.GetComponentsInChildren<TextMeshProUGUI>()[1].text = "cost: " + GruntCost;
TankButton.interactable = lives >= TankCost;
TankButton.GetComponentsInChildren<TextMeshProUGUI>()[1].text = "cost: " + TankCost;
SprintlingButton.interactable = lives >= SprintlingCost;
SprintlingButton.GetComponentsInChildren<TextMeshProUGUI>()[1].text = "cost: " + SprintlingCost;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Checkpoint : MonoBehaviour {
public enum CheckpointType {
Start, End
}
public CheckpointType type;
public LayerMask pawnLayer;
private bool won = false;
private void OnDrawGizmos() {
if (type == CheckpointType.Start) {
Gizmos.color = new Color(0.2f, 0.3f, 1, 0.2f);
} else {
Gizmos.color = new Color(1f, 0.3f, 0.2f, 0.2f);
}
Gizmos.DrawSphere(transform.position, 0.5f);
}
private void OnTriggerEnter(Collider other) {
if (type != CheckpointType.End)
return;
if (other.transform.parent.tag == "Pawn") {
other.gameObject.SetActive(false);
Win();
}
}
public void Win() {
if (won)
return;
won = true;
Level level = LevelManager.instance.currentLevel;
int score = level.CalculateScore();
int bestScore = level.GetBestScore();
GameManager.instance.OpenLevelResults(score, bestScore);
}
}
<file_sep>using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sentry : MonoBehaviour {
private WaitForSeconds attackRate;
private List<Transform> targetsInRange = new List<Transform>();
public SentryInfo SentryInfo;
public Transform RotateTransform;
public Transform FireTransform;
public SentryBullet SentryBulletPrefab;
[HideInInspector]
public Transform currentTarget;
[HideInInspector]
public Pawn currentPawnTarget;
public LayerMask attackables;
public void Start() {
StartCoroutine(AttackRoutine());
attackRate = new WaitForSeconds(SentryInfo.attackRate);
}
public IEnumerator AttackRoutine() {
bool attacking = true;
while (attacking) {
TryFire();
yield return attackRate;
}
}
public void Update() {
targetsInRange.Clear();
bool currentTargetOutOfReach = true;
Collider[] colliders = Physics.OverlapSphere(this.transform.position, SentryInfo.Range, attackables);
if (colliders != null && colliders.Length > 0) {
for (int i = 0; i < colliders.Length; i++) {
targetsInRange.Add(colliders[i].transform);
if (CurrentTarget != null && CurrentTarget == colliders[i].transform) {
currentTargetOutOfReach = false;
}
}
}
if (targetsInRange.Count == 0) {
CurrentTarget = null;
SmoothLook(null);
return;
}
if (CurrentTarget == null) {
SelectTarget();
} else {
if (currentTargetOutOfReach) {
CurrentTarget = null;
SelectTarget();
} else {
if (currentPawnTarget.Dead) {
currentTarget = null;
SelectTarget();
}
}
}
if (CurrentTarget != null) {
SmoothLook(CurrentTarget);
}
}
public void SmoothLook(Transform target) {
if (target == null) {
Quaternion rot = RotateTransform.localRotation;
rot = Quaternion.Lerp(rot, Quaternion.identity, 10 * Time.deltaTime);
RotateTransform.localRotation = rot;
} else {
Quaternion oldRot = RotateTransform.localRotation;
RotateTransform.LookAt(CurrentTarget);
Quaternion newRot = RotateTransform.localRotation;
Quaternion rot = Quaternion.Lerp(oldRot, newRot, 10 * Time.deltaTime);
RotateTransform.localRotation = rot;
}
}
public void TryFire() {
if (CurrentTarget == null) {
return;
}
SentryBullet sb = Instantiate(SentryBulletPrefab, this.transform);
sb.SetPositions(FireTransform.position, currentPawnTarget.transform.position);
currentPawnTarget.Health -= SentryInfo.Damage;
}
public void SelectTarget() {
List<Transform> candidates = SortListByRandom(targetsInRange);
CurrentTarget = candidates[0];
}
public List<Transform> SortListByRandom(List<Transform> list) {
List<Transform> dupList = new List<Transform>(list);
for (int i = 0; i < dupList.Count; i++) {
Transform temp = dupList[i];
int randomIndex = Random.Range(i, dupList.Count);
dupList[i] = dupList[randomIndex];
dupList[randomIndex] = temp;
}
return dupList;
}
public List<Transform> SortListByDistance(List<Transform> list) {
List<Transform> dupList = new List<Transform>(list);
return dupList;
}
public Transform CurrentTarget {
get {
return currentTarget;
}
set {
currentTarget = value;
if (value == null) {
currentPawnTarget = null;
} else {
currentPawnTarget = currentTarget.GetComponentInParent<Pawn>();
}
}
}
public void OnDrawGizmosSelected() {
if (SentryInfo != null) {
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, SentryInfo.Range);
}
Gizmos.color = Color.cyan;
foreach (Transform target in targetsInRange) {
if (target == null)
continue;
Gizmos.DrawLine(transform.position, target.position);
}
if (currentTarget != null) {
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, currentTarget.position);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SentryBullet : MonoBehaviour {
private static WaitForSeconds lifetime = new WaitForSeconds(0.05f);
public LineRenderer LineRenderer;
public void SetPositions(Vector3 position0, Vector3 position1) {
LineRenderer.positionCount = 2;
LineRenderer.SetPosition(0, position0);
LineRenderer.SetPosition(1, position1);
StartCoroutine(DelayedDestroy());
}
IEnumerator DelayedDestroy() {
yield return lifetime;
Destroy(this.gameObject);
}
}
<file_sep>## Ludum Dare 44
## Spec inveders
* [Play here](https://aerosolswe.github.io/LD44-Spec-inveders/index.html)
### General idea:
Wow, people took our lands. We take back.
### Art:
3D and some 2D art, by me.. Sadly I didnt have time enough to make it more diverse or interesting.
### Sound fx & music:
None, sorry
### World story:
They came and took our land. Now we make stand and take back!
### Game mechanics:
Tower defense.. Except reversed. :)
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour {
private Camera cam;
public bool grabbed = false;
private Vector2 mousePos = new Vector2();
private Vector3 velocity = new Vector3();
public float dragSpeed = 1;
private Vector3 dragOrigin;
private void Start() {
cam = CameraManager.instance.worldCamera;
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
dragOrigin = GetMousePosition();
grabbed = true;
return;
}
if (Input.GetMouseButtonUp(0)) {
grabbed = false;
}
if (grabbed) {
Vector3 pos = Camera.main.ScreenToViewportPoint(GetMousePosition() - dragOrigin);
velocity = new Vector3(-pos.x * dragSpeed, 0, -pos.y * dragSpeed);
dragOrigin = GetMousePosition();
}
transform.Translate(velocity, Space.World);
velocity = Vector3.Lerp(velocity, Vector3.zero, 10 * Time.deltaTime);
/*if (Input.GetMouseButtonDown(0)) {
grabbed = true;
mousePos = GetMousePosition();
}
if (Input.GetMouseButtonUp(0)) {
grabbed = false;
}
Vector2 mouseDelta = new Vector2();
if (grabbed) {
Vector2 mPos = GetMousePosition();
mouseDelta = mPos - mousePos;
Debug.Log(mouseDelta);
mousePos = mPos;
}
velocity.x -= mouseDelta.x * Time.deltaTime;
velocity.z -= mouseDelta.y * Time.deltaTime;
Vector3 pos = transform.position;
pos += velocity;
transform.position = pos;
velocity = Vector3.Lerp(velocity, Vector3.zero, 10 * Time.deltaTime);*/
}
Vector3 GetMousePosition() {
Vector2 mousePos = Input.mousePosition;
//Vector3 worldMousePos = cam.screen
return mousePos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level : MonoBehaviour {
public Transform StartPoint;
public Transform EndPoint;
public int LevelIndex = 0;
public int StartLives = 10;
private void Start() {
LevelManager.instance.currentLevel = this;
GameManager.instance.Lives = StartLives;
PawnManager.instance.alivePawns.Clear();
GameManager.instance.OpenBuyUI();
}
public int CalculateScore() {
int livesLeft = GameManager.instance.Lives;
int pawnsAliveScore = 0;
foreach (Pawn p in PawnManager.instance.alivePawns) {
pawnsAliveScore += p.pawnInfo.ScoreAmount;
}
int livesLeftScore = 100 * livesLeft;
int score = pawnsAliveScore + livesLeftScore;
if (score > GetBestScore()) {
PlayerPrefs.SetInt("LEVEL" + LevelIndex + "_HS", score);
PlayerPrefs.Save();
}
return score;
}
public int GetBestScore() {
return PlayerPrefs.GetInt("LEVEL" + LevelIndex + "_HS", 0);
}
public void RemoveLevel() {
UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync("Level" + LevelIndex);
Destroy(this.gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Sentry", menuName = "Sentries/Sentry", order = 1)]
public class SentryInfo : ScriptableObject {
public int Damage = 25;
public float Range = 3;
public float attackRate = 0.3f;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Pawn : MonoBehaviour {
public PawnInfo pawnInfo;
public PawnHealthBar healthBar;
public Animator animator;
[HideInInspector]
public NavMeshAgent agent;
[HideInInspector]
public Transform moveTarget;
private int health;
private bool playedDeathAnimation = false;
public void Init() {
Health = BaseHealth;
healthBar.pawn = this;
}
private void Update() {
float speed = agent.velocity.magnitude;
float normalizedSpeed = speed / agent.speed;
normalizedSpeed = Mathf.Clamp(normalizedSpeed, 0, 1);
animator.SetFloat("SpeedModifier", normalizedSpeed);
}
public void StartMoving() {
MoveToPoint(moveTarget.position);
}
public void MoveToPoint(Vector3 point) {
agent.destination = point;
}
public void Die() {
if (playedDeathAnimation) {
return;
}
playedDeathAnimation = true;
PawnManager.instance.alivePawns.Remove(this);
Destroy(this.gameObject);
GameManager.instance.CheckIfLost();
}
public int BaseHealth {
get {
return pawnInfo.Health;
}
}
public int Health {
get {
return health;
}
set {
health = value;
if (health <= 0) {
health = 0;
Die();
}
}
}
public bool Dead {
get {
return Health <= 0;
}
}
}
| 429aad7409026810abbdb6707e91e89ab4dd5029 | [
"Markdown",
"C#"
] | 13 | C# | aerosolswe/LD44-Spec-inveders | 0d303b34523411e1cafca319571170378d62b5fd | 283e6c2ba53749885ae10edb2549ba8a825e74dd |
refs/heads/master | <repo_name>manyaginm/weather<file_sep>/src/main/java/ru/manyagin/Senders/ForecastTopicListener.java
package ru.manyagin.Senders;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import ru.manyagin.DAO.YahooForecastDAO;
import ru.manyagin.Interfaces.Forecast;
import ru.manyagin.Interfaces.ForecastsDAO;
import javax.jms.*;
/**
* Created by MManiagin on 14.06.2017.
*/
@Component(value = "forecastTopicListener")
public class ForecastTopicListener implements MessageListener {
@Autowired
ForecastsDAO dao;
public void onMessage(Message message) {
System.out.println("Receiver");
ObjectMessage msg = (ObjectMessage) message;
try{
Forecast forecast = (Forecast) msg.getObject();
dao.saveForecast(forecast);
System.out.println("MESSAGE: " + forecast.toString());
}catch (JMSException e){
e.printStackTrace();
}catch(ConstraintViolationException e){
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/ru/manyagin/Controllers/RestController.java
package ru.manyagin.Controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import ru.manyagin.Forecasts.YahooForecastImpl.YahooDailyWeather;
import ru.manyagin.Forecasts.YahooForecastImpl.YahooForecastImpl;
import ru.manyagin.Forecasts.YahooForecastImpl.YahooWeatherWrapper;
import ru.manyagin.Interfaces.ForecastsDAO;
import ru.manyagin.Interfaces.JMSSender;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Created by MManiagin on 20.06.2017.
*/
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
JMSSender sender;
@Autowired
ForecastsDAO dao;
@Autowired
YahooForecastImpl impl;
@RequestMapping(method = RequestMethod.GET, value = "/forecasts/{city}")
public ResponseEntity getForecastfromDB(ModelAndView modelAndView, @PathVariable String city) throws ParseException {
List<YahooWeatherWrapper> list = dao.getForecast(city);
return new ResponseEntity(list, HttpStatus.OK);
}
}
<file_sep>/src/test/java/ru/manyagin/Connectors/testYahooConnector.java
package ru.manyagin.Connectors;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import ru.manyagin.Conectors.YahooConnector;
import ru.manyagin.Forecasts.YahooForecastImpl.YahooForecastImpl;
/**
* Created by MManiagin on 22.06.2017.
*/
public class testYahooConnector {
YahooForecastImpl impl;
YahooConnector conn = new YahooConnector();
@Test
public void getForecastTest(){
impl = (YahooForecastImpl) conn.getForecast("saratov");
Assert.assertEquals("Saratov", impl.getCity());
Assert.assertEquals("Russia", impl.getCountry());
Assert.assertEquals(" Saratov Oblast", impl.getRegion());
}
@Test
public void testNull(){
impl = (YahooForecastImpl) conn.getForecast("Moscow");
Assert.assertNotSame("Saratov", impl.getCity());
Assert.assertNotSame("Russia", impl.getCountry());
Assert.assertNotSame(" Saratov Oblast", impl.getRegion());
}
}
| 37d140d8758365d86099e06f67b8edfed91bb4a1 | [
"Java"
] | 3 | Java | manyaginm/weather | 774f3ddb4c8ada64b5b2ed47f90289d317fbcff2 | 99155a268b1b3a99eb4a694ead61c28b9c75a3fe |
refs/heads/master | <repo_name>sunjiajia/AlphaGOZero-python-tensorflow<file_sep>/model/AVP_MCTS.py
import copy
import math
import sys
import time
import numpy as np
import utils.go as go
from utils.features import extract_features,bulk_extract_features
from multiprocessing import Pool
from numpy.random import gamma
# All terminology here (Q, U, N, p_UCT) uses the same notation as in the
# AlphaGo paper.
# Exploration constant
c_PUCT = 5
def split(a, n):
'''
Example:
>>> list(split(range(11), 3))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
'''
k, m = divmod(len(a), n)
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))
class MCTSNode():
'''
A MCTSNode has two states: plain, and expanded.
An plain MCTSNode merely knows its Q + U values, so that a decision
can be made about which MCTS node to expand during the selection phase.
When expanded, a MCTSNode also knows the actual position at that node,
as well as followup moves/probabilities via the policy network.
Each of these followup moves is instantiated as a plain MCTSNode.
'''
@staticmethod
def root_node(position, move_probabilities):
node = MCTSNode(None, None, 0)
node.position = position
node.expand(move_probabilities)
return node
def __init__(self, parent, move, prior):
self.parent = parent # pointer to another MCTSNode
self.move = move # the move that led to this node
self.prior = prior
self.position = None # lazily computed upon expansion
self.children = {} # map of moves to resulting MCTSNode
self.Q = self.parent.Q if self.parent is not None else 0 # average of all outcomes involving this node
self.U = prior # monte carlo exploration bonus
self.N = 0 # number of times node was visited
def __repr__(self):
return "<AVPMCTSNode move=%s prior=%s score=%s is_expanded=%s>" % (self.move, self.prior, self.action_score, self.is_expanded())
@property
def action_score(self):
return self.Q + self.U
@property
def action_score_dirichlet(self):
# new_prior = (1-epsilon)*prior+epsilon*gamma(alpha)
alpha,ep=0.03,0.25
return self.Q + self.U * ((1-ep)+ep*gamma(alpha)/(self.prior+1e-8))
def is_expanded(self):
return self.position is not None
def compute_position(self):
self.position = self.parent.position.play_move(self.move)
return self.position
def expand(self, move_probabilities):
self.children = {move: MCTSNode(self, move, prob)
for move, prob in np.ndenumerate(move_probabilities)}
# Pass should always be an option! Say, for example, seki.
self.children[None] = MCTSNode(self, None, 0)
def backup_value(self, value):
'''
Since Python lacks Tail Call Optimization(TCO)
use while loop to reduce the burden of a huge stack
'''
while True:
self.N += 1
if self.parent is None:
return
self.Q, self.U = (
self.Q + (value - self.Q) / self.N,
c_PUCT * math.sqrt(self.parent.N) * self.prior / self.N,
) # notice sum(all children's N) == parent's N
# must invert, because alternate layers have opposite desires
value *= -1
self = self.parent
def select_leaf(self):
current = self
while current.is_expanded():
current = max(current.children.values(), key=lambda node: node.action_score)
return current
def select_leaf_dirichlet(self):
current = self
while current.is_expanded():
current = max(current.children.values(), key=lambda node: node.action_score_dirichlet)
return current
class MCTSPlayerMixin:
def __init__(self, policy_network, seconds_per_move=5):
self.policy_network = policy_network
self.seconds_per_move = seconds_per_move
self.max_rollout_depth = go.N * go.N * 3
super().__init__()
def suggest_move(self, position):
start = time.time()
move_probs = self.policy_network.run(extract_features(position))
root = MCTSNode.root_node(position, move_probs)
while time.time() - start < self.seconds_per_move:
self.multi_tree_search(root,iters=1)
print("Searched for %s seconds" % (time.time() - start), file=sys.stderr)
sorted_moves = sorted(root.children.keys(), key=lambda move, root=root: root.children[move].N, reverse=True)
for move in sorted_moves:
if is_move_reasonable(position, move):
return move
return None
def multi_tree_search(self, root, iters=1600):
print("tree search", file=sys.stderr)
pool = Pool()
# selection
results = [None]*iters
chosen_leaves = []
select = lambda root:root.select_leaf_dirichlet()
for i in range(iters):
results.append(pool.apply_async(select,args=(root,)))
for i in range(iters):
chosen_leaf = results[i].get()
position = chosen_leaf.compute_position()
if position is None:
print("illegal move!", file=sys.stderr)
# See go.Position.play_move for notes on detecting legality
del chosen_leaf.parent.children[chosen_leaf.move]
continue
chosen_leaves.append(chosen_leaf)
print("Investigating following position:\n%s" % (chosen_leaf.position,), file=sys.stderr)
# evaluation
expand = lambda leaf,probs:leaf.expand(probs)
backup = lambda leaf,value:leaf.backup_value(value)
for batch in list(split(range(len(chosen_leaves)),8)):
batch_leaves = [chosen_leaves[i] for i in batch]
leaf_positions = [batch_leaves[i].position for i in range(len(batch_leaves))]
move_probs,values = self.policy_network.evaluate_node(bulk_extract_features(leaf_positions,dihedral=True))
perspective = []
for leaf_position in leaf_positions:
perspective = 1 if leaf_position.to_play == root.position.to_play else -1
perspectives.append(perspective)
values = values*np.asarray(perspectives)
# expansion & backup
pool.map(expand,zip(batch_leaves,move_probs))
pool.map(backup,zip(batch_leaves,values))
for i in range(len(batch_leaves)):
#batch_leaves[i].expand(move_probs[i])
print("value: %s" % values[i], file=sys.stderr)
#batch_leaves[i].backup_value(values[i])
pool.close()
pool.join()
sys.stderr.flush()
| b084cb4c8e33731dbb387cc1ef5a3596506b822f | [
"Python"
] | 1 | Python | sunjiajia/AlphaGOZero-python-tensorflow | ee1d9567c9680c45f74efbfdf06ec37b8bb70d10 | ca601b9de67e011f76175db75b7c0483b2e195ba |
refs/heads/master | <file_sep>class CohortsController < ApplicationController
before_action :authenticate_admin!
def index
@cohorts = Cohort.all
end
def new
@cohort = Cohort.new
end
def show
@cohort = Cohort.find(params[:id])
@students = Cohort.find(params[:id]).students
end
def create
@cohort = Cohort.new(cohort_params)
if @cohort.save
redirect_to '/cohorts'
end
end
def edit
@cohort = Cohort.find(params[:id])
end
def update
@cohort = Cohort.find(params[:id])
if @cohort.update(cohort_params)
redirect_to '/cohorts'
else
render 'edit'
end
end
def destroy
@cohort = Cohort.find(params[:id])
@cohort.delete
redirect_to '/cohorts'
end
private
def cohort_params
params.require(:cohort).permit(:title, :start_date, :end_date, :instructor_id, :course_id)
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Instructor.create(firstname: 'Yagi', lastname: 'Toshinori', postion:'Heroics Teacher', quirk: 'One For All', age:28 , salary:25000 ,education:'College');
Instructor.create(firstname: 'Aizawa', lastname: 'Shota', postion:'Homeroom Teacher', quirk: 'Erasure', age:28 , salary:25000 ,education:'Masters');
Instructor.create(firstname: 'Yamada', lastname: 'Hizashi', postion:'English Teacher', quirk: 'Voice', age:28 , salary:25000 ,education:'Masters');
Instructor.create(firstname: 'Ekuto', lastname: 'Purazumu', postion:'Mathematics Teacher', quirk: 'Clones', age:30 , salary:25000 ,education:'College');
Instructor.create(firstname: 'Ishiyama', lastname: 'Ken', postion:'Modern Literature', quirk: 'Cement', age:30 , salary:25000 ,education:'Masters');
Instructor.create(firstname: 'Magima', lastname: 'Higari', postion:'Development Studio Head', quirk: 'Iron Claws', age:25 , salary:25000 ,education:'PHD');
Instructor.create(firstname: 'Kayama', lastname: 'Nemuri', postion:'Head of Management', quirk: 'Somnambulist', age:25 , salary:25000 ,education:'PHD');
Course.create(title: 'Heroics Course', hours: 600);
Course.create(title: 'General Education Course', hours: 400);
Course.create(title: 'Support Course', hours: 300);
Course.create(title: 'Management Course', hours: 300);
Cohort.create(title: "Identity Course", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 1, course_id: 1);
Cohort.create(title: "Rescue Course", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 2, course_id: 1);
Cohort.create(title: "Power Course", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 1, course_id: 1);
Cohort.create(title: "English 101", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 3, course_id: 2);
Cohort.create(title: "Mathematics 101", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 4, course_id: 2);
Cohort.create(title: "Modern Literature 101", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 5, course_id: 2);
Cohort.create(title: "Costume Design", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 6, course_id: 3);
Cohort.create(title: "Costume Developer", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 6, course_id: 3);
Cohort.create(title: "Management 101", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 7, course_id: 4);
Cohort.create(title: "Management 102", start_date: Faker::Date.backward(100) , end_date: Faker::Date.forward(100), instructor_id: 7, course_id: 4);
Student.create(firstname: 'Izuku', lastname: 'Midoria', quirk: 'One For All', cohort_id: 1, age: 15);
Student.create(firstname: 'Shoto', lastname: 'Todoroki', quirk: 'Half-Cold Half-Hot', cohort_id: 1, age: 15);
Student.create(firstname: 'Katsuki', lastname: 'Bakugo', quirk: 'Explosion', cohort_id: 1, age: 15);
Student.create(firstname: 'Ochaco', lastname: 'Uraraka', quirk: 'Zero Gravity', cohort_id: 1, age: 15);
Student.create(firstname: 'Tenya', lastname: 'Iida', quirk: 'Engine', cohort_id: 1, age: 15);
Student.create(firstname: 'Tsuyu', lastname: 'Asui', quirk: 'Frog',cohort_id: 2, age: 15);
Student.create(firstname: 'Mina', lastname: 'Ashido', quirk: 'Acid',cohort_id: 2, age: 15);
Student.create(firstname: 'Yuga', lastname: 'Aoyama', quirk: 'Navel Laser',cohort_id: 2, age: 15);
Student.create(firstname: 'Mashirao', lastname: 'Ojiro', quirk: 'Tail',cohort_id: 2, age: 15);
Student.create(firstname: 'Denki', lastname: 'Kaminari', quirk: 'Electrification',cohort_id: 2, age: 15);
Student.create(firstname: 'Eijiro', lastname: 'Kirishima', quirk: 'Hardening',cohort_id: 3, age: 15);
Student.create(firstname: 'Koji', lastname: 'Koda', quirk: 'Anivoice', cohort_id: 3, age: 15);
Student.create(firstname: 'Rikido', lastname: 'Sado', quirk: 'Sugar Rush',cohort_id: 4, age: 15);
Student.create(firstname: 'Mezo', lastname: 'Shoji', quirk: 'Dupli-Arms',cohort_id: 4, age: 15);
Student.create(firstname: 'Kyoka', lastname: 'Jiro', quirk: 'Earphone Jack',cohort_id: 5, age: 15);
Student.create(firstname: 'Hanata', lastname: 'Sero', quirk: 'Tape',cohort_id: 5, age: 15);
Student.create(firstname: 'Fumikage', lastname: 'Tokoyami', quirk: 'Dark Shadow',cohort_id: 6, age: 15);
Student.create(firstname: 'Toru', lastname: 'Hagakure', quirk: 'Invisible',cohort_id: 6, age: 15);
Student.create(firstname: 'Minoru', lastname: 'Minata', quirk: 'Pop Off', cohort_id: 7, age: 15);
Student.create(firstname: 'Momo', lastname: 'Yaoyorozu', quirk: 'Creation',cohort_id: 7, age: 15);
Student.create(firstname: 'Itsuka', lastname: 'Kendo', quirk: 'Big Fist',cohort_id: 8, age: 15);
Student.create(firstname: 'Ibara', lastname: 'Shiozaki', quirk: 'Vines', cohort_id: 8, age: 15);
Student.create(firstname: 'Shihai', lastname: 'Kuroiro', quirk: 'Black',cohort_id: 9, age: 15);
Student.create(firstname: 'Neito', lastname: 'Monoma', quirk: 'Copy',cohort_id: 9, age: 15);
Student.create(firstname: 'Juzo', lastname: 'Honenuki', quirk: 'Softening', cohort_id: 10, age: 15);
Student.create(firstname: 'Yosetsu', lastname: 'Awase', quirk: 'Weld',cohort_id: 10, age: 15);<file_sep>class Cohort < ActiveRecord::Base
belongs_to :course
belongs_to :instructor
has_many :students
end
<file_sep>class Instructor < ActiveRecord::Base
has_many :cohorts
end
<file_sep># UA Academy Admin Panel
## Goal
#### Fictitious school where the administrator can create users and complete common administrative tasks.
## Summary
#### This website is designed for administrators of a fictitious school, where all users have the same accesss and are able to add, edit, view, and delete courses, cohorts, instructors, and students.
## Deployment
#### Deployed Heroku link https://obscure-shelf-75373.herokuapp.com
### Login
#### Email: <EMAIL>
#### Password : <PASSWORD>
## Built With:
* Ruby
* Ruby on rails
* ActiveRecord
* PostgreSQL
* Deploying to Heroku
<file_sep>class WelcomeController < ApplicationController
before_action :authenticate_admin!
def index
@course_count = Course.count
@cohort_count = Cohort.count
@student_count = Student.count
@instructor_count = Instructor.count
end
end | 4bcf774c4627a0153e69a738d295f378c2bc1405 | [
"Markdown",
"Ruby"
] | 6 | Ruby | csherpa/ua_academy | ef64261e09ce254c395d9012902c2767c48e6cd6 | 44cd722a54c00dcc92cdcd5e9fb1b7977547af51 |
refs/heads/master | <repo_name>SJM541/RemD<file_sep>/SoilAndWeather.py
# Use SoilGrids and APIXU APIs to retrieve soil and recent weather for a location
#
# SoilGrids: Info at https://rest.soilgrids.org/query.html
# APIXU: info at https://www.apixu.com/doc/request.aspx
# Written for Python 3.5
# <NAME> 20/01/2017
# 02/2017 Tried aWhere for weather but unsuitable data model
# 02/2017 Added APIXU for weather, refactored and added work over date range
import sys
import requests
from pprint import pprint
from datetime import datetime, timedelta
def retrieveSoilGridsData(latitude,longitude):
domain = "rest.soilgrids.org"
route = "query"
url = "https://%s/%s" % (domain,route)
# Specify organic carbon and CEC only in response
#soilProperties = "ORCDRC,CEC"
#payload = {"lat" : latitude, "lon" : longitude, "attributes" : soilProperties }
payload = {"lat" : latitude, "lon" : longitude}
try:
response = requests.get(url, params = payload)
except requests.exceptions.ConnectionError as e:
print("Something wrong calling SoilGrids for soil data \n")
print (e)
sys.exit(1)
#print ("\n")
#print ("URL called: %s" % response.url)
#print ("HTTP Staus Code: %s " % response.status_code)
#print ("\n")
return(response.json())
def apixuWeather(latitude,longitude,date):
API_KEY = "<KEY>"
domain = "api.apixu.com/v1"
route = "history.json" #Alternatives are "current" and "forecast", also as xml
url = "http://%s/%s" % (domain,route)
location = "%s,%s" % (latitude,longitude)
payload = {"key" : API_KEY, "q" : location, "dt" : date}
try:
response = requests.get(url, params = payload)
except requests.exceptions.ConnectionError as e:
print("Something wrong calling APIXU for weather data \n")
print (e)
sys.exit(1)
#print ("\n")
#print ("URL called: %s" % response.url)
#print ("HTTP Staus Code: %s " % response.status_code)
#print ("\n")
return(response.json())
def main():
# Irish Hill, Kintbury
latitude = "51.399205"
longitude = "-1.424458"
# Get soil data
SoilGridsResponse = retrieveSoilGridsData(latitude,longitude)
#pprint(SoilGridsResponse)
# Parse out CEC at 0.1m (sl2)
CEC_10 = SoilGridsResponse['properties']['CECSOL']['M']['sl2']
units = SoilGridsResponse['properties']['CECSOL']['units_of_measure']
print (" \n CEC at 0.1m: %s %s" % (CEC_10, units))
# Get weather data
dayCount = 5
dates = []
now = datetime.now()
while dayCount > 0:
date = now - timedelta(dayCount)
strDate = date.strftime("%Y-%m-%d")
dates.append(strDate)
dayCount = dayCount - 1
totalPrecip = 0.0
for date in dates:
apixuResponse = apixuWeather(latitude, longitude, date)
#pprint(apixuResponse)
# Parse out total precipitation for the day
# NB "forecastday" is a list so needs an index to resolve
dayPrecip = apixuResponse['forecast']['forecastday'][0]["day"]['totalprecip_mm']
responseDate = apixuResponse['forecast']['forecastday'][0]["date"]
print (" \n Precipitation for %s: %.1f mm" % (responseDate, dayPrecip))
totalPrecip = totalPrecip+dayPrecip
print(" \n Total precipitation for the period was %.1f mm" % (totalPrecip))
if __name__ == "__main__":
main()
<file_sep>/tryExcelRead.py
# Tryout for reading pest-crop data from excel file
import pandas as pd
def main():
targetCountry='UK'
targetCrop = 'Cabbage'
fileName = 'C:/Users/marshalls/Documents/SJM/RemoteDiagnostics/ContextModel/Remote_Diagnostics_Data.xlsx'
locations = pd.read_excel(open(fileName,'rb'),sheetname='CPC_pest_location_model_data')
crops = pd.read_excel(open(fileName,'rb'),sheetname='CPC_crop-host_model_data')
# Create list of pests in the chosen country
countrySelection=[]
for index, row in locations.iterrows(): # Iterrows is a Genrator from Pandas
if row['Country'] == targetCountry:
countrySelection.append(row['Scientific name'])
print('countrySelection\n')
print(countrySelection)
# Create list of pests of the chosen crop and then place in a DataFrame
rowList=[]
for index, row in crops.iterrows():
if row['Crop'] == targetCrop:
rowList.append([row['Scientific'],row['Host Type']])
cropSelection = pd.DataFrame(rowList, columns=['Scientific name','Host Type'])
print('\n cropSelection \n')
print(cropSelection)
# get the intersection of the countrySelection and cropSelection based on scientific names
pestList=[]
for pest in countrySelection:
for index, row in cropSelection.iterrows():
if pest == row['Scientific name']:
pestList.append([row['Scientific name'],row['Host Type']])
pestsOfCropInCountry = pd.DataFrame(pestList, columns=['Scientific name','Host Type'])
print('Pests of %s in county %s \n' % (targetCrop, targetCountry))
print(pestsOfCropInCountry)
if __name__ == "__main__":
main()
<file_sep>/ContextModelV2.py
# ContextModelV2
# TO DO
# Presence or absesnce in country acts as hard filter but would like to
# apply a factor instead of exclude.
# Does not take any account of Major or Minor pest staus - just is or is not
# a pest of the crop. Add in this factor.
# Tidy up naming - some are clumsey
# Currently only uses preciptation data to set score
# Add in temperature and wind
import sys
import requests
from pprint import pprint
from datetime import datetime, timedelta
import pandas as pd
def retrieveSoilGridsData(latitude,longitude):
domain = "rest.soilgrids.org"
route = "query"
url = "https://%s/%s" % (domain,route)
# Specify organic carbon and CEC only in response
#soilProperties = "ORCDRC,CEC"
#payload = {"lat" : latitude, "lon" : longitude, "attributes" : soilProperties }
payload = {"lat" : latitude, "lon" : longitude}
try:
response = requests.get(url, params = payload)
except requests.exceptions.ConnectionError as e:
print("Something wrong calling SoilGrids for soil data \n")
print (e)
sys.exit(1)
return(response.json())
def soilData(latitude,longitude):
# Get soil data
# Return just CEC at 0.1m for now
#
# - will extend to return a DataFrame of all required soil data when known
SoilGridsResponse = retrieveSoilGridsData(latitude,longitude)
#pprint(SoilGridsResponse)
# Parse out CEC at 0.1m (sl2)
CEC_10 = SoilGridsResponse['properties']['CECSOL']['M']['sl2']
CEC_units = SoilGridsResponse['properties']['CECSOL']['units_of_measure']
# print (" \n CEC at 0.1m: %s %s" % (CEC_10, CEC_units))
return CEC_10
def apixuWeather(latitude,longitude,date):
API_KEY = "<KEY>"
domain = "api.apixu.com/v1"
route = "history.json" #Alternatives are "current" and "forecast", also as xml
url = "http://%s/%s" % (domain,route)
location = "%s,%s" % (latitude,longitude)
payload = {"key" : API_KEY, "q" : location, "dt" : date}
try:
response = requests.get(url, params = payload)
except requests.exceptions.ConnectionError as e:
print("Something wrong calling APIXU for weather data \n")
print (e)
sys.exit(1)
return(response.json())
def weatherData(latitude,longitude,numDays):
# Get weather data for today and previous <numDays> days
# For now, returns total precipitation and wet days, as a Dictionary
dayCount = numDays
dates = []
now = datetime.now()
while dayCount > 0:
date = now - timedelta(dayCount)
strDate = date.strftime("%Y-%m-%d")
dates.append(strDate)
dayCount = dayCount - 1
totalPrecip = 0.0
wetDays = 0
for date in dates:
apixuResponse = apixuWeather(latitude, longitude, date)
#pprint(apixuResponse)
# Parse out total precipitation for the day
# NB "forecastday" is a list so needs an index to resolve
dayPrecip = apixuResponse['forecast']['forecastday'][0]["day"]['totalprecip_mm']
responseDate = apixuResponse['forecast']['forecastday'][0]["date"]
#print (" \n Precipitation for %s: %.1f mm" % (responseDate, dayPrecip))
if dayPrecip > 0.0:
wetDays = wetDays+1
totalPrecip = totalPrecip+dayPrecip
# Force "Dry"
#wetDays = 0
#totalPrecip = 0.1
# Force "Wet"
#wetDays = 10
#totalPrecip = 50.0
weatherSummary = {'wetDays':wetDays, 'totalPrecip':totalPrecip}
#print(weatherSummary)
return weatherSummary
def assessWeather(summaryData):
# Takes summary weather data (for now just totalPrecip and wetDays)
# and returns assessment of wet, dry, hot and windy
# as a Dictionary of Boolean values
# These thresholds need careful consideration!
wetPrecipThreshold = 1.0 # "Wet" if more than n mm rain
wetDaysThreshold = 5 # and more than n wet days
dryPrecipThreshold = 0.5 # "Dry" if less than n mm rain
dryDaysThreshold = 0 # and less than n wet days
isWet = False
isDry = False
isHot = False
isWindy = False
if (summaryData['totalPrecip'] > wetPrecipThreshold)and(summaryData['wetDays'] > wetDaysThreshold):
isWet = True
if (summaryData['totalPrecip'] < dryPrecipThreshold)and(summaryData['wetDays'] <= dryDaysThreshold):
isDry = True
return ({'wet': isWet, 'dry': isDry, 'hot': isHot, 'windy': isWindy})
def scoreForCountry(locations,targetCountry):
inCountryScore = 1.5
notInCountryScore = 0.5
scoredPests = locations
# Create list of pests in the chosen country
countryScoreList=[]
for index, row in scoredPests.iterrows(): # Iterrows is a Generator from Pandas
if row['Country'] == targetCountry:
countryScoreList.append(inCountryScore)
else:
countryScoreList.append(notInCountryScore)
scoredPests['Country Score'] = countryScoreList
#print(scoredPests)
return scoredPests
def scoreForCrop(pests,crops,targetCrop):
majorCropScore = 1.5
minorCropScore = 1.2
notOnCropScore = 0.5
cropScoreDict={}
for index, row in crops.iterrows():
if row['Crop'] == targetCrop:
if(row['Host Type'] == 'Major'):
cropScoreDict[row['Scientific name']] = majorCropScore
elif(row['Host Type'] == 'Minor'):
cropScoreDict[row['Scientific name']] = minorCropScore
else:
cropScoreDict[row['Scientific name']] = notOnCropScore
print(cropScoreDict)
#cropScoreDF = pd.DataFrame.from_dict(data=cropScoreDict,orient='index')
#Below is more clumsey but provides column headings to use later in the merge
cropScoreDF = pd.DataFrame()
cropScoreDF['Scientific name'] = cropScoreDict.keys()
cropScoreDF['Crop Score'] = cropScoreDict.values()
print('\n crop score DF \n')
print(cropScoreDF)
# Innner join on cropSelection and countrySelection
cropAndCountryScores = pd.merge(cropScoreDF,pests,on='Scientific name',how='inner')
return cropAndCountryScores
def environmentalMultipliers(pests,crop,fileName):
# Takes DataFrame of pests and location of lookup data
# Returns a DataFrame of pests and their environmental multipliers
# NB Game_model_data table contains multiple entries for each pest organism
# because it is organised by crop and a pest may be of >1 crop
multipliers = pd.read_excel(open(fileName,'rb'),sheetname='Game_model_data')
# Inner join of pests and multipliers
# This gives multipliers for pests of crop, in country, but with multiple entries
# - see "NB" above
envMultipliers = pd.merge(pests,multipliers, on='Scientific name', how='inner')
# Filter again for crop
envCropMultipliers = envMultipliers[(envMultipliers.Crop == crop)]
return envCropMultipliers
def applyModelFactors(multipliers, weather):
# Takes a DataFrame of pests with model scores and a Dict of weather attributes
# Returns DataFrame of pest species and overall scores
isWet = weather['wet']
isDry = weather['dry']
isHot = weather['hot']
isWindy = weather['windy']
#isWet = False
#isDry = True
#isHot = True
#isWindy = True
scoreDict = {}
for index, row in multipliers.iterrows():
score = 1.0
if isWet:
score = score * row['Mwet']
if isDry:
score = score * row['Mdry']
if isHot:
score = score * row['Mhot']
if isWindy:
score = score * row['Mwind']
scoreDict[row['Scientific name']] = score
#print(scoreDict)
pestScores = pd.DataFrame.from_dict(data=scoreDict,orient='index')
return pestScores
def main():
# Setup
latitude = "-0.453718" # Nyeri, Kenya
longitude = "36.951524"
weatherDays = 10 # Number of days over which to accumulate historical weather data
targetCountry='Kenya'
targetCrop = 'Cabbage'
parametersFileName = 'C:/Users/marshalls/Documents/SJM/RemoteDiagnostics/ContextModel/Remote_Diagnostics_Data.xlsx'
# Get Soil Data
#CEC = soilData(latitude,longitude)
#print(' CEC at 10cm: %s \n' % CEC)
# Get WeatherData
#weatherSummary = weatherData(latitude,longitude,weatherDays)
#print("\n Total precipitation for the period was %.1f mm" % (weatherSummary['totalPrecip']))
#print(" Number of wet days was %d" % (weatherSummary['wetDays']))
#weatherFactors = assessWeather(weatherSummary)
#print(weatherFactors)
# DataFrames to hold location and crop data
locations = pd.read_excel(open(parametersFileName,'rb'),sheetname='CPC_pest_location_model_data')
crops = pd.read_excel(open(parametersFileName,'rb'),sheetname='CPC_crop-host_model_data')
countryScoredPests = scoreForCountry(locations,targetCountry)
#print(countryScoredPests)
countryCropScoredPests = scoreForCrop(countryScoredPests,crops,targetCrop)
print(countryCropScoredPests)
# get the environmental multipliers for the pests of the crop in the country
#multipliers = environmentalMultipliers(cropCountryPests,targetCrop,parametersFile)
#print('Multipliers in filtered list \n')
#print(multipliers)
# Apply factors for weather to generate a scored set of pest species
#scoredPests = applyModelFactors(multipliers, weatherFactors)
#print('Pests of the crop, in the country, scored for impact of weather \n')
#print(scoredPests)
if __name__ == "__main__":
main()
<file_sep>/README.md
# RemD
Experimenting with the RemD Model.
TODOs
=====
Selection for Country: Currently presence/absemce. Need to make this a scoring factor.
Does not yet take account of Pest status - "Minor" or "Major"
Weather data is only precipitation at present - no account of wind or temperature
Naming of methods is a bit clumsy - need to ridy this up.
Have written code to access Soil data is from SoilGrids but soil information is not used at present
Creation of a two column List in e.g. creating a List of pests for crop shouldn't work but seems to. Need to understand this. (It should probably be a Dict, as in the applyModelFactors function.)
Other Notes
===========
The model data spreadsheet had inconsistent headings (e.g. "Scientific name", "Scientific Name", "Scientific" ...
When used to identify columns in a DataFrame these differences matter so the spreadsheet was fixed, in my copy only.
The number of pest species for which we have have model scores is small compared to the number listed for each country/crop
E.g. for Maize in Kenya, we have 855 spp in keya, and 865 for Maize but in the table of model values there are only 29 records for Maize, - so we can only operate on those 29. Once filtered for country/crop we end up with 11 spp for which we have model factors.
Thresholds for "wet", "Dry" etc. are arbitrary.
Ideally we will compare recent weather with mean data for the location. The lattter is available but for a fee (with a short free trial.)
TODOs - Done
============
xxx
| c346b4f607086339621860f9608bb11cbb922bd6 | [
"Markdown",
"Python"
] | 4 | Python | SJM541/RemD | 9c2ed9eed73b1fc5c6f8952843dd44aa95e884f7 | ee5c57466fd8610f5a0669bb7893ae88fe883f1c |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManagementTool.Framework.Models.Task
{
public class TaskVM
{
public string Title { get; set; }
public int Status { get; set; }
public string Desription { get; set; }
public string DueDate { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ManagementTool.Framework.Models.Project;
namespace ManagementTool.Controllers
{
public class ProjectController : Controller
{
//
// GET: /Project/
public ActionResult Index()
{
var projectModel = new ProjectVM();
return View("~/Views/Project/Index.cshtml", projectModel);
}
public ActionResult Create()
{
var projectModel = new ProjectVM();
return View("~/Views/Project/CreateProject.cshtml", projectModel);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManagementTool.Framework.Enums
{
public enum Status
{
NotStarted,
InProgress,
ReadyForTesting,
Complete
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ManagementTool.Framework.Models.Account;
namespace ManagementTool.Controllers
{
public class AccountController : Controller
{
//
// GET: /Account/
public ActionResult Index()
{
return Login();
}
public ActionResult Login()
{
var loginModel = new LoginVM();
return View("~/Views/Account/Login.cshtml", loginModel);
}
public ActionResult Register()
{
return View();
}
}
}
<file_sep>SWE-6633-Project
================
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ManagementTool.Framework.Models.Task;
namespace ManagementTool.Controllers
{
public class TaskController : Controller
{
//
// GET: /Task/
public ActionResult Index()
{
return View("~/Views/Task/Tasks.cshtml");
}
public ActionResult Create()
{
var taskModel = new TaskVM();
return View("~/Views/Task/CreateTask.cshtml", taskModel);
}
}
}
| 3c1e53944a23de7b485e9a4d377c2e3571cb5572 | [
"Markdown",
"C#"
] | 6 | C# | mmintz1/SWE-6633-Project | 43283308b649a93e0d12d9b31f236782b122183a | ecc81fbdb142c417b7c1151ba2779f8be72d42d0 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TPIHM.ViewModels;
namespace TPIHM
{
/// <summary>
/// Interaction logic for AddActView.xaml
/// </summary>
public partial class AddActView : Window
{
public ActViewModel ActView;
public AddActView()
{
ActView = new ActViewModel();
DataContext = ActView;
InitializeComponent();
}
}
}
<file_sep>using Library;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TPIHM.Events;
using TPIHM.Models;
using View.Models;
namespace TPIHM.ViewModels
{
public class ActViewModel : NotifyPropertyChangedBase
{
public Uri Parcourir { get; set; }
public bool Valid { get; set; }
public DelegateCommand AddCommand { get; set; }
public DelegateCommand CancelCommand { get; set; }
public DelegateCommand BrowseCommand { get; set; }
private Personne _acteur;
public Personne Acteur
{
get
{
return _acteur;
}
set
{
_acteur = value;
NotifyPropertyChanged("Acteur");
}
}
public ActViewModel()
{
Acteur = new Personne("", "");
Acteur.DateNaissance = new Date(1, 1, 1);
AddCommand = new DelegateCommand(OnAddCommand, CanAddCommand);
CancelCommand = new DelegateCommand(OnCancelCommand, CanCancelCommand);
BrowseCommand = new DelegateCommand(OnBrowseCommand, CanBrowseCommand);
Parcourir = new Uri(System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString() + "/photoVide.jpg");
}
private void OnAddCommand(object o)
{
string source = Parcourir.ToString();
string fileName = System.IO.Path.GetFileName(Parcourir.ToString());
if (System.IO.Directory.GetParent(Parcourir.LocalPath).ToString() != System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString())
{
string targetFile = System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString();
System.IO.File.Copy(@Parcourir.LocalPath, @targetFile + "/" + fileName, true);
}
Acteur.Photo = new Uri(@System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString() + "/" + fileName);
Valid = true;
CommandChangedEvent2.GetEvent().OnButtonPressedActionHandler2(EventArgs.Empty);
}
private void OnCancelCommand(object o)
{
Valid = false;
CommandChangedEvent2.GetEvent().OnButtonPressedActionHandler2(EventArgs.Empty);
}
private void OnBrowseCommand(object o)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";
f.ShowDialog();
String chemin = f.FileName;
if (chemin != "")
Parcourir = new Uri(@chemin);
NotifyPropertyChanged("Parcourir");
}
private bool CanAddCommand(object o)
{
return true;
}
private bool CanCancelCommand(object o)
{
return true;
}
private bool CanBrowseCommand(object o)
{
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TPIHM.Models;
namespace BuisnessLayer.Entities
{
public class FilmEntities
{
public String Titre { get; set; }
public String TitreFrancais { get; set; }
public String Pays { get; set; }
public int Budget { get; set; }
public PersonneEntities Realisateur { get; set; }
public int Duree { get; set; }
public Date DateSortie { get; set; }
public Uri Source { get; set; }
public int Note { get; set; }
public String Synopsis { get; set; }
public List<PersonneEntities> Acteurs { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TPIHM.ViewModels;
using View.Models;
namespace TPIHM
{
/// <summary>
/// Interaction logic for AddView.xaml
/// </summary>
public partial class AddView : Window
{
public FilmViewModel FilmViewModel;
public AddView()
{
FilmViewModel = new FilmViewModel(new Film());
DataContext = FilmViewModel;
InitializeComponent();
}
}
}
<file_sep>using BuisnessLayer.Entities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TPIHM.Models;
namespace BuisnessLayer
{
public class FilmDAO
{
public static List<FilmEntities> GetAllFilm()
{
List<FilmEntities> listFilm = new List<FilmEntities>();
return lectureFichier(listFilm);
}
public static List<FilmEntities> lectureFichier(List<FilmEntities> listFilm)
{
StreamReader streamReader = new StreamReader(@System.IO.Directory.GetParent(@Application.ResourceAssembly.Location).ToString() + "/films.txt");
string ligne = streamReader.ReadLine();
int nbfilm;
List<PersonneEntities> acteurs = new List<PersonneEntities>();
if (ligne == null) nbfilm = 0;
else nbfilm = int.Parse(ligne);
for (int i = 0; i < nbfilm; i++)
{
string s_nbacteurs = streamReader.ReadLine();
int nbacteurs=0;
int.TryParse(s_nbacteurs, out nbacteurs);
string titre = streamReader.ReadLine();
string titreFrancais = streamReader.ReadLine();
string pays = streamReader.ReadLine();
int budget;
int.TryParse(streamReader.ReadLine(),out budget);
PersonneEntities realisateur = new PersonneEntities(streamReader.ReadLine(), streamReader.ReadLine());
int duree;
int.TryParse(streamReader.ReadLine(),out duree);
int annee;
int.TryParse(streamReader.ReadLine(),out annee);
int mois;
int.TryParse(streamReader.ReadLine(),out mois);
int jour;
int.TryParse(streamReader.ReadLine(),out jour);
Uri source = new Uri(@System.IO.Directory.GetParent(@Application.ResourceAssembly.Location).ToString() + streamReader.ReadLine());
int note;
int.TryParse(streamReader.ReadLine(), out note);
string synopsis = streamReader.ReadLine();
for (int j = 0; j < nbacteurs; j++)
{
PersonneEntities p = new PersonneEntities(streamReader.ReadLine(), streamReader.ReadLine());
int anneeP;
int.TryParse(streamReader.ReadLine(), out anneeP);
int moisP;
int.TryParse(streamReader.ReadLine(), out moisP);
int jourP;
int.TryParse(streamReader.ReadLine(), out jourP);
p.DateNaissance = new Date(anneeP, moisP, jourP);
p.Photo= new Uri(@System.IO.Directory.GetParent(@Application.ResourceAssembly.Location).ToString() + streamReader.ReadLine());
acteurs.Add(p);
}
FilmEntities film = new FilmEntities()
{
Titre = titre,
TitreFrancais = titreFrancais,
Pays = pays,
Budget = budget,
Duree = duree,
Realisateur = realisateur,
DateSortie = new Date(annee, mois, jour),
Source = source,
Note = note,
Synopsis = synopsis,
Acteurs=acteurs
};
listFilm.Add(film);
acteurs = new List<PersonneEntities>();
}
streamReader.Close();
return listFilm;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using View.Models;
using BuisnessLayer.Entities;
using TPIHM.Models;
namespace TPIHM.Factorys
{
public static class FilmFactory
{
public static Film FilmEntitiesToFilmModele(FilmEntities film)
{
List<Personne> tmp = new List<Personne>();
foreach (PersonneEntities p in film.Acteurs)
{
Personne p1 = new Personne(p.Nom, p.Prenom);
p1.DateNaissance = new Date(p.DateNaissance.Annee, p.DateNaissance.Mois, p.DateNaissance.Jour);
p1.Photo = p.Photo;
tmp.Add(p1);
}
return new Film
{
Titre = film.Titre,
TitreFrancais = film.TitreFrancais,
Pays = film.Pays,
Budget = film.Budget,
Source = film.Source,
Note=film.Note,
Realisateur = new Personne(film.Realisateur.Nom, film.Realisateur.Prenom),
Duree = film.Duree,
DateSortie = film.DateSortie,
Synopsis= film.Synopsis,
Acteurs=new ObservableCollection<Personne>(tmp)
};
}
public static ObservableCollection<Film> AllFilmEntitieToFilm(List<FilmEntities> list)
{
return new ObservableCollection<Film>(list.Select(FilmEntitiesToFilmModele).ToList());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TPIHM.Events
{
public class CommandChangedEvent2
{
private static CommandChangedEvent2 _myEvent2 { get; set; }
private CommandChangedEvent2() { }
public static CommandChangedEvent2 GetEvent() {
if(_myEvent2 == null)
{
_myEvent2 = new CommandChangedEvent2();
}
return _myEvent2;
}
public event EventHandler Handler;
public void OnButtonPressedActionHandler2(EventArgs e)
{
if(Handler != null)
{
Handler(this, e);
}
}
}
}<file_sep>using System;
using System.Text.RegularExpressions;
using System.Windows;
using TPIHM.Events;
using TPIHM.ViewModels;
namespace TPIHM
{
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ListFilmViewModel _viewModel;
public MainWindow()
{
InitializeComponent();
_viewModel = new ListFilmViewModel();
DataContext = _viewModel;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TPIHM.Events
{
public class CommandChangedEvent
{
private static CommandChangedEvent _myEvent { get; set; }
private CommandChangedEvent() { }
public static CommandChangedEvent GetEvent() {
if(_myEvent == null)
{
_myEvent = new CommandChangedEvent();
}
return _myEvent;
}
public event EventHandler Handler;
public void OnButtonPressedActionHandler(EventArgs e)
{
if(Handler != null)
{
Handler(this, e);
}
}
}
}<file_sep>using BuisnessLayer;
using Library;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using TPIHM.Events;
using TPIHM.Factorys;
using View.Models;
namespace TPIHM.ViewModels
{
public class ListFilmViewModel : NotifyPropertyChangedBase
{
public DelegateCommand AddCommand { get; set; }
public DelegateCommand EditCommand { get; set; }
public DelegateCommand SupprCommand { get; set; }
public DelegateCommand SearchCommand { get; set; }
public DelegateCommand SaveCommand { get; set; }
private AddView _addView { get; set; }
private EditView _editView { get; set; }
private Validation _validView { get; set; }
public String ToSearch { get; set; }
private Film _film;
public Film Film
{
get
{
return _film;
}
set
{
_film = value;
CommandChangedEvent.GetEvent().OnButtonPressedActionHandler(EventArgs.Empty);
NotifyPropertyChanged("Film");
NotifyPropertyChanged("ListFilm");
EditCommand.RaiseCanExecuteChanged();
SupprCommand.RaiseCanExecuteChanged();
}
}
private ObservableCollection<Film> _listFilm;
public ObservableCollection<Film> ListFilm
{
get
{
return _listFilm;
}
set
{
_listFilm = value;
_listFilm = new ObservableCollection<Film>(_listFilm.OrderByDescending(a => a.Titre));
}
}
private ObservableCollection<Film> _toDisplay;
public ObservableCollection<Film> ToDisplay
{
get
{
return _toDisplay;
}
set
{
_toDisplay = value;
_toDisplay = new ObservableCollection<Film>(_toDisplay.OrderByDescending(a => a.Titre));
}
}
private Personne _acteur;
public Personne Acteur
{
get
{
return _acteur;
}
set
{
_acteur = value;
NotifyPropertyChanged("Acteur");
}
}
/// <summary>
///
/// </summary>
public ListFilmViewModel()
{
ListFilm = FilmFactory.AllFilmEntitieToFilm(FilmDAO.GetAllFilm());
ToDisplay = ListFilm;
AddCommand = new DelegateCommand(OnAddCommand, CanAddCommand);
EditCommand = new DelegateCommand(OnEditCommand, CanEditCommand);
SupprCommand = new DelegateCommand(OnSupprCommand, CanSupprCommand);
SearchCommand = new DelegateCommand(OnSearchCommand, CanSearchCommand);
SaveCommand = new DelegateCommand(OnSaveCommand, CanSaveCommand);
}
public void enregistrer(string fichier)
{
System.IO.File.Delete(@System.IO.Directory.GetParent(@Application.ResourceAssembly.Location).ToString() + fichier);
StreamWriter streamWriter = new StreamWriter(@System.IO.Directory.GetParent(@Application.ResourceAssembly.Location).ToString() + fichier, true);
int nbfilm = ListFilm.Count();
streamWriter.WriteLine(nbfilm);
foreach (Film f in ListFilm)
{
streamWriter.WriteLine(f.Acteurs.Count);
streamWriter.WriteLine(f.Titre);
streamWriter.WriteLine(f.TitreFrancais);
streamWriter.WriteLine(f.Pays);
streamWriter.WriteLine(f.Budget);
streamWriter.WriteLine(f.Realisateur.Nom);
streamWriter.WriteLine(f.Realisateur.Prenom);
streamWriter.WriteLine(f.Duree);
streamWriter.WriteLine(f.DateSortie.Annee);
streamWriter.WriteLine(f.DateSortie.Mois);
streamWriter.WriteLine(f.DateSortie.Jour);
streamWriter.WriteLine("/" + Path.GetFileName(f.Source.LocalPath));
streamWriter.WriteLine(f.Note);
streamWriter.WriteLine(f.Synopsis);
foreach (Personne a in f.Acteurs)
{
streamWriter.WriteLine(a.Nom);
streamWriter.WriteLine(a.Prenom);
streamWriter.WriteLine(a.DateNaissance.Annee);
streamWriter.WriteLine(a.DateNaissance.Mois);
streamWriter.WriteLine(a.DateNaissance.Jour);
streamWriter.WriteLine("/" + Path.GetFileName(a.Photo.LocalPath));
}
}
streamWriter.Close();
}
public ObservableCollection<Film> Search()
{
ObservableCollection<Film> results = new ObservableCollection<Film>();
String titre;
String titreFrancais;
if (ToSearch != null) ToSearch = ToSearch.ToLower();
foreach (Film film in ListFilm)
{
if (film.Titre != null) titre = film.Titre.ToLower();
else titre = "";
if (film.TitreFrancais != null) titreFrancais = film.TitreFrancais.ToLower();
else titreFrancais = "";
if (titre.Contains(ToSearch) || titreFrancais.Contains(ToSearch))
{
results.Add(film);
}
}
return results;
}
private ObservableCollection<Film> ListSort(ObservableCollection<Film> listFilm)
{
return new ObservableCollection<Film>(listFilm.OrderByDescending(a => a.Titre));
}
private void CloseAddWindows(object sender, EventArgs e)
{
_addView.Close();
CommandChangedEvent.GetEvent().Handler -= CloseAddWindows;
}
private void CloseEditWindows(object sender, EventArgs e)
{
_editView.Close();
CommandChangedEvent.GetEvent().Handler -= CloseEditWindows;
}
private void CloseValidWindows(object sender, EventArgs e)
{
_validView.Close();
CommandChangedEvent.GetEvent().Handler -= CloseValidWindows;
}
private void OnAddCommand(object o)
{
CommandChangedEvent.GetEvent().Handler += CloseAddWindows;
_addView = new AddView();
_addView.Name = "Ajouter";
_addView.ShowDialog();
if (_addView.FilmViewModel.Valid == true)
{
ListFilm.Add(_addView.FilmViewModel.Film);
ListFilm = ListSort(ListFilm);
ToDisplay = ListFilm;
NotifyPropertyChanged("ToDisplay");
System.Windows.Forms.MessageBox.Show("Ajout effectué.");
}
else System.Windows.Forms.MessageBox.Show("Ajout annulé.");
}
private void OnEditCommand(object o)
{
CommandChangedEvent.GetEvent().Handler += CloseEditWindows;
_editView = new EditView(Film);
_editView.Name = "Editer";
_editView.ShowDialog();
if (_editView.FilmView.Valid == true)
{
ListFilm.Remove(Film);
ListFilm.Add(_editView.FilmView.Film);
ToDisplay = ListFilm;
NotifyPropertyChanged("ToDisplay");
System.Windows.Forms.MessageBox.Show("Edition effectuée.");
}
else System.Windows.Forms.MessageBox.Show("Edition annulée.");
}
private void OnSupprCommand(object o)
{
CommandChangedEvent.GetEvent().Handler += CloseValidWindows;
_validView = new Validation("Voulez vous vraiment supprimer ce film ?");
_validView.Name = "Validation";
_validView.ShowDialog();
if (_validView.ValidView.Valid == true)
{
ListFilm.Remove(Film);
ToDisplay = ListFilm;
NotifyPropertyChanged("ToDisplay");
System.Windows.Forms.MessageBox.Show("Suppression effectuée.");
}
else System.Windows.Forms.MessageBox.Show("Suppression annulée.");
}
private void OnSearchCommand(object o)
{
ObservableCollection<Film> results = Search();
if (results == null) return;
ToDisplay = results;
NotifyPropertyChanged("ToDisplay");
}
private void OnSaveCommand(object o)
{
CommandChangedEvent.GetEvent().Handler += CloseValidWindows;
_validView = new Validation("Voulez vous vraiment enregistrer tous les changements ?");
_validView.Name = "Validation";
_validView.ShowDialog();
if (_validView.ValidView.Valid == true)
{
enregistrer("/films.txt");
System.Windows.Forms.MessageBox.Show("Enregistrement effectué.");
}
else System.Windows.Forms.MessageBox.Show("Enregistrement annulé.");
}
private bool CanAddCommand(object o)
{
return true;
}
private bool CanEditCommand(object o)
{
return Film != null;
}
private bool CanSupprCommand(object o)
{
return Film != null;
}
private bool CanSearchCommand(object o)
{
return true;
}
private bool CanSaveCommand(object o)
{
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library;
using View.Models;
using TPIHM.Events;
using static TPIHM.Events.CommandChangedEvent;
using Microsoft.Win32;
using System.Windows;
using TPIHM.Models;
using System.Collections.ObjectModel;
namespace TPIHM.ViewModels
{
public class FilmViewModel : NotifyPropertyChangedBase
{
public DelegateCommand AddCommand { get; set; }
public DelegateCommand CancelCommand { get; set; }
public DelegateCommand BrowseCommand { get; set; }
public DelegateCommand AddActCommand { get; set; }
public DelegateCommand SupprActCommand { get; set; }
public Uri Parcourir { get; set; }
public bool Valid { get; set; }
private AddActView _addActView { get; set; }
private Personne _acteur;
public Personne Acteur
{
get
{
return _acteur;
}
set
{
_acteur = value;
NotifyPropertyChanged("Acteur");
}
}
private Film _film;
public Film Film
{
get
{
return _film;
}
set
{
_film = value;
NotifyPropertyChanged("Film");
AddCommand.RaiseCanExecuteChanged();
}
}
public FilmViewModel(Film film)
{
AddCommand = new DelegateCommand(OnAddCommand, CanAddCommand);
CancelCommand = new DelegateCommand(OnCancelCommand, CanCancelCommand);
BrowseCommand = new DelegateCommand(OnBrowseCommand, CanBrowseCommand);
AddActCommand = new DelegateCommand(OnAddActCommand, CanAddActCommand);
SupprActCommand = new DelegateCommand(OnSupprActCommand, CanSupprActCommand);
Film = film;
if (Film.Realisateur == null)
{
Film.Realisateur = new Personne("Nom", "Prenom");
}
if (Film.DateSortie == null)
{
Film.DateSortie = new Date(1, 1, 1);
}
if (Film.Source == null) Parcourir = new Uri(System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString() + "/photoVide.jpg");
else Parcourir = Film.Source;
if (Film.Acteurs == null)
{
Film.Acteurs = new ObservableCollection<Personne>();
}
}
public void FileCopy(string source, string fileName)
{
if (System.IO.Directory.GetParent(source).ToString() != System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString())
{
string targetFile = System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString();
System.IO.File.Copy(@source, @targetFile + "/" + fileName, true);
}
}
private void OnAddCommand(object o)
{
string source = Parcourir.ToString();
string fileName = System.IO.Path.GetFileName(Parcourir.ToString());
FileCopy(Parcourir.LocalPath, fileName);
Film.Source = new Uri(@System.IO.Directory.GetParent(Application.ResourceAssembly.Location).ToString() + "/" + fileName);
Valid = true;
CommandChangedEvent.GetEvent().OnButtonPressedActionHandler(EventArgs.Empty);
}
private void OnCancelCommand(object o)
{
Valid = false;
CommandChangedEvent.GetEvent().OnButtonPressedActionHandler(EventArgs.Empty);
}
private void OnBrowseCommand(object o)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";
f.ShowDialog();
String chemin = f.FileName;
if(chemin != "")
Parcourir = new Uri(@chemin);
NotifyPropertyChanged("Parcourir");
}
private void CloseAddActWindows(object sender, EventArgs e)
{
_addActView.Close();
CommandChangedEvent2.GetEvent().Handler -= CloseAddActWindows;
}
private void OnAddActCommand(object o)
{
CommandChangedEvent2.GetEvent().Handler += CloseAddActWindows;
_addActView = new AddActView();
_addActView.Name = "Ajouter";
_addActView.ShowDialog();
if (_addActView.ActView.Valid == true)
{
Film.Acteurs.Add(_addActView.ActView.Acteur);
NotifyPropertyChanged("Film");
}
}
private void OnSupprActCommand(object o)
{
Film.Acteurs.Remove(Acteur);
NotifyPropertyChanged("Film");
}
private bool CanAddCommand(object o)
{
return true;
}
private bool CanCancelCommand(object o)
{
return true;
}
private bool CanBrowseCommand(object o)
{
return true;
}
private bool CanAddActCommand(object o)
{
return true;
}
private bool CanSupprActCommand(object o)
{
return true;
}
}
}<file_sep>using Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TPIHM.Models;
namespace View.Models
{
public class Personne : NotifyPropertyChangedBase
{
private String _nom;
public string Nom
{
get
{
return _nom;
}
set
{
_nom = value;
}
}
private String _prenom;
public string Prenom
{
get
{
return _prenom;
}
set
{
_prenom = value;
}
}
private Date _dateNaissance;
public Date DateNaissance
{
get
{
return _dateNaissance;
}
set
{
_dateNaissance = value;
}
}
public Uri Photo { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", Prenom, Nom);
}
public Personne(string nom,string prenom)
{
Nom = nom;
Prenom = prenom;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library;
using System.Windows.Media;
using TPIHM.Models;
using System.Collections.ObjectModel;
namespace View.Models
{
public class Film : NotifyPropertyChangedBase
{
public String Titre { get; set; }
public String TitreFrancais { get; set; }
public String Pays { get; set; }
public int Budget { get; set; }
public Personne Realisateur { get; set; }
public int Duree { get; set; }
public Date DateSortie { get; set; }
public Uri Source { get; set; }
public int Note { get; set; }
public String Synopsis { get; set; }
public ObservableCollection<Personne> Acteurs { get; set; }
public override string ToString()
{
return string.Format("{0} - {1}", Titre, TitreFrancais);
}
}
}
<file_sep>using Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TPIHM.Events;
namespace TPIHM.ViewModels
{
public class ValidationViewModel : NotifyPropertyChangedBase
{
public DelegateCommand YesCommand { get; set; }
public DelegateCommand NoCommand { get; set; }
public bool Valid { get; set; }
public string Text { get; set; }
public ValidationViewModel(string text)
{
Text = text;
YesCommand = new DelegateCommand(OnYesCommand, CanYesCommand);
NoCommand = new DelegateCommand(OnNoCommand, CanNoCommand);
}
private void OnYesCommand(object o)
{
CommandChangedEvent.GetEvent().OnButtonPressedActionHandler(EventArgs.Empty);
Valid = true;
}
private bool CanYesCommand(object o)
{
return true;
}
private void OnNoCommand(object o)
{
CommandChangedEvent.GetEvent().OnButtonPressedActionHandler(EventArgs.Empty);
}
private bool CanNoCommand(object o)
{
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TPIHM.Models
{
public class Date
{
public int Jour { get; set; }
public int Mois { get; set; }
public int Annee { get; set; }
public Date(int annee, int mois, int jour)
{
Annee = annee;
Mois = mois;
Jour = jour;
}
override
public String ToString()
{
return Jour + "/" + Mois + "/" + Annee;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TPIHM.ViewModels;
namespace TPIHM
{
/// <summary>
/// Interaction logic for Validation.xaml
/// </summary>
public partial class Validation : Window
{
public ValidationViewModel ValidView;
public Validation(string text)
{
ValidView = new ValidationViewModel(text);
DataContext = ValidView;
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TPIHM.Models;
namespace BuisnessLayer.Entities
{
public class PersonneEntities
{
public String Nom { get; set; }
public String Prenom { get; set; }
public Date DateNaissance { get; set; }
public Uri Photo { get; set; }
public PersonneEntities(string nom, string prenom)
{
Nom = nom;
Prenom = prenom;
}
}
}
| 87893f3005a5f8a37c04e9956794986878a5bfef | [
"C#"
] | 17 | C# | nalchaz/TPIHM | 3965a38cae07a7d3acdc1a222022d239eb52fa7f | 27c9b4369309da7f49bed962484df109038d3fde |
refs/heads/master | <file_sep>//
// PopUpViewController.swift
// XyloLearn
//
// Created by <NAME> on 20/9/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ImageIO
import AVFoundation
class PopUpViewController: UIViewController {
var timeLeft = 0
var myTimer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
//MARK:- Timer for removing the view
myTimer = Timer.scheduledTimer(timeInterval: 25.0, target: self, selector: #selector(PopUpViewController.timerRunning), userInfo: nil, repeats: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
@IBOutlet var customView: UIView!
@IBOutlet var gif: UIImageView!
override func viewWillDisappear(_ animated: Bool) {
player?.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Timer Function
@objc func timerRunning() {
self.view.removeFromSuperview()
}
}
<file_sep>//
// HomePageViewController.swift
// XyloLearn
//
// Created by <NAME> on 30/7/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class StartupPageViewController: UIViewController {
@IBOutlet var gifBackground: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// gifBackground.loadGif(name: "homeGif")
//
// DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
//
// // Navigate to HomePageViewController
//
// let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Home") as! HomePageViewController
// self.navigationController?.pushViewController(vc2, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
gifBackground.loadGif(name: "homeGif")
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
// Navigate to HomePageViewController
let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Home") as! HomePageViewController
self.navigationController?.pushViewController(vc2, animated: false)
}
}
}
<file_sep>//
// Sound.swift
// XyloLearn
//
// Created by <NAME> on 8/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
var player: AVAudioPlayer?
func playSound(soundName: String){
guard let path = Bundle.main.path(forResource: soundName, ofType: "wav") else { return }
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
print("Couldn't Load the Sound File..")
}
}
<file_sep>//
// ImageSizeExtension.swift
// XyloLearn
//
// Created by <NAME> on 21/9/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import ImageIO
extension UIImageView {
func gifSize(){
let imageView = UIImageView()
imageView.frame.origin = CGPoint(x: 8, y: frame.height + frame.origin.y + 8)
imageView.frame.size = CGSize(width: frame.width - 16 , height: frame.height - 16)
imageView.image = image
imageView.layer.cornerRadius = 4
imageView.clipsToBounds = true
addSubview(imageView)
}
}
<file_sep>//
// MainPageVieController.swift
// XyloLearn
//
// Created by <NAME> on 31/7/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class HomePageViewController: UIViewController {
@IBAction func colourButtonPressed(_ sender: UIButton) {
let cVC = self.storyboard?.instantiateViewController(withIdentifier: "colourVC") as! ColorsViewController
self.navigationController?.pushViewController(cVC, animated: false)
}
@IBAction func animalButtonPressed(_ sender: UIButton) {
let aVC = self.storyboard?.instantiateViewController(withIdentifier: "animalVC") as! AnimalsViewController
self.navigationController?.pushViewController(aVC, animated: false)
}
@IBAction func xyloButtonPressed(_ sender: UIButton) {
let xVC = self.storyboard?.instantiateViewController(withIdentifier: "xyloVC") as! xyloViewController
self.navigationController?.pushViewController(xVC, animated: false)
}
@IBAction func fruitsButtonPressed(_ sender: UIButton) {
let fVC = self.storyboard?.instantiateViewController(withIdentifier: "fruitVC") as! FruitsViewController
self.navigationController?.pushViewController(fVC, animated: false)
}
@IBAction func vegesButtonPressed(_ sender: UIButton) {
let vVC = self.storyboard?.instantiateViewController(withIdentifier: "vegetableVC") as! VegetablesViewController
self.navigationController?.pushViewController(vVC, animated: false)
}
@IBAction func shapesButtonPressed(_ sender: UIButton) {
let sVC = self.storyboard?.instantiateViewController(withIdentifier: "shapesVC") as! ShapesViewController
self.navigationController?.pushViewController(sVC, animated: false)
}
@IBAction func numbersButtonPressed(_ sender: UIButton) {
let nVC = self.storyboard?.instantiateViewController(withIdentifier: "numbersVC") as! NumbersViewController
self.navigationController?.pushViewController(nVC, animated: false)
}
}
<file_sep>
import Foundation
import UIKit
import ImageIO
import AVFoundation
class ColorsViewController: UIViewController {
var player:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Home Button function
@IBAction func homePressed(_ sender: UIButton) {
let hVC = self.storyboard?.instantiateViewController(withIdentifier: "Home") as! HomePageViewController
self.navigationController?.pushViewController(hVC, animated: false)
}
//MARK:- Button for Colors & Alert Initialization
@IBAction func colorPressed(_ sender: UIButton) {
let customAlert = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "popUpID") as! PopUpViewController
self.present(customAlert, animated: true, completion:{
customAlert.view.superview?.isUserInteractionEnabled = true
customAlert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTap)))
})
// self.addChild(customAlert)
// customAlert.view.frame = self.view.frame
// self.view.addSubview(customAlert.view)
// customAlert.didMove(toParent: self)
//MARK:- Image View Initialization
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.isAccessibilityElement = true
customAlert.view.addSubview(imageView)
//MARK:- Loop For Different Images and Sounds
if sender.currentTitle == "1" {
imageView.loadGif(name: "redheart")
}
else if sender.currentTitle == "2" {
imageView.loadGif(name: "orange")
}
else if sender.currentTitle == "3" {
imageView.loadGif(name: "blue")
playSound(soundName: "Blue")
}
else if sender.currentTitle == "4" {
imageView.loadGif(name: "green")
playSound(soundName: "Green1")
}
else if sender.currentTitle == "5" {
imageView.loadGif(name: "purple")
}
else if sender.currentTitle == "6" {
imageView.loadGif(name: "yellow")
}
else {
imageView.loadGif(name: "pink")
}
//MARK:- Image Constraints
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: customAlert.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: customAlert.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: customAlert.view.safeAreaLayoutGuide.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: customAlert.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
}
<file_sep>
import Foundation
import UIKit
import ImageIO
extension UIView {
func blurredEffect() {
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
addSubview(blurEffectView)
}
func dismissBlurredEffect() {
for subview in self.subviews {
if subview is UIVisualEffectView{
subview.removeFromSuperview()
}
}
}
}
extension UIViewController {
@objc func dismissOnTap() {
dismiss(animated: true, completion: nil)
view.dismissBlurredEffect()
}
}
<file_sep>
import UIKit
import AVFoundation
class xyloViewController: UIViewController {
var player: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Home Button function
@IBAction func homePressed(_ sender: UIButton) {
let hVC = self.storyboard?.instantiateViewController(withIdentifier: "Home") as! HomePageViewController
self.navigationController?.pushViewController(hVC, animated: false)
}
//MARK:- Button for Xylo & Custom Alert Initialization
@IBAction func xyloKeyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
//Reduces the sender's (the button that got pressed) opacity to half.
sender.alpha = 0.5
//Code should execute after 0.2 second delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//Bring's sender's opacity back up to fully opaque.
sender.alpha = 1.0
}
}
}
| 5f399ebc947f850693f7cf337b219df7da3878bf | [
"Swift"
] | 8 | Swift | DN2511/XyoLearn | 454b10addbf25fdb5e87129c30cbc3f7f9b08894 | c63f09e4c567c92608623ac1234290cda7254d57 |
refs/heads/master | <repo_name>niemonie/TAU-Monika-Niewiarowska<file_sep>/Lab1/src/main/java/zad04/Gra.java
package zad04;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Gra implements Psikus{
public Integer cyfrokrad(Integer liczba) {
String bezCyfry = null;
String liczbaString= Integer.toString(liczba);
if (liczbaString.length() > 1) {
int index = (int)(Math.random() * liczbaString.length());
bezCyfry = liczbaString.substring(0, index) + liczbaString.substring(index + 1);
return Integer.parseInt(bezCyfry);
}
else return null;
}
public Integer hultajchochla(Integer liczba) throws NieudanyPsikusException {
String liczbaString = Integer.toString(liczba);
if(liczbaString.length()==1) throw new NieudanyPsikusException();
else{
int index1 = (int)(Math.random() * liczbaString.length());
int index2 = (int)(Math.random() * liczbaString.length());
ArrayList<String> tablica = new ArrayList<String>();
for (int i = 0; i < liczbaString.length(); i++)
{
tablica.add(liczbaString.substring(i,i+1));
}
String schowek = tablica.get(index1);
tablica.set(index1, tablica.get(index2));
tablica.set(index2, schowek);
StringBuilder nowyString = new StringBuilder();
for (int i = 0; i < liczbaString.length(); i++)
{
nowyString.append(tablica.get(i));
}
return Integer.parseInt(nowyString.toString());
}
}
public Integer nieksztaltek(Integer liczba) {
String liczbaString = Integer.toString(liczba);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(3, 8);
map.put(7, 1);
map.put(6, 9);
List<Integer> lista = new ArrayList<Integer>(map.keySet());
int index = new Random().nextInt(lista.size());
Integer index2 = lista.get(index);
liczbaString = liczbaString.replace(Integer.toString(index2), Integer.toString(map.get(index2)));
return Integer.parseInt(liczbaString);
}
}
<file_sep>/Lab1/src/test/java/zad01/CalculatorTest.java
package zad01;
import static org.junit.Assert.*;
import org.junit.Test;
import zad01.Calculator;
public class CalculatorTest {
Calculator calculator = new Calculator();
@Test
public void addCheck(){
assertEquals(5, calculator.add(2, 3));
}
@Test
public void subCheck(){
assertEquals(5, calculator.sub(10, 5));
}
@Test
public void multiCheck(){
assertEquals(6, calculator.multi(2, 3));
}
@Test
public void divCheck(){
assertEquals(6, calculator.div(12, 2));
}
@Test
public void greater(){
assertEquals(true, calculator.greater(6, 2));
}
@Test
public void greaterFalse() {
assertFalse("Should be false", calculator.greater(2, 6));
}
@Test
public void divByZero() {
assertEquals(0, calculator.div(6, 0));
}
}
<file_sep>/Lab4/src/test/java/zad3/RomanNumberSteps.java
package zad3;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
public class RomanNumberSteps {
private RomanNumber romanNumber;
@Given("an arabic number of $number")
public void romanNumberSetUp(int number) {
romanNumber = new RomanNumber(number);
}
@Then("the roman number should be $result")
public void romanNumberCheck(String result){
assertThat(romanNumber.toString(),is(result));
}
@Given("a higher number of $number")
public void higherRomanNumberSetUp(int number) {
romanNumber = new RomanNumber(number);
}
@Then("the result of a higher number should be $result")
public void higherRomanNumberCheck(String result){
assertThat(romanNumber.toString(),is(result));
}
@Given("a lower number of $number")
public void lowerRomanNumberSetUp(int number) {
romanNumber = new RomanNumber(number);
}
@Then("the result of a lower number should be $result")
public void lowerRomanNumberCheck(String result){
assertThat(romanNumber.toString(),is(result));
}
@Given("a different format of an arabic number of $number")
public void formattedRomanNumberSetUp(int number) {
romanNumber = new RomanNumber(number);
}
@Then("the result of the different format should be $result")
public void fortmattedRomanNumberCheck(String result){
assertThat(romanNumber.toString(),is(result));
}
}
<file_sep>/Lab4/src/main/java/zad2/CalculatorDouble.java
package zad2;
public class CalculatorDouble {
public double add(double a, double b){
return a + b;
}
public double sub(double a, double b){
return a-b;
}
public double multi(double a, double b){
return a*b;
}
public double div(double a, double b) {
if (Double.isInfinite(a/b)) return 0;
return a/b;
}
public boolean greater(double a, double b){
if (a>b) return true;
return false;
}
}
<file_sep>/Lab3/messenger/src/test/java/com/example/mockdemo/app/MessageAppTest.java
package com.example.mockdemo.app;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.example.mockdemo.messenger.ConnectionStatus;
import com.example.mockdemo.messenger.MalformedRecipientException;
import com.example.mockdemo.messenger.MessageService;
import com.example.mockdemo.messenger.SendingStatus;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MessageAppTest {
private static final String VALID_SERVER = "inf.ug.edu.pl";
private static final String VALID_MESSAGE = "some message";
private static final String INVALID_SERVER = "inf.ug.edu.eu";
private static final String INVALID_MESSAGE = "ab";
@Mock
MessageService messageService;
Messenger messenger;
@Before
public void setUp() {
messenger = new Messenger(messageService);
}
@Test
public void connectionValidServerTest() {
when(messageService.checkConnection(VALID_SERVER)).thenReturn(ConnectionStatus.SUCCESS);
assertEquals(0, messenger.testConnection(VALID_SERVER));
}
@Test
public void connectionInvalidServerTest() {
when(messageService.checkConnection(INVALID_SERVER)).thenReturn(ConnectionStatus.FAILURE);
assertEquals(1, messenger.testConnection(INVALID_SERVER));
}
@Test
public void sendValidServerValidMessageTest() throws MalformedRecipientException {
when(messageService.send(VALID_SERVER, VALID_MESSAGE)).thenReturn(SendingStatus.SENT);
assertEquals(0, messenger.sendMessage(VALID_SERVER, VALID_MESSAGE));
}
@Test
public void sendValidServerInvalidMessageTest() throws MalformedRecipientException {
when(messageService.send(VALID_SERVER, INVALID_MESSAGE)).thenThrow(new MalformedRecipientException()).thenReturn(SendingStatus.SENDING_ERROR);
assertEquals(2, messenger.sendMessage(VALID_SERVER, INVALID_MESSAGE));
}
@Test
public void sendInvalidServerValidMessageTest() throws MalformedRecipientException {
when(messageService.send(INVALID_SERVER, VALID_MESSAGE)).thenThrow(new MalformedRecipientException()).thenReturn(SendingStatus.SENDING_ERROR);
assertEquals(2, messenger.sendMessage(INVALID_SERVER, VALID_MESSAGE));
}
@Test
public void sendInvalidServerInvalidMessageTest() throws MalformedRecipientException {
when(messageService.send(INVALID_SERVER, INVALID_MESSAGE)).thenThrow(new MalformedRecipientException()).thenReturn(SendingStatus.SENDING_ERROR);
assertEquals(2, messenger.sendMessage(INVALID_SERVER, INVALID_MESSAGE));
}
} | e355c02a1760e1add49120cbad62b38e3482f303 | [
"Java"
] | 5 | Java | niemonie/TAU-Monika-Niewiarowska | dcafc0afbb23961ae3812b3e8e47210f8cc2a273 | fda3ed83d3b7b18cd4e924add965fb2b84c28c89 |
refs/heads/master | <repo_name>nandakishorereddy-chundi/Ubuntu-Bash-Script<file_sep>/install.sh
#!/bin/bash
# for update and upgrade
echo " <--------------------------------------------- UPDATING AND UPGRADING --------------------------------------------->"
sudo apt-get update && sudo apt-get upgrade
# installing vim
echo " <--------------------------------------------- INSTALLING VIM --------------------------------------------->"
sudo apt-get install vim
# installing flash player
echo " <--------------------------------------------- INSTALLING FLASH PLAYER --------------------------------------------->"
sudo apt-get install flashplugin-installer
#installing vlc player
echo " <--------------------------------------------- INSTALLING VLC PLAYER --------------------------------------------->"
sudo apt-get install vlc
# for setting .vimrc file
echo "set nu" >> .vimrc
echo "set cindent" >> .vimrc
echo "set autoindent" >> .vimrc
sudo apt-get update && sudo apt-get upgrade
# installing chrome
echo " <--------------------------------------------- INSTALLING CHROME --------------------------------------------->"
if [ $(uname -m) == "x86_64" ]
then
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt-get -f install
sudo dpkg -i google-chrome-stable_current_amd64.deb
else
wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
sudo apt-get -f install
sudo dpkg -i google-chrome-stable_current_i386.deb
fi
sudo apt-get -f install
sudo apt-get update && sudo apt-get upgrade
# installing skype
echo " <--------------------------------------------- INSTALLING SKYPE --------------------------------------------->"
if [ $(uname -m) == "x86_64" ]
then
wget http://www.skype.com/go/getskype-linux-beta-ubuntu-64
else
wget http://www.skype.com/go/getskype-linux-beta-ubuntu-32
fi
sudo apt-get -f install
sudo dpkg -i getskype-*
sudo apt-get -f install
<file_sep>/readme.txt
This is a bash script file which helps to download all required softwares and updates in ubuntu
How to run:
1. Download Script File
2. Open Terminal (Ctrl+Alt+T)
3. cd Downloads
3. mv install.sh ~
4. chmod 777 install.sh
5. bash install.sh
If you face any troubles or errors during installing softwares you can leave a message to "<EMAIL>" (without quotes)
Download and enjoy :)
| d10cc83f56c2bbc0b7f44972a084ddafa4f9f6a6 | [
"Text",
"Shell"
] | 2 | Shell | nandakishorereddy-chundi/Ubuntu-Bash-Script | 361f3d8cf2f300110bb583101c1f5dc212312bd6 | 8f17faccb9bc9bc8bd2feec2a8a3e6c25803110a |
refs/heads/main | <repo_name>Moamaldev/python-solve<file_sep>/README.md
# solve-task-paython
<file_sep>/solve-task-paython.py
class StringOperations():
def __init__(self, string):
self.string = string
def reverse(self):
print("Reverse :",self.string[::-1])
class ReversedString(StringOperations):
def Get(self):
return self
a=input("Enter String: ")
s= ReversedString(a)
print("Enterd : ",a)
s.reverse()
| b1b6b285f18b26706cb9fbc067746b7fafcdab03 | [
"Markdown",
"Python"
] | 2 | Markdown | Moamaldev/python-solve | d07298006074321be6e1c7373a76a202d3a7df0b | 7d27e8245c896ec296bddf06f800e052062d3594 |
refs/heads/master | <repo_name>CarlMendez/Microsoft-Teams-Shifts-WFM-Connectors<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/IGraphUtility.cs
// <copyright file="IGraphUtility.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
/// <summary>
/// This interface will contain the necessary methods to interface with Microsoft Graph.
/// </summary>
public interface IGraphUtility
{
/// <summary>
/// This method will make the call to Microsoft Graph to be able to register the workforce integration.
/// </summary>
/// <param name="workforceIntegration">The data to register the workforce integration.</param>
/// <param name="accessToken">The MS Graph API token.</param>
/// <returns>A string that contains the necessary response.</returns>
Task<HttpResponseMessage> RegisterWorkforceIntegrationAsync(
Models.RequestModels.WorkforceIntegration workforceIntegration,
string accessToken);
/// <summary>
/// Fetch user details for shifts using graph api tokens.
/// </summary>
/// <param name="accessToken">Access Token.</param>
/// <returns>The shift user.</returns>
Task<List<ShiftUser>> FetchShiftUserDetailsAsync(
string accessToken);
/// <summary>
/// Fetch user details for shifts using graph api tokens.
/// </summary>
/// <param name="accessToken">Access Token.</param>
/// <returns>The shift user.</returns>
Task<List<ShiftTeams>> FetchShiftTeamDetailsAsync(
string accessToken);
/// <summary>
/// Method that will get the Microsoft Graph token.
/// </summary>
/// <param name="tenantId">The Tenant ID.</param>
/// <param name="instance">The instance.</param>
/// <param name="clientId">The App ID of the Configuration Web App.</param>
/// <param name="clientSecret">The Client Secret.</param>
/// <param name="userId">The user ID.</param>
/// <returns>The string that represents the Microsoft Graph token.</returns>
Task<string> GetAccessTokenAsync(
string tenantId,
string instance,
string clientId,
string clientSecret,
string userId = default(string));
/// <summary>
/// Method that will remove the WorkforceIntegrationId from MS Graph.
/// </summary>
/// <param name="workforceIntegrationId">The Workforce Integration ID to delete.</param>
/// <param name="accessToken">The graph access token.</param>
/// <returns>A unit of exection that represents the response.</returns>
Task<string> DeleteWorkforceIntegrationAsync(
string workforceIntegrationId,
string accessToken);
/// <summary>
/// Method that fetchs the scheduling group details based on the shift teams Id provided.
/// </summary>
/// <param name="accessToken">The graph access token.</param>
/// <param name="shiftTeamId">The Shift team Id.</param>
/// <returns>Shift scheduling group details.</returns>
Task<string> FetchSchedulingGroupDetailsAsync(
string accessToken,
string shiftTeamId);
/// <summary>
/// Method that fetchs the scheduling group details based on the shift teams Id provided.
/// </summary>
/// <param name="teamsId">The Shift team Id.</param>
/// <param name="graphClient">The Graph Client.</param>
/// <param name="wfIID">The Workforce Integration Id.</param>
/// <param name="accessToken">The MS Graph Access token.</param>
/// <returns>A unit of execution that contains the success or failure Response.</returns>
Task<bool> AddWFInScheduleAsync(string teamsId, GraphServiceClient graphClient, string wfIID, string accessToken);
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/TeamDepartmentMappingProvider.cs
// <copyright file="TeamDepartmentMappingProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.Graph;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// This class implements all of the methods defined in <see cref="ITeamDepartmentMappingProvider"/>.
/// </summary>
public class TeamDepartmentMappingProvider : ITeamDepartmentMappingProvider
{
private const string TeamDepartmentMappingTableName = "TeamToDepartmentWithJobMapping";
private readonly Lazy<Task> initializeTask;
private readonly TelemetryClient telemetryClient;
private CloudTable teamDepartmentMappingCloudTable;
/// <summary>
/// Initializes a new instance of the <see cref="TeamDepartmentMappingProvider"/> class.
/// </summary>
/// <param name="connectionString">The Azure Table storage connection string.</param>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
public TeamDepartmentMappingProvider(string connectionString, TelemetryClient telemetryClient)
{
this.initializeTask = new Lazy<Task>(() => this.InitializeAsync(connectionString));
this.telemetryClient = telemetryClient;
}
/// <summary>
/// Retrieves a single TeamDepartmentMapping from Azure Table storage.
/// </summary>
/// <param name="workForceIntegrationId">WorkForceIntegration Id.</param>
/// <param name="orgJobPath">Kronos Org Job Path.</param>
/// <returns>A unit of execution that boxes a <see cref="ShiftsTeamDepartmentMappingEntity"/>.</returns>
public async Task<TeamToDepartmentJobMappingEntity> GetTeamMappingForOrgJobPathAsync(
string workForceIntegrationId,
string orgJobPath)
{
var getTeamDepartmentMappingProps = new Dictionary<string, string>()
{
{ "QueryingOrgJobPath", orgJobPath },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}", getTeamDepartmentMappingProps);
try
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
var searchOperation = TableOperation.Retrieve<TeamToDepartmentJobMappingEntity>(workForceIntegrationId, orgJobPath);
TableResult searchResult = await this.teamDepartmentMappingCloudTable.ExecuteAsync(searchOperation).ConfigureAwait(false);
var result = (TeamToDepartmentJobMappingEntity)searchResult.Result;
return result;
}
catch (Exception ex)
{
this.telemetryClient.TrackException(ex);
return null;
throw;
}
}
/// <summary>
/// Saving or updating a mapping between a Team in Shifts and Department in Kronos.
/// </summary>
/// <param name="shiftsTeamsDetails">Shifts team details fetched via Graph api calls.</param>
/// <param name="kronosDepartmentName">Department name fetched from Kronos.</param>
/// <param name="workforceIntegrationId">The Workforce Integration Id.</param>
/// <param name="tenantId">Tenant Id.</param>
/// <returns>A unit of execution.</returns>
public async Task<bool> SaveOrUpdateShiftsTeamDepartmentMappingAsync(
Team shiftsTeamsDetails,
string kronosDepartmentName,
string workforceIntegrationId,
string tenantId)
{
try
{
var saveOrUpdateShiftsProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
{ "ExecutingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, saveOrUpdateShiftsProps);
// TODO: The following code is for experimental purpose and incomplete, will change the code once the blockers are removed.
var entity = new ShiftsTeamDepartmentMappingEntity()
{
PartitionKey = tenantId,
RowKey = kronosDepartmentName,
ShiftsTeamName = shiftsTeamsDetails?.DisplayName,
TeamId = shiftsTeamsDetails.Id,
WorkforceIntegrationId = workforceIntegrationId,
IsArchived = shiftsTeamsDetails.IsArchived ?? false,
TeamDescription = shiftsTeamsDetails.Description,
TeamInternalId = shiftsTeamsDetails.InternalId,
TeamUrl = shiftsTeamsDetails.WebUrl,
};
var result = await this.StoreOrUpdateEntityAsync(entity).ConfigureAwait(false);
return result.HttpStatusCode == (int)HttpStatusCode.NoContent;
}
catch (Exception ex)
{
this.telemetryClient.TrackException(ex);
return false;
throw;
}
}
/// <summary>
/// Function that will return all of the teams that are mapped in Azure Table storage.
/// </summary>
/// <returns>A list of the mapped teams.</returns>
public async Task<List<ShiftsTeamDepartmentMappingEntity>> GetMappedTeamDetailsAsync()
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
// Table query
TableQuery<ShiftsTeamDepartmentMappingEntity> query = new TableQuery<ShiftsTeamDepartmentMappingEntity>();
// Results list
List<ShiftsTeamDepartmentMappingEntity> results = new List<ShiftsTeamDepartmentMappingEntity>();
TableContinuationToken continuationToken = null;
do
{
TableQuerySegment<ShiftsTeamDepartmentMappingEntity> queryResults = await this.teamDepartmentMappingCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
}
while (continuationToken != null);
return results;
}
/// <summary>
/// This method is to make sure to get all the records from the TeamToDepartmentJobMappingEntity table.
/// </summary>
/// <returns>A list of TeamToDepartmentJobMappingEntity.</returns>
public async Task<List<TeamToDepartmentJobMappingEntity>> GetMappedTeamToDeptsWithJobPathsAsync()
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
// Table query
TableQuery<TeamToDepartmentJobMappingEntity> query = new TableQuery<TeamToDepartmentJobMappingEntity>();
// Results list
List<TeamToDepartmentJobMappingEntity> results = new List<TeamToDepartmentJobMappingEntity>();
TableContinuationToken continuationToken = null;
do
{
TableQuerySegment<TeamToDepartmentJobMappingEntity> queryResults = await this.teamDepartmentMappingCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
}
while (continuationToken != null);
return results;
}
/// <summary>
/// Method that will get all the org job paths.
/// </summary>
/// <returns>A list of org job paths.</returns>
public async Task<List<string>> GetAllOrgJobPathsAsync()
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
List<string> orgJobPathList = new List<string>();
// Table query
TableQuery<TeamToDepartmentJobMappingEntity> query = new TableQuery<TeamToDepartmentJobMappingEntity>();
// Results list
List<TeamToDepartmentJobMappingEntity> results = new List<TeamToDepartmentJobMappingEntity>();
TableContinuationToken continuationToken = null;
do
{
TableQuerySegment<TeamToDepartmentJobMappingEntity> queryResults = await this.teamDepartmentMappingCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
}
while (continuationToken != null);
foreach (var item in results)
{
orgJobPathList.Add(item.RowKey.Replace('$', '/'));
}
return orgJobPathList;
}
/// <summary>
/// Method to save or update Teams to Department mapping.
/// </summary>
/// <param name="entity">Mapping entity reference.</param>
/// <returns>http status code representing the asynchronous operation.</returns>
public async Task<bool> TeamsToDepartmentMappingAsync(TeamsDepartmentMappingModel entity)
{
if (entity is null)
{
throw new ArgumentNullException(nameof(entity));
}
try
{
var result = await this.StoreOrUpdateEntityAsync(entity).ConfigureAwait(false);
return result.HttpStatusCode == (int)HttpStatusCode.NoContent;
}
catch (Exception)
{
return false;
throw;
}
}
/// <summary>
/// Function that will return all of the teams and department that are
/// mapped in Azure Table storage.
/// </summary>
/// <returns>List of Team and Department mapping model.</returns>
public async Task<List<TeamsDepartmentMappingModel>> GetTeamDeptMappingDetailsAsync()
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
// Table query
TableQuery<TeamsDepartmentMappingModel> query = new TableQuery<TeamsDepartmentMappingModel>();
// Results list
List<TeamsDepartmentMappingModel> results = new List<TeamsDepartmentMappingModel>();
TableContinuationToken continuationToken = null;
do
{
TableQuerySegment<TeamsDepartmentMappingModel> queryResults = await this.teamDepartmentMappingCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
}
while (continuationToken != null);
return results;
}
/// <summary>
/// Method to delete teams and Department mapping.
/// </summary>
/// <param name="partitionKey">The partition key.</param>
/// <param name="rowKey">The row key.</param>
/// <returns>boolean value that indicates delete success.</returns>
public async Task<bool> DeleteMappedTeamDeptDetailsAsync(string partitionKey, string rowKey)
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
// Table query
TableQuery<TeamsDepartmentMappingModel> deleteQuery = new TableQuery<TeamsDepartmentMappingModel>();
deleteQuery
.Where(TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey),
TableOperators.And,
TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey)));
TableContinuationToken continuationToken = null;
if (await this.teamDepartmentMappingCloudTable.ExistsAsync().ConfigureAwait(false))
{
TableQuerySegment<TeamsDepartmentMappingModel> queryResults = await this.teamDepartmentMappingCloudTable.ExecuteQuerySegmentedAsync(
deleteQuery, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
var row = queryResults.Results.FirstOrDefault();
TableOperation delete = TableOperation.Delete(row);
var result = await this.teamDepartmentMappingCloudTable.ExecuteAsync(delete).ConfigureAwait(false);
if (result.HttpStatusCode == (int)HttpStatusCode.NoContent)
{
return true;
}
}
return false;
}
private async Task<TableResult> StoreOrUpdateEntityAsync(TableEntity entity)
{
if (entity is null)
{
throw new ArgumentNullException(nameof(entity));
}
await this.EnsureInitializedAsync().ConfigureAwait(false);
var storeOrUpdateEntityProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
{ "ExecutingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, storeOrUpdateEntityProps);
TableOperation addOrUpdateOperation = TableOperation.InsertOrReplace(entity);
return await this.teamDepartmentMappingCloudTable.ExecuteAsync(addOrUpdateOperation).ConfigureAwait(false);
}
private async Task InitializeAsync(string connectionString)
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();
this.teamDepartmentMappingCloudTable = cloudTableClient.GetTableReference(TeamDepartmentMappingTableName);
await this.teamDepartmentMappingCloudTable.CreateIfNotExistsAsync().ConfigureAwait(false);
}
private async Task EnsureInitializedAsync()
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
await this.initializeTask.Value.ConfigureAwait(false);
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/ShiftsToKronos/CreateTimeOff/ICreateTimeOffActivity.cs
// <copyright file="ICreateTimeOffActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.ShiftsToKronos.CreateTimeOff
{
using System;
using System.Threading.Tasks;
/// <summary>
/// Create TimeOff Activity Interface.
/// </summary>
public interface ICreateTimeOffActivity
{
/// <summary>
/// Submit time of request which is in draft.
/// </summary>
/// <param name="jSession">jSession object.</param>
/// <param name="personNumber">Person number.</param>
/// <param name="reqId">RequestId of the time off request.</param>
/// <param name="queryStartDate">Query Start.</param>
/// <param name="queryEndDate">Query End.</param>
/// <param name="endPointUrl">Endpoint url for Kronos.</param>
/// <returns>Time of submit response.</returns>
Task<Models.ResponseEntities.ShiftsToKronos.TimeOffRequests.SubmitResponse.Response> SubmitTimeOffRequestAsync(
string jSession, string personNumber, string reqId, string queryStartDate, string queryEndDate, Uri endPointUrl);
/// <summary>
/// Send time off request to Kronos API and get response.
/// </summary>
/// <param name="jSession">J Session.</param>
/// <param name="startDateTime">Start Date.</param>
/// <param name="endDateTime">End Date.</param>
/// <param name="personNumber">Person Number.</param>
/// <param name="reason">Reason string.</param>
/// <param name="endPointUrl">Endpoint url for Kronos.</param>
/// <param name="kronosTimeZone">The time zone for Kronos WFC API.</param>
/// <returns>Time of add response.</returns>
Task<Models.ResponseEntities.ShiftsToKronos.TimeOffRequests.Response> TimeOffRequestAsync(
string jSession,
DateTimeOffset startDateTime,
DateTimeOffset endDateTime,
string personNumber,
string reason,
Uri endPointUrl,
TimeZoneInfo kronosTimeZone);
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.Models/RequestEntities/Comments.cs
// <copyright file="Comments.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift.SubmitRequest
{
using System.Xml.Serialization;
/// <summary>
/// This class models the Comments.
/// </summary>
public class Comments
{
/// <summary>
/// Gets or sets the comment.
/// </summary>
[XmlElement("Comment")]
#pragma warning disable CA1819 // Properties should not return arrays
public Comment[] Comment { get; set; }
#pragma warning restore CA1819 // Properties should not return arrays
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Models/ShiftsTeamDepartmentMappingEntity.cs
// <copyright file="ShiftsTeamDepartmentMappingEntity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Models
{
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// This class models the Team-Department mapping.
/// </summary>
public class ShiftsTeamDepartmentMappingEntity : TableEntity
{
/// <summary>
/// Gets or sets the workforceIntegrationId.
/// </summary>
public string WorkforceIntegrationId { get; set; }
/// <summary>
/// Gets or sets the TeamId.
/// </summary>
public string TeamId { get; set; }
/// <summary>
/// Gets or sets the Team name in Shifts.
/// </summary>
public string ShiftsTeamName { get; set; }
/// <summary>
/// Gets or sets the Team description.
/// </summary>
public string TeamDescription { get; set; }
/// <summary>
/// Gets or sets the Team description.
/// </summary>
public string TeamInternalId { get; set; }
/// <summary>
/// Gets or sets the Team url.
/// </summary>
#pragma warning disable CA1056 // Uri properties should not be strings
public string TeamUrl { get; set; }
#pragma warning restore CA1056 // Uri properties should not be strings
/// <summary>
/// Gets or sets a value indicating whether the status of Shifts team is archived.
/// </summary>
public bool IsArchived { get; set; }
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/SwapShift/SwapShiftActivity.cs
// <copyright file="SwapShiftActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.SwapShift
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift.ApproveDecline.RequestManagementApproveDecline;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift.SubmitRequest;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.SwapShift;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.SwapShift.SubmitRequest;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.TimeOffRequests;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.SwapShift;
using Microsoft.Teams.App.KronosWfc.Service;
using FetchApprove = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.SwapShift.FetchApprovals;
using SubmitRequest = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.SwapShift.SubmitRequest;
using SubmitResponse = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.SwapShift.SubmitSwapShift;
using TimeOff = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.TimeOffRequests;
/// <summary>
/// This class implements all the methods that are defined in <see cref="ISwapShiftActivity"/>.
/// </summary>
public class SwapShiftActivity : ISwapShiftActivity
{
private readonly TelemetryClient telemetryClient;
private readonly IApiHelper apiHelper;
/// <summary>
/// Initializes a new instance of the <see cref="SwapShiftActivity"/> class.
/// </summary>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="apiHelper">API helper to fetch tuple response by post soap requests.</param>
public SwapShiftActivity(TelemetryClient telemetryClient, IApiHelper apiHelper)
{
this.telemetryClient = telemetryClient;
this.apiHelper = apiHelper;
}
/// <summary>
/// Fecth swap shift request details for displaying history.
/// </summary>
/// <param name="endPointUrl">The Kronos WFC endpoint URL.</param>
/// <param name="jSession">JSession.</param>
/// <param name="queryDateSpan">QueryDateSpan string.</param>
/// <param name="personNumbers">List of person numbers whose request is approved.</param>
/// <param name="statusName">Request status name.</param>
/// <returns>Request details response object.</returns>
public async Task<FetchApprove.SwapShiftData.Response> GetSwapShiftRequestDetailsAsync(
Uri endPointUrl,
string jSession,
string queryDateSpan,
List<string> personNumbers,
string statusName)
{
if (personNumbers is null)
{
throw new ArgumentNullException(nameof(personNumbers));
}
var xmlSwapShiftRequest = this.CreateApprovedSwapShiftRequests(
personNumbers,
queryDateSpan,
statusName);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endPointUrl,
ApiConstants.SoapEnvOpen,
xmlSwapShiftRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
FetchApprove.SwapShiftData.Response swapResponse = this.ProcessSwapShiftApproved(tupleResponse.Item1);
return swapResponse;
}
/// <summary>
/// The method to create the Swap Shift Request in Draft state.
/// </summary>
/// <param name="jSession">The jSession.</param>
/// <param name="obj">The input SwapShiftObj.</param>
/// <param name="apiEndpoint">The Kronos API Endpoint.</param>
/// <returns>A unit of execution that contains the response object.</returns>
public async Task<SubmitResponse.Response> DraftSwapShiftAsync(
string jSession,
SwapShiftObj obj,
string apiEndpoint)
{
this.telemetryClient.TrackTrace($"SwapShiftActivity - DraftSwapShiftAsync starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
try
{
string xmlRequest = this.CreateSwapShiftDraftRequest(obj);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
new Uri(apiEndpoint),
ApiConstants.SoapEnvOpen,
xmlRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
SubmitResponse.Response response = this.ProcessSwapShiftDraftResponse(tupleResponse.Item1);
this.telemetryClient.TrackTrace($"SwapShiftActivity - DraftSwapShiftAsync ends at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return response;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.telemetryClient.TrackException(ex);
return null;
}
}
/// <summary>
/// The method to post a SwapShift request in a offered state.
/// </summary>
/// <param name="jSession">Kronos session.</param>
/// <param name="personNumber">The Kronos personNumber.</param>
/// <param name="reqId">The reqId of swap shift request.</param>
/// <param name="querySpan">The querySpan.</param>
/// <param name="comment">The comment for request.</param>
/// <param name="endpointUrl">Endpoint Kronos URL.</param>
/// <returns>request to send to Kronos.</returns>
public async Task<SubmitResponse.Response> SubmitSwapShiftAsync(
string jSession,
string personNumber,
string reqId,
string querySpan,
string comment,
Uri endpointUrl)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "KronosRequestId", reqId },
{ "KronosPersonNumber", personNumber },
{ "QueryDateSpan", querySpan },
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - SubmitSwapShiftAsync starts: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
try
{
string xmlRequest = this.CreateSwapShiftSubmitRequest(
personNumber,
reqId,
querySpan,
comment);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endpointUrl,
ApiConstants.SoapEnvOpen,
xmlRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
SubmitResponse.Response response = this.ProcessSwapShiftDraftResponse(tupleResponse.Item1);
this.telemetryClient.TrackTrace($"SwapShiftActivity - SubmitSwapShiftAsync ends: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
return response;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.telemetryClient.TrackException(ex, telemetryProps);
return null;
}
}
/// <summary>
/// The method to post a SwapShift request in an offered state.
/// </summary>
/// <param name="jSession">The JSession (Kronos "token").</param>
/// <param name="reqId">The SwapShift Request ID.</param>
/// <param name="personNumber">The Kronos Person Number.</param>
/// <param name="status">The status to update.</param>
/// <param name="querySpan">The query date span.</param>
/// <param name="comment">The comment to be applied wherever applicable.</param>
/// <param name="endpointUrl">The Kronos WFC API Endpoint URL.</param>
/// <returns>A unit of execution that contains the response object.</returns>
public async Task<Response> SubmitApprovalAsync(
string jSession,
string reqId,
string personNumber,
string status,
string querySpan,
string comment,
Uri endpointUrl)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "KronosRequestId", reqId },
{ "KronosPersonNumber", personNumber },
{ "KronosStatus", status },
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - SubmitApprovalAsync starts: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
string xmlRequest = this.CreateApprovalRequest(
personNumber,
reqId,
status,
querySpan,
comment);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endpointUrl,
ApiConstants.SoapEnvOpen,
xmlRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
Response swapShiftResponse = this.ProcessSwapShiftResponse(tupleResponse.Item1);
this.telemetryClient.TrackTrace($"SwapShiftActivity - SubmitApprovalAsync ends: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
return swapShiftResponse;
}
/// <summary>
/// Processes the response for the approve SwapShift.
/// </summary>
/// <param name="strResponse">The incoming response XML string.</param>
/// <returns>A response object.</returns>
private FetchApprove.SwapShiftData.Response ProcessSwapShiftApproved(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<FetchApprove.SwapShiftData.Response>(xResponse.ToString());
}
/// <summary>
/// This method will create the XML request string for a Swap Shift Request.
/// </summary>
/// <param name="swapShiftObj">The current swap shift object.</param>
/// <returns>A string that represents the XML request.</returns>
private string CreateSwapShiftDraftRequest(SwapShiftObj swapShiftObj)
{
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftDraftRequest starts: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
var requestorEmployee = new Employee
{
PersonIdentity = new Models.RequestEntities.OpenShift.ApproveDecline.RequestManagementApproveDecline.PersonIdentity
{
PersonNumber = swapShiftObj.RequestorPersonNumber,
},
};
var requestedToEmployee = new Employee
{
PersonIdentity = new Models.RequestEntities.OpenShift.ApproveDecline.RequestManagementApproveDecline.PersonIdentity
{
PersonNumber = swapShiftObj.RequestedToPersonNumber,
},
};
SubmitRequest.Request rq = new SubmitRequest.Request()
{
Action = ApiConstants.AddRequests,
EmployeeRequestMgmt = new EmployeeRequestMgmt
{
Employee = requestorEmployee,
QueryDateSpan = swapShiftObj.QueryDateSpan,
RequestItems = new RequestItems
{
SwapShiftRequestItem = new SwapShiftRequestItem
{
Employee = requestorEmployee,
RequestFor = ApiConstants.SwapShiftRequest,
OfferedShift = new OfferedShift
{
ShiftRequestItem = new ShiftRequestItem
{
Employee = requestorEmployee,
// The Kronos is expecting only these formats to be serialized,
// however we are converting the correct date format while creating actual shifts, timeoff etc.
EndDateTime = swapShiftObj.Emp1ToDateTime.ToString(ApiConstants.KronosAcceptableDateFormat, System.Globalization.CultureInfo.InvariantCulture),
OrgJobPath = swapShiftObj.SelectedJob,
StartDateTime = swapShiftObj.Emp1FromDateTime.ToString(ApiConstants.KronosAcceptableDateFormat, System.Globalization.CultureInfo.InvariantCulture),
},
},
RequestedShift = new RequestedShift
{
ShiftRequestItem = new ShiftRequestItem
{
Employee = requestedToEmployee,
EndDateTime = swapShiftObj.Emp2ToDateTime.ToString(ApiConstants.KronosAcceptableDateFormat, System.Globalization.CultureInfo.InvariantCulture),
OrgJobPath = swapShiftObj.SelectedJob,
StartDateTime = swapShiftObj.Emp2FromDateTime.ToString(ApiConstants.KronosAcceptableDateFormat, System.Globalization.CultureInfo.InvariantCulture),
},
},
},
},
},
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftDraftRequest: {rq.XmlSerialize().ToString(CultureInfo.InvariantCulture)}");
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftDraftRequest ends: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return rq.XmlSerialize();
}
/// <summary>
/// This method will process the response after a draft request has been submitted.
/// </summary>
/// <param name="strResponse">The response string.</param>
/// <returns>A response object is returned.</returns>
private SubmitResponse.Response ProcessSwapShiftDraftResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<SubmitResponse.Response>(xResponse.ToString());
}
/// <summary>
/// The method to create a SwapShift request in a offered state.
/// </summary>
/// <param name="personNumber">The Kronos personNumber.</param>
/// <param name="reqId">The reqId of swap shift request.</param>
/// <param name="querySpan">The querySpan.</param>
/// <param name="comment">The comment for request.</param>
/// <returns>Request to send to Kronos.</returns>
private string CreateSwapShiftSubmitRequest(
string personNumber,
string reqId,
string querySpan,
string comment)
{
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftSubmitRequest starts: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
RequestManagementSwap.Request rq = new RequestManagementSwap.Request()
{
Action = ApiConstants.UpdateStatus,
RequestMgmt = new RequestManagementSwap.RequestMgmt()
{
Employees = new RequestManagementSwap.Employee()
{
PersonIdentity = new RequestManagementSwap.PersonIdentity()
{
PersonNumber = personNumber,
},
},
QueryDateSpan = querySpan,
RequestStatusChanges = new RequestManagementSwap.RequestStatusChanges(),
},
};
rq.RequestMgmt.RequestStatusChanges.RequestStatusChange = new RequestManagementSwap.RequestStatusChange[]
{
new RequestManagementSwap.RequestStatusChange
{
Comments = comment == null ? null : new Comments()
{
Comment = new Comment[]
{
new Comment
{
CommentText = ApiConstants.SwapShiftComment,
Notes = new Notes
{
Note = new Note
{
#pragma warning disable CA1303 // Do not pass literals as localized parameters
Text = ApiConstants.SwapShiftNoteText,
#pragma warning restore CA1303 // Do not pass literals as localized parameters
},
},
},
},
},
RequestId = reqId,
ToStatusName = ApiConstants.Offered,
},
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftSubmitRequest: {rq.XmlSerialize().ToString(CultureInfo.InvariantCulture)}");
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateSwapShiftSubmitRequest ends: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return rq.XmlSerialize();
}
/// <summary>
/// Create approved SwapShift requests for a list of people.
/// </summary>
/// <param name="personNumbers">List of person numbers whose request is approved.</param>
/// <param name="queryDateSpan">QueryDateSpan string.</param>
/// <param name="statusName">Request statusName.</param>
/// <returns>XML request string.</returns>
private string CreateApprovedSwapShiftRequests(
List<string> personNumbers,
string queryDateSpan,
string statusName)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "QueryDateSpan", queryDateSpan },
{ "KronosStatus", statusName },
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApproveSwapShiftRequests starts: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
List<TimeOff.PersonIdentity> personIdentities = new List<TimeOff.PersonIdentity>();
foreach (var personNumber in personNumbers)
{
TimeOff.PersonIdentity personIdentity = new TimeOff.PersonIdentity
{
PersonNumber = personNumber,
};
personIdentities.Add(personIdentity);
}
TimeOff.Request rq = new TimeOff.Request
{
Action = ApiConstants.RetrieveWithDetails,
RequestMgmt = new TimeOff.RequestMgmt
{
QueryDateSpan = $"{queryDateSpan}",
RequestFor = ApiConstants.SwapShiftRequest,
StatusName = statusName,
Employees = new Employees
{
PersonIdentity = personIdentities,
},
},
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApproveSwapShiftRequests: {rq.XmlSerialize().ToString(CultureInfo.InvariantCulture)}", telemetryProps);
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApproveSwapShiftRequests ends: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
return rq.XmlSerialize();
}
/// <summary>
/// Process response for request details.
/// </summary>
/// <param name="strResponse">Response received from request for TOR detail.</param>
/// <returns>Response object.</returns>
private Response ProcessSwapShiftResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<Response>(xResponse.ToString());
}
/// <summary>
/// This method creates the approval request.
/// </summary>
/// <param name="personNumber">The Kronos Person Number.</param>
/// <param name="reqId">The SwapShift Request ID.</param>
/// <param name="status">The incoming status.</param>
/// <param name="querySpan">The query date span.</param>
/// <param name="comment">The comment to apply if applicable.</param>
/// <returns>A string that represents the request XML.</returns>
private string CreateApprovalRequest(
string personNumber,
string reqId,
string status,
string querySpan,
string comment)
{
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApprovalRequest starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
RequestManagementSwap.Request rq = new RequestManagementSwap.Request()
{
Action = ApiConstants.UpdateStatus,
RequestMgmt = new RequestManagementSwap.RequestMgmt()
{
Employees = new RequestManagementSwap.Employee()
{
PersonIdentity = new RequestManagementSwap.PersonIdentity()
{
PersonNumber = personNumber,
},
},
QueryDateSpan = querySpan,
RequestStatusChanges = new RequestManagementSwap.RequestStatusChanges(),
},
};
rq.RequestMgmt.RequestStatusChanges.RequestStatusChange = new RequestManagementSwap.RequestStatusChange[]
{
new RequestManagementSwap.RequestStatusChange
{
Comments = comment == null ? null : new Comments()
{
Comment = new Comment[]
{
new Comment
{
CommentText = ApiConstants.SwapShiftComment,
Notes = new Notes
{
Note = new Note
{
Text = comment,
},
},
},
},
},
RequestId = reqId,
ToStatusName = status,
},
};
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApprovalRequest: {rq.XmlSerialize().ToString(CultureInfo.InvariantCulture)}");
this.telemetryClient.TrackTrace($"SwapShiftActivity - CreateApprovalRequest starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return rq.XmlSerialize();
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TeamsController.cs
// <copyright file="TeamsController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.Shifts.Encryption.Encryptors;
using Microsoft.Teams.Shifts.Integration.API.Models.IntegrationAPI;
using Microsoft.Teams.Shifts.Integration.API.Models.IntegrationAPI.Incoming;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.ResponseModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// This is the teams controller that is being used here.
/// </summary>
[Route("/v1/teams")]
[ApiController]
public class TeamsController : Controller
{
private readonly TelemetryClient telemetryClient;
private readonly IConfigurationProvider configurationProvider;
private readonly OpenShiftRequestController openShiftRequestController;
private readonly SwapShiftController swapShiftController;
private readonly Common.Utility utility;
private readonly IUserMappingProvider userMappingProvider;
private readonly IShiftMappingEntityProvider shiftMappingEntityProvider;
private readonly IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider;
private readonly IOpenShiftMappingEntityProvider openShiftMappingEntityProvider;
private readonly ISwapShiftMappingEntityProvider swapShiftMappingEntityProvider;
/// <summary>
/// Initializes a new instance of the <see cref="TeamsController"/> class.
/// </summary>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="configurationProvider">ConfigurationProvider DI.</param>
/// <param name="openShiftRequestController">OpenShiftRequestController DI.</param>
/// <param name="swapShiftController">SwapShiftController DI.</param>
/// <param name="utility">The common utility methods DI.</param>
/// <param name="userMappingProvider">The user mapping provider DI.</param>
/// <param name="shiftMappingEntityProvider">The shift entity mapping provider DI.</param>
/// <param name="openShiftRequestMappingEntityProvider">The open shift request mapping entity provider DI.</param>
/// <param name="openShiftMappingEntityProvider">The open shift mapping entity provider DI.</param>
/// <param name="swapShiftMappingEntityProvider">The swap shift mapping entity provider DI.</param>
public TeamsController(
TelemetryClient telemetryClient,
IConfigurationProvider configurationProvider,
OpenShiftRequestController openShiftRequestController,
SwapShiftController swapShiftController,
Common.Utility utility,
IUserMappingProvider userMappingProvider,
IShiftMappingEntityProvider shiftMappingEntityProvider,
IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider,
IOpenShiftMappingEntityProvider openShiftMappingEntityProvider,
ISwapShiftMappingEntityProvider swapShiftMappingEntityProvider)
{
this.telemetryClient = telemetryClient;
this.configurationProvider = configurationProvider;
this.openShiftRequestController = openShiftRequestController;
this.swapShiftController = swapShiftController;
this.utility = utility;
this.userMappingProvider = userMappingProvider;
this.shiftMappingEntityProvider = shiftMappingEntityProvider;
this.openShiftRequestMappingEntityProvider = openShiftRequestMappingEntityProvider;
this.openShiftMappingEntityProvider = openShiftMappingEntityProvider;
this.swapShiftMappingEntityProvider = swapShiftMappingEntityProvider;
}
/// <summary>
/// Method to update the Workforce Integration ID to the schedule.
/// </summary>
/// <returns>A unit of execution that contains the HTTP Response.</returns>
[HttpGet]
[Route("/api/teams/CheckSetup")]
public async Task<HttpResponseMessage> CheckSetupAsync()
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
var isSetUpDone = await this.utility.IsSetUpDoneAsync().ConfigureAwait(false);
// Check for all the setup i.e User to user mapping, team department mapping, user logged in to configuration web app
if (isSetUpDone)
{
httpResponseMessage.StatusCode = HttpStatusCode.OK;
}
else
{
httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
}
return httpResponseMessage;
}
/// <summary>
/// The method that will be called from Shifts.
/// </summary>
/// <param name="aadGroupId">The AAD Group Id for the Team.</param>
/// <returns>An action result.</returns>
[HttpPost]
[Route("/v1/teams/{aadGroupId}/update")]
public async Task<ActionResult> UpdateTeam([FromRoute] string aadGroupId)
{
var request = this.Request;
var requestHeaders = request.Headers;
Microsoft.Extensions.Primitives.StringValues passThroughValue = string.Empty;
this.telemetryClient.TrackTrace("IncomingRequest, starts for method: UpdateTeam - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
// Step 1 - Obtain the secret from the database.
var configurationEntities = await this.configurationProvider.GetConfigurationsAsync().ConfigureAwait(false);
var configurationEntity = configurationEntities?.FirstOrDefault();
// Check whether Request coming from correct workforce integration is present and is equal to workforce integration id.
// Request is valid for OpenShift and SwapShift request FLM approval when the value of X-MS-WFMRequest coming
// from correct workforce integration is equal to current workforce integration id.
var isRequestFromCorrectIntegration = requestHeaders.TryGetValue("X-MS-WFMPassthrough", out passThroughValue) &&
string.Equals(passThroughValue, configurationEntity.WorkforceIntegrationId, StringComparison.Ordinal);
// Step 2 - Create/declare the byte arrays, and other data types required.
byte[] secretKeyBytes = Encoding.UTF8.GetBytes(configurationEntity?.WorkforceIntegrationSecret);
// Step 3 - Extract the incoming request using the symmetric key, and the HttpRequest.
var jsonModel = await DecryptEncryptedRequestFromShiftsAsync(
secretKeyBytes,
this.Request).ConfigureAwait(false);
IntegrationApiResponseModel responseModel = new IntegrationApiResponseModel();
ShiftsIntegResponse integrationResponse;
List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>();
string responseModelStr = string.Empty;
var updateProps = new Dictionary<string, string>()
{
{ "IncomingAadGroupId", aadGroupId },
};
// Check if payload is for open shift request.
if (jsonModel.Requests.Any(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture)))
{
// Process payload for open shift request.
responseModelList = await this.ProcessOpenShiftRequest(jsonModel, updateProps, aadGroupId, isRequestFromCorrectIntegration).ConfigureAwait(false);
}
// Check if payload is for swap shift request.
else if (jsonModel.Requests.Any(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)))
{
this.telemetryClient.TrackTrace("Teams Controller swapRequests " + JsonConvert.SerializeObject(jsonModel));
// Process payload for swap shift request.
responseModelList = await this.ProcessSwapShiftRequest(jsonModel, aadGroupId, isRequestFromCorrectIntegration).ConfigureAwait(true);
}
// Check if payload is for open shift.
else if (jsonModel.Requests.Any(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)))
{
// Acknowledge with status OK for open shift as solution does not synchronize open shifts into Kronos, Kronos being single source of truth for front line manager actions.
integrationResponse = ProcessOpenShiftAcknowledgement(jsonModel, updateProps);
responseModelList.Add(integrationResponse);
}
// Check if payload is for shift.
else if (jsonModel.Requests.Any(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)))
{
// Acknowledge with status OK for shift as solution does not synchronize shifts into Kronos, Kronos being single source of truth for front line manager actions.
integrationResponse = ProcessShiftAcknowledgement(jsonModel, updateProps);
responseModelList.Add(integrationResponse);
}
responseModel.ShiftsIntegResponses = responseModelList;
responseModelStr = JsonConvert.SerializeObject(responseModel);
this.telemetryClient.TrackTrace("IncomingRequest, ends for method: UpdateTeam - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
// Sends response back to Shifts.
return this.Ok(responseModelStr);
}
/// <summary>
/// This method will create the necessary acknowledgement response whenever Shift entities are created, or updated.
/// </summary>
/// <param name="jsonModel">The decrypted JSON payload.</param>
/// <param name="updateProps">The type of <see cref="Dictionary{TKey, TValue}"/> that contains properties that are being logged to ApplicationInsights.</param>
/// <returns>A type of <see cref="ShiftsIntegResponse"/>.</returns>
private static ShiftsIntegResponse ProcessShiftAcknowledgement(RequestModel jsonModel, Dictionary<string, string> updateProps)
{
if (jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Body != null)
{
var incomingShift = JsonConvert.DeserializeObject<Shift>(jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Body.ToString());
updateProps.Add("ShiftId", incomingShift.Id);
updateProps.Add("UserIdForShift", incomingShift.UserId);
updateProps.Add("SchedulingGroupId", incomingShift.SchedulingGroupId);
var integrationResponse = GenerateResponse(incomingShift.Id, HttpStatusCode.OK, null, null);
return integrationResponse;
}
else
{
var nullBodyShiftId = jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Id;
updateProps.Add("NullBodyShiftId", nullBodyShiftId);
// The outbound acknowledgement does not honor the null Etag, 502 Bad Gateway is thrown if so.
// Checking for the null eTag value, from the attributes in the payload and generate a non-null value in GenerateResponse method.
var integrationResponse = GenerateResponse(
nullBodyShiftId,
HttpStatusCode.OK,
null,
null);
return integrationResponse;
}
}
/// <summary>
/// This method will generate the necessary response for acknowledging the open shift being created or changed.
/// </summary>
/// <param name="jsonModel">The decrypted JSON payload.</param>
/// <param name="updateProps">The type of <see cref="Dictionary{TKey, TValue}"/> which contains various properties to log to ApplicationInsights.</param>
/// <returns>A type of <see cref="ShiftsIntegResponse"/>.</returns>
private static ShiftsIntegResponse ProcessOpenShiftAcknowledgement(RequestModel jsonModel, Dictionary<string, string> updateProps)
{
ShiftsIntegResponse integrationResponse;
if (jsonModel.Requests.First(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)).Body != null)
{
var incomingOpenShift = JsonConvert.DeserializeObject<OpenShiftIS>(jsonModel.Requests.First().Body.ToString());
updateProps.Add("OpenShiftId", incomingOpenShift.Id);
updateProps.Add("SchedulingGroupId", incomingOpenShift.SchedulingGroupId);
integrationResponse = GenerateResponse(incomingOpenShift.Id, HttpStatusCode.OK, null, null);
}
else
{
var nullBodyIncomingOpenShiftId = jsonModel.Requests.First(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)).Id;
updateProps.Add("NullBodyOpenShiftId", nullBodyIncomingOpenShiftId);
integrationResponse = GenerateResponse(nullBodyIncomingOpenShiftId, HttpStatusCode.OK, null, null);
}
return integrationResponse;
}
/// <summary>
/// Generates the response for each outbound request.
/// </summary>
/// <param name="itemId">Id for response.</param>
/// <param name="statusCode">HttpStatusCode for the request been processed.</param>
/// <param name="eTag">Etag based on response.</param>
/// <param name="error">Forward error to Shifts if any.</param>
/// <returns>ShiftsIntegResponse.</returns>
private static ShiftsIntegResponse GenerateResponse(string itemId, HttpStatusCode statusCode, string eTag, ResponseError error)
{
// The outbound acknowledgement does not honor the null Etag, 502 Bad Gateway is thrown if so.
// Checking for the null eTag value, from the attributes in the payload.
string responseEtag;
if (string.IsNullOrEmpty(eTag))
{
responseEtag = GenerateNewGuid();
}
else
{
responseEtag = eTag;
}
var integrationResponse = new ShiftsIntegResponse()
{
Id = itemId,
Status = (int)statusCode,
Body = new Body
{
Error = error,
ETag = responseEtag,
},
};
return integrationResponse;
}
/// <summary>
/// Generates the Guid for outbound call response.
/// </summary>
/// <returns>Returns newly generated GUID string.</returns>
private static string GenerateNewGuid()
{
return Guid.NewGuid().ToString();
}
/// <summary>
/// This method will properly decrypt the encrypted payload that is being received from Shifts.
/// </summary>
/// <param name="secretKeyBytes">The sharedSecret from Shifts casted into a byte array.</param>
/// <param name="request">The incoming request from Shifts UI that contains an encrypted payload.</param>
/// <returns>A unit of execution which contains the RequestModel.</returns>
private static async Task<RequestModel> DecryptEncryptedRequestFromShiftsAsync(byte[] secretKeyBytes, HttpRequest request)
{
string decryptedRequestBody = null;
// Step 1 - using a memory stream for the processing of the request.
using (MemoryStream ms = new MemoryStream())
{
await request.Body.CopyToAsync(ms).ConfigureAwait(false);
byte[] encryptedRequestBytes = ms.ToArray();
Aes256CbcHmacSha256Encryptor decryptor = new Aes256CbcHmacSha256Encryptor(secretKeyBytes);
byte[] decryptedRequestBodyBytes = decryptor.Decrypt(encryptedRequestBytes);
decryptedRequestBody = Encoding.UTF8.GetString(decryptedRequestBodyBytes);
}
// Step 2 - Parse the decrypted request into the correct model.
return JsonConvert.DeserializeObject<RequestModel>(decryptedRequestBody);
}
/// <summary>
/// Generate response to prevent actions.
/// </summary>
/// <param name="jsonModel">The request payload.</param>
/// <param name="errorMessage">Error message to send while preventing action.</param>
/// <returns>List of ShiftsIntegResponse.</returns>
private static List<ShiftsIntegResponse> GenerateResponseToPreventAction(RequestModel jsonModel, string errorMessage)
{
List<ShiftsIntegResponse> shiftsIntegResponses = new List<ShiftsIntegResponse>();
var integrationResponse = new ShiftsIntegResponse();
foreach (var item in jsonModel.Requests)
{
ResponseError responseError = new ResponseError();
responseError.Code = HttpStatusCode.BadRequest.ToString();
responseError.Message = errorMessage;
integrationResponse = GenerateResponse(item.Id, HttpStatusCode.BadRequest, null, responseError);
shiftsIntegResponses.Add(integrationResponse);
}
return shiftsIntegResponses;
}
/// <summary>
/// Process open shift requests outbound calls.
/// </summary>
/// <param name="jsonModel">Incoming payload for the request been made in Shifts.</param>
/// <param name="updateProps">telemetry properties.</param>
/// <returns>Returns list of ShiftIntegResponse for request.</returns>
private async Task<List<ShiftsIntegResponse>> ProcessOpenShiftRequest(RequestModel jsonModel, Dictionary<string, string> updateProps, string teamsId, bool isRequestFromCorrectIntegration)
{
List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>();
var requestBody = jsonModel.Requests.First(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture)).Body;
if (requestBody != null)
{
var requestState = requestBody?["state"].Value<string>();
switch (requestState)
{
// The Open shift request is submitted in Shifts and is pending with manager for approval.
case ApiConstants.ShiftsPending:
{
var openShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(requestBody.ToString());
responseModelList = await this.ProcessOutboundOpenShiftRequestAsync(openShiftRequest, updateProps, teamsId).ConfigureAwait(false);
}
break;
// The Open shift request is approved by manager.
case ApiConstants.ShiftsApproved:
{
// The request is coming from intended workforce integration.
if (isRequestFromCorrectIntegration)
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest approval outbound call.");
responseModelList = await this.ProcessOpenShiftRequestApprovalAsync(jsonModel, updateProps).ConfigureAwait(false);
}
// Request is coming from either Shifts UI or from incorrect workforce integration.
else
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest approval outbound call.");
responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval);
}
}
break;
// The code below would be when there is a decline.
case ApiConstants.ShiftsDeclined:
{
// The request is coming from intended workforce integration.
if (isRequestFromCorrectIntegration)
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest decline outbound call.");
var integrationResponse = new ShiftsIntegResponse();
foreach (var item in jsonModel.Requests)
{
integrationResponse = GenerateResponse(item.Id, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponse);
}
}
// Request is coming from either Shifts UI or from incorrect workforce integration.
else
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest decline outbound call.");
responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval);
}
}
break;
}
}
return responseModelList;
}
/// <summary>
/// Process swap shift requests outbound calls.
/// </summary>
/// <param name="jsonModel">Incoming payload for the request been made in Shifts.</param>
/// <param name="aadGroupId">AAD Group id.</param>
/// <returns>Returns list of ShiftIntegResponse for request.</returns>
private async Task<List<ShiftsIntegResponse>> ProcessSwapShiftRequest(RequestModel jsonModel, string aadGroupId, bool isRequestFromCorrectIntegration)
{
List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>();
var requestBody = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Body;
ShiftsIntegResponse integrationResponseSwap = null;
try
{
// If the requestBody is not null - represents either a new Swap Shift request being created by FLW1,
// FLW2 accepts or declines FLW1's request, or FLM approves or declines the Swap Shift request.
// If the requestBody is null - represents FLW1's cancellation of the Swap Shift Request.
if (requestBody != null)
{
var requestState = requestBody?["state"].Value<string>();
var requestAssignedTo = requestBody?["assignedTo"].Value<string>();
var swapRequest = JsonConvert.DeserializeObject<SwapRequest>(requestBody.ToString());
// FLW1 has requested for swap shift, submit the request in Kronos.
if (requestState == ApiConstants.ShiftsPending && requestAssignedTo == ApiConstants.ShiftsRecipient)
{
integrationResponseSwap = await this.swapShiftController.SubmitSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false);
responseModelList.Add(integrationResponseSwap);
}
// FLW2 has approved the swap shift, updates the status in Kronos to submitted and request goes to manager for approval.
else if (requestState == ApiConstants.ShiftsPending && requestAssignedTo == ApiConstants.ShiftsManager)
{
integrationResponseSwap = await this.swapShiftController.ApproveOrDeclineSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false);
responseModelList.Add(integrationResponseSwap);
}
// FLW2 has declined the swap shift, updates the status in Kronos to refused.
else if (requestState == ApiConstants.Declined && requestAssignedTo == ApiConstants.ShiftsRecipient)
{
integrationResponseSwap = await this.swapShiftController.ApproveOrDeclineSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false);
responseModelList.Add(integrationResponseSwap);
}
// Manager has declined the request in Kronos, which declines the request in Shifts also.
else if (requestState == ApiConstants.ShiftsDeclined && requestAssignedTo == ApiConstants.ShiftsManager)
{
// The request is coming from intended workforce integration.
if (isRequestFromCorrectIntegration)
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest decline outbound call.");
integrationResponseSwap = GenerateResponse(swapRequest.Id, HttpStatusCode.OK, swapRequest.ETag, null);
responseModelList.Add(integrationResponseSwap);
}
// Request is coming from either Shifts UI or from incorrect workforce integration.
else
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest decline outbound call.");
responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval);
}
}
// Manager has approved the request in Kronos.
else if (requestState == ApiConstants.ShiftsApproved && requestAssignedTo == ApiConstants.ShiftsManager)
{
// The request is coming from intended workforce integration.
if (isRequestFromCorrectIntegration)
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest approval outbound call.");
responseModelList = await this.ProcessSwapShiftRequestApprovalAsync(jsonModel, aadGroupId).ConfigureAwait(false);
}
// Request is coming from either Shifts UI or from incorrect workforce integration.
else
{
this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest approval outbound call.");
responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval);
}
}
// There is a System decline with the Swap Shift Request
else if (requestState == ApiConstants.Declined && requestAssignedTo == ApiConstants.System)
{
var systemDeclineSwapReqId = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Id;
ResponseError responseError = new ResponseError
{
Message = Resource.SystemDeclined,
};
integrationResponseSwap = GenerateResponse(systemDeclineSwapReqId, HttpStatusCode.OK, null, responseError);
responseModelList.Add(integrationResponseSwap);
}
}
else if (jsonModel.Requests.Any(c => c.Method == "DELETE"))
{
// Code below handles the delete swap shift request.
var deleteSwapRequestId = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Id;
// Logging to telemetry the incoming cancelled request by FLW1.
this.telemetryClient.TrackTrace($"The Swap Shift Request: {deleteSwapRequestId} has been declined by FLW1.");
var entityToCancel = await this.swapShiftMappingEntityProvider.GetKronosReqAsync(deleteSwapRequestId).ConfigureAwait(false);
// Updating the ShiftsStatus to Cancelled.
entityToCancel.ShiftsStatus = ApiConstants.SwapShiftCancelled;
// Updating the entity accordingly
await this.swapShiftMappingEntityProvider.AddOrUpdateSwapShiftMappingAsync(entityToCancel).ConfigureAwait(false);
integrationResponseSwap = GenerateResponse(deleteSwapRequestId, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponseSwap);
}
}
catch (Exception)
{
this.telemetryClient.TrackTrace("Teams Controller swapRequests responseModelList Exception" + JsonConvert.SerializeObject(responseModelList));
throw;
}
this.telemetryClient.TrackTrace("Teams Controller swapRequests responseModelList" + JsonConvert.SerializeObject(responseModelList));
return responseModelList;
}
/// <summary>
/// This method processes the open shift request approval, and proceeds to update the Azure table storage accordingly with the Shifts status
/// of the open shift request, and also ensures that the ShiftMappingEntity table is properly in sync.
/// </summary>
/// <param name="jsonModel">The decrypted JSON payload.</param>
/// <param name="updateProps">A dictionary of string, string that will be logged to ApplicationInsights.</param>
/// <returns>A unit of execution.</returns>
private async Task<List<ShiftsIntegResponse>> ProcessOpenShiftRequestApprovalAsync(RequestModel jsonModel, Dictionary<string, string> updateProps)
{
List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>();
ShiftsIntegResponse integrationResponse = null;
var openShiftRequests = jsonModel?.Requests?.Where(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture));
var finalOpenShiftObj = jsonModel?.Requests?.FirstOrDefault(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture));
var finalShiftObj = jsonModel?.Requests?.FirstOrDefault(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture));
// Filter all the system declined requests.
var autoDeclinedRequests = openShiftRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.Declined && c.Body["assignedTo"].Value<string>() == ApiConstants.System).ToList();
// Filter approved open shift request.
var approvedOpenShiftRequest = openShiftRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.ShiftsApproved && c.Body["assignedTo"].Value<string>() == ApiConstants.ShiftsManager).FirstOrDefault();
var finalShift = JsonConvert.DeserializeObject<Shift>(finalShiftObj.Body.ToString());
var finalOpenShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(approvedOpenShiftRequest.Body.ToString());
var finalOpenShift = JsonConvert.DeserializeObject<OpenShiftIS>(finalOpenShiftObj.Body.ToString());
updateProps.Add("NewShiftId", finalShift.Id);
updateProps.Add("GraphOpenShiftRequestId", finalOpenShiftRequest.Id);
updateProps.Add("GraphOpenShiftId", finalOpenShift.Id);
// Step 1 - Create the Kronos Unique ID.
var kronosUniqueId = this.utility.CreateUniqueId(finalShift);
this.telemetryClient.TrackTrace("KronosHash-OpenShiftRequestApproval-TeamsController: " + kronosUniqueId);
try
{
this.telemetryClient.TrackTrace("Updating entities-OpenShiftRequestApproval started: " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
// Step 1 - Get the temp shift record first by table scan against RowKey.
var tempShiftRowKey = $"SHFT_PENDING_{finalOpenShiftRequest.Id}";
var tempShiftEntity = await this.shiftMappingEntityProvider.GetShiftMappingEntityByRowKeyAsync(tempShiftRowKey).ConfigureAwait(false);
// We need to check if the tempShift is not null because in the Open Shift Request controller, the tempShift was created
// as part of the Graph API call to approve the Open Shift Request.
if (tempShiftEntity != null)
{
// Step 2 - Form the new shift record.
var shiftToInsert = new TeamsShiftMappingEntity()
{
RowKey = finalShift.Id,
KronosPersonNumber = tempShiftEntity.KronosPersonNumber,
KronosUniqueId = tempShiftEntity.KronosUniqueId,
PartitionKey = tempShiftEntity.PartitionKey,
AadUserId = tempShiftEntity.AadUserId,
ShiftStartDate = this.utility.UTCToKronosTimeZone(finalShift.SharedShift.StartDateTime),
};
// Step 3 - Save the new shift record.
await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync(shiftToInsert, shiftToInsert.RowKey, shiftToInsert.PartitionKey).ConfigureAwait(false);
// Step 4 - Delete the temp shift record.
await this.shiftMappingEntityProvider.DeleteOrphanDataFromShiftMappingAsync(tempShiftEntity).ConfigureAwait(false);
// Adding response for create new shift.
integrationResponse = GenerateResponse(finalShift.Id, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponse);
}
else
{
// We are logging to ApplicationInsights that the tempShift entity could not be found.
this.telemetryClient.TrackTrace(string.Format(CultureInfo.InvariantCulture, Resource.EntityNotFoundWithRowKey, tempShiftRowKey));
}
// Logging to ApplicationInsights the OpenShiftRequestId.
this.telemetryClient.TrackTrace("OpenShiftRequestId = " + finalOpenShiftRequest.Id);
// Find the open shift request for which we update the ShiftsStatus to Approved.
var openShiftRequestEntityToUpdate = await this.openShiftRequestMappingEntityProvider.GetOpenShiftRequestMappingEntityByOpenShiftIdAsync(
finalOpenShift.Id,
finalOpenShiftRequest.Id).ConfigureAwait(false);
openShiftRequestEntityToUpdate.ShiftsStatus = finalOpenShiftRequest.State;
// Update the open shift request to Approved in the ShiftStatus column.
await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(openShiftRequestEntityToUpdate).ConfigureAwait(false);
// Delete the open shift entity accordingly from the OpenShiftEntityMapping table in Azure Table storage as the open shift request has been approved.
await this.openShiftMappingEntityProvider.DeleteOrphanDataFromOpenShiftMappingByOpenShiftIdAsync(finalOpenShift.Id).ConfigureAwait(false);
// Adding response for delete open shift.
integrationResponse = GenerateResponse(finalOpenShift.Id, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponse);
// Adding response for approved open shift request.
integrationResponse = GenerateResponse(finalOpenShiftRequest.Id, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponse);
foreach (var declinedRequest in autoDeclinedRequests)
{
this.telemetryClient.TrackTrace($"SystemDeclinedOpenShiftRequestId: {declinedRequest.Id}");
var declinedOpenShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(declinedRequest.Body.ToString());
// Update the status in Azure table storage.
var entityToUpdate = await this.openShiftRequestMappingEntityProvider.GetOpenShiftRequestMappingEntityByOpenShiftRequestIdAsync(
declinedRequest.Id).ConfigureAwait(false);
entityToUpdate.KronosStatus = declinedOpenShiftRequest.State;
entityToUpdate.ShiftsStatus = declinedOpenShiftRequest.State;
// Commit the change to the database.
await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(entityToUpdate).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"OpenShiftRequestId: {declinedOpenShiftRequest.Id}, assigned to: {declinedOpenShiftRequest.AssignedTo}, state: {declinedOpenShiftRequest.State}");
// Adding response for system declined open shift request.
integrationResponse = GenerateResponse(declinedOpenShiftRequest.Id, HttpStatusCode.OK, null, null);
responseModelList.Add(integrationResponse);
}
this.telemetryClient.TrackTrace("Updating entities-OpenShiftRequestApproval complete: " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
this.telemetryClient.TrackTrace($"Shift mapping has failed for {finalOpenShiftRequest.Id}: " + ex.InnerException.ToString());
}
this.telemetryClient.TrackTrace($"Shift mapping has resulted in some type of error with the following: {ex.StackTrace.ToString(CultureInfo.InvariantCulture)}");
throw;
}
return responseModelList;
}
/// <summary>
/// This method further processes the Swap Shift request approval.
/// </summary>
/// <param name="jsonModel">The decryped JSON payload from Shifts/MS Graph.</param>
/// <param name="aadGroupId">The team ID for which the Swap Shift request has been approved.</param>
/// <returns>A unit of execution that contains the type of <see cref="ShiftsIntegResponse"/>.</returns>
private async Task<List<ShiftsIntegResponse>> ProcessSwapShiftRequestApprovalAsync(RequestModel jsonModel, string aadGroupId)
{
List<ShiftsIntegResponse> swapShiftsIntegResponses = new List<ShiftsIntegResponse>();
ShiftsIntegResponse integrationResponse = null;
var swapShiftApprovalRes = from requests in jsonModel.Requests
group requests by requests.Url;
var swapRequests = jsonModel.Requests.Where(c => c.Url.Contains("/swapRequests/", StringComparison.InvariantCulture));
// Filter all the system declined requests.
var autoDeclinedRequests = swapRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.Declined && c.Body["assignedTo"].Value<string>() == ApiConstants.System).ToList();
// Filter approved swap shift request.
var approvedSwapShiftRequest = swapRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.ShiftsApproved && c.Body["assignedTo"].Value<string>() == ApiConstants.ShiftsManager).FirstOrDefault();
var swapShiftRequest = JsonConvert.DeserializeObject<SwapRequest>(approvedSwapShiftRequest.Body.ToString());
var postedShifts = jsonModel.Requests.Where(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture) && x.Method == "POST").ToList();
var deletedShifts = jsonModel.Requests.Where(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture) && x.Method == "DELETE").ToList();
if (swapShiftRequest != null)
{
var newShiftFirst = JsonConvert.DeserializeObject<Shift>(postedShifts.First().Body.ToString());
var newShiftSecond = JsonConvert.DeserializeObject<Shift>(postedShifts.Last().Body.ToString());
// Step 1 - Create the Kronos Unique ID.
var kronosUniqueIdFirst = this.utility.CreateUniqueId(newShiftFirst);
var kronosUniqueIdSecond = this.utility.CreateUniqueId(newShiftSecond);
try
{
var userMappingRecord = await this.userMappingProvider.GetUserMappingEntityAsyncNew(
newShiftFirst?.UserId,
aadGroupId).ConfigureAwait(false);
// When getting the month partition key, make sure to take into account the Kronos Time Zone as well
var provider = CultureInfo.InvariantCulture;
var actualStartDateTimeStr = this.utility.CalculateStartDateTime(
newShiftFirst.SharedShift.StartDateTime.Date).ToString("M/dd/yyyy", provider);
var actualEndDateTimeStr = this.utility.CalculateEndDateTime(
newShiftFirst.SharedShift.EndDateTime.Date).ToString("M/dd/yyyy", provider);
// Create the month partition key based on the finalShift object.
var monthPartitions = Common.Utility.GetMonthPartition(actualStartDateTimeStr, actualEndDateTimeStr);
var monthPartition = monthPartitions?.FirstOrDefault();
// Create the shift mapping entity based on the finalShift object also.
var shiftEntity = this.utility.CreateShiftMappingEntity(newShiftFirst, userMappingRecord, kronosUniqueIdFirst);
await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync(
shiftEntity,
newShiftFirst.Id,
monthPartition).ConfigureAwait(false);
var userMappingRecordSec = await this.userMappingProvider.GetUserMappingEntityAsyncNew(
newShiftSecond?.UserId,
aadGroupId).ConfigureAwait(false);
integrationResponse = GenerateResponse(newShiftFirst.Id, HttpStatusCode.OK, null, null);
swapShiftsIntegResponses.Add(integrationResponse);
// When getting the month partition key, make sure to take into account the Kronos Time Zone as well
var actualStartDateTimeStrSec = this.utility.CalculateStartDateTime(
newShiftSecond.SharedShift.StartDateTime).ToString("M/dd/yyyy", provider);
var actualEndDateTimeStrSec = this.utility.CalculateEndDateTime(
newShiftSecond.SharedShift.EndDateTime).ToString("M/dd/yyyy", provider);
// Create the month partition key based on the finalShift object.
var monthPartitionsSec = Common.Utility.GetMonthPartition(actualStartDateTimeStrSec, actualEndDateTimeStrSec);
var monthPartitionSec = monthPartitionsSec?.FirstOrDefault();
// Create the shift mapping entity based on the finalShift object also.
var shiftEntitySec = this.utility.CreateShiftMappingEntity(newShiftSecond, userMappingRecordSec, kronosUniqueIdSecond);
await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync(
shiftEntitySec,
newShiftSecond.Id,
monthPartitionSec).ConfigureAwait(false);
integrationResponse = GenerateResponse(newShiftSecond.Id, HttpStatusCode.OK, null, null);
swapShiftsIntegResponses.Add(integrationResponse);
foreach (var delShifts in deletedShifts)
{
integrationResponse = GenerateResponse(delShifts.Id, HttpStatusCode.OK, null, null);
swapShiftsIntegResponses.Add(integrationResponse);
}
integrationResponse = GenerateResponse(approvedSwapShiftRequest.Id, HttpStatusCode.OK, swapShiftRequest.ETag, null);
swapShiftsIntegResponses.Add(integrationResponse);
foreach (var declinedRequest in autoDeclinedRequests)
{
this.telemetryClient.TrackTrace($"SystemDeclinedOpenShiftRequestId: {declinedRequest.Id}");
var declinedSwapShiftRequest = JsonConvert.DeserializeObject<SwapRequest>(declinedRequest.Body.ToString());
// Get the requests from storage.
var entityToUpdate = await this.swapShiftMappingEntityProvider.GetKronosReqAsync(
declinedRequest.Id).ConfigureAwait(false);
entityToUpdate.KronosStatus = declinedSwapShiftRequest.State;
entityToUpdate.ShiftsStatus = declinedSwapShiftRequest.State;
// Commit the change to the database.
await this.swapShiftMappingEntityProvider.AddOrUpdateSwapShiftMappingAsync(entityToUpdate).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"OpenShiftRequestId: {declinedSwapShiftRequest.Id}, assigned to: {declinedSwapShiftRequest.AssignedTo}, state: {declinedSwapShiftRequest.State}");
// Adding response for system declined open shift request.
integrationResponse = GenerateResponse(declinedSwapShiftRequest.Id, HttpStatusCode.OK, declinedSwapShiftRequest.ETag, null);
swapShiftsIntegResponses.Add(integrationResponse);
}
}
catch (Exception ex)
{
var exceptionProps = new Dictionary<string, string>()
{
{ "NewFirstShiftId", newShiftFirst.Id },
{ "NewSecondShiftId", newShiftSecond.Id },
};
this.telemetryClient.TrackException(ex, exceptionProps);
throw;
}
}
return swapShiftsIntegResponses;
}
/// <summary>
/// Process outbound open shift request.
/// </summary>
/// <param name="openShiftRequest">Open shift request payload.</param>
/// <param name="updateProps">Telemetry properties.</param>
/// <param name="teamsId">The Shifts team id.</param>
/// <returns>Returns list of shiftIntegResponse.</returns>
private async Task<List<ShiftsIntegResponse>> ProcessOutboundOpenShiftRequestAsync(
OpenShiftRequestIS openShiftRequest,
Dictionary<string, string> updateProps,
string teamsId)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOutboundOpenShiftRequestAsync} starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>();
ShiftsIntegResponse openShiftReqSubmitResponse;
updateProps.Add("OpenShiftRequestId", openShiftRequest.Id);
updateProps.Add("OpenShiftId", openShiftRequest.OpenShiftId);
this.telemetryClient.TrackTrace(Resource.IncomingOpenShiftRequest, updateProps);
// This code will be submitting the Open Shift request to Kronos.
openShiftReqSubmitResponse = await this.openShiftRequestController.SubmitOpenShiftRequestToKronosAsync(openShiftRequest, teamsId).ConfigureAwait(false);
responseModelList.Add(openShiftReqSubmitResponse);
this.telemetryClient.TrackTrace($"{Resource.ProcessOutboundOpenShiftRequestAsync} ends at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return responseModelList;
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/ShiftsToKronos/CreateTimeOff/CreateTimeOffActivity.cs
// <copyright file="CreateTimeOffActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.ShiftsToKronos.CreateTimeOff
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Service;
using TimeOffAddRequest = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.ShiftsToKronos.AddRequest;
using TimeOffAddResponse = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.ShiftsToKronos.TimeOffRequests;
using TimeOffSubmitRequest = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.ShiftsToKronos.SubmitRequest;
using TimeOffSubmitResponse = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.ShiftsToKronos.TimeOffRequests.SubmitResponse;
/// <summary>
/// Create TimeOff Activity Class.
/// </summary>
public class CreateTimeOffActivity : ICreateTimeOffActivity
{
private readonly TelemetryClient telemetryClient;
private readonly IApiHelper apiHelper;
/// <summary>
/// Initializes a new instance of the <see cref="CreateTimeOffActivity"/> class.
/// </summary>
/// <param name="telemetryClient">The mechanisms to capture telemetry.</param>
/// <param name="apiHelper">API helper to fetch tuple response by post soap requests.</param>
public CreateTimeOffActivity(TelemetryClient telemetryClient, IApiHelper apiHelper)
{
this.telemetryClient = telemetryClient;
this.apiHelper = apiHelper;
}
/// <summary>
/// Submit time of request which is in draft.
/// </summary>
/// <param name="jSession">jSession object.</param>
/// <param name="personNumber">Person number.</param>
/// <param name="reqId">RequestId of the time off request.</param>
/// <param name="queryStartDate">Query Start.</param>
/// <param name="queryEndDate">Query End.</param>
/// <param name="endPointUrl">Endpoint url for Kronos.</param>
/// <returns>Time of submit response.</returns>
public async Task<TimeOffSubmitResponse.Response> SubmitTimeOffRequestAsync(
string jSession,
string personNumber,
string reqId,
string queryStartDate,
string queryEndDate,
Uri endPointUrl)
{
string querySpan = queryStartDate + '-' + queryEndDate;
string xmlTimeOffRequest = this.CreateSubmitTimeOffRequest(personNumber, reqId, querySpan);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endPointUrl,
ApiConstants.SoapEnvOpen,
xmlTimeOffRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
TimeOffSubmitResponse.Response timeOffSubmitResponse = this.ProcessSubmitResponse(tupleResponse.Item1);
return timeOffSubmitResponse;
}
/// <summary>
/// Send time off request to Kronos API and get response.
/// </summary>
/// <param name="jSession">J Session.</param>
/// <param name="startDateTime">Start Date.</param>
/// <param name="endDateTime">End Date.</param>
/// <param name="personNumber">Person Number.</param>
/// <param name="reason">Reason string.</param>
/// <param name="endPointUrl">Endpoint url for Kronos.</param>
/// <param name="kronosTimeZone">The time zone for Kronos WFC.</param>
/// <returns>Time of add response.</returns>
public async Task<TimeOffAddResponse.Response> TimeOffRequestAsync(
string jSession,
DateTimeOffset startDateTime,
DateTimeOffset endDateTime,
string personNumber,
string reason,
Uri endPointUrl,
TimeZoneInfo kronosTimeZone)
{
string xmlTimeOffRequest = this.CreateAddTimeOffRequest(startDateTime, endDateTime, personNumber, reason, kronosTimeZone);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endPointUrl,
ApiConstants.SoapEnvOpen,
xmlTimeOffRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
TimeOffAddResponse.Response timeOffResponse = this.ProcessResponse(tupleResponse.Item1);
return timeOffResponse;
}
/// <summary>
/// This method will calculate the necessary duration of the time off.
/// </summary>
/// <param name="startDateTime">The start date/time stamp for the time off request.</param>
/// <param name="endDateTime">The end date/time stamp for the time off request.</param>
/// <param name="reason">The time off reason from Shifts.</param>
/// <param name="timeOffPeriod">The list of Time Off periods.</param>
/// <param name="kronosTimeZone">The time zone of Kronos WFC.</param>
/// <returns>A string that represents the duration period.</returns>
private static string CalculateTimeOffPeriod(
DateTimeOffset startDateTime,
DateTimeOffset endDateTime,
string reason,
List<TimeOffAddRequest.TimeOffPeriod> timeOffPeriod,
TimeZoneInfo kronosTimeZone)
{
string duration;
var length = (endDateTime - startDateTime).TotalHours;
DateTimeOffset modifiedEndDateTimeForKronos = endDateTime.AddDays(-1);
if (length % 24 == 0 || length > 24)
{
duration = ApiConstants.FullDayDuration;
timeOffPeriod.Add(
new TimeOffAddRequest.TimeOffPeriod()
{
Duration = duration,
EndDate = modifiedEndDateTimeForKronos.ToString("M/d/yyyy", CultureInfo.InvariantCulture),
PayCodeName = reason,
StartDate = startDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture),
});
}
else
{
duration = ApiConstants.HoursDuration;
timeOffPeriod.Add(
new TimeOffAddRequest.TimeOffPeriod()
{
Duration = duration,
EndDate = endDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture),
PayCodeName = reason,
StartDate = startDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture),
StartTime = TimeZoneInfo.ConvertTime(startDateTime, kronosTimeZone).ToString("hh:mm tt", CultureInfo.InvariantCulture),
Length = Convert.ToString(length, CultureInfo.InvariantCulture),
});
}
return duration;
}
/// <summary>
/// Create XML to submit time off request which is in draft.
/// </summary>
/// <param name="personNumber">Person Number.</param>
/// <param name="reqId">RequestId of the time off request.</param>
/// <param name="querySpan">Query Span.</param>
/// <returns>Submit time off request.</returns>
private string CreateSubmitTimeOffRequest(string personNumber, string reqId, string querySpan)
{
var monthStartDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
var monthEndDt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(monthStartDt.Year, monthStartDt.Month));
TimeOffSubmitRequest.Request rq = new TimeOffSubmitRequest.Request()
{
Action = ApiConstants.SubmitRequests,
EmployeeRequestMgm = new TimeOffSubmitRequest.EmployeeRequestMgmt()
{
Employees = new TimeOffSubmitRequest.Employee() { PersonIdentity = new TimeOffSubmitRequest.PersonIdentity() { PersonNumber = personNumber } },
QueryDateSpan = querySpan,
RequestIds = new TimeOffSubmitRequest.RequestIds() { RequestId = new TimeOffSubmitRequest.RequestId[] { new TimeOffSubmitRequest.RequestId() { Id = reqId } } },
},
};
return rq.XmlSerialize();
}
/// <summary>
/// Deserialize xml response for submit request operation.
/// </summary>
/// <param name="strResponse">Response string.</param>
/// <returns>Process submit response.</returns>
private TimeOffSubmitResponse.Response ProcessSubmitResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<TimeOffSubmitResponse.Response>(xResponse.ToString());
}
/// <summary>
/// Create XML to add time off request.
/// </summary>
/// <param name="startDateTime">Start date.</param>
/// <param name="endDateTime">End Date.</param>
/// <param name="personNumber">Person number.</param>
/// <param name="reason">Reason string.</param>
/// <param name="kronosTimeZone">The time zone of Kronos WFC.</param>
/// <returns>Add time of request.</returns>
private string CreateAddTimeOffRequest(DateTimeOffset startDateTime, DateTimeOffset endDateTime, string personNumber, string reason, TimeZoneInfo kronosTimeZone)
{
var duration = string.Empty;
var timeOffPeriod = new List<TimeOffAddRequest.TimeOffPeriod>();
duration = CalculateTimeOffPeriod(startDateTime, endDateTime, reason, timeOffPeriod, kronosTimeZone);
TimeOffAddRequest.Request rq = new TimeOffAddRequest.Request()
{
Action = ApiConstants.AddRequests,
EmployeeRequestMgm = new TimeOffAddRequest.EmployeeRequestMgmt()
{
Employees = new TimeOffAddRequest.Employee() { PersonIdentity = new TimeOffAddRequest.PersonIdentity() { PersonNumber = personNumber } },
QueryDateSpan = $"{startDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture)} - {endDateTime.ToString("M/d/yyyy", CultureInfo.InvariantCulture)}",
RequestItems = new TimeOffAddRequest.RequestItems()
{
GlobalTimeOffRequestItem = new TimeOffAddRequest.GlobalTimeOffRequestItem()
{
Employee = new TimeOffAddRequest.Employee() { PersonIdentity = new TimeOffAddRequest.PersonIdentity() { PersonNumber = personNumber } },
RequestFor = ApiConstants.TOR,
TimeOffPeriods = new TimeOffAddRequest.TimeOffPeriods() { TimeOffPeriod = timeOffPeriod },
},
},
},
};
return rq.XmlSerialize<TimeOffAddRequest.Request>();
}
/// <summary>
/// Read the xml response into Response object.
/// </summary>
/// <param name="strResponse">xml response string.</param>
/// <returns>Response object.</returns>
private TimeOffAddResponse.Response ProcessResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<TimeOffAddResponse.Response>(xResponse.ToString());
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/TimeOffRequestProvider.cs
// <copyright file="TimeOffRequestProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// This class implements the methods defined in <see cref="ITimeOffRequestProvider"/>.
/// </summary>
public class TimeOffRequestProvider : ITimeOffRequestProvider
{
private const string TimeOffTable = "TimeOffMapping";
private readonly Lazy<Task> initializeTask;
private readonly TelemetryClient telemetryClient;
private CloudTable timeoffEntityMappingTable;
/// <summary>
/// Initializes a new instance of the <see cref="TimeOffRequestProvider"/> class.
/// </summary>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="connectionString">The Azure table storage connection string.</param>
public TimeOffRequestProvider(
TelemetryClient telemetryClient,
string connectionString)
{
this.telemetryClient = telemetryClient;
this.initializeTask = new Lazy<Task>(() => this.InitializeAsync(connectionString));
}
/// <summary>
/// Method to get the TimeOffReqMappingEntities.
/// </summary>
/// <param name="monthPartitionKey">The month partition key.</param>
/// <param name="timeOffReqId">The TimeOffRequestId.</param>
/// <returns>A unit of execution that contains a List of <see cref="TimeOffMappingEntity"/>.</returns>
public async Task<List<TimeOffMappingEntity>> GetAllTimeOffReqMappingEntitiesAsync(string monthPartitionKey, string timeOffReqId)
{
await this.EnsureInitializedAsync().ConfigureAwait(false);
var getEntitiesProps = new Dictionary<string, string>()
{
{ "CurrentCallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, getEntitiesProps);
// Table query
TableQuery<TimeOffMappingEntity> query = new TableQuery<TimeOffMappingEntity>();
query.Where(TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, monthPartitionKey), TableOperators.And, TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("ShiftsRequestId", QueryComparisons.Equal, timeOffReqId), TableOperators.And, TableQuery.GenerateFilterConditionForBool("IsActive", QueryComparisons.Equal, true))));
// Results list
List<TimeOffMappingEntity> results = new List<TimeOffMappingEntity>();
TableContinuationToken continuationToken = null;
if (await this.timeoffEntityMappingTable.ExistsAsync().ConfigureAwait(false))
{
do
{
TableQuerySegment<TimeOffMappingEntity> queryResults = await this.timeoffEntityMappingTable.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
}
while (continuationToken != null);
}
return results;
}
private async Task EnsureInitializedAsync()
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
await this.initializeTask.Value.ConfigureAwait(false);
}
private async Task InitializeAsync(string connectionString)
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();
this.timeoffEntityMappingTable = cloudTableClient.GetTableReference(TimeOffTable);
await this.timeoffEntityMappingTable.CreateIfNotExistsAsync().ConfigureAwait(false);
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/OpenShiftController.cs
// <copyright file="OpenShiftController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.App.KronosWfc.BusinessLogic.OpenShift;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models.RequestModels.OpenShift;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using Newtonsoft.Json;
/// <summary>
/// Open Shift controller.
/// </summary>
[Authorize(Policy = "AppID")]
[Route("api/OpenShifts")]
[ApiController]
public class OpenShiftController : ControllerBase
{
private readonly AppSettings appSettings;
private readonly TelemetryClient telemetryClient;
private readonly IOpenShiftActivity openShiftActivity;
private readonly Utility utility;
private readonly IOpenShiftMappingEntityProvider openShiftMappingEntityProvider;
private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider;
private readonly IHttpClientFactory httpClientFactory;
private readonly IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider;
private readonly BackgroundTaskWrapper taskWrapper;
/// <summary>
/// Initializes a new instance of the <see cref="OpenShiftController"/> class.
/// </summary>
/// <param name="appSettings">Configuration DI.</param>
/// <param name="telemetryClient">Telemetry Client.</param>
/// <param name="openShiftActivity">OpenShift activity.</param>
/// <param name="utility">Unique ID utility DI.</param>
/// <param name="openShiftMappingEntityProvider">Open Shift Entity Mapping DI.</param>
/// <param name="teamDepartmentMappingProvider">Team Department Mapping Provider DI.</param>
/// <param name="httpClientFactory">http client.</param>
/// <param name="openShiftRequestMappingEntityProvider">Open Shift Request Entity Mapping DI.</param>
/// <param name="taskWrapper">Wrapper class instance for BackgroundTask.</param>
public OpenShiftController(
AppSettings appSettings,
TelemetryClient telemetryClient,
IOpenShiftActivity openShiftActivity,
Utility utility,
IOpenShiftMappingEntityProvider openShiftMappingEntityProvider,
ITeamDepartmentMappingProvider teamDepartmentMappingProvider,
IHttpClientFactory httpClientFactory,
IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider,
BackgroundTaskWrapper taskWrapper)
{
if (appSettings is null)
{
throw new ArgumentNullException(nameof(appSettings));
}
this.appSettings = appSettings;
this.telemetryClient = telemetryClient;
this.openShiftActivity = openShiftActivity;
this.utility = utility;
this.openShiftMappingEntityProvider = openShiftMappingEntityProvider;
this.teamDepartmentMappingProvider = teamDepartmentMappingProvider;
this.httpClientFactory = httpClientFactory;
this.openShiftRequestMappingEntityProvider = openShiftRequestMappingEntityProvider;
this.taskWrapper = taskWrapper;
}
/// <summary>
/// Get the list of time off details from Kronos and push it to Shifts.
/// </summary>
/// <param name="isRequestFromLogicApp">Checks if request is coming from logic app or portal.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
internal async Task ProcessOpenShiftsAsync(string isRequestFromLogicApp)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsAsync} started at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)} for isRequestFromLogicApp: {isRequestFromLogicApp}");
if (isRequestFromLogicApp == null)
{
throw new ArgumentNullException(nameof(isRequestFromLogicApp));
}
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
this.utility.SetQuerySpan(Convert.ToBoolean(isRequestFromLogicApp, CultureInfo.InvariantCulture), out var openShiftStartDate, out var openShiftEndDate);
// Check whether date range are in correct format.
var isCorrectDateRange = Utility.CheckDates(openShiftStartDate, openShiftEndDate);
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists && isCorrectDateRange)
{
var monthPartitions = Utility.GetMonthPartition(openShiftStartDate, openShiftEndDate);
// Adding the telemetry properties.
var telemetryProps = new Dictionary<string, string>()
{
{ "MethodName", Resource.ProcessOpenShiftsAsync },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
var processNumberOfOrgJobsInBatch = this.appSettings.ProcessNumberOfOrgJobsInBatch;
var orgJobPaths = await this.teamDepartmentMappingProvider.GetAllOrgJobPathsAsync().ConfigureAwait(false);
var mappedTeams = await this.teamDepartmentMappingProvider.GetMappedTeamToDeptsWithJobPathsAsync().ConfigureAwait(false);
var orgJobsCount = orgJobPaths.Count;
int orgJobPathIterations = Utility.GetIterablesCount(Convert.ToInt32(processNumberOfOrgJobsInBatch, CultureInfo.InvariantCulture), orgJobsCount);
if (monthPartitions != null && monthPartitions.Count > 0)
{
// The monthPartitions is a list of strings which are formatted as: MM_YYYY where
// MM represents the integer representation of the month, and YYYY is the integer
// representation of the year. (i.e. December 2019 = 12_2019) - the month partitions
// are used when the data synced from Kronos is over a wide duration.
foreach (var monthPartitionKey in monthPartitions)
{
if (monthPartitionKey != null)
{
this.telemetryClient.TrackTrace($"Processing data for the month partition: {monthPartitionKey} at {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
Utility.GetNextDateSpan(
monthPartitionKey,
monthPartitions.FirstOrDefault(),
monthPartitions.LastOrDefault(),
openShiftStartDate,
openShiftEndDate,
out string queryStartDate,
out string queryEndDate);
// Add to queue
var processKronosOrgJobsQueue = new Queue<string>(orgJobPaths);
// This for loop will iterate over the number of batches of Org Job Paths.
for (int batchedOpenShiftCount = 0; batchedOpenShiftCount < orgJobPathIterations; batchedOpenShiftCount++)
{
this.telemetryClient.TrackTrace($"OpenShiftController - Processing on iteration number: {batchedOpenShiftCount}");
var processKronosOrgJobsQueueInBatch = processKronosOrgJobsQueue?.Skip(Convert.ToInt32(processNumberOfOrgJobsInBatch, CultureInfo.InvariantCulture) * batchedOpenShiftCount).Take(Convert.ToInt32(processNumberOfOrgJobsInBatch, CultureInfo.InvariantCulture));
// Get the response for a batch of org job paths.
var openShiftsResponse = await this.GetOpenShiftResultsByOrgJobPathInBatchAsync(
allRequiredConfigurations.WFIId,
allRequiredConfigurations.WfmEndPoint,
allRequiredConfigurations.KronosSession,
processKronosOrgJobsQueueInBatch.ToList(),
queryStartDate,
queryEndDate).ConfigureAwait(false);
var openShiftDisplayName = string.Empty;
var openShiftNotes = string.Empty;
var openShiftTheme = this.appSettings.OpenShiftTheme;
if (openShiftsResponse != null)
{
// This foreach loop will iterate through a list of orgJobPaths.
// Each orgJobPath in Kronos corresponds to a Scheduling Group
// in Shifts.
foreach (var orgJob in processKronosOrgJobsQueueInBatch)
{
this.telemetryClient.TrackTrace($"OpenShiftController - Processing the org job path: {orgJob}");
// Open Shift models for Create/Update operation
var lookUpEntriesFoundList = new List<AllOpenShiftMappingEntity>();
var openShiftsNotFoundList = new List<OpenShiftRequestModel>();
var mappedTeam = mappedTeams?.FirstOrDefault(x => x.PartitionKey == allRequiredConfigurations.WFIId &&
x.RowKey == Utility.OrgJobPathDBConversion(orgJob));
// Retrieve lookUpData for the open shift entity.
var lookUpData = await this.openShiftMappingEntityProvider.GetAllOpenShiftMappingEntitiesInBatch(
monthPartitionKey,
mappedTeam?.TeamsScheduleGroupId,
queryStartDate,
queryEndDate).ConfigureAwait(false);
if (lookUpData != null)
{
// This foreach loop will process the openShiftSchedule item(s) that belong to a specific Kronos Org Job Path.
foreach (var openShiftSchedule in openShiftsResponse?.Schedules.Where(x => x.OrgJobPath == orgJob))
{
this.telemetryClient.TrackTrace($"OpenShiftController - Processing the Open Shift schedule for: {openShiftSchedule.OrgJobPath}, and date range: {openShiftSchedule.QueryDateSpan}");
var scheduleShiftCount = (int)openShiftSchedule.ScheduleItems?.ScheduleShifts?.Count;
if (scheduleShiftCount > 0)
{
if (mappedTeam != null)
{
this.telemetryClient.TrackTrace($"OpenShiftController - Processing Open Shifts for the mapped team: {mappedTeam.ShiftsTeamName}");
// This foreach builds the Open Shift object to push to Shifts via Graph API.
foreach (var scheduleShift in openShiftSchedule?.ScheduleItems?.ScheduleShifts)
{
var shiftSegmentCount = scheduleShift.ShiftSegments;
this.telemetryClient.TrackTrace($"OpenShiftController - Processing {scheduleShift.StartDate} with {shiftSegmentCount} segments.");
var openShiftActivity = new List<Activity>();
// This foreach loop will build the OpenShift activities.
foreach (var segment in scheduleShift.ShiftSegments.ShiftSegment)
{
openShiftActivity.Add(new Activity
{
IsPaid = true,
StartDateTime = this.utility.CalculateStartDateTime(segment),
EndDateTime = this.utility.CalculateEndDateTime(segment),
Code = string.Empty,
DisplayName = segment.SegmentTypeName,
});
}
var shift = new OpenShiftRequestModel()
{
SchedulingGroupId = mappedTeam.TeamsScheduleGroupId,
SharedOpenShift = new OpenShiftItem
{
DisplayName = string.Empty,
OpenSlotCount = Constants.ShiftsOpenSlotCount,
Notes = this.utility.GetOpenShiftNotes(scheduleShift),
StartDateTime = openShiftActivity.First().StartDateTime,
EndDateTime = openShiftActivity.Last().EndDateTime,
Theme = openShiftTheme,
Activities = openShiftActivity,
},
};
// Generates the uniqueId for the OpenShift.
shift.KronosUniqueId = this.utility.CreateUniqueId(shift, shift.SchedulingGroupId);
// Logging the output of the KronosHash creation.
this.telemetryClient.TrackTrace("OpenShiftController-KronosHash: " + shift.KronosUniqueId);
if (lookUpData.Count == 0)
{
this.telemetryClient.TrackTrace($"OpenShiftController - Adding {shift.KronosUniqueId} to the openShiftsNotFoundList as the lookUpData count = 0");
openShiftsNotFoundList.Add(shift);
}
else
{
var kronosUniqueIdExists = lookUpData.Where(c => c.RowKey == shift.KronosUniqueId);
if ((kronosUniqueIdExists != default(List<AllOpenShiftMappingEntity>)) && kronosUniqueIdExists.Any())
{
this.telemetryClient.TrackTrace($"OpenShiftController - Adding {kronosUniqueIdExists.FirstOrDefault().RowKey} to the lookUpEntriesFoundList as there is data in the lookUpData list.");
lookUpEntriesFoundList.Add(kronosUniqueIdExists.FirstOrDefault());
}
else
{
this.telemetryClient.TrackTrace($"OpenShiftController - Adding {shift.KronosUniqueId} to the openShiftsNotFoundList.");
openShiftsNotFoundList.Add(shift);
}
}
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.SyncOpenShiftsFromKronos} - There is no mappedTeam found with WFI ID: {allRequiredConfigurations.WFIId}");
continue;
}
}
else
{
this.telemetryClient.TrackTrace($"ScheduleShiftCount - {scheduleShiftCount} for {openShiftSchedule.OrgJobPath}");
continue;
}
}
if (lookUpData.Except(lookUpEntriesFoundList).Any())
{
this.telemetryClient.TrackTrace($"OpenShiftController - The lookUpEntriesFoundList has {lookUpEntriesFoundList.Count} items which could be deleted");
await this.DeleteOrphanDataOpenShiftsEntityMappingAsync(allRequiredConfigurations.ShiftsAccessToken, lookUpEntriesFoundList, lookUpData, mappedTeam).ConfigureAwait(false);
}
if (openShiftsNotFoundList.Count > 0)
{
this.telemetryClient.TrackTrace($"OpenShiftController - The openShiftsNotFoundList has {openShiftsNotFoundList.Count} items which could be added.");
await this.CreateEntryOpenShiftsEntityMappingAsync(allRequiredConfigurations.ShiftsAccessToken, openShiftsNotFoundList, monthPartitionKey, mappedTeam).ConfigureAwait(false);
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.SyncOpenShiftsFromKronos} - There is no lookup data present with the schedulingGroupId: " + mappedTeam?.TeamsScheduleGroupId);
continue;
}
}
}
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.MonthPartitionKeyStatus} - MonthPartitionKey cannot be found please check the data.");
this.telemetryClient.TrackTrace(Resource.SyncOpenShiftsFromKronos, telemetryProps);
continue;
}
}
}
else
{
telemetryProps.Add("MonthPartitionsStatus", "There are no month partitions found!");
}
}
else
{
throw new Exception($"{Resource.SyncOpenShiftsFromKronos} - {Resource.SetUpNotDoneMessage}");
}
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsAsync} ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)} for isRequestFromLogicApp: {isRequestFromLogicApp}");
}
/// <summary>
/// Method that creates the Open Shift Entity Mapping, posts to Graph, and saves the data in Azure
/// table storage upon successful creation in Graph.
/// </summary>
/// <param name="accessToken">The Graph access token.</param>
/// <param name="openShiftNotFound">The open shift to post to Graph.</param>
/// <param name="monthPartitionKey">The monthwise partition key.</param>
/// <param name="mappedTeam">The mapped team.</param>
/// <returns>A unit of execution.</returns>
private async Task CreateEntryOpenShiftsEntityMappingAsync(
string accessToken,
List<OpenShiftRequestModel> openShiftNotFound,
string monthPartitionKey,
TeamToDepartmentJobMappingEntity mappedTeam)
{
this.telemetryClient.TrackTrace($"CreateEntryOpenShiftsEntityMappingAsync start at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
// This foreach loop iterates over the OpenShifts which are to be added into Shifts UI.
foreach (var item in openShiftNotFound)
{
this.telemetryClient.TrackTrace($"Processing the open shift entity with schedulingGroupId: {item.SchedulingGroupId}");
// create entries from not found list
var telemetryProps = new Dictionary<string, string>()
{
{ "SchedulingGroupId", item.SchedulingGroupId },
};
var requestString = JsonConvert.SerializeObject(item);
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + mappedTeam.TeamId + "/schedule/openShifts")
{
Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var openShiftResponse = JsonConvert.DeserializeObject<Models.Response.OpenShifts.GraphOpenShift>(responseContent);
var openShiftMappingEntity = this.CreateNewOpenShiftMappingEntity(openShiftResponse, item.KronosUniqueId, monthPartitionKey, mappedTeam?.RowKey);
telemetryProps.Add("ResultCode", response.StatusCode.ToString());
telemetryProps.Add("TeamsOpenShiftId", openShiftResponse.Id);
this.telemetryClient.TrackTrace(Resource.CreateEntryOpenShiftsEntityMappingAsync, telemetryProps);
await this.openShiftMappingEntityProvider.SaveOrUpdateOpenShiftMappingEntityAsync(openShiftMappingEntity).ConfigureAwait(false);
}
else
{
var errorProps = new Dictionary<string, string>()
{
{ "ResultCode", response.StatusCode.ToString() },
{ "ResponseHeader", response.Headers.ToString() },
{ "SchedulingGroupId", item.SchedulingGroupId },
{ "MappedTeamId", mappedTeam?.TeamId },
};
// Have the log to capture the 403.
this.telemetryClient.TrackTrace(Resource.CreateEntryOpenShiftsEntityMappingAsync, errorProps);
}
}
}
this.telemetryClient.TrackTrace($"CreateEntryOpenShiftsEntityMappingAsync end at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
}
/// <summary>
/// Method that will delete an orphaned open shift entity.
/// </summary>
/// <param name="accessToken">The MS Graph Access token.</param>
/// <param name="lookUpDataFoundList">The found open shifts.</param>
/// <param name="lookUpData">All of the look up (reference data).</param>
/// <param name="mappedTeam">The list of mapped teams.</param>
/// <returns>A unit of execution.</returns>
private async Task DeleteOrphanDataOpenShiftsEntityMappingAsync(
string accessToken,
List<AllOpenShiftMappingEntity> lookUpDataFoundList,
List<AllOpenShiftMappingEntity> lookUpData,
TeamToDepartmentJobMappingEntity mappedTeam)
{
// delete entries from orphan list
var orphanList = lookUpData.Except(lookUpDataFoundList);
this.telemetryClient.TrackTrace($"DeleteOrphanDataOpenShiftsEntityMappingAsync started at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
// This foreach loop iterates over items that are to be deleted from Shifts UI. In other
// words, these are Open Shifts which have been deleted in Kronos WFC, and those deletions
// are propagating to Shifts.
foreach (var item in orphanList)
{
this.telemetryClient.TrackTrace($"OpenShiftController - Checking {item.TeamsOpenShiftId} to see if there are any Open Shift Requests");
var isInOpenShiftRequestMappingTable = await this.openShiftRequestMappingEntityProvider.CheckOpenShiftRequestExistance(item.TeamsOpenShiftId).ConfigureAwait(false);
if (!isInOpenShiftRequestMappingTable)
{
this.telemetryClient.TrackTrace($"{item.TeamsOpenShiftId} is not in the Open Shift Request mapping table - deletion can be done.");
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, "teams/" + mappedTeam.TeamId + "/schedule/openShifts/" + item.TeamsOpenShiftId))
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var successfulDeleteProps = new Dictionary<string, string>()
{
{ "ResponseCode", response.StatusCode.ToString() },
{ "ResponseHeader", response.Headers.ToString() },
{ "MappedTeamId", mappedTeam?.TeamId },
{ "OpenShiftIdToDelete", item.TeamsOpenShiftId },
};
this.telemetryClient.TrackTrace(Resource.DeleteOrphanDataOpenShiftsEntityMappingAsync, successfulDeleteProps);
await this.openShiftMappingEntityProvider.DeleteOrphanDataFromOpenShiftMappingAsync(item).ConfigureAwait(false);
}
else
{
var errorDeleteProps = new Dictionary<string, string>()
{
{ "ResponseCode", response.StatusCode.ToString() },
{ "ResponseHeader", response.Headers.ToString() },
{ "MappedTeamId", mappedTeam?.TeamId },
{ "OpenShiftIdToDelete", item.TeamsOpenShiftId },
};
this.telemetryClient.TrackTrace(Resource.DeleteOrphanDataOpenShiftsEntityMappingAsync, errorDeleteProps);
}
}
}
else
{
// Log that the open shift exists in another table and it should not be deleted.
this.telemetryClient.TrackTrace($"OpenShiftController - Open Shift ID: {item.TeamsOpenShiftId} is being handled by another process.");
}
}
this.telemetryClient.TrackTrace($"DeleteOrphanDataOpenShiftsEntityMappingAsync ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
}
/// <summary>
/// Method that will get the open shifts in a batch manner.
/// </summary>
/// <param name="workforceIntegrationId">The Workforce Integration Id.</param>
/// <param name="kronosEndpoint">The Kronos WFC API Endpoint.</param>
/// <param name="jSession">The Kronos Jsession.</param>
/// <param name="orgJobPathsList">The list of org job paths.</param>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns>A unit of execution that contains the Kronos response model.</returns>
private async Task<App.KronosWfc.Models.ResponseEntities.OpenShift.Batch.Response> GetOpenShiftResultsByOrgJobPathInBatchAsync(
string workforceIntegrationId,
string kronosEndpoint,
string jSession,
List<string> orgJobPathsList,
string startDate,
string endDate)
{
this.telemetryClient.TrackTrace($"OpenShiftController - GetOpenShiftResultsByOrgJobPathInBatchAsync started at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
var telemetryProps = new Dictionary<string, string>()
{
{ "WorkforceIntegrationId", workforceIntegrationId },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(Resource.GetOpenShiftResultsByOrgJobPathInBatchAsync, telemetryProps);
var openShiftQueryDateSpan = $"{startDate}-{endDate}";
var openShiftRequests = await this.openShiftActivity.GetOpenShiftDetailsInBatchAsync(
new Uri(kronosEndpoint),
jSession,
orgJobPathsList,
openShiftQueryDateSpan).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"OpenShiftController - GetOpenShiftResultsByOrgJobPathInBatchAsync ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return openShiftRequests;
}
/// <summary>
/// Method that will create a new Open Shift Entity Mapping that conforms to the newest schema.
/// </summary>
/// <param name="responseModel">The OpenShift response from MS Graph.</param>
/// <param name="uniqueId">The Kronos Unique Id.</param>
/// <param name="monthPartitionKey">The monthwise partition key.</param>
/// <param name="orgJobPath">The Kronos Org Job Path.</param>
/// <returns>The new AllOpenShiftMappingEntity which conforms to schema.</returns>
private AllOpenShiftMappingEntity CreateNewOpenShiftMappingEntity(
Models.Response.OpenShifts.GraphOpenShift responseModel,
string uniqueId,
string monthPartitionKey,
string orgJobPath)
{
var createNewOpenShiftMappingEntityProps = new Dictionary<string, string>()
{
{ "GraphOpenShiftId", responseModel.Id },
{ "GraphOpenShiftEtag", responseModel.ETag },
{ "KronosUniqueId", uniqueId },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
AllOpenShiftMappingEntity openShiftMappingEntity = new AllOpenShiftMappingEntity
{
PartitionKey = monthPartitionKey,
RowKey = uniqueId,
TeamsOpenShiftId = responseModel.Id,
KronosSlots = Constants.KronosOpenShiftsSlotCount,
SchedulingGroupId = responseModel.SchedulingGroupId,
OrgJobPath = orgJobPath,
OpenShiftStartDate = this.utility.UTCToKronosTimeZone(responseModel.SharedOpenShift.StartDateTime),
};
this.telemetryClient.TrackTrace(Resource.CreateNewOpenShiftMappingEntity, createNewOpenShiftMappingEntityProps);
return openShiftMappingEntity;
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.Models/ResponseEntities/Shifts/UpcomingShifts/ScheduleItems.cs
// <copyright file="ScheduleItems.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.Shifts.UpcomingShifts
{
using System.Xml.Serialization;
/// <summary>
/// Gets or sets the scheduleItems.
/// </summary>
public class ScheduleItems
{
/// <summary>
/// Gets or sets the scheduleShift.
/// </summary>
[XmlElement("ScheduleShift", typeof(ScheduleShift))]
#pragma warning disable CA1819 // Properties should not return arrays
public ScheduleShift[] ScheduleShift { get; set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// Gets or sets the schedulePayCodeEdit.
/// </summary>
[XmlElement("SchedulePayCodeEdit", typeof(SchedulePayCodeEdit))]
#pragma warning disable CA1819 // Properties should not return arrays
public SchedulePayCodeEdit[] SchedulePayCodeEdit { get; set; }
#pragma warning restore CA1819 // Properties should not return arrays
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/ITeamDepartmentMappingProvider.cs
// <copyright file="ITeamDepartmentMappingProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
/// <summary>
/// The interface for defining the necessary methods to get the necessary mappings
/// between a Team in Shifts and a Department in Kronos.
/// </summary>
public interface ITeamDepartmentMappingProvider
{
/// <summary>
/// Retrieves a single TeamDepartmentMapping from Azure Table storage.
/// </summary>
/// <param name="workForceIntegrationId">WorkForceIntegration Id.</param>
/// <param name="orgJobPath">Kronos Org Job Path.</param>
/// <returns>A unit of execution that boxes a <see cref="ShiftsTeamDepartmentMappingEntity"/>.</returns>
Task<TeamToDepartmentJobMappingEntity> GetTeamMappingForOrgJobPathAsync(string workForceIntegrationId, string orgJobPath);
/// <summary>
/// Saving or updating a mapping between a Team in Shifts and Department in Kronos.
/// </summary>
/// <param name="shiftsTeamsDetails">Shifts team details fetched via Graph api calls.</param>
/// <param name="kronosDepartmentName">Department name fetched from Kronos.</param>
/// <param name="workforceIntegrationId">The Workforce Integration Id.</param>
/// <param name="tenantId">Tenant Id.</param>
/// <returns><see cref="Task"/> that resolves successfully if the data was saved successfully.</returns>
Task<bool> SaveOrUpdateShiftsTeamDepartmentMappingAsync(
Team shiftsTeamsDetails,
string kronosDepartmentName,
string workforceIntegrationId,
string tenantId);
/// <summary>
/// Function that will return all of the teams that are mapped in Azure Table storage.
/// </summary>
/// <returns>A list of the mapped teams.</returns>
Task<List<ShiftsTeamDepartmentMappingEntity>> GetMappedTeamDetailsAsync();
/// <summary>
/// This method definition will be getting all of the team to department mappings
/// that have OrgJobPaths.
/// </summary>
/// <returns>A list of TeamToDepartmentJobMappingEntity.</returns>
Task<List<TeamToDepartmentJobMappingEntity>> GetMappedTeamToDeptsWithJobPathsAsync();
/// <summary>
/// This method will get all of the OrgJobPaths at one shot.
/// </summary>
/// <returns>A list of string records contained in a unit of execution.</returns>
Task<List<string>> GetAllOrgJobPathsAsync();
/// <summary>
/// Method to save or update Teams to Department mapping.
/// </summary>
/// <param name="entity">The entity to delete.</param>
/// <returns>http status code representing the asynchronous operation.</returns>
Task<bool> TeamsToDepartmentMappingAsync(TeamsDepartmentMappingModel entity);
/// <summary>
/// Function that will return all of the teams and department that are mapped in Azure Table storage.
/// </summary>
/// <returns>List of Team and Department mapping model.</returns>
Task<List<TeamsDepartmentMappingModel>> GetTeamDeptMappingDetailsAsync();
/// <summary>
/// Method to delete teams and Department mapping.
/// </summary>
/// <param name="partitionKey">The partition key.</param>
/// <param name="rowKey">The row key.</param>
/// <returns>boolean value that indicates delete success.</returns>
Task<bool> DeleteMappedTeamDeptDetailsAsync(string partitionKey, string rowKey);
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TimeOffRequestsController.cs
// <copyright file="TimeOffRequestsController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.App.KronosWfc.BusinessLogic.ShiftsToKronos.CreateTimeOff;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using TimeOffRequestResponse = Microsoft.Teams.Shifts.Integration.API.Models.Response.TimeOffRequest;
/// <summary>
/// Time Off Requests controller.
/// </summary>
[Authorize(Policy = "AppID")]
[Route("api/TimeOffRequests")]
[ApiController]
public class TimeOffRequestsController : ControllerBase
{
private readonly AppSettings appSettings;
private readonly TelemetryClient telemetryClient;
private readonly ICreateTimeOffActivity createTimeOffActivity;
private readonly IUserMappingProvider userMappingProvider;
private readonly ITimeOffReasonProvider timeOffReasonProvider;
private readonly IAzureTableStorageHelper azureTableStorageHelper;
private readonly ITimeOffRequestProvider timeOffReqMappingEntityProvider;
private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider;
private readonly Utility utility;
private readonly IHttpClientFactory httpClientFactory;
private readonly BackgroundTaskWrapper taskWrapper;
/// <summary>
/// Initializes a new instance of the <see cref="TimeOffRequestsController"/> class.
/// </summary>
/// <param name="appSettings">Configuration DI.</param>
/// <param name="telemetryClient">Telemetry Client.</param>
/// <param name="userMappingProvider">User To User Mapping Provider.</param>
/// <param name="createTimeOffActivity">Create time off activity.</param>
/// <param name="timeOffReasonProvider">Paycodes to Time Off Reasons Mapping provider.</param>
/// <param name="utility">The local Utility DI.</param>
/// <param name="azureTableStorageHelper">The Azure table storage helper.</param>
/// <param name="timeOffReqMappingEntityProvider">time off entity provider.</param>
/// <param name="teamDepartmentMappingProvider">TeamDepartmentMapping provider DI.</param>
/// <param name="httpClientFactory">http client.</param>
/// <param name="taskWrapper">Wrapper class instance for BackgroundTask.</param>
public TimeOffRequestsController(
AppSettings appSettings,
TelemetryClient telemetryClient,
ICreateTimeOffActivity createTimeOffActivity,
IUserMappingProvider userMappingProvider,
ITimeOffReasonProvider timeOffReasonProvider,
IAzureTableStorageHelper azureTableStorageHelper,
ITimeOffRequestProvider timeOffReqMappingEntityProvider,
ITeamDepartmentMappingProvider teamDepartmentMappingProvider,
Utility utility,
IHttpClientFactory httpClientFactory,
BackgroundTaskWrapper taskWrapper)
{
this.appSettings = appSettings;
this.telemetryClient = telemetryClient;
this.createTimeOffActivity = createTimeOffActivity;
this.userMappingProvider = userMappingProvider;
this.timeOffReasonProvider = timeOffReasonProvider;
this.azureTableStorageHelper = azureTableStorageHelper;
this.timeOffReqMappingEntityProvider = timeOffReqMappingEntityProvider;
this.teamDepartmentMappingProvider = teamDepartmentMappingProvider;
this.utility = utility;
this.httpClientFactory = httpClientFactory;
this.taskWrapper = taskWrapper;
}
/// <summary>
/// start timeoffrequests sync from Kronos and push it to Shifts.
/// </summary>
/// <param name="isRequestFromLogicApp">Checks if request is coming from logic app or portal.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
internal async Task ProcessTimeOffRequestsAsync(string isRequestFromLogicApp)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessTimeOffRequetsAsync} starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)} for isRequestFromLogicApp: " + isRequestFromLogicApp);
var tenantId = this.appSettings.TenantId;
var clientId = this.appSettings.ClientId;
var clientSecret = this.appSettings.ClientSecret;
var instance = this.appSettings.Instance;
var graphBetaUrl = this.appSettings.GraphBetaApiUrl;
var timeOffStartDate = string.Empty;
var timeOffEndDate = string.Empty;
this.utility.SetQuerySpan(Convert.ToBoolean(isRequestFromLogicApp, CultureInfo.InvariantCulture), out timeOffStartDate, out timeOffEndDate);
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
// Check whether date range are in correct format.
var isCorrectDateRange = Utility.CheckDates(timeOffStartDate, timeOffEndDate);
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists && isCorrectDateRange)
{
TimeOffRequestResponse.TimeOffRequestRes timeOffRequestContent = default(TimeOffRequestResponse.TimeOffRequestRes);
// Get the mapped user details from user to user mapping table.
var allUsers = await this.GetAllMappedUserDetailsAsync(allRequiredConfigurations.WFIId).ConfigureAwait(false);
// Get distinct Teams.
var allteamDetails = allUsers?.Select(x => x.ShiftTeamId).Distinct().ToList();
// Get list of time off reasons from User mapping table
var timeOffReasons = await this.timeOffReasonProvider.GetTimeOffReasonsAsync().ConfigureAwait(false);
var monthPartitions = Utility.GetMonthPartition(timeOffStartDate, timeOffEndDate);
List<TimeOffRequestResponse.TimeOffRequestItem> timeOffRequestItems = new List<TimeOffRequestResponse.TimeOffRequestItem>();
bool hasMoreTimeOffs = false;
if (monthPartitions != null && monthPartitions.Count > 0)
{
foreach (var monthPartitionKey in monthPartitions)
{
timeOffRequestItems.Clear();
hasMoreTimeOffs = false;
string queryStartDate, queryEndDate;
Utility.GetNextDateSpan(
monthPartitionKey,
monthPartitions.FirstOrDefault(),
monthPartitions.LastOrDefault(),
timeOffStartDate,
timeOffEndDate,
out queryStartDate,
out queryEndDate);
foreach (var team in allteamDetails)
{
timeOffRequestItems.Clear();
hasMoreTimeOffs = false;
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
Uri requestUri = new Uri(graphBetaUrl + "teams/" + team + "/schedule/timeoffrequests?$filter=state eq 'pending'");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", allRequiredConfigurations.ShiftsAccessToken);
do
{
using (var httpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = requestUri,
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
timeOffRequestContent = await response.Content.ReadAsAsync<TimeOffRequestResponse.TimeOffRequestRes>().ConfigureAwait(false);
timeOffRequestItems.AddRange(timeOffRequestContent.TORItem);
if (timeOffRequestContent.NextLink != null)
{
hasMoreTimeOffs = true;
requestUri = timeOffRequestContent.NextLink;
}
else
{
hasMoreTimeOffs = false;
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffRequestsFromShiftsToKronos - " + response.StatusCode.ToString());
}
}
}
while (hasMoreTimeOffs == true);
if (timeOffRequestItems != null && timeOffRequestItems.Count > 0)
{
foreach (var item in timeOffRequestItems)
{
var timeOffReqStartDate = this.utility.UTCToKronosTimeZone(item.StartDateTime);
if (timeOffReqStartDate < DateTime.ParseExact(queryStartDate, Common.Constants.DateFormat, CultureInfo.InvariantCulture)
|| timeOffReqStartDate > DateTime.ParseExact(queryEndDate, Common.Constants.DateFormat, CultureInfo.InvariantCulture).AddDays(1))
{
continue;
}
List<TimeOffMappingEntity> timeOffMappingEntity = await this.timeOffReqMappingEntityProvider.GetAllTimeOffReqMappingEntitiesAsync(
monthPartitionKey,
item.Id).ConfigureAwait(false);
if (timeOffMappingEntity.Count == 0)
{
var timeOffReason = timeOffReasons.Where(t => t.TimeOffReasonId == item.TimeOffReasonId).FirstOrDefault();
var personDetails = allUsers.Where(u => u.ShiftUserId == Convert.ToString(item.SenderUserId, CultureInfo.InvariantCulture)).FirstOrDefault();
// Get the Kronos WFC API Time Zone from App Settings.
var kronosTimeZoneId = this.appSettings.KronosTimeZone;
var kronosTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(kronosTimeZoneId);
// Create the Kronos Time Off Request.
var timeOffResponse = await this.createTimeOffActivity.TimeOffRequestAsync(
allRequiredConfigurations.KronosSession,
item.StartDateTime,
item.EndDateTime,
personDetails?.KronosPersonNumber,
timeOffReason?.RowKey,
new Uri(allRequiredConfigurations.WfmEndPoint),
kronosTimeZoneInfo).ConfigureAwait(false);
// If there is an error from Kronos side.
if (string.IsNullOrWhiteSpace(timeOffResponse?.Error?.Message))
{
var submitTimeOffResponse = await this.createTimeOffActivity.SubmitTimeOffRequestAsync(
allRequiredConfigurations.KronosSession,
personDetails.KronosPersonNumber,
timeOffResponse?.EmployeeRequestMgm?.RequestItem?.GlobalTimeOffRequestItms?.FirstOrDefault()?.Id,
queryStartDate,
queryEndDate,
new Uri(allRequiredConfigurations.WfmEndPoint)).ConfigureAwait(false);
TimeOffMappingEntity newTimeOffReq = new TimeOffMappingEntity();
if (submitTimeOffResponse?.Status == ApiConstants.Failure)
{
newTimeOffReq.IsActive = false;
}
else
{
newTimeOffReq.IsActive = true;
}
newTimeOffReq.Duration = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault().Duration;
newTimeOffReq.EndDate = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault().EndDate;
newTimeOffReq.StartDate = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault().StartDate;
newTimeOffReq.StartTime = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault().StartTime;
newTimeOffReq.PayCodeName = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().TimeOffPeriodsList.TimeOffPerd.FirstOrDefault().PayCodeName;
newTimeOffReq.KronosPersonNumber = timeOffResponse.EmployeeRequestMgm.Employees.PersonIdentity.PersonNumber;
newTimeOffReq.PartitionKey = monthPartitionKey;
newTimeOffReq.RowKey = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id;
newTimeOffReq.ShiftsRequestId = item.Id;
newTimeOffReq.KronosRequestId = timeOffResponse.EmployeeRequestMgm.RequestItem.GlobalTimeOffRequestItms.FirstOrDefault().Id;
newTimeOffReq.StatusName = ApiConstants.SubmitRequests;
this.AddorUpdateTimeOffMappingAsync(newTimeOffReq);
}
else
{
this.telemetryClient.TrackTrace(timeOffResponse.Error.DetailErrors.Error[0].Message);
}
}
}
}
}
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffRequestsFromShifsToKronos - " + Resource.NullMonthPartitionsMessage);
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffRequestsFromShiftsToKronos - " + Resource.SetUpNotDoneMessage);
}
this.telemetryClient.TrackTrace($"{Resource.ProcessTimeOffRequetsAsync} ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
}
/// <summary>
/// Method to either add or update the Time Off Entity Mapping.
/// </summary>
/// <param name="timeOffMappingEntity">A type of <see cref="TimeOffMappingEntity"/>.</param>
private async void AddorUpdateTimeOffMappingAsync(TimeOffMappingEntity timeOffMappingEntity)
{
await this.azureTableStorageHelper.InsertOrMergeTableEntityAsync(timeOffMappingEntity, "TimeOffMapping").ConfigureAwait(false);
}
/// <summary>
/// Get All users for time off.
/// </summary>
/// <returns>A task.</returns>
private async Task<IEnumerable<UserDetailsModel>> GetAllMappedUserDetailsAsync(
string workForceIntegrationId)
{
List<UserDetailsModel> kronosUsers = new List<UserDetailsModel>();
List<AllUserMappingEntity> mappedUsersResult = await this.userMappingProvider.GetAllMappedUserDetailsAsync().ConfigureAwait(false);
foreach (var element in mappedUsersResult)
{
var teamMappingEntity = await this.teamDepartmentMappingProvider.GetTeamMappingForOrgJobPathAsync(
workForceIntegrationId,
element.PartitionKey).ConfigureAwait(false);
// If team department mapping for a user not present. Skip the user.
if (teamMappingEntity != null)
{
kronosUsers.Add(new UserDetailsModel
{
KronosPersonNumber = element.RowKey,
ShiftUserId = element.ShiftUserAadObjectId,
ShiftTeamId = teamMappingEntity.TeamId,
ShiftScheduleGroupId = teamMappingEntity.TeamsScheduleGroupId,
OrgJobPath = element.PartitionKey,
ShiftUserDisplayName = element.ShiftUserDisplayName,
});
}
}
return kronosUsers;
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Models/IntegrationAPI/SetupDetails.cs
// <copyright file="SetupDetails.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Models.IntegrationAPI
{
/// <summary>
/// This class models the SetupDetails.
/// </summary>
public class SetupDetails
{
/// <summary>
/// Gets or sets the ErrorMessage.
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// Gets or sets the WFI Id.
/// </summary>
public string WFIId { get; set; }
/// <summary>
/// Gets or sets the KronosSession.
/// </summary>
public string KronosSession { get; set; }
/// <summary>
/// Gets or sets the MS Graph Access token.
/// </summary>
public string ShiftsAccessToken { get; set; }
/// <summary>
/// Gets or sets the Kronos API Endpoint.
/// </summary>
public string WfmEndPoint { get; set; }
/// <summary>
/// Gets or sets the TenantId.
/// </summary>
public string TenantId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether or not the prerequisites have been established.
/// </summary>
public bool IsAllSetUpExists { get; set; }
/// <summary>
/// Gets or sets the AAD Object Id of the Shifts Admin (Admin using the configurator web app).
/// </summary>
public string ShiftsAdminAadObjectId { get; set; }
/// <summary>
/// Gets or sets the Kronos User Name.
/// </summary>
public string KronosUserName { get; set; }
/// <summary>
/// Gets or sets the Kronos Password.
/// </summary>
public string KronosPassword { get; set; }
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/ITimeOffMappingEntityProvider.cs
// <copyright file="ITimeOffMappingEntityProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
/// <summary>
/// This interface defines all of the necessary methods that are required for mapping time off between Kronos and Shifts.
/// </summary>
public interface ITimeOffMappingEntityProvider
{
/// <summary>
/// Get all the time off entities.
/// </summary>
/// <param name="processKronosUsersInBatchList">Users in batch.</param>
/// <param name="monthPartitionKey">Month Partition.</param>
/// <returns>Mapped time off entities based on month partition and batched users.</returns>
Task<List<TimeOffMappingEntity>> GetAllTimeOffMappingEntitiesAsync(
IEnumerable<UserDetailsModel> processKronosUsersInBatchList,
string monthPartitionKey);
}
}
<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TimeOffController.cs
// <copyright file="TimeOffController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Teams.App.KronosWfc.BusinessLogic.TimeOff;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.HyperFind;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.TimeOffRequests;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.API.Models.Response.TimeOffRequest;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using Newtonsoft.Json;
using TimeOffReq = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.TimeOffRequests;
using TimeOffRequest = Microsoft.Teams.Shifts.Integration.API.Models.Response.TimeOffRequest;
/// <summary>
/// Time off controller.
/// </summary>
[Route("api/TimeOff")]
[Authorize(Policy = "AppID")]
[ApiController]
public class TimeOffController : Controller
{
private readonly AppSettings appSettings;
private readonly TelemetryClient telemetryClient;
private readonly IUserMappingProvider userMappingProvider;
private readonly ITimeOffActivity timeOffActivity;
private readonly ITimeOffReasonProvider timeOffReasonProvider;
private readonly IAzureTableStorageHelper azureTableStorageHelper;
private readonly ITimeOffMappingEntityProvider timeOffMappingEntityProvider;
private readonly Utility utility;
private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider;
private readonly IHttpClientFactory httpClientFactory;
private readonly BackgroundTaskWrapper taskWrapper;
/// <summary>
/// Initializes a new instance of the <see cref="TimeOffController"/> class.
/// </summary>
/// <param name="appSettings">Application Settings DI.</param>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="userMappingProvider">The User Mapping Provider DI.</param>
/// <param name="timeOffActivity">Time Off Activity DI.</param>
/// <param name="timeOffReasonProvider">Time Off Reason Provider DI.</param>
/// <param name="azureTableStorageHelper">Azure Storage Helper DI.</param>
/// <param name="timeOffMappingEntityProvider">Time Off Mapping Provider DI.</param>
/// <param name="utility">Utility DI.</param>
/// <param name="teamDepartmentMappingProvider">Team Department Mapping Provider DI.</param>
/// <param name="httpClientFactory">HttpClientFactory DI.</param>
/// <param name="taskWrapper">Wrapper class instance for BackgroundTask.</param>
public TimeOffController(
AppSettings appSettings,
TelemetryClient telemetryClient,
IUserMappingProvider userMappingProvider,
ITimeOffActivity timeOffActivity,
ITimeOffReasonProvider timeOffReasonProvider,
IAzureTableStorageHelper azureTableStorageHelper,
ITimeOffMappingEntityProvider timeOffMappingEntityProvider,
Utility utility,
ITeamDepartmentMappingProvider teamDepartmentMappingProvider,
IHttpClientFactory httpClientFactory,
BackgroundTaskWrapper taskWrapper)
{
this.appSettings = appSettings;
this.telemetryClient = telemetryClient;
this.userMappingProvider = userMappingProvider;
this.timeOffActivity = timeOffActivity;
this.timeOffReasonProvider = timeOffReasonProvider;
this.azureTableStorageHelper = azureTableStorageHelper;
this.timeOffMappingEntityProvider = timeOffMappingEntityProvider ?? throw new ArgumentNullException(nameof(timeOffMappingEntityProvider));
this.utility = utility;
this.teamDepartmentMappingProvider = teamDepartmentMappingProvider;
this.httpClientFactory = httpClientFactory;
this.taskWrapper = taskWrapper;
}
/// <summary>
/// Get the list of time off details from Kronos and push it to Shifts.
/// </summary>
/// <param name="isRequestFromLogicApp">True if request is coming from logic app.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
internal async Task ProcessTimeOffsAsync(string isRequestFromLogicApp)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessTimeOffsAsync} started, isRequestFromLogicApp: {isRequestFromLogicApp}");
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
var timeOffReasons = await this.timeOffReasonProvider.GetTimeOffReasonsAsync().ConfigureAwait(false);
this.utility.SetQuerySpan(Convert.ToBoolean(isRequestFromLogicApp, CultureInfo.InvariantCulture), out var timeOffStartDate, out var timeOffEndDate);
// Check whether date range are in correct format.
var isCorrectDateRange = Utility.CheckDates(timeOffStartDate, timeOffEndDate);
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists && isCorrectDateRange)
{
// Get the mapped user details from user to user mapping table.
var allUsers = await this.GetAllMappedUserDetailsAsync(allRequiredConfigurations.WFIId).ConfigureAwait(false);
var monthPartitions = Utility.GetMonthPartition(timeOffStartDate, timeOffEndDate);
var processNumberOfUsersInBatch = this.appSettings.ProcessNumberOfUsersInBatch;
var userCount = allUsers.Count();
int userIteration = Utility.GetIterablesCount(Convert.ToInt32(processNumberOfUsersInBatch, CultureInfo.InvariantCulture), userCount);
var graphClient = await this.CreateGraphClientWithDelegatedAccessAsync(allRequiredConfigurations.ShiftsAccessToken).ConfigureAwait(false);
if (monthPartitions != null && monthPartitions.Count > 0)
{
foreach (var monthPartitionKey in monthPartitions)
{
Utility.GetNextDateSpan(
monthPartitionKey,
monthPartitions.FirstOrDefault(),
monthPartitions.LastOrDefault(),
timeOffStartDate,
timeOffEndDate,
out var queryStartDate,
out var queryEndDate);
var processUsersInBatchList = new List<ResponseHyperFindResult>();
var usersDetails = allUsers?.ToList();
// TODO #1 - Add the code for checking the dates.
foreach (var item in usersDetails)
{
processUsersInBatchList.Add(new ResponseHyperFindResult
{
PersonNumber = item.KronosPersonNumber,
});
}
var processBatchUsersQueue = new Queue<ResponseHyperFindResult>(processUsersInBatchList);
var processKronosUsersQueue = new Queue<UserDetailsModel>(allUsers);
for (int batchedUserCount = 0; batchedUserCount < userIteration; batchedUserCount++)
{
var processKronosUsersQueueInBatch = processKronosUsersQueue?.Skip(Convert.ToInt32(processNumberOfUsersInBatch, CultureInfo.InvariantCulture) * batchedUserCount).Take(Convert.ToInt32(processNumberOfUsersInBatch, CultureInfo.InvariantCulture));
var processBatchUsersQueueInBatch = processBatchUsersQueue?.Skip(Convert.ToInt32(processNumberOfUsersInBatch, CultureInfo.InvariantCulture) * batchedUserCount).Take(Convert.ToInt32(processNumberOfUsersInBatch, CultureInfo.InvariantCulture));
var lookUpData = await this.timeOffMappingEntityProvider.GetAllTimeOffMappingEntitiesAsync(
processKronosUsersQueueInBatch,
monthPartitionKey).ConfigureAwait(false);
var timeOffDetails = await this.GetTimeOffResultsByBatchAsync(
processBatchUsersQueueInBatch.ToList(),
allRequiredConfigurations.WfmEndPoint,
allRequiredConfigurations.WFIId,
allRequiredConfigurations.KronosSession,
queryStartDate,
queryEndDate).ConfigureAwait(false);
if (timeOffDetails?.RequestMgmt?.RequestItems?.GlobalTimeOffRequestItem is null)
{
continue;
}
var timeOffResponseDetails = timeOffDetails?.RequestMgmt?.RequestItems?.GlobalTimeOffRequestItem;
var timeOffLookUpEntriesFoundList = new List<TimeOffMappingEntity>();
var timeOffNotFoundList = new List<GlobalTimeOffRequestItem>();
var userModelList = new List<UserDetailsModel>();
var userModelNotFoundList = new List<UserDetailsModel>();
var kronosPayCodeList = new List<PayCodeToTimeOffReasonsMappingEntity>();
var timeOffRequestsPayCodeList = new List<PayCodeToTimeOffReasonsMappingEntity>();
var globalTimeOffRequestDetails = new List<GlobalTimeOffRequestItem>();
await this.ProcessTimeOffEntitiesBatchAsync(
allRequiredConfigurations.ShiftsAccessToken,
timeOffLookUpEntriesFoundList,
timeOffNotFoundList,
userModelList,
userModelNotFoundList,
kronosPayCodeList,
processKronosUsersQueueInBatch,
lookUpData,
timeOffResponseDetails,
timeOffReasons,
graphClient,
monthPartitionKey,
timeOffRequestsPayCodeList,
globalTimeOffRequestDetails).ConfigureAwait(false);
}
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffsFromKronos - " + Resource.NullMonthPartitionsMessage);
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffsFromKronos - " + Resource.SetUpNotDoneMessage);
}
this.telemetryClient.TrackTrace($"{Resource.ProcessTimeOffsAsync} ended; isRequestFromLogicApp: {isRequestFromLogicApp}");
}
/// <summary>
/// This method processes all of the time offs in a batch manner.
/// </summary>
/// <param name="accessToken">The MS Graph Access token.</param>
/// <param name="timeOffLookUpEntriesFoundList">The look up Time Off entries that are not found.</param>
/// <param name="timeOffNotFoundList">The list of time offs that are not found.</param>
/// <param name="userModelList">The list of users.</param>
/// <param name="userModelNotFoundList">The list of users that are not found.</param>
/// <param name="kronosPayCodeList">The Kronos pay code list.</param>
/// <param name="processKronosUsersQueueInBatch">The users in batch.</param>
/// <param name="lookUpData">The look up data.</param>
/// <param name="timeOffResponseDetails">The time off response details.</param>
/// <param name="timeOffReasons">The time off reasons.</param>
/// <param name="graphClient">The MS Graph Service client.</param>
/// <param name="monthPartitionKey">The montwise partition key.</param>
/// <param name="timeOffRequestsPayCodeList">The list of time off request pay codes.</param>
/// <param name="globalTimeOffRequestDetails">The time off request details.</param>
/// <returns>A unit of execution.</returns>
private async Task ProcessTimeOffEntitiesBatchAsync(
string accessToken,
List<TimeOffMappingEntity> timeOffLookUpEntriesFoundList,
List<GlobalTimeOffRequestItem> timeOffNotFoundList,
List<UserDetailsModel> userModelList,
List<UserDetailsModel> userModelNotFoundList,
List<PayCodeToTimeOffReasonsMappingEntity> kronosPayCodeList,
IEnumerable<UserDetailsModel> processKronosUsersQueueInBatch,
List<TimeOffMappingEntity> lookUpData,
List<GlobalTimeOffRequestItem> timeOffResponseDetails,
List<PayCodeToTimeOffReasonsMappingEntity> timeOffReasons,
GraphServiceClient graphClient,
string monthPartitionKey,
List<PayCodeToTimeOffReasonsMappingEntity> timeOffRequestsPayCodeList,
List<GlobalTimeOffRequestItem> globalTimeOffRequestDetails)
{
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync start at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
foreach (var item in processKronosUsersQueueInBatch)
{
foreach (var timeOffRequestItem in timeOffResponseDetails.Where(x => x.Employee.PersonIdentity.PersonNumber == item.KronosPersonNumber))
{
if (timeOffRequestItem.StatusName.Equals(ApiConstants.ApprovedStatus, StringComparison.Ordinal))
{
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync look up count: {lookUpData.Count} ");
if (lookUpData.Count == 0)
{
// Getting a TimeOffReasonId object based on the TimeOff paycode from Kronos and the team ID in Shifts.
var timeOffReasonId = timeOffReasons.
Where(t => t.RowKey == timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName && t.PartitionKey == item.ShiftTeamId).FirstOrDefault();
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync PaycodeName : {timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName} ");
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync ReqId : {timeOffRequestItem.Id} ");
if (timeOffReasonId != null)
{
timeOffNotFoundList.Add(timeOffRequestItem);
userModelNotFoundList.Add(item);
kronosPayCodeList.Add(timeOffReasonId);
}
else
{
// Track in telemetry saying that the TimeOffReasonId cannot be found.
this.telemetryClient.TrackTrace($"Cannot find the TimeOffReason corresponding to the Kronos paycode: {timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName}, Kronos request ID: {timeOffRequestItem.Id}");
}
}
else
{
var kronosUniqueIdExists = lookUpData.Where(x => x.KronosRequestId == timeOffRequestItem.Id);
var monthPartitions = Utility.GetMonthPartition(
timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.StartDate, timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.EndDate);
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync PaycodeName : {timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName} ");
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync ReqId : {timeOffRequestItem.Id} ");
if (kronosUniqueIdExists.Any() && kronosUniqueIdExists.FirstOrDefault().StatusName == ApiConstants.SubmitRequests)
{
// Getting a TimeOffReasonId object based on the TimeOff paycode from Kronos and the team ID in Shifts.
var timeOffReasonId = timeOffReasons.
Where(t => t.RowKey == timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName && t.PartitionKey == item.ShiftTeamId).FirstOrDefault();
// Kronos API does not return all the PayCodes present in Kronos UI. For such cases TimeOffReason mapping
// will be null and that TimeOffs will not be synced.
if (timeOffReasonId != null)
{
timeOffLookUpEntriesFoundList.Add(kronosUniqueIdExists.FirstOrDefault());
userModelList.Add(item);
timeOffRequestsPayCodeList.Add(timeOffReasonId);
globalTimeOffRequestDetails.Add(timeOffRequestItem);
}
else
{
// Track in telemetry saying that the TimeOffReasonId cannot be found.
this.telemetryClient.TrackTrace($"Cannot find the TimeOffReason corresponding to the Kronos paycode: {timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName}, Kronos request ID: {timeOffRequestItem.Id}");
}
}
else if (kronosUniqueIdExists.Any() || monthPartitions?.FirstOrDefault() != monthPartitionKey)
{
continue;
}
else
{
// Getting a TimeOffReasonId object based on the TimeOff paycode from Kronos and the team ID in Shifts.
var timeOffReasonId = timeOffReasons.
Where(t => t.RowKey == timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName && t.PartitionKey == item.ShiftTeamId).FirstOrDefault();
// Kronos API does not return all the PayCodes present in Kronos UI. For such cases TimeOffReason mapping
// will be null and that TimeOffs will not be synced.
if (timeOffReasonId != null)
{
timeOffNotFoundList.Add(timeOffRequestItem);
userModelNotFoundList.Add(item);
kronosPayCodeList.Add(timeOffReasonId);
}
else
{
// Track in telemetry saying that the TimeOffReasonId cannot be found.
this.telemetryClient.TrackTrace($"Cannot find the TimeOffReason corresponding to the Kronos paycode: {timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName}, Kronos request ID: {timeOffRequestItem.Id}");
}
}
}
}
if (timeOffRequestItem.StatusName.Equals(ApiConstants.Refused, StringComparison.Ordinal)
|| timeOffRequestItem.StatusName.Equals(ApiConstants.Retract, StringComparison.Ordinal))
{
var reqDetails = lookUpData.Where(c => c.KronosRequestId == timeOffRequestItem.Id).FirstOrDefault();
var timeOffReasonIdtoUpdate = timeOffReasons.Where(t => t.RowKey == timeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName && t.PartitionKey == item.ShiftTeamId).FirstOrDefault();
if (reqDetails != null && timeOffReasonIdtoUpdate != null && reqDetails.StatusName == ApiConstants.SubmitRequests)
{
await this.DeclineTimeOffRequestAsync(
timeOffRequestItem,
item,
reqDetails.ShiftsRequestId,
accessToken,
monthPartitionKey).ConfigureAwait(false);
}
else
{
this.telemetryClient.TrackTrace($"The declined timeoff request {timeOffRequestItem.Id} is not submitted from Shifts or timeOff reason selected while submitting" +
"is not a valid paycode. Hence mapping is not present for TimeOffReason and Paycode.");
}
}
}
}
await this.ApproveTimeOffRequestAsync(
timeOffLookUpEntriesFoundList,
userModelList,
timeOffRequestsPayCodeList,
accessToken,
monthPartitionKey,
globalTimeOffRequestDetails).ConfigureAwait(false);
await this.AddTimeOffRequestAsync(
graphClient,
userModelNotFoundList,
timeOffNotFoundList,
kronosPayCodeList,
monthPartitionKey).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"ProcessTimeOffEntitiesBatchAsync ended for {monthPartitionKey}.");
}
/// <summary>
/// Retrieves time off results in a batch manner.
/// </summary>
/// <param name="employees">The list of employees.</param>
/// <param name="kronosEndpoint">The Kronos WFC API endpoint.</param>
/// <param name="workforceIntegrationId">The Workforce Integration ID.</param>
/// <param name="jsession">The Kronos Jsession.</param>
/// <param name="queryStartDate">The query start date.</param>
/// <param name="queryEndDate">The query end date.</param>
/// <returns>Returns a unit of execution that contains the type of timeOff.Response.</returns>
private async Task<TimeOffReq.Response> GetTimeOffResultsByBatchAsync(
List<ResponseHyperFindResult> employees,
string kronosEndpoint,
string workforceIntegrationId,
string jsession,
string queryStartDate,
string queryEndDate)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "PersonNumber", employees.FirstOrDefault().PersonNumber },
{ "WorkforceIntegrationId", workforceIntegrationId },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, telemetryProps);
var timeOffQueryDateSpan = queryStartDate + "-" + queryEndDate;
var timeOffRequests = await this.timeOffActivity.GetTimeOffRequestDetailsByBatchAsync(
new Uri(kronosEndpoint),
jsession,
timeOffQueryDateSpan,
employees).ConfigureAwait(false);
return timeOffRequests;
}
/// <summary>
/// Method that creates the Microsoft Graph Service client.
/// </summary>
/// <param name="token">The Graph Access token.</param>
/// <returns>A type of <see cref="GraphServiceClient"/> contained in a unit of execution.</returns>
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
private async Task<GraphServiceClient> CreateGraphClientWithDelegatedAccessAsync(
string token)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
if (string.IsNullOrEmpty(token))
{
throw new ArgumentNullException(token);
}
var provider = CultureInfo.InvariantCulture;
this.telemetryClient.TrackTrace($"CreateGraphClientWithDelegatedAccessAsync-TimeController called at {DateTime.Now.ToString("o", provider)}");
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return Task.FromResult(0);
}));
return graphClient;
}
/// <summary>
/// Method that will calculate the end date accordingly.
/// </summary>
/// <param name="requestItem">An object of type <see cref="GlobalTimeOffRequestItem"/>.</param>
/// <returns>A type of DateTimeOffset.</returns>
private DateTimeOffset CalculateEndDate(GlobalTimeOffRequestItem requestItem)
{
var correctStartDate = this.utility.CalculateStartDateTime(requestItem);
var provider = CultureInfo.InvariantCulture;
var kronosTimeZoneId = this.appSettings.KronosTimeZone;
var kronosTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(kronosTimeZoneId);
var telemetryProps = new Dictionary<string, string>()
{
{ "CorrectedStartDate", correctStartDate.ToString("o", provider) },
{ "TimeOffPeriodDuration", requestItem.TimeOffPeriods.TimeOffPeriod.Duration.ToString(CultureInfo.InvariantCulture) },
};
if (requestItem.TimeOffPeriods.TimeOffPeriod.Duration == Resource.DurationInFullDay)
{
// If the time off request is for a full-day.
// Add 24 hours to the correct start date.
telemetryProps.Add("TimeOffPeriodLength", "24");
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, telemetryProps);
var dateTimeEnd = DateTime.ParseExact(requestItem.TimeOffPeriods.TimeOffPeriod.EndDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
var dateTimeStart = DateTime.ParseExact(requestItem.TimeOffPeriods.TimeOffPeriod.StartDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
if (dateTimeEnd.Equals(dateTimeStart))
{
return correctStartDate.AddHours(24);
}
else
{
return TimeZoneInfo.ConvertTimeToUtc(dateTimeEnd, kronosTimeZoneInfo).AddHours(24);
}
}
else if (requestItem.TimeOffPeriods.TimeOffPeriod.Duration == Resource.DurationInHour)
{
// If the time off has a number of hours attached to it.
// Take the necessary start date and start time, and add the hours to the time off.
var timeSpan = TimeSpan.Parse(requestItem.TimeOffPeriods.TimeOffPeriod.Length, CultureInfo.InvariantCulture);
telemetryProps.Add("TimeOffPeriodLength", timeSpan.Hours.ToString(CultureInfo.InvariantCulture));
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, telemetryProps);
return correctStartDate.AddHours(timeSpan.Hours);
}
else
{
// If the time off is either a first-half day, second-half day, or half-day.
// Add 12 hours to the correct start date.
return correctStartDate.AddHours(12);
}
}
/// <summary>
/// Method that will add a time off request.
/// </summary>
/// <param name="graphClient">The MS Graph Client.</param>
/// <param name="userModelNotFoundList">The list of users that are not found.</param>
/// <param name="timeOffNotFoundList">This list of time off records that are not found.</param>
/// <param name="kronosPayCodeList">The list of Kronos WFC Paycodes.</param>
/// <param name="monthPartitionKey">The month partition key.</param>
/// <returns>A unit of execution.</returns>
private async Task AddTimeOffRequestAsync(
GraphServiceClient graphClient,
List<UserDetailsModel> userModelNotFoundList,
List<GlobalTimeOffRequestItem> timeOffNotFoundList,
List<PayCodeToTimeOffReasonsMappingEntity> kronosPayCodeList,
string monthPartitionKey)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace($"AddTimeOffRequestAsync started for {monthPartitionKey}.", telemetryProps);
// create entries from not found list
for (int i = 0; i < timeOffNotFoundList.Count && kronosPayCodeList?.Count > 0; i++)
{
if (kronosPayCodeList[i]?.TimeOffReasonId != null)
{
var timeOff = new TimeOff
{
UserId = userModelNotFoundList[i].ShiftUserId,
SharedTimeOff = new TimeOffItem
{
TimeOffReasonId = kronosPayCodeList[i].TimeOffReasonId,
StartDateTime = this.utility.CalculateStartDateTime(timeOffNotFoundList[i]),
EndDateTime = this.CalculateEndDate(timeOffNotFoundList[i]),
Theme = ScheduleEntityTheme.White,
},
};
var timeOffs = await graphClient.Teams[userModelNotFoundList[i].ShiftTeamId].Schedule.TimesOff
.Request()
.AddAsync(timeOff).ConfigureAwait(false);
TimeOffMappingEntity timeOffMappingEntity = new TimeOffMappingEntity
{
Duration = timeOffNotFoundList[i].TimeOffPeriods.TimeOffPeriod.Duration,
EndDate = timeOffNotFoundList[i].TimeOffPeriods.TimeOffPeriod.EndDate,
StartDate = timeOffNotFoundList[i].TimeOffPeriods.TimeOffPeriod.StartDate,
StartTime = timeOffNotFoundList[i].TimeOffPeriods.TimeOffPeriod.StartTime,
PayCodeName = timeOffNotFoundList[i].TimeOffPeriods.TimeOffPeriod.PayCodeName,
KronosPersonNumber = timeOffNotFoundList[i].Employee.PersonIdentity.PersonNumber,
PartitionKey = monthPartitionKey,
RowKey = timeOffNotFoundList[i].Id,
ShiftsRequestId = timeOffs.Id,
KronosRequestId = timeOffNotFoundList[i].Id,
StatusName = timeOffNotFoundList[i].StatusName,
IsActive = true,
};
this.AddorUpdateTimeOffMappingAsync(timeOffMappingEntity);
}
else
{
telemetryProps.Add("TimeOffReason for " + timeOffNotFoundList[i].Id, "NotFound");
}
this.telemetryClient.TrackTrace($"AddTimeOffRequestAsync ended for {monthPartitionKey}.", telemetryProps);
}
}
/// <summary>
/// Method that approves a time off request.
/// </summary>
/// <param name="timeOffLookUpEntriesFoundList">The time off look up entries that are found.</param>
/// <param name="user">The user.</param>
/// <param name="timeOffReasonId">The Shifts Time Off Reason ID.</param>
/// <param name="accessToken">The MS Graph Access Token.</param>
/// <param name="monthPartitionKey">The monthwise partition key.</param>
/// <param name="globalTimeOffRequestDetails">The list of global time off request details.</param>
/// <returns>A unit of execution.</returns>
private async Task ApproveTimeOffRequestAsync(
List<TimeOffMappingEntity> timeOffLookUpEntriesFoundList,
List<UserDetailsModel> user,
List<PayCodeToTimeOffReasonsMappingEntity> timeOffReasonId,
string accessToken,
string monthPartitionKey,
List<GlobalTimeOffRequestItem> globalTimeOffRequestDetails)
{
this.telemetryClient.TrackTrace($"ApproveTimeOffRequestAsync started for {monthPartitionKey}.");
for (int i = 0; i < timeOffLookUpEntriesFoundList.Count; i++)
{
var timeOffReqCon = new TimeOffRequestItem
{
Id = timeOffLookUpEntriesFoundList[i].ShiftsRequestId,
CreatedDateTime = DateTime.Now,
LastModifiedDateTime = DateTime.Now,
AssignedTo = ApiConstants.Manager,
State = ApiConstants.Pending,
SenderDateTime = DateTime.Now,
SenderMessage = globalTimeOffRequestDetails[i].Comments?.Comment.FirstOrDefault()?.CommentText,
SenderUserId = Guid.Parse(user[i].ShiftUserId),
ManagerActionDateTime = null,
ManagerActionMessage = null,
ManagerUserId = string.Empty,
StartDateTime = this.utility.CalculateStartDateTime(globalTimeOffRequestDetails[i]),
EndDateTime = this.CalculateEndDate(globalTimeOffRequestDetails[i]),
TimeOffReasonId = timeOffReasonId[i].TimeOffReasonId,
LastModifiedBy = new LastModifiedBy
{
Application = null,
Device = null,
Conversation = null,
User = new TimeOffRequest.User
{
Id = Guid.Parse(user[i].ShiftUserId),
DisplayName = user[i].ShiftUserDisplayName,
},
},
};
var requestString = JsonConvert.SerializeObject(timeOffReqCon);
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + user[i].ShiftTeamId + "/schedule/timeOffRequests/" + timeOffLookUpEntriesFoundList[i].ShiftsRequestId + "/approve")
{
Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
TimeOffMappingEntity timeOffMappingEntity = new TimeOffMappingEntity
{
Duration = globalTimeOffRequestDetails[i].TimeOffPeriods.TimeOffPeriod.Duration,
EndDate = globalTimeOffRequestDetails[i].TimeOffPeriods.TimeOffPeriod.EndDate,
StartDate = globalTimeOffRequestDetails[i].TimeOffPeriods.TimeOffPeriod.StartDate,
StartTime = globalTimeOffRequestDetails[i].TimeOffPeriods.TimeOffPeriod.StartTime,
PayCodeName = globalTimeOffRequestDetails[i].TimeOffPeriods.TimeOffPeriod.PayCodeName,
KronosPersonNumber = globalTimeOffRequestDetails[i].Employee.PersonIdentity.PersonNumber,
PartitionKey = monthPartitionKey,
RowKey = globalTimeOffRequestDetails[i].Id,
ShiftsRequestId = timeOffLookUpEntriesFoundList[i].ShiftsRequestId,
IsActive = true,
KronosRequestId = globalTimeOffRequestDetails[i].Id,
StatusName = ApiConstants.ApprovedStatus,
};
this.AddorUpdateTimeOffMappingAsync(timeOffMappingEntity);
}
}
}
this.telemetryClient.TrackTrace($"ApproveTimeOffRequestAsync ended for {monthPartitionKey}.");
}
/// <summary>
/// Method to decline the time off request.
/// </summary>
/// <param name="globalTimeOffRequestItem">The time off request item.</param>
/// <param name="user">The user.</param>
/// <param name="timeOffId">The time off Id from Kronos.</param>
/// <param name="accessToken">The MS Graph Access token.</param>
/// <param name="monthPartitionKey">The month wise partition key.</param>
/// <returns>A unit of execution.</returns>
private async Task DeclineTimeOffRequestAsync(
GlobalTimeOffRequestItem globalTimeOffRequestItem,
UserDetailsModel user,
string timeOffId,
string accessToken,
string monthPartitionKey)
{
this.telemetryClient.TrackTrace($"DeclineTimeOffRequestAsync started for time off id {timeOffId}.");
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + user.ShiftTeamId + "/schedule/timeOffRequests/" + timeOffId + "/decline"))
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
TimeOffMappingEntity timeOffMappingEntity = new TimeOffMappingEntity
{
Duration = globalTimeOffRequestItem.TimeOffPeriods.TimeOffPeriod.Duration,
EndDate = globalTimeOffRequestItem.TimeOffPeriods.TimeOffPeriod.EndDate,
StartDate = globalTimeOffRequestItem.TimeOffPeriods.TimeOffPeriod.StartDate,
StartTime = globalTimeOffRequestItem.TimeOffPeriods.TimeOffPeriod.StartTime,
PayCodeName = globalTimeOffRequestItem.TimeOffPeriods.TimeOffPeriod.PayCodeName,
KronosPersonNumber = globalTimeOffRequestItem.Employee.PersonIdentity.PersonNumber,
PartitionKey = monthPartitionKey,
RowKey = globalTimeOffRequestItem.Id,
ShiftsRequestId = timeOffId,
IsActive = true,
KronosRequestId = globalTimeOffRequestItem.Id,
StatusName = globalTimeOffRequestItem.StatusName,
};
this.AddorUpdateTimeOffMappingAsync(timeOffMappingEntity);
}
}
this.telemetryClient.TrackTrace($"DeclineTimeOffRequestAsync ended for time off id {timeOffId}.");
}
/// <summary>
/// The method which will add or update a Time Off Mapping in Azure table storage.
/// </summary>
/// <param name="timeOffMappingEntity">The time off mapping entity to update or add.</param>
private async void AddorUpdateTimeOffMappingAsync(TimeOffMappingEntity timeOffMappingEntity)
{
await this.azureTableStorageHelper.InsertOrMergeTableEntityAsync(timeOffMappingEntity, "TimeOffMapping").ConfigureAwait(false);
}
/// <summary>
/// Get All users for time off.
/// </summary>
/// <returns>A task.</returns>
private async Task<IEnumerable<UserDetailsModel>> GetAllMappedUserDetailsAsync(string workForceIntegrationId)
{
List<UserDetailsModel> kronosUsers = new List<UserDetailsModel>();
List<AllUserMappingEntity> mappedUsersResult = await this.userMappingProvider.GetAllMappedUserDetailsAsync().ConfigureAwait(false);
foreach (var element in mappedUsersResult)
{
var teamMappingEntity = await this.teamDepartmentMappingProvider.GetTeamMappingForOrgJobPathAsync(workForceIntegrationId, element.PartitionKey).ConfigureAwait(false);
// If team department mapping for a user not present. Skip the user.
if (teamMappingEntity != null)
{
kronosUsers.Add(new UserDetailsModel
{
KronosPersonNumber = element.RowKey,
ShiftUserId = element.ShiftUserAadObjectId,
ShiftTeamId = teamMappingEntity.TeamId,
ShiftScheduleGroupId = teamMappingEntity.TeamsScheduleGroupId,
OrgJobPath = element.PartitionKey,
ShiftUserDisplayName = element.ShiftUserDisplayName,
});
}
else
{
this.telemetryClient.TrackTrace($"Team {element.PartitionKey} not mapped.");
}
}
return kronosUsers;
}
}
}<file_sep>/JDA_v17.2-Shifts-Connector/src/JdaTeams.Connector.Functions/Options/InitializeOrchestratorOptions.cs
using JdaTeams.Connector.Options;
using Microsoft.Azure.WebJobs;
using System;
namespace JdaTeams.Connector.Functions.Options
{
public class InitializeOrchestratorOptions : ConnectorOptions
{
public bool ClearScheduleEnabled { get; set; } = false;
public RetryOptions AsRetryOptions()
{
var retryInterval = TimeSpan.FromSeconds(RetryIntervalSeconds);
return new RetryOptions(retryInterval, RetryMaxAttempts);
}
}
}
<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/Shifts/UpcomingShiftsActivity.cs
// <copyright file="UpcomingShiftsActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.Shifts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.HyperFind;
using Microsoft.Teams.App.KronosWfc.Service;
using ScheduleRequest = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.Schedule;
using UpcomingShifts = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.Shifts.UpcomingShifts;
/// <summary>
/// Upcoming shifts activity class.
/// </summary>
[Serializable]
public class UpcomingShiftsActivity : IUpcomingShiftsActivity
{
private readonly TelemetryClient telemetryClient;
private readonly IApiHelper apiHelper;
/// <summary>
/// Initializes a new instance of the <see cref="UpcomingShiftsActivity"/> class.
/// </summary>
/// <param name="telemetryClient">Having the telemetry capturing mechanism.</param>
/// <param name="apiHelper">API helper to fetch tuple response by post soap requests.</param>
public UpcomingShiftsActivity(TelemetryClient telemetryClient, IApiHelper apiHelper)
{
this.telemetryClient = telemetryClient;
this.apiHelper = apiHelper;
}
/// <summary>
/// This method retrieves all the upcoming shifts.
/// </summary>
/// <param name="endPointUrl">The Kronos API endpoint.</param>
/// <param name="jSession">The Kronos "token".</param>
/// <param name="startDate">The query start date.</param>
/// <param name="endDate">The query end date.</param>
/// <param name="employees">The list of users to query.</param>
/// <returns>A unit of execution that contains the response.</returns>
public async Task<UpcomingShifts.Response> ShowUpcomingShiftsInBatchAsync(
Uri endPointUrl,
string jSession,
string startDate,
string endDate,
List<ResponseHyperFindResult> employees)
{
if (employees is null)
{
throw new ArgumentNullException(nameof(employees));
}
var xmlScheduleRequest = this.CreateUpcomingShiftsRequestEmployees(
startDate,
endDate,
employees);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endPointUrl,
ApiConstants.SoapEnvOpen,
xmlScheduleRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
UpcomingShifts.Response scheduleResponse = this.ProcessResponse(tupleResponse.Item1);
scheduleResponse.Jsession = tupleResponse.Item2;
return scheduleResponse;
}
private string CreateUpcomingShiftsRequestEmployees(string startDate, string endDate, List<ResponseHyperFindResult> employees)
{
ScheduleRequest.Request request = new ScheduleRequest.Request()
{
Action = ApiConstants.LoadAction,
Schedule = new ScheduleRequest.ScheduleReq()
{
Employees = new List<ScheduleRequest.PersonIdentity>(),
QueryDateSpan = $"{startDate} - {endDate}",
},
};
var scheduledEmployees = employees.ConvertAll(x => new ScheduleRequest.PersonIdentity { PersonNumber = x.PersonNumber });
request.Schedule.Employees.AddRange(scheduledEmployees);
return request.XmlSerialize();
}
/// <summary>
/// Read the xml response into Response object.
/// </summary>
/// <param name="strResponse">xml response string.</param>
/// <returns>Response object.</returns>
private UpcomingShifts.Response ProcessResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<UpcomingShifts.Response>(xResponse.ToString());
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.Models/RequestEntities/OpenShift/OpenShiftSchedule.cs
// <copyright file="OpenShiftSchedule.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift
{
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.Schedule;
/// <summary>
/// This class models the OpenShiftSchedule.
/// </summary>
public class OpenShiftSchedule
{
/// <summary>
/// Gets or sets the scheduleItems.
/// </summary>
public ScheduleItems ScheduleItems { get; set; }
/// <summary>
/// Gets or sets the employee.
/// </summary>
public Employees Employee { get; set; }
/// <summary>
/// Gets or sets the queryDateSpan.
/// </summary>
public string QueryDateSpan { get; set; }
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TimeOffReasonController.cs
// <copyright file="TimeOffReasonController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.App.KronosWfc.BusinessLogic.PayCodes;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using Newtonsoft.Json;
using TimeOffReasonRequest = Microsoft.Teams.Shifts.Integration.API.Models.Request;
using TimeOffReasonResponse = Microsoft.Teams.Shifts.Integration.API.Models.Response;
/// <summary>
/// Fetch TimeOffReasons from Kronos and create the same in Shifts.
/// </summary>
[Authorize(Policy = "AppID")]
[Route("/api/TimeOffReason")]
[ApiController]
public class TimeOffReasonController : ControllerBase
{
private readonly TelemetryClient telemetryClient;
private readonly IAzureTableStorageHelper azureTableStorageHelper;
private readonly ITimeOffReasonProvider timeOffReasonProvider;
private readonly IPayCodeActivity payCodeActivity;
private readonly AppSettings appSettings;
private readonly IHttpClientFactory httpClientFactory;
private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider;
private readonly Utility utility;
private readonly string tenantId;
/// <summary>
/// Initializes a new instance of the <see cref="TimeOffReasonController"/> class.
/// </summary>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="azureTableStorageHelper">The Azure Table Storage Helper DI.</param>
/// <param name="timeOffReasonProvider">The time off reason provider DI.</param>
/// <param name="payCodeActivity">The paycode activity DI.</param>
/// <param name="appSettings">Application Settings DI.</param>
/// <param name="httpClientFactory">Http Client Factory DI.</param>
/// <param name="teamDepartmentMappingProvider">Team department mapping provider DI.</param>
/// <param name="utility">Utility common methods DI.</param>
public TimeOffReasonController(
TelemetryClient telemetryClient,
IAzureTableStorageHelper azureTableStorageHelper,
ITimeOffReasonProvider timeOffReasonProvider,
IPayCodeActivity payCodeActivity,
AppSettings appSettings,
IHttpClientFactory httpClientFactory,
ITeamDepartmentMappingProvider teamDepartmentMappingProvider,
Utility utility)
{
this.telemetryClient = telemetryClient;
this.azureTableStorageHelper = azureTableStorageHelper;
this.appSettings = appSettings;
this.payCodeActivity = payCodeActivity;
this.timeOffReasonProvider = timeOffReasonProvider;
this.tenantId = this.appSettings?.TenantId;
this.httpClientFactory = httpClientFactory;
this.teamDepartmentMappingProvider = teamDepartmentMappingProvider;
this.utility = utility;
}
/// <summary>
/// Maps the Paycode of Kronos with TimeOffReasons.
/// </summary>
/// <returns>JSONResult.</returns>
[HttpGet]
public async Task MapPayCodeTimeOffReasonsAsync()
{
this.telemetryClient.TrackTrace($"{Resource.MapPayCodeTimeOffReasonsAsync} starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists)
{
var result = await this.teamDepartmentMappingProvider.GetTeamDeptMappingDetailsAsync().ConfigureAwait(false);
if (result != null)
{
foreach (var team in result)
{
await this.UpdateTimeOffReasonsAsync(
allRequiredConfigurations.ShiftsAccessToken,
team.TeamId,
this.tenantId,
allRequiredConfigurations.WfmEndPoint,
allRequiredConfigurations.KronosSession).ConfigureAwait(false);
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffReasonsFromKronosPayCodes - " + Resource.TeamDepartmentDetailsNotFoundMessage);
}
}
else
{
this.telemetryClient.TrackTrace("SyncTimeOffReasonsFromKronosPayCodes - " + Resource.SetUpNotDoneMessage);
}
this.telemetryClient.TrackTrace($"{Resource.MapPayCodeTimeOffReasonsAsync} ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
}
/// <summary>
/// Update mapping reasons in storage.
/// </summary>
/// <param name="accessToken">Cached AccessToken.</param>
/// <param name="teamsId">MS Teams Id.</param>
/// <param name="tenantId">tenant Id.</param>
/// <param name="kronosEndpoint">The Kronos WFC API endpoint.</param>
/// <param name="kronosSession">The Kronos WFC Jsession.</param>
/// <returns>List of TimeOffReasons.</returns>
private async Task<dynamic> UpdateTimeOffReasonsAsync(
string accessToken,
string teamsId,
string tenantId,
string kronosEndpoint,
string kronosSession)
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
var paycodeList = await this.payCodeActivity.FetchPayCodesAsync(new Uri(kronosEndpoint), kronosSession).ConfigureAwait(true);
var lstTimeOffReasons = await this.GetTimeOffReasonAsync(accessToken, teamsId).ConfigureAwait(true);
if (lstTimeOffReasons != null)
{
var reasonList = lstTimeOffReasons.Select(c => c.DisplayName).ToList();
var newCodes = paycodeList.Except(reasonList);
foreach (var payCode in newCodes)
{
await this.CreateTimeOffReasonAsync(accessToken, teamsId, payCode).ConfigureAwait(true);
}
var timeOffReasons = await this.GetTimeOffReasonAsync(accessToken, teamsId).ConfigureAwait(true);
var mappedReasons = await this.timeOffReasonProvider.FetchReasonsForTeamsAsync(teamsId, tenantId).ConfigureAwait(true);
foreach (var timeOffReason in timeOffReasons)
{
if ((paycodeList.Contains(timeOffReason.DisplayName) && !mappedReasons.ContainsKey(timeOffReason.Id))
|| (paycodeList.Contains(timeOffReason.DisplayName)
&& mappedReasons.ContainsKey(timeOffReason.Id)
&& !mappedReasons[timeOffReason.Id].Contains(timeOffReason.DisplayName, StringComparison.InvariantCulture)))
{
var payCodeToTimeOffReasonsMappingEntity = new PayCodeToTimeOffReasonsMappingEntity
{
PartitionKey = teamsId,
RowKey = timeOffReason.DisplayName,
TimeOffReasonId = timeOffReason.Id,
};
await this.azureTableStorageHelper.InsertOrMergeTableEntityAsync(payCodeToTimeOffReasonsMappingEntity, "PayCodeToTimeOffReasonsMapping").ConfigureAwait(true);
}
}
}
return null;
}
/// <summary>
/// Get time off reasons for a team.
/// </summary>
/// <param name="accessToken">Cached AccessToken.</param>
/// <param name="teamsId">MS Teams Id.</param>
/// <returns>List of TimeOffReasons.</returns>
private async Task<List<TimeOffReasonResponse.TimeOffReason>> GetTimeOffReasonAsync(string accessToken, string teamsId)
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
var graphBetaUrl = this.appSettings.GraphBetaApiUrl;
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (HttpResponseMessage response = await httpClient.GetAsync(new Uri(graphBetaUrl + "teams/" + teamsId + "/schedule/timeOffReasons?$search=\"isActive=true\"")).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync().ConfigureAwait(false);
if (result != null)
{
var res = JsonConvert.DeserializeObject<TimeOffReasonResponse.Temp>(result);
return res.Value.Where(c => c.IsActive == true).ToList();
}
}
}
else
{
var failedTimeOffReasonsProps = new Dictionary<string, string>()
{
{ "TeamId", teamsId },
};
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}", failedTimeOffReasonsProps);
return null;
}
}
return null;
}
/// <summary>
/// Create TimeOff Reasons in Shifts.
/// </summary>
/// <param name="accessToken">Cached AccessToken.</param>
/// <param name="teamsId">MS Teams Id.</param>
/// <param name="payCode">Kronos payCode.</param>
/// <returns>None.</returns>
private async Task<dynamic> CreateTimeOffReasonAsync(string accessToken, string teamsId, string payCode)
{
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}");
TimeOffReasonRequest.TimeOffReason timeOffReason = new TimeOffReasonRequest.TimeOffReason
{
DisplayName = payCode,
IconType = "plane",
IsActive = true,
};
var requestString = JsonConvert.SerializeObject(timeOffReason);
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + teamsId + "/schedule/timeOffReasons")
{
Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(true);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
return responseContent;
}
else
{
var failedCreateTimeOffReasonsProps = new Dictionary<string, string>()
{
{ "TeamId", teamsId },
{ "PayCode", payCode },
};
this.telemetryClient.TrackTrace($"{MethodBase.GetCurrentMethod().Name}", failedCreateTimeOffReasonsProps);
return string.Empty;
}
}
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.Models/RequestEntities/OpenShift/OpenShiftRequest/GlobalOpenShiftRequestItem.cs
// <copyright file="GlobalOpenShiftRequestItem.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift.OpenShiftRequest
{
using System.Collections.Generic;
using System.Xml.Serialization;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.ShiftsToKronos.AddRequest;
/// <summary>
/// This class models the GlobalOpenShiftRequestItem.
/// </summary>
public class GlobalOpenShiftRequestItem
{
/// <summary>
/// Gets or sets the Employee.
/// </summary>
[XmlElement]
public Employee Employee { get; set; }
/// <summary>
/// Gets or sets the RequestFor.
/// </summary>
[XmlAttribute]
public string RequestFor { get; set; }
/// <summary>
/// Gets or sets the ShiftDate.
/// </summary>
[XmlAttribute]
public string ShiftDate { get; set; }
/// <summary>
/// Gets or sets the ShiftSegments.
/// </summary>
[XmlElement]
#pragma warning disable CA2227 // Collection properties should be read only
public ShiftSegments ShiftSegments { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/OpenShiftRequestController.cs
// <copyright file="OpenShiftRequestController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.App.KronosWfc.BusinessLogic.OpenShift;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Models.RequestEntities.OpenShift.OpenShiftRequest;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.FetchApproval;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.API.Models.Response.OpenShifts;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models.RequestModels.OpenShift;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.RequestModels;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.ResponseModels;
using Newtonsoft.Json;
/// <summary>
/// Open Shift Requests controller.
/// </summary>
[Route("api/OpenShiftRequests")]
[ApiController]
[Authorize(Policy = "AppID")]
public class OpenShiftRequestController : Controller
{
private readonly AppSettings appSettings;
private readonly TelemetryClient telemetryClient;
private readonly IOpenShiftActivity openShiftActivity;
private readonly IUserMappingProvider userMappingProvider;
private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider;
private readonly IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider;
private readonly IHttpClientFactory httpClientFactory;
private readonly IOpenShiftMappingEntityProvider openShiftMappingEntityProvider;
private readonly string openShiftQueryDateSpan;
private readonly Utility utility;
private readonly IShiftMappingEntityProvider shiftMappingEntityProvider;
private readonly BackgroundTaskWrapper taskWrapper;
/// <summary>
/// Initializes a new instance of the <see cref="OpenShiftRequestController"/> class.
/// </summary>
/// <param name="appSettings">The key/value application settings DI.</param>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="openShiftActivity">The open shift activity DI.</param>
/// <param name="userMappingProvider">The user mapping provider DI.</param>
/// <param name="teamDepartmentMappingProvider">The Team Department Mapping DI.</param>
/// <param name="openShiftRequestMappingEntityProvider">The Open Shift Request Mapping DI.</param>
/// <param name="httpClientFactory">http client.</param>
/// <param name="openShiftMappingEntityProvider">The Open Shift Mapping DI.</param>
/// <param name="utility">The common utility methods DI.</param>
/// <param name="shiftMappingEntityProvider">Shift entity mapping provider DI.</param>
/// <param name="taskWrapper">Wrapper class instance for BackgroundTask.</param>
public OpenShiftRequestController(
AppSettings appSettings,
TelemetryClient telemetryClient,
IOpenShiftActivity openShiftActivity,
IUserMappingProvider userMappingProvider,
ITeamDepartmentMappingProvider teamDepartmentMappingProvider,
IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider,
IHttpClientFactory httpClientFactory,
IOpenShiftMappingEntityProvider openShiftMappingEntityProvider,
Utility utility,
IShiftMappingEntityProvider shiftMappingEntityProvider,
BackgroundTaskWrapper taskWrapper)
{
if (appSettings is null)
{
throw new ArgumentNullException(nameof(appSettings));
}
this.appSettings = appSettings;
this.telemetryClient = telemetryClient;
this.openShiftActivity = openShiftActivity;
this.userMappingProvider = userMappingProvider;
this.teamDepartmentMappingProvider = teamDepartmentMappingProvider;
this.openShiftRequestMappingEntityProvider = openShiftRequestMappingEntityProvider;
this.openShiftMappingEntityProvider = openShiftMappingEntityProvider;
this.httpClientFactory = httpClientFactory;
this.openShiftQueryDateSpan = $"{this.appSettings.ShiftStartDate}-{this.appSettings.ShiftEndDate}";
this.utility = utility;
this.shiftMappingEntityProvider = shiftMappingEntityProvider;
this.taskWrapper = taskWrapper;
}
/// <summary>
/// Method to submit the Open Shift Request in Kronos.
/// </summary>
/// <param name="request">The request object that is coming in.</param>
/// <param name="teamsId">The Shifts team id.</param>
/// <returns>Making sure to return a successful response code.</returns>
[AllowAnonymous]
[HttpPost]
public async Task<ShiftsIntegResponse> SubmitOpenShiftRequestToKronosAsync(
Models.IntegrationAPI.OpenShiftRequestIS request, string teamsId)
{
ShiftsIntegResponse openShiftSubmitResponse;
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} starts at: {DateTime.Now.ToString("O", CultureInfo.InvariantCulture)}");
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
GraphOpenShift graphOpenShift;
var telemetryProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
{ "CallingMethod", "UpdateTeam" },
{ "OpenShiftId", request.OpenShiftId },
{ "OpenShiftRequestId", request.Id },
{ "RequesterId", request.SenderUserId },
};
// Prereq. Steps
// Step 1 - Obtain the necessary prerequisites required.
// Step 1a - Obtain the ConfigurationInfo entity.
// Step 1b - Obtain the Team-Department Mapping.
// Step 1c - Obtain the Graph Token and other prerequisite information.
// Step 1d - Obtain the user from the user to user mapping table.
// Step 1e - Login to Kronos.
// Step 1c.
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
var kronosTimeZoneId = this.appSettings.KronosTimeZone;
var kronosTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(kronosTimeZoneId);
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists)
{
// Step 1d.
var userMappingRecord = await this.GetMappedUserDetailsAsync(
allRequiredConfigurations.WFIId,
request?.SenderUserId,
teamsId).ConfigureAwait(false);
// Submit open shift request to Kronos if user and it's corresponding team is mapped correctly.
if (string.IsNullOrEmpty(userMappingRecord.Error))
{
var queryingOrgJobPath = userMappingRecord.OrgJobPath;
var teamDepartmentMapping = await this.teamDepartmentMappingProvider.GetTeamMappingForOrgJobPathAsync(
allRequiredConfigurations.WFIId,
queryingOrgJobPath).ConfigureAwait(false);
telemetryProps.Add("TenantId", allRequiredConfigurations.TenantId);
telemetryProps.Add("WorkforceIntegrationId", allRequiredConfigurations.WFIId);
// Step 2 - Getting the Open Shift - the start date/time and end date/time are needed.
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", allRequiredConfigurations.ShiftsAccessToken);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "teams/" + teamDepartmentMapping.TeamId + "/schedule/openShifts/" + request.OpenShiftId))
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
graphOpenShift = JsonConvert.DeserializeObject<GraphOpenShift>(responseContent);
// Logging the required Open Shift ID from the Graph call.
this.telemetryClient.TrackTrace($"OpenShiftRequestController - OpenShift Graph API call succeeded with getting the Open Shift: {graphOpenShift?.Id}");
var shiftStartDate = graphOpenShift.SharedOpenShift.StartDateTime.AddDays(
-Convert.ToInt16(this.appSettings.CorrectedDateSpanForOutboundCalls, CultureInfo.InvariantCulture))
.ToString(this.appSettings.KronosQueryDateSpanFormat, CultureInfo.InvariantCulture);
var shiftEndDate = graphOpenShift.SharedOpenShift.EndDateTime.AddDays(
Convert.ToInt16(this.appSettings.CorrectedDateSpanForOutboundCalls, CultureInfo.InvariantCulture))
.ToString(this.appSettings.KronosQueryDateSpanFormat, CultureInfo.InvariantCulture);
var openShiftReqQueryDateSpan = $"{shiftStartDate}-{shiftEndDate}";
// Builds out the Open Shift Segments prior to actual object being built.
// Take into account the activities of the open shift that has been retrieved
// from the Graph API call for open shift details.
var openShiftSegments = this.BuildKronosOpenShiftSegments(
graphOpenShift.SharedOpenShift.Activities,
queryingOrgJobPath,
kronosTimeZoneInfo,
graphOpenShift.Id);
// Step 3 - Create the necessary OpenShiftObj
// Having the open shift segments which have been retrieved.
var inputDraftOpenShiftRequest = new OpenShiftObj()
{
StartDayNumber = Constants.StartDayNumberString,
EndDayNumber = Constants.EndDayNumberString,
SegmentTypeName = Resource.DraftOpenShiftRequestSegmentTypeName,
StartTime = TimeZoneInfo.ConvertTime(graphOpenShift.SharedOpenShift.StartDateTime, kronosTimeZoneInfo).ToString("h:mm tt", CultureInfo.InvariantCulture),
EndTime = TimeZoneInfo.ConvertTime(graphOpenShift.SharedOpenShift.EndDateTime, kronosTimeZoneInfo).ToString("h:mm tt", CultureInfo.InvariantCulture),
ShiftDate = TimeZoneInfo.ConvertTime(graphOpenShift.SharedOpenShift.StartDateTime, kronosTimeZoneInfo).ToString(Constants.DateFormat, CultureInfo.InvariantCulture).Replace('-', '/'),
OrgJobPath = Utility.OrgJobPathKronosConversion(userMappingRecord?.OrgJobPath),
QueryDateSpan = openShiftReqQueryDateSpan,
PersonNumber = userMappingRecord?.KronosPersonNumber,
OpenShiftSegments = openShiftSegments,
};
// Step 4 - Submit over to Kronos WFC, Open Shift Request goes into DRAFT state.
var postDraftOpenShiftRequestResult = await this.openShiftActivity.PostDraftOpenShiftRequestAsync(
allRequiredConfigurations.TenantId,
allRequiredConfigurations.KronosSession,
inputDraftOpenShiftRequest,
new Uri(allRequiredConfigurations.WfmEndPoint)).ConfigureAwait(false);
if (postDraftOpenShiftRequestResult?.Status == ApiConstants.Success)
{
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} - Operation to submit the DRAFT request has succeeded with: {postDraftOpenShiftRequestResult?.Status}");
// Step 5 - Update the submitted Open Shift Request from DRAFT to SUBMITTED
// so that it renders inside of the Kronos WFC Request Manager for final approval/decline.
var postUpdateOpenShiftRequestStatusResult = await this.openShiftActivity.PostOpenShiftRequestStatusUpdateAsync(
userMappingRecord.KronosPersonNumber,
postDraftOpenShiftRequestResult.EmployeeRequestMgmt?.RequestItems?.EmployeeGlobalOpenShiftRequestItem?.Id,
openShiftReqQueryDateSpan,
Resource.KronosOpenShiftStatusUpdateToSubmittedMessage,
new Uri(allRequiredConfigurations.WfmEndPoint),
allRequiredConfigurations.KronosSession).ConfigureAwait(false);
if (postUpdateOpenShiftRequestStatusResult?.Status == ApiConstants.Success)
{
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} - Operation to update the DRAFT request to SUBMITTED has succeeded with: {postUpdateOpenShiftRequestStatusResult?.Status}");
var openShiftEntityWithKronosUniqueId = await this.openShiftMappingEntityProvider.GetOpenShiftMappingEntitiesAsync(
request.OpenShiftId).ConfigureAwait(false);
// Step 6 - Insert the submitted open shift request into Azure table storage.
// Ensuring to pass the monthwise partition key from the Open Shift as the partition key for the Open Shift
// Request mapping entity.
var openShiftRequestMappingEntity = CreateOpenShiftRequestMapping(
request?.OpenShiftId,
request?.Id,
request?.SenderUserId,
userMappingRecord?.KronosPersonNumber,
postDraftOpenShiftRequestResult.EmployeeRequestMgmt?.RequestItems?.EmployeeGlobalOpenShiftRequestItem?.Id,
ApiConstants.Submitted,
openShiftEntityWithKronosUniqueId.FirstOrDefault().RowKey,
openShiftEntityWithKronosUniqueId.FirstOrDefault().PartitionKey,
ApiConstants.Pending);
telemetryProps.Add(
"KronosRequestId",
postDraftOpenShiftRequestResult.EmployeeRequestMgmt?.RequestItems?.EmployeeGlobalOpenShiftRequestItem?.Id);
telemetryProps.Add(
"KronosRequestStatus",
postUpdateOpenShiftRequestStatusResult.EmployeeRequestMgmt?.RequestItems?.EmployeeGlobalOpenShiftRequestItem?.StatusName);
telemetryProps.Add("KronosOrgJobPath", Utility.OrgJobPathKronosConversion(userMappingRecord?.OrgJobPath));
await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(openShiftRequestMappingEntity).ConfigureAwait(false);
this.telemetryClient.TrackTrace(Resource.SubmitOpenShiftRequestToKronosAsync, telemetryProps);
openShiftSubmitResponse = new ShiftsIntegResponse()
{
Id = request.Id,
Status = StatusCodes.Status200OK,
Body = new Body
{
Error = null,
ETag = GenerateNewGuid(),
},
};
}
else
{
this.telemetryClient.TrackTrace(Resource.SubmitOpenShiftRequestToKronosAsync, telemetryProps);
openShiftSubmitResponse = new ShiftsIntegResponse()
{
Id = request.Id,
Status = StatusCodes.Status500InternalServerError,
Body = new Body
{
Error = new ResponseError
{
Code = Resource.KronosWFCOpenShiftRequestErrorCode,
Message = postUpdateOpenShiftRequestStatusResult?.Status,
},
},
};
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} - There was an error from Kronos WFC when updating the DRAFT request to SUBMITTED status: {postDraftOpenShiftRequestResult?.Status}");
openShiftSubmitResponse = new ShiftsIntegResponse()
{
Id = request.Id,
Status = StatusCodes.Status500InternalServerError,
Body = new Body
{
Error = new ResponseError
{
Code = Resource.KronosWFCOpenShiftRequestErrorCode,
Message = postDraftOpenShiftRequestResult?.Status,
},
},
};
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} - There is an error when getting Open Shift: {request?.OpenShiftId} from Graph APIs: {response.StatusCode.ToString()}");
openShiftSubmitResponse = new ShiftsIntegResponse
{
Id = request.Id,
Status = StatusCodes.Status404NotFound,
Body = new Body
{
Error = new ResponseError()
{
Code = Resource.OpenShiftNotFoundCode,
Message = string.Format(CultureInfo.InvariantCulture, Resource.OpenShiftNotFoundMessage, request.OpenShiftId),
},
},
};
}
}
}
// Either user or it's team is not mapped correctly.
else
{
openShiftSubmitResponse = new ShiftsIntegResponse
{
Id = request.Id,
Status = StatusCodes.Status500InternalServerError,
Body = new Body
{
Error = new ResponseError
{
Code = userMappingRecord.Error,
Message = userMappingRecord.Error,
},
},
};
}
}
else
{
this.telemetryClient.TrackTrace(Resource.SubmitOpenShiftRequestToKronosAsync + "-" + Resource.SetUpNotDoneMessage);
openShiftSubmitResponse = new ShiftsIntegResponse
{
Id = request.Id,
Status = StatusCodes.Status500InternalServerError,
Body = new Body
{
Error = new ResponseError
{
Code = Resource.SetUpNotDoneCode,
Message = Resource.SetUpNotDoneMessage,
},
},
};
}
this.telemetryClient.TrackTrace($"{Resource.SubmitOpenShiftRequestToKronosAsync} ends at: {DateTime.Now.ToString("O", CultureInfo.InvariantCulture)}");
return openShiftSubmitResponse;
}
/// <summary>
/// This method will Process the Open Shift requests accordingly.
/// </summary>
/// <param name="isRequestFromLogicApp">The value indicating whether or not the request is coming from logic app.</param>
/// <returns>A unit of execution.</returns>
internal async Task ProcessOpenShiftsRequests(string isRequestFromLogicApp)
{
var provider = CultureInfo.InvariantCulture;
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} start at: {DateTime.Now.ToString("o", provider)}");
this.utility.SetQuerySpan(Convert.ToBoolean(isRequestFromLogicApp, CultureInfo.InvariantCulture), out var openShiftStartDate, out var openShiftEndDate);
var openShiftQueryDateSpan = $"{openShiftStartDate}-{openShiftEndDate}";
// Get all the necessary prerequisites.
var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false);
// Check whether date range are in correct format.
var isCorrectDateRange = Utility.CheckDates(openShiftStartDate, openShiftEndDate);
var telemetryProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
if (allRequiredConfigurations != null && (bool)allRequiredConfigurations?.IsAllSetUpExists && isCorrectDateRange)
{
// Get all of the mapped users from Azure table storage.
var mappedUsers = await this.GetAllMappedUsersDetailsAsync(allRequiredConfigurations?.WFIId).ConfigureAwait(false);
var mappedUsersList = mappedUsers?.ToList();
foreach (var user in mappedUsersList)
{
this.telemetryClient.TrackTrace($"Looking up user: {user.KronosPersonNumber}");
var approvedOrDeclinedOpenShiftRequests =
await this.openShiftActivity.GetApprovedOrDeclinedOpenShiftRequestsForUserAsync(
new Uri(allRequiredConfigurations.WfmEndPoint),
allRequiredConfigurations.KronosSession,
openShiftQueryDateSpan,
user.KronosPersonNumber).ConfigureAwait(false);
var responseItems = approvedOrDeclinedOpenShiftRequests.RequestMgmt.RequestItems.GlobalOpenShiftRequestItem;
if (approvedOrDeclinedOpenShiftRequests != null)
{
// Iterate over each of the responseItems.
// 1. Mark the KronosStatus accordingly.
// If approved, create a temp shift, calculate the KronosHash, then make a call to the approval endpoint.
// If retract, or refused, then make a call to the decline endpoint.
foreach (var item in responseItems)
{
// Update the status in Azure table storage.
var entityToUpdate = await this.openShiftRequestMappingEntityProvider.GetOpenShiftRequestMappingEntityByKronosReqIdAsync(
item.Id).ConfigureAwait(false);
if (entityToUpdate != null)
{
if (item.StatusName == ApiConstants.ApprovedStatus && entityToUpdate.ShiftsStatus == ApiConstants.Pending)
{
// Update the KronosStatus to Approved here.
entityToUpdate.KronosStatus = ApiConstants.ApprovedStatus;
// Commit the change to the database.
await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(entityToUpdate).ConfigureAwait(false);
// Build the request to get the open shift from Graph.
var httpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", allRequiredConfigurations.ShiftsAccessToken);
using (var getOpenShiftRequestMessage = new HttpRequestMessage(HttpMethod.Get, "teams/" + user.ShiftTeamId + "/schedule/openShifts/" + entityToUpdate.TeamsOpenShiftId))
{
var getOpenShiftResponse = await httpClient.SendAsync(getOpenShiftRequestMessage).ConfigureAwait(false);
if (getOpenShiftResponse.IsSuccessStatusCode)
{
// Calculate the expected Shift hash prior to making the approval call.
// 1. Have to get the response string.
var getOpenShiftResponseStr = await getOpenShiftResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
// 2. Deserialize the response string into the Open Shift object.
var openShiftObj = JsonConvert.DeserializeObject<GraphOpenShift>(getOpenShiftResponseStr);
// 3. Creating the expected shift hash from the above and the userId.
var expectedShiftHash = this.utility.CreateUniqueId(openShiftObj, user.ShiftUserId);
this.telemetryClient.TrackTrace($"Hash From OpenShiftRequestController: {expectedShiftHash}");
// 4. Create the shift entity from the open shift details, the user Id, and having a RowKey of SHFT_PENDING.
var expectedShift = Utility.CreateShiftMappingEntity(
user.ShiftUserId,
expectedShiftHash,
user.KronosPersonNumber);
// 5. Calculate the necessary monthwise partitions - this is the partition key for the shift entity mapping table.
var actualStartDateTimeStr = this.utility.CalculateStartDateTime(openShiftObj.SharedOpenShift.StartDateTime).ToString("d", provider);
var actualEndDateTimeStr = this.utility.CalculateEndDateTime(openShiftObj.SharedOpenShift.EndDateTime).ToString("d", provider);
var monthPartitions = Utility.GetMonthPartition(actualStartDateTimeStr, actualEndDateTimeStr);
var monthPartition = monthPartitions?.FirstOrDefault();
var rowKey = $"SHFT_PENDING_{entityToUpdate.RowKey}";
this.telemetryClient.TrackTrace("OpenShiftRequestId = " + rowKey);
// 6. Insert into the Shift Mapping Entity table.
await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync(
expectedShift,
rowKey,
monthPartition).ConfigureAwait(false);
// 7. Having the necessary Graph API call made here - to the approval endpoint.
var approvalMessageModel = new OpenShiftRequestApproval
{
Message = Resource.OpenShiftRequestApprovalMessage,
};
var approvalMessageModelStr = JsonConvert.SerializeObject(approvalMessageModel);
var approvalHttpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
approvalHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", allRequiredConfigurations.ShiftsAccessToken);
// Send Passthrough header to indicate the sender of request in outbound call.
approvalHttpClient.DefaultRequestHeaders.Add("X-MS-WFMPassthrough", allRequiredConfigurations.WFIId);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + user.ShiftTeamId + "/schedule/openshiftchangerequests/" + entityToUpdate.RowKey + "/approve")
{
Content = new StringContent(approvalMessageModelStr, Encoding.UTF8, "application/json"),
})
{
var approvalHttpResponse = await approvalHttpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (approvalHttpResponse.IsSuccessStatusCode)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} ShiftRequestId: {entityToUpdate.RowKey} KronosRequestId: {item.Id}");
}
else
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} -Error The service is acting on Open Shift Request: {entityToUpdate?.RowKey} which may have been approved");
}
}
}
else
{
// Output to AppInsights logging.
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} - Getting Open Shift for {entityToUpdate.TeamsOpenShiftId} results in {getOpenShiftResponse.Content.ToString()}");
}
}
}
if ((item.StatusName == ApiConstants.Retract || item.StatusName == ApiConstants.Refused) && entityToUpdate.ShiftsStatus == ApiConstants.Pending)
{
entityToUpdate.KronosStatus = item.StatusName;
entityToUpdate.ShiftsStatus = item.StatusName;
// Commit the change to the database.
await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(entityToUpdate).ConfigureAwait(false);
var declineMessageModel = new OpenShiftRequestApproval
{
Message = Resource.OpenShiftRequestDeclinedMessage,
};
var declineMessageModelStr = JsonConvert.SerializeObject(declineMessageModel);
var declineHttpClient = this.httpClientFactory.CreateClient("ShiftsAPI");
declineHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", allRequiredConfigurations.ShiftsAccessToken);
// Send Passthrough header to indicate the sender of request in outbound call.
declineHttpClient.DefaultRequestHeaders.Add("X-MS-WFMPassthrough", allRequiredConfigurations.WFIId);
using (var declineRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teams/" + user.ShiftTeamId + "/schedule/openshiftchangerequests/" + entityToUpdate.RowKey + "/decline")
{
Content = new StringContent(declineMessageModelStr, Encoding.UTF8, "application/json"),
})
{
var declineHttpResponse = await declineHttpClient.SendAsync(declineRequestMessage).ConfigureAwait(false);
if (declineHttpResponse.IsSuccessStatusCode)
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests}- DeclinedShiftRequestId: {entityToUpdate.RowKey}, DeclinedKronosRequestId: {item.Id}");
}
else
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} -Error: The service is acting on Open Shift Request: {entityToUpdate?.RowKey} which may have been approved or declined.");
}
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests}: The {item.Id} Kronos Open Shift request is in {item.StatusName} status.");
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests}-Error: The data for {item.Id} does not exist in the database.");
continue;
}
}
}
else
{
throw new Exception(string.Format(CultureInfo.InvariantCulture, Resource.GenericNotAbleToRetrieveDataMessage, Resource.ProcessOpenShiftsAsync));
}
}
}
else
{
this.telemetryClient.TrackTrace(Resource.ProcessOpenShiftsRequests + "-" + Resource.SetUpNotDoneMessage);
}
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} end at: {DateTime.Now.ToString("O", provider)}");
}
/// <summary>
/// This method returns a random string.
/// </summary>
/// <returns>A random GUID that would represent an eTag.</returns>
private static string GenerateNewGuid()
{
return Guid.NewGuid().ToString();
}
/// <summary>
/// Method to create an Open Shift Mapping Entity to store in Azure Table storage.
/// </summary>
/// <param name="openShiftId">The Graph Open Shift ID.</param>
/// <param name="shiftRequestId">The incoming Shift Request ID.</param>
/// <param name="teamsUserAadObjectId">The User AAD Object ID that made the Open Shift Request.</param>
/// <param name="kronosPersonNumber">The Kronos Person Number.</param>
/// <param name="kronosRequestId">The Kronos Request ID.</param>
/// <param name="kronosRequestStatus">The Kronos Request status.</param>
/// <param name="kronosUniqueId">The system generated ID.</param>
/// <param name="monthPartitionKey">The month partition key of the requested Open Shift.</param>
/// <param name="openShiftRequestStatus">The Open Shift Request status from the incoming request.</param>
/// <returns>An object of type <see cref="AllOpenShiftRequestMappingEntity"/>.</returns>
private static AllOpenShiftRequestMappingEntity CreateOpenShiftRequestMapping(
string openShiftId,
string shiftRequestId,
string teamsUserAadObjectId,
string kronosPersonNumber,
string kronosRequestId,
string kronosRequestStatus,
string kronosUniqueId,
string monthPartitionKey,
string openShiftRequestStatus)
{
// Forming the open shift request mapping entity with the parameters defined,
// and using the month partition key of the open shift entity as the month
// partition key of the open shift request entity.
var openShiftRequestMappingEntity = new AllOpenShiftRequestMappingEntity()
{
TeamsOpenShiftId = openShiftId,
RowKey = shiftRequestId,
AadUserId = teamsUserAadObjectId,
KronosPersonNumber = kronosPersonNumber,
KronosOpenShiftRequestId = kronosRequestId,
KronosStatus = kronosRequestStatus,
KronosOpenShiftUniqueId = kronosUniqueId,
ShiftsStatus = openShiftRequestStatus,
PartitionKey = monthPartitionKey,
};
return openShiftRequestMappingEntity;
}
/// <summary>
/// This method will build the Kronos Open Shift Segments from the activities of the Open Shift.
/// </summary>
/// <param name="activities">The list of open shift activities.</param>
/// <param name="orgJobPath">The Kronos Org Job Path.</param>
/// <param name="kronosTimeZoneInfo">The Kronos Time Zone Information.</param>
/// <param name="openShiftId">The MS Graph Open Shift ID.</param>
/// <returns>A list of <see cref="ShiftSegment"/>.</returns>
private List<App.KronosWfc.Models.ResponseEntities.OpenShift.ShiftSegment> BuildKronosOpenShiftSegments(
List<Activity> activities,
string orgJobPath,
TimeZoneInfo kronosTimeZoneInfo,
string openShiftId)
{
this.telemetryClient.TrackTrace($"BuildKronosOpenShiftSegments start at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
this.telemetryClient.TrackTrace($"BuildKronosOpenShiftSegments for the Org Job Path: {orgJobPath}, TeamsOpenShiftId = {openShiftId}");
var shiftSegmentList = new List<App.KronosWfc.Models.ResponseEntities.OpenShift.ShiftSegment>();
// Ensuring to format the org job path from database in Kronos WFC format.
var kronosOrgJob = Utility.OrgJobPathKronosConversion(orgJobPath);
foreach (var item in activities)
{
// The code below will construct an object of type ShiftSegment, and checks
// if the current item in the iteration is a BREAK activity. If the current item
// is a BREAK, then the Kronos Org Job Path should not be included.
var segmentToAdd = new App.KronosWfc.Models.ResponseEntities.OpenShift.ShiftSegment
{
OrgJobPath = item.DisplayName == "BREAK" ? null : kronosOrgJob,
EndDayNumber = "1",
StartDayNumber = "1",
StartTime = TimeZoneInfo.ConvertTime(item.StartDateTime, kronosTimeZoneInfo).ToString("hh:mm tt", CultureInfo.InvariantCulture),
EndTime = TimeZoneInfo.ConvertTime(item.EndDateTime, kronosTimeZoneInfo).ToString("hh:mm tt", CultureInfo.InvariantCulture),
SegmentTypeName = item.DisplayName,
};
shiftSegmentList.Add(segmentToAdd);
}
this.telemetryClient.TrackTrace($"BuildKronosOpenShiftSegments end at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}");
return shiftSegmentList;
}
/// <summary>
/// Gets a user model from Shifts in order to return the Org Job Path.
/// </summary>
/// <returns>A task.</returns>
private async Task<UserDetailsModel> GetMappedUserDetailsAsync(
string workForceIntegrationId,
string userAadObjectId,
string teamsId)
{
UserDetailsModel kronosUser;
AllUserMappingEntity mappedUsersResult = await this.userMappingProvider.GetUserMappingEntityAsyncNew(userAadObjectId, teamsId).ConfigureAwait(false);
if (mappedUsersResult != null)
{
var teamMappingEntity = await this.teamDepartmentMappingProvider.GetTeamMappingForOrgJobPathAsync(
workForceIntegrationId,
mappedUsersResult.PartitionKey).ConfigureAwait(false);
if (teamMappingEntity != null)
{
kronosUser = new UserDetailsModel()
{
KronosPersonNumber = mappedUsersResult.RowKey,
ShiftUserId = mappedUsersResult.ShiftUserAadObjectId,
ShiftTeamId = teamsId,
ShiftScheduleGroupId = teamMappingEntity.TeamsScheduleGroupId,
OrgJobPath = mappedUsersResult.PartitionKey,
};
}
else
{
this.telemetryClient.TrackTrace($"Team id {teamsId} is not mapped.");
kronosUser = new UserDetailsModel()
{
Error = Resource.UserTeamNotExists,
};
}
}
else
{
this.telemetryClient.TrackTrace($"User id {userAadObjectId} is not mapped.");
kronosUser = new UserDetailsModel()
{
Error = Resource.UserMappingNotFound,
};
}
return kronosUser;
}
private async Task<List<UserDetailsModel>> GetAllMappedUsersDetailsAsync(
string workForceIntegrationId)
{
List<UserDetailsModel> kronosUsers = new List<UserDetailsModel>();
List<AllUserMappingEntity> mappedUsersResult = await this.userMappingProvider.GetAllMappedUserDetailsAsync().ConfigureAwait(false);
foreach (var element in mappedUsersResult)
{
var teamMappingEntity = await this.teamDepartmentMappingProvider.GetTeamMappingForOrgJobPathAsync(
workForceIntegrationId,
element.PartitionKey).ConfigureAwait(false);
// If team department mapping for a user not present. Skip the user.
if (teamMappingEntity != null)
{
kronosUsers.Add(new UserDetailsModel
{
KronosPersonNumber = element.RowKey,
ShiftUserId = element.ShiftUserAadObjectId,
ShiftTeamId = teamMappingEntity.TeamId,
ShiftScheduleGroupId = teamMappingEntity.TeamsScheduleGroupId,
OrgJobPath = element.PartitionKey,
});
}
}
return kronosUsers;
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/Shifts/IUpcomingShiftsActivity.cs
// <copyright file="IUpcomingShiftsActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.Shifts
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.HyperFind;
using UpcomingShifts = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.Shifts.UpcomingShifts;
/// <summary>
/// Upcoming shift activity interface.
/// </summary>
public interface IUpcomingShiftsActivity
{
/// <summary>
/// Shows upcoming shifts.
/// </summary>
/// <param name="endPointUrl">end Point Url.</param>
/// <param name="jSession">jSession object.</param>
/// <param name="startDate">Start Date.</param>
/// <param name="endDate">End Date.</param>
/// <param name="employees">Employees shift data.</param>
/// <returns>Upcoming shifts response.</returns>
Task<UpcomingShifts.Response> ShowUpcomingShiftsInBatchAsync(
Uri endPointUrl,
string jSession,
string startDate,
string endDate,
List<ResponseHyperFindResult> employees);
}
}<file_sep>/JDA_v17.2-Shifts-Connector/src/JdaTeams.Connector.Functions/Orchestrators/TeamOrchestrator.cs
using JdaTeams.Connector.Extensions;
using JdaTeams.Connector.Functions.Activities;
using JdaTeams.Connector.Functions.Extensions;
using JdaTeams.Connector.Functions.Models;
using JdaTeams.Connector.Functions.Options;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace JdaTeams.Connector.Functions.Orchestrators
{
public class TeamOrchestrator
{
private readonly TeamOrchestratorOptions _options;
public TeamOrchestrator(TeamOrchestratorOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
[FunctionName(nameof(TeamOrchestrator))]
public async Task Run([OrchestrationTrigger] DurableOrchestrationContext context,
ILogger log)
{
var teamModel = context.GetInput<TeamModel>();
if (!teamModel.Initialized)
{
await context.CallSubOrchestratorWithRetryAsync(nameof(InitializeOrchestrator), _options.AsRetryOptions(), teamModel);
teamModel.Initialized = true;
}
try
{
var weeks = context.CurrentUtcDateTime.Date
.Range(_options.PastWeeks, _options.FutureWeeks, _options.StartDayOfWeek);
var weekTasks = weeks
.Select(startDate => new WeekModel
{
StartDate = startDate,
StoreId = teamModel.StoreId,
TeamId = teamModel.TeamId
})
.Select(weekModel => context.CallSubOrchestratorWithRetryAsync(nameof(WeekOrchestrator), _options.AsRetryOptions(), weekModel));
await Task.WhenAll(weekTasks);
}
catch (Exception ex) when (_options.ContinueOnError)
{
log.LogTeamError(ex, teamModel);
}
if (_options.FrequencySeconds < 0)
{
return;
}
var dueTime = context.CurrentUtcDateTime.AddSeconds(_options.FrequencySeconds);
await context.CreateTimer(dueTime, CancellationToken.None);
context.ContinueAsNew(teamModel);
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/ITimeOffRequestProvider.cs
// <copyright file="ITimeOffRequestProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
/// <summary>
/// This interface defines methods to be implemented with regards to the TimeOff Request Entity.
/// </summary>
public interface ITimeOffRequestProvider
{
/// <summary>
/// Method definition to get all the TimeOffReqMappingEntities.
/// </summary>
/// <param name="monthPartitionKey">The Month partition key.</param>
/// <param name="timeOffReqId">The TimeOffReqId.</param>
/// <returns>A unit of execution containing a list of the time off requests.</returns>
Task<List<TimeOffMappingEntity>> GetAllTimeOffReqMappingEntitiesAsync(string monthPartitionKey, string timeOffReqId);
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/SyncKronosToShiftsController.cs
// <copyright file="SyncKronosToShiftsController.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Teams.Shifts.Integration.API.Common;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers;
/// <summary>
/// Sync Kronos To Shifts Controller.
/// </summary>
[Route("api/SyncKronosToShifts")]
public class SyncKronosToShiftsController : ControllerBase
{
private readonly TelemetryClient telemetryClient;
private readonly IConfigurationProvider configurationProvider;
private readonly OpenShiftController openShiftController;
private readonly OpenShiftRequestController openShiftRequestController;
private readonly SwapShiftController swapShiftController;
private readonly TimeOffController timeOffController;
private readonly TimeOffReasonController timeOffReasonController;
private readonly TimeOffRequestsController timeOffRequestsController;
private readonly ShiftController shiftController;
private readonly BackgroundTaskWrapper taskWrapper;
/// <summary>
/// Initializes a new instance of the <see cref="SyncKronosToShiftsController"/> class.
/// </summary>
/// <param name="telemetryClient">ApplicationInsights DI.</param>
/// <param name="configurationProvider">The Configuration Provider DI.</param>
/// <param name="openShiftController">OpenShiftController DI.</param>
/// <param name="openShiftRequestController">OpenShiftRequestController DI.</param>
/// <param name="swapShiftController">SwapShiftController DI.</param>
/// <param name="timeOffController">TimeOffController DI.</param>
/// <param name="timeOffReasonController">TimeOffReasonController DI.</param>
/// <param name="timeOffRequestsController">TimeOffRequestsController DI.</param>
/// <param name="shiftController">ShiftController DI.</param>
/// <param name="taskWrapper">Wrapper class instance for BackgroundTask.</param>
public SyncKronosToShiftsController(
TelemetryClient telemetryClient,
IConfigurationProvider configurationProvider,
OpenShiftController openShiftController,
OpenShiftRequestController openShiftRequestController,
SwapShiftController swapShiftController,
TimeOffController timeOffController,
TimeOffReasonController timeOffReasonController,
TimeOffRequestsController timeOffRequestsController,
ShiftController shiftController,
BackgroundTaskWrapper taskWrapper)
{
this.telemetryClient = telemetryClient;
this.configurationProvider = configurationProvider;
this.openShiftController = openShiftController;
this.openShiftRequestController = openShiftRequestController;
this.swapShiftController = swapShiftController;
this.timeOffController = timeOffController;
this.timeOffReasonController = timeOffReasonController;
this.timeOffRequestsController = timeOffRequestsController;
this.shiftController = shiftController;
this.taskWrapper = taskWrapper;
}
/// <summary>
/// Http get method to start Kronos to Shifts sync.
/// </summary>
/// <param name="isRequestFromLogicApp">True if request is coming from logic app, false otherwise.</param>
/// <returns>Returns Ok if request is successfully queued.</returns>
[Authorize(Policy = "AppID")]
[HttpGet]
[Route("StartSync/{isRequestFromLogicApp}")]
public ActionResult SyncKronosToShifts(string isRequestFromLogicApp)
{
var telemetryProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
{ "APIRoute", this.ControllerContext.ActionDescriptor.AttributeRouteInfo.Name },
};
this.telemetryClient.TrackTrace($"SyncKronosToShifts starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
if (bool.TryParse(isRequestFromLogicApp, out bool isFromLogicApp))
{
this.taskWrapper.Enqueue(this.ProcessKronosToShiftsShiftsAsync(isRequestFromLogicApp));
this.telemetryClient.TrackTrace($"SyncKronosToShifts ends at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}", telemetryProps);
return this.Ok(string.Empty);
}
else
{
this.telemetryClient.TrackTrace($"Unable to call SyncKronosToShifts service at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}. {Resource.IncorrectArgumentType}", telemetryProps);
return this.BadRequest(Resource.IncorrectArgumentType);
}
}
/// <summary>
/// Process all the entities from Kronos to Shifts.
/// </summary>
/// <param name="isRequestFromLogicApp">true if the call is coming from logic app, false otherwise.</param>
/// <returns>Returns task.</returns>
private async Task ProcessKronosToShiftsShiftsAsync(string isRequestFromLogicApp)
{
var isOpenShiftRequestSyncSuccessful = false;
var isSwapShiftRequestSyncSuccessful = false;
var isMapPayCodeTimeOffReasonsSuccessful = false;
try
{
this.telemetryClient.TrackTrace($"{Resource.ProcessKronosToShiftsShiftsAsync} start at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}" + " for isRequestFromLogicApp: " + isRequestFromLogicApp);
// Sync open shifts from Kronos to Shifts.
await this.openShiftController.ProcessOpenShiftsAsync(isRequestFromLogicApp).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsAsync} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.telemetryClient.TrackException(ex);
}
try
{
// Sync open shifts requests from Kronos to Shifts.
await this.openShiftRequestController.ProcessOpenShiftsRequests(isRequestFromLogicApp).ConfigureAwait(false);
isOpenShiftRequestSyncSuccessful = true;
this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsRequests} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
isOpenShiftRequestSyncSuccessful = false;
this.telemetryClient.TrackException(ex);
}
try
{
// Sync swap shifts from Kronos to Shifts.
await this.swapShiftController.ProcessSwapShiftsAsync(isRequestFromLogicApp).ConfigureAwait(false);
isSwapShiftRequestSyncSuccessful = true;
this.telemetryClient.TrackTrace($"{Resource.ProcessSwapShiftsAsync} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
isSwapShiftRequestSyncSuccessful = false;
this.telemetryClient.TrackException(ex);
}
try
{
// Sync TimeOffReasons from Kronos to Shifts.
await this.timeOffReasonController.MapPayCodeTimeOffReasonsAsync().ConfigureAwait(false);
isMapPayCodeTimeOffReasonsSuccessful = true;
this.telemetryClient.TrackTrace($"{Resource.MapPayCodeTimeOffReasonsAsync} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
isMapPayCodeTimeOffReasonsSuccessful = false;
this.telemetryClient.TrackException(ex);
}
// Sync TimeOff and TimeOffRequest only if Paycodes in Kronos synced successfully.
if (isMapPayCodeTimeOffReasonsSuccessful)
{
try
{
// Sync timeoff from Kronos to Shifts.
await this.timeOffController.ProcessTimeOffsAsync(isRequestFromLogicApp).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"{Resource.ProcessTimeOffsAsync} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.telemetryClient.TrackException(ex);
}
try
{
// Sync timeoff from Kronos to Shifts.
await this.timeOffRequestsController.ProcessTimeOffRequestsAsync(isRequestFromLogicApp).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"{Resource.SyncTimeOffRequestsFromShiftsToKronos} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
this.telemetryClient.TrackException(ex);
}
}
else
{
this.telemetryClient.TrackTrace($"{Resource.MapPayCodeTimeOffReasonsAsync} status: " + isMapPayCodeTimeOffReasonsSuccessful);
}
// sync Shifts from Kronos to Shifts only if OpenShiftRequest and SwapShiftRequest sync is successful.
if (isSwapShiftRequestSyncSuccessful && isOpenShiftRequestSyncSuccessful)
{
// Sync shifts from Kronos to Shifts.
await this.shiftController.ProcessShiftsAsync(isRequestFromLogicApp).ConfigureAwait(false);
this.telemetryClient.TrackTrace($"{Resource.ProcessShiftsAsync} completed from {Resource.ProcessKronosToShiftsShiftsAsync} ");
}
// Do not sync shifts from Kronos to Shifts. Log the status of OpenShiftRequest and SwapShiftRequest sync.
else
{
this.telemetryClient.TrackTrace("Shifts sync not processed. isSwapShiftRequestSuccessful: " + isSwapShiftRequestSyncSuccessful + ", isOpenShiftRequestSuccessful: " + isOpenShiftRequestSyncSuccessful);
}
this.telemetryClient.TrackTrace($"{Resource.ProcessKronosToShiftsShiftsAsync} completed at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}" + " for isRequestFromLogicApp: " + isRequestFromLogicApp);
}
}
}
<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/TimeOff/ITimeOffActivity.cs
// <copyright file="ITimeOffActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.TimeOff
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.TimeOffRequests;
/// <summary>
/// TimeOff Activity Interface.
/// </summary>
public interface ITimeOffActivity
{
/// <summary>
/// Fecth time off request details for displaying history.
/// </summary>
/// <param name="endPointUrl">The Kronos WFC endpoint URL.</param>
/// <param name="jSession">JSession.</param>
/// <param name="queryDateSpan">QueryDateSpan string.</param>
/// <param name="employees">Employees who created request.</param>
/// <returns>Request details response object.</returns>
Task<Response> GetTimeOffRequestDetailsByBatchAsync(
Uri endPointUrl,
string jSession,
string queryDateSpan,
List<Models.ResponseEntities.HyperFind.ResponseHyperFindResult> employees);
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.Common/Providers/GraphUtility.cs
// <copyright file="GraphUtility.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Cache;
using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models;
using Newtonsoft.Json;
/// <summary>
/// Implements the methods that are defined in <see cref="IGraphUtility"/>.
/// </summary>
public class GraphUtility : IGraphUtility
{
private readonly TelemetryClient telemetryClient;
private readonly IDistributedCache cache;
private readonly System.Net.Http.IHttpClientFactory httpClientFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GraphUtility"/> class.
/// </summary>
/// <param name="telemetryClient">The application insights DI.</param>
/// <param name="cache">Cache.</param>
/// <param name="httpClientFactory">Http Client Factory DI.</param>
public GraphUtility(
TelemetryClient telemetryClient,
IDistributedCache cache,
System.Net.Http.IHttpClientFactory httpClientFactory)
{
this.telemetryClient = telemetryClient;
this.cache = cache;
this.httpClientFactory = httpClientFactory;
}
/// <summary>
/// Method to call the Graph API to register the workforce integration.
/// </summary>
/// <param name="workforceIntegration">The workforce integration.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>The JSON response of the Workforce Integration registration.</returns>
public async Task<HttpResponseMessage> RegisterWorkforceIntegrationAsync(
Models.RequestModels.WorkforceIntegration workforceIntegration,
string accessToken)
{
var provider = CultureInfo.InvariantCulture;
this.telemetryClient.TrackTrace(BusinessLogicResource.RegisterWorkforceIntegrationAsync + " called at " + DateTime.Now.ToString("o", provider));
var requestString = JsonConvert.SerializeObject(workforceIntegration);
var httpClientWFI = this.httpClientFactory.CreateClient("GraphBetaAPI");
httpClientWFI.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClientWFI.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "teamwork/workforceIntegrations")
{
Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
})
{
var response = await httpClientWFI.SendAsync(httpRequestMessage).ConfigureAwait(false);
return response;
}
}
/// <summary>
/// Fetch user details for shifts using graph api tokens.
/// </summary>
/// <param name="accessToken">Access Token.</param>
/// <returns>The shift user.</returns>
public async Task<List<ShiftUser>> FetchShiftUserDetailsAsync(
string accessToken)
{
var fetchShiftUserDetailsProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(BusinessLogicResource.FetchShiftUserDetailsAsync, fetchShiftUserDetailsProps);
List<ShiftUser> shiftUsers = new List<ShiftUser>();
bool hasMoreUsers = false;
var httpClient = this.httpClientFactory.CreateClient("GraphBetaAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var requestUri = "users";
do
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var jsonResult = JsonConvert.DeserializeObject<ShiftUserModel>(responseContent);
shiftUsers.AddRange(jsonResult.Value);
if (jsonResult.NextLink != null)
{
hasMoreUsers = true;
requestUri = jsonResult.NextLink.ToString();
}
else
{
hasMoreUsers = false;
}
}
else
{
var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var failedResponseProps = new Dictionary<string, string>()
{
{ "FailedResponse", failedResponseContent },
};
this.telemetryClient.TrackTrace(BusinessLogicResource.FetchShiftUserDetailsAsync, failedResponseProps);
}
}
}
while (hasMoreUsers == true);
return shiftUsers;
}
/// <summary>
/// Fetch user details for shifts using graph api tokens.
/// </summary>
/// <param name="accessToken">Access Token.</param>
/// <returns>The shift user.</returns>
public async Task<List<ShiftTeams>> FetchShiftTeamDetailsAsync(
string accessToken)
{
var fetchShiftUserDetailsProps = new Dictionary<string, string>()
{
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
List<ShiftTeams> shiftTeams = new List<ShiftTeams>();
var hasMoreTeams = false;
this.telemetryClient.TrackTrace(BusinessLogicResource.FetchShiftTeamDetailsAsync, fetchShiftUserDetailsProps);
var hcfClient = this.httpClientFactory.CreateClient("GraphBetaAPI");
hcfClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
hcfClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Filter group who has associated teams also.
var requestUri = "groups?$filter=resourceProvisioningOptions/Any(x:x eq 'Team')";
do
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri))
{
var response = await hcfClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var allResponse = JsonConvert.DeserializeObject<AllShiftsTeam>(responseContent);
shiftTeams.AddRange(allResponse.ShiftTeams);
// If Shifts has more Teams. Typically graph API has 100 teams in one batch.
// Using nextlink, teams from next batch is fetched.
if (allResponse.NextLink != null)
{
requestUri = allResponse.NextLink.ToString();
hasMoreTeams = true;
}
// nextlink is null when there are no batch of teams to be fetched.
else
{
hasMoreTeams = false;
}
}
else
{
hasMoreTeams = false;
var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var failedResponseProps = new Dictionary<string, string>()
{
{ "FailedResponse", failedResponseContent },
};
this.telemetryClient.TrackTrace(BusinessLogicResource.FetchShiftTeamDetailsAsync, failedResponseProps);
}
}
}
// loop until Shifts has more teams to fetch.
while (hasMoreTeams);
return shiftTeams;
}
/// <summary>
/// Method that will obtain the Graph token.
/// </summary>
/// <param name="tenantId">The Tenant ID.</param>
/// <param name="instance">The instance.</param>
/// <param name="clientId">The App ID of the Web Application.</param>
/// <param name="clientSecret">The client secret.</param>
/// <param name="userId">The AAD Object ID of the Admin, could also be the UPN.</param>
/// <returns>A string that represents the Microsoft Graph API token.</returns>
public async Task<string> GetAccessTokenAsync(
string tenantId,
string instance,
string clientId,
string clientSecret,
string userId = default(string))
{
string authority = $"{instance}{tenantId}";
var cache = new RedisTokenCache(this.cache, clientId);
var authContext = new AuthenticationContext(authority, cache);
var userIdentity = new UserIdentifier(userId, UserIdentifierType.UniqueId);
try
{
var result = await authContext.AcquireTokenSilentAsync(
"https://graph.microsoft.com",
new ClientCredential(
clientId,
clientSecret),
userIdentity).ConfigureAwait(false);
return result.AccessToken;
}
catch (AdalException adalEx)
{
this.telemetryClient.TrackException(adalEx);
var retryResult = await authContext.AcquireTokenAsync(
"https://graph.microsoft.com",
new ClientCredential(
clientId,
clientSecret)).ConfigureAwait(false);
return retryResult.AccessToken;
}
}
/// <summary>
/// Method that will delete the workforce integration from MS Graph.
/// </summary>
/// <param name="workforceIntegrationId">The workforce integration ID to delete.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A unit of execution that contains the response.</returns>
public async Task<string> DeleteWorkforceIntegrationAsync(
string workforceIntegrationId,
string accessToken)
{
var wfiDeletionProps = new Dictionary<string, string>()
{
{ "WorkforceIntegrationId", workforceIntegrationId },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, wfiDeletionProps);
var httpClient = this.httpClientFactory.CreateClient("GraphBetaAPI");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, $"teamwork/workforceIntegrations/{workforceIntegrationId}")
{
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return response.StatusCode.ToString();
}
else
{
var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var failedResponseProps = new Dictionary<string, string>()
{
{ "FailedResponse", failedResponseContent },
{ "WorkForceIntegrationId", workforceIntegrationId },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, failedResponseProps);
return string.Empty;
}
}
}
/// <summary>
/// Method that fetchs the scheduling group details based on the shift teams Id provided.
/// </summary>
/// <param name="accessToken">Access Token.</param>
/// <param name="shiftTeamId">Shift Team Id.</param>
/// <returns>Shift scheduling group details.</returns>
public async Task<string> FetchSchedulingGroupDetailsAsync(
string accessToken,
string shiftTeamId)
{
var fetchShiftUserDetailsProps = new Dictionary<string, string>()
{
{ "IncomingShiftsTeamId", shiftTeamId },
{ "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, fetchShiftUserDetailsProps);
var httpClient = this.httpClientFactory.CreateClient("GraphBetaAPI");
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "teams/" + shiftTeamId + "/schedule/schedulingGroups")
{
Headers =
{
{ HttpRequestHeader.Authorization.ToString(), $"Bearer {accessToken}" },
},
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseContent;
}
else
{
var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var failedResponseProps = new Dictionary<string, string>()
{
{ "FailedResponse", failedResponseContent },
{ "ShiftTeamId", shiftTeamId },
};
this.telemetryClient.TrackTrace(MethodBase.GetCurrentMethod().Name, failedResponseProps);
return string.Empty;
}
}
}
/// <summary>
/// Method to update the Workforce Integration ID to the schedule.
/// </summary>
/// <param name="teamsId">The Shift team Id.</param>
/// <param name="graphClient">The Graph Client.</param>
/// <param name="wfIID">The Workforce Integration Id.</param>
/// <param name="accessToken">The MS Graph Access token.</param>
/// <returns>A unit of execution that contains the success or failure Response.</returns>
public async Task<bool> AddWFInScheduleAsync(
string teamsId,
GraphServiceClient graphClient,
string wfIID,
string accessToken)
{
if (graphClient is null)
{
throw new ArgumentNullException(nameof(graphClient));
}
try
{
var sched = await graphClient.Teams[teamsId].Schedule
.Request()
.GetAsync().ConfigureAwait(false);
var schedule = new Schedule
{
Enabled = true,
TimeZone = sched.TimeZone,
WorkforceIntegrationIds = new List<string>() { wfIID },
};
var requestString = JsonConvert.SerializeObject(schedule);
var httpClient = this.httpClientFactory.CreateClient("GraphBetaAPI");
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, "teams/" + teamsId + "/schedule")
{
Headers =
{
{ HttpRequestHeader.Authorization.ToString(), $"Bearer {accessToken}" },
},
Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
})
{
var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return true;
}
else
{
var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var failedResponseProps = new Dictionary<string, string>()
{
{ "FailedResponse", failedResponseContent },
};
this.telemetryClient.TrackTrace(BusinessLogicResource.AddWorkForceIntegrationToSchedule, failedResponseProps);
return false;
}
}
}
catch (Exception ex)
{
this.telemetryClient.TrackException(ex);
throw;
}
}
}
}<file_sep>/Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.App.KronosWfc.BusinessLogic/TimeOff/TimeOffActivity.cs
// <copyright file="TimeOffActivity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.App.KronosWfc.BusinessLogic.TimeOff
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.Teams.App.KronosWfc.Common;
using Microsoft.Teams.App.KronosWfc.Service;
using TimeOffRequest = Microsoft.Teams.App.KronosWfc.Models.RequestEntities.TimeOffRequests;
using TimeOffResponse = Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.TimeOffRequests;
/// <summary>
/// TimeOff Activity Class.
/// </summary>
public class TimeOffActivity : ITimeOffActivity
{
private readonly TelemetryClient telemetryClient;
private readonly IApiHelper apiHelper;
/// <summary>
/// Initializes a new instance of the <see cref="TimeOffActivity"/> class.
/// </summary>
/// <param name="telemetryClient">The mechanisms to capture telemetry.</param>
/// <param name="apiHelper">API helper to fetch tuple response by post soap requests.</param>
public TimeOffActivity(TelemetryClient telemetryClient, IApiHelper apiHelper)
{
this.telemetryClient = telemetryClient;
this.apiHelper = apiHelper;
}
/// <summary>
/// Fecth time off request details for displaying history.
/// </summary>
/// <param name="endPointUrl">The Kronos WFC endpoint URL.</param>
/// <param name="jSession">JSession.</param>
/// <param name="queryDateSpan">QueryDateSpan string.</param>
/// <param name="employees">Employees who created request.</param>
/// <returns>Request details response object.</returns>
public async Task<TimeOffResponse.Response> GetTimeOffRequestDetailsByBatchAsync(
Uri endPointUrl,
string jSession,
string queryDateSpan,
List<Models.ResponseEntities.HyperFind.ResponseHyperFindResult> employees)
{
if (employees is null)
{
throw new ArgumentNullException(nameof(employees));
}
var xmlTimeOffRequest = this.FetchTimeOffRequestsByBatch(employees, queryDateSpan);
var tupleResponse = await this.apiHelper.SendSoapPostRequestAsync(
endPointUrl,
ApiConstants.SoapEnvOpen,
xmlTimeOffRequest,
ApiConstants.SoapEnvClose,
jSession).ConfigureAwait(false);
TimeOffResponse.Response timeOffResponse = this.ProcessTimeOffResponse(tupleResponse.Item1);
return timeOffResponse;
}
/// <summary>
/// Fetch TimeOff request.
/// </summary>
/// <param name="employees">Employees who created request.</param>
/// <param name="queryDateSpan">QueryDateSpan string.</param>
/// <returns>XML request string.</returns>
private string FetchTimeOffRequestsByBatch(List<Models.ResponseEntities.HyperFind.ResponseHyperFindResult> employees, string queryDateSpan)
{
TimeOffRequest.Request rq = new TimeOffRequest.Request
{
Action = ApiConstants.RetrieveWithDetails,
RequestMgmt = new TimeOffRequest.RequestMgmt
{
QueryDateSpan = $"{queryDateSpan}",
RequestFor = ApiConstants.TOR,
Employees = new TimeOffRequest.Employees
{
PersonIdentity = new List<TimeOffRequest.PersonIdentity>(),
},
},
};
var timeOffEmployees = employees.ConvertAll(x => new TimeOffRequest.PersonIdentity { PersonNumber = x.PersonNumber });
rq.RequestMgmt.Employees.PersonIdentity.AddRange(timeOffEmployees);
return rq.XmlSerialize();
}
/// <summary>
/// Process response for request details.
/// </summary>
/// <param name="strResponse">Response received from request for TOR detail.</param>
/// <returns>Response object.</returns>
private TimeOffResponse.Response ProcessTimeOffResponse(string strResponse)
{
XDocument xDoc = XDocument.Parse(strResponse);
var xResponse = xDoc.Root.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals(ApiConstants.Response, StringComparison.Ordinal));
return XmlConvertHelper.DeserializeObject<TimeOffResponse.Response>(xResponse.ToString());
}
}
} | b33d89c7c48170055ce356ae512dcc262df23a6a | [
"C#"
] | 29 | C# | CarlMendez/Microsoft-Teams-Shifts-WFM-Connectors | 126cb3b10cfddcdee3f27f7879afd9998dc7c3e9 | b1cda03b48a8da07871d63667647aed8f1f6c0ab |
refs/heads/master | <file_sep>#!/bin/sh
echo "## TEST 3 - create holes in file system and fill them"
echo "## initialize filesystem"
./fs init --size 1M --path test3.fs
echo "## create small files filling most of drive"
for i in $(seq 500); do
./fs create --filesystem test3.fs --size 1k --name $i;
done;
echo "## remove even files"
for i in $(seq 2 2 500); do
./fs delete --filesystem test3.fs --name $i;
done;
echo "## create big file"
./fs create --filesystem test3.fs --size 400k --name big_file
echo "## display info"
./fs info --filesystem test3.fs
<file_sep>#ifndef SOI_FS_FILESYSTEM_H
#define SOI_FS_FILESYSTEM_H
#include <fstream>
#include <stdint.h>
#include <error.h>
#include <cassert>
#define BIT(n) (1 << (n))
class FileSystem {
static const uint32_t MAGIC = 0x12879247;
static const size_t MAX_FILENAME = 52;
static const size_t BLOCK_SIZE = 512; // block size in bytes
static const size_t EFFECTIVE_BLOCK_SIZE = BLOCK_SIZE - sizeof(uint32_t); // usable part of block
static const size_t BLOCKS_PER_BDTC = EFFECTIVE_BLOCK_SIZE * 8;
static const uint32_t FIRST_FDC = 1;
static const uint32_t FIRST_BDTC = 2;
// file system descriptor is contained in first block of filesystem
struct FileSystemDescriptor {
uint32_t magic;
uint32_t size; // size of filesystem in bytes
uint32_t fdtOffset; // offset to first file descriptor chunk
uint32_t bdtcOffset; // offset to first block descriptor table chunk
uint32_t totalBlocks;
uint32_t usedBlocks;
char padding[BLOCK_SIZE - 6 * sizeof(uint32_t)];
};
// sizeof(FileDescriptor) == 64
struct FileDescriptor {
uint32_t size; // size of file in blocks; zero if entry not used
uint32_t usedSize; // size used by user
uint32_t offset; // offset in blocks to first block
char filename[MAX_FILENAME];
};
static const size_t FD_IN_CHUNK = (BLOCK_SIZE / sizeof(FileDescriptor)) - 1;
// sizeof(FileDescriptorChunk) == BLOCK_SIZE
struct FileDescriptorChunk {
FileDescriptor descriptors[FD_IN_CHUNK];
char padding[BLOCK_SIZE - sizeof(FileDescriptor) * FD_IN_CHUNK - sizeof(uint32_t)];
uint32_t next; // offset to next file descriptor chunk; zero if next chunk does not exists
};
struct BlockDescriptorTableChunk {
uint8_t usage[EFFECTIVE_BLOCK_SIZE]; // each bit describes if block with its index is used
uint32_t next; // offset to next chunk
bool getBit(size_t idx) const {
assert(idx < BLOCKS_PER_BDTC);
uint8_t byte = usage[idx / 8];
return (byte & BIT(idx % 8)) != 0;
}
void setBit(size_t idx) {
assert(idx < BLOCKS_PER_BDTC);
usage[idx / 8] |= BIT(idx % 8);
}
void resetBit(size_t idx) {
assert(idx < BLOCKS_PER_BDTC);
usage[idx / 8] &= ~BIT(idx % 8);
}
};
static const size_t NEXT_BLOCK_OFFSET = BLOCK_SIZE - sizeof(uint32_t);
struct Block {
char data[BLOCK_SIZE - sizeof(uint32_t)];
uint32_t next; // offset to next block
};
std::fstream file;
FileSystemDescriptor fileSystemDescriptor;
std::ostream* exportFileStream; // use in exportFile method
size_t exportFileSize;
public:
class Error : public std::exception {
std::string message;
public:
Error() { }
Error(const std::string& message) : message(message) { }
~Error() throw() { }
virtual const char* what() const throw() {
return message.c_str();
}
};
FileSystem(const std::string& path);
void createFile(const std::string& filename, size_t size);
void deleteFile(const std::string& filename);
void importFile(std::istream& source, const std::string& filename);
void exportFile(std::ostream& destination, const std::string& filename);
void displayInfo(std::ostream& out);
void displayFSDBlocks(std::ostream& out);
void displayFDTBlocks(std::ostream& out);
void displayBDTBlocks(std::ostream& out);
void displayDataBlocks(std::ostream& out);
static void init(const std::string& path, size_t size);
private:
void loadFS();
void allocBlock(uint32_t idx);
void freeBlock(uint32_t idx);
// Allocs specified number of blocks.
uint32_t allocBlockChain(size_t count);
// sets bdtc at specified index to specified value
//
// @returns previous value
static bool setBdtc(std::fstream& file, uint32_t bdtcOffset, uint32_t idx, bool value);
// Searches for a file
//
// @param path path to file
// @param outFd [out] file descriptor
// @param outFDCblock [out] Offset in blocks of FDC in which FD is stored.
// @param outFDCidx [out] Index of FD in FDC.
bool findFile(const std::string& path, FileDescriptor* outFd = NULL, uint32_t* outFDCblock = NULL,
size_t* outFDCidx = NULL);
void foreachBlock(const std::string& path, void(FileSystem::*func)(Block& block, uint32_t blockOffset));
void deleteBlock(Block& block, uint32_t blockOffset);
void saveToOut(Block& block, uint32_t blockOffset);
bool insertFileIntoFDC(const std::string& filename, size_t size, const uint32_t blocksCount,
uint32_t dataBlocks, uint32_t fdcOffset, FileDescriptorChunk& fdc);
void displayBlockChain(uint32_t first, std::ostream& out);
};
#endif //SOI_FS_FILESYSTEM_H
<file_sep>##Description
Simple file system with no real use case.
###Commands
```
help displays help
init initializes new filesystem
--size SIZE size of filesystem
--path STR path to file which will contain filesystem
create create new file
--filesystem STR path to filesystem
--name STR path to file
--size SIZE size of file
delete deletes file from filesystem
--filesystem STR path to filesystem
--name STR path to file
import imports file from external filesystem
--filesystem STR path to filesystem
--source STR path to source file
--destination STR path to destination file
extract extracts file from virtual filesystem
--filesystem STR path to filesystem
--source STR path to source file
--destination STR path to destination file
info displays information about filesystem
--filesystem STR path to filesystem
```
###Examples
Create new file system:
```
./fs init --size 10M --path test.fs
```
Create empty file:
```
./fs create --filesystem test.fs --name penguin.txt --size 1M
```
Import file:
```
./fs import --filesystem test.fs --source main.cpp --destination main.cpp
```
Delete file:
```
./fs delete --filesystem test.fs --name main.cpp
```
<file_sep>fs: Argparse.o FileSystem.o Synchronization.o main.o
g++ Argparse.o FileSystem.o Synchronization.o main.o -o fs -lpthread -lrt
Argparse.o: Argparse.cpp Argparse.h
g++ -c Argparse.cpp -o Argparse.o
FileSystem.o: FileSystem.cpp FileSystem.h
g++ -c FileSystem.cpp -o FileSystem.o
Synchronization.o: Synchronization.cpp Synchronization.h
g++ -c Synchronization.cpp -o Synchronization.o
main.o: main.cpp
g++ -c main.cpp -o main.o
clean:
rm *.o
rm fs
<file_sep>#!/bin/bash
echo "## TEST 1 - simple operations on filesystem"
echo "## initialize filesystem"
./fs init --size 10M --path test1.fs
echo "## import file into filesystem"
./fs import --filesystem test1.fs --source main.cpp --destination main.cpp
echo "## extract file from filesystem"
./fs extract --filesystem test1.fs --source main.cpp --destination test.cpp
echo "## check if files are same"
diff main.cpp test.cpp
echo "## create empty file"
./fs create --filesystem test1.fs --name penguin.txt --size 1M
echo "## display files"
./fs info --filesystem test1.fs
<file_sep>#ifndef SOI_FS_SYNCHRONIZATION_H
#define SOI_FS_SYNCHRONIZATION_H
#include <semaphore.h>
#include <fcntl.h>
#include <string>
class Synchronization {
struct shared_data {
bool init;
int readersCount;
sem_t fsLock;
sem_t readersLock;
sem_t enterLock;
};
static shared_data *data;
public:
static void init(const std::string &filename);
struct Reader {
Reader();
~Reader();
};
struct Writer {
Writer();
~Writer();
};
};
#endif //SOI_FS_SYNCHRONIZATION_H
<file_sep>#include <sstream>
#include <cstring>
#include <vector>
#include <iomanip>
#include <stdint.h>
#include <iostream>
#include "FileSystem.h"
using namespace std;
FileSystem::FileSystem(const std::string& path) : exportFileStream(NULL) {
assert(sizeof(Block) == sizeof(FileSystemDescriptor));
assert(sizeof(Block) == sizeof(FileDescriptorChunk));
file.open(path.c_str(), fstream::binary | fstream::in | fstream::out);
if (!file.is_open()) {
stringstream err;
err << "Unable to open " << path;
throw Error(err.str());
}
loadFS();
}
void FileSystem::createFile(const std::string& filename, size_t size) {
if (filename.size() + 1 > MAX_FILENAME) {
throw Error("filename too long");
}
if (findFile(filename)) {
throw Error("file already exists");
}
const uint32_t blocksCount = static_cast<uint32_t>((size + EFFECTIVE_BLOCK_SIZE - 1) / EFFECTIVE_BLOCK_SIZE);
if (fileSystemDescriptor.totalBlocks - fileSystemDescriptor.usedBlocks < blocksCount + 1) {
throw Error("not enough free space");
}
uint32_t dataBlocks = allocBlockChain(blocksCount);
uint32_t fdcOffset = fileSystemDescriptor.fdtOffset, prevOffset;
FileDescriptorChunk fdc;
do {
prevOffset = fdcOffset;
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&fdc), sizeof(fdc));
if (insertFileIntoFDC(filename, size, blocksCount, dataBlocks, fdcOffset, fdc)) {
return;
}
fdcOffset = fdc.next;
} while (fdcOffset);
// allocate next fdc
uint32_t nextFdc = allocBlockChain(1);
// update last fdc
fdc.next = nextFdc;
file.seekg(prevOffset * BLOCK_SIZE, file.beg);
file.write(reinterpret_cast<char*>(&fdc), sizeof(fdc));
// fill new fdc
memset(&fdc, 0, sizeof(fdc));
insertFileIntoFDC(filename, size, blocksCount, dataBlocks, nextFdc, fdc);
}
void FileSystem::deleteFile(const std::string& filename) {
foreachBlock(filename, &FileSystem::deleteBlock);
FileDescriptor fd;
uint32_t fdcOffset;
size_t fdIndex;
findFile(filename, &fd, &fdcOffset, &fdIndex);
FileDescriptorChunk fdc;
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&fdc), sizeof(fdc));
uint32_t blocksCount = fdc.descriptors[fdIndex].size;
fdc.descriptors[fdIndex].size = 0;
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.write(reinterpret_cast<char*>(&fdc), sizeof(fdc));
fileSystemDescriptor.usedBlocks -= blocksCount;
file.seekg(0, file.beg);
file.write(reinterpret_cast<char*>(&fileSystemDescriptor), sizeof(fileSystemDescriptor));
}
void FileSystem::importFile(std::istream& source, const std::string& filename) {
streampos begin = source.tellg();
source.seekg(0, source.end);
size_t size = static_cast<size_t>(source.tellg() - begin);
source.seekg(begin, source.beg);
createFile(filename, size);
FileDescriptor fd;
findFile(filename, &fd);
Block block;
uint32_t currBlock = fd.offset;
while (size) {
file.seekg(currBlock * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&block), sizeof(block));
const size_t effBlockSize = EFFECTIVE_BLOCK_SIZE;
const size_t writeSize = min(effBlockSize, size);
source.read(block.data, writeSize);
file.seekg(currBlock * BLOCK_SIZE, file.beg);
file.write(reinterpret_cast<char*>(&block), sizeof(block));
currBlock = block.next;
size -= writeSize;
}
}
void FileSystem::exportFile(std::ostream& destination, const std::string& filename) {
FileDescriptor fd;
if (!findFile(filename, &fd)) {
stringstream ss;
ss << "File " << filename << " not found";
throw Error(ss.str());
}
exportFileStream = &destination;
exportFileSize = fd.usedSize;
foreachBlock(filename, &FileSystem::saveToOut);
}
void FileSystem::displayInfo(std::ostream& out) {
const streamsize NAME_W = 16, SIZE_W = 16, BLOCK_W = 16;
out << "Size: " << fileSystemDescriptor.size << " bytes" << endl;
out << "Total blocks: " << fileSystemDescriptor.totalBlocks << endl;
out << "Used blocks: " << fileSystemDescriptor.usedBlocks << endl;
out << "Free blocks: " << fileSystemDescriptor.totalBlocks - fileSystemDescriptor.usedBlocks << endl;
out << endl << "Files: " << endl;
out << left << setw(NAME_W) << "NAME"
<< left << setw(SIZE_W) << "SIZE"
<< left << setw(BLOCK_W) << "BLOCK COUNT" << endl;
uint32_t fdcOffset = fileSystemDescriptor.fdtOffset;
FileDescriptorChunk fdc;
do {
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&fdc), sizeof(fdc));
for (size_t i = 0; i < FD_IN_CHUNK; ++i) {
FileDescriptor& fd = fdc.descriptors[i];
if (fd.size != 0) {
out << left << setw(NAME_W) << fd.filename
<< left << setw(SIZE_W) << fd.usedSize
<< left << setw(BLOCK_W) << fd.size << endl;
}
}
fdcOffset = fdc.next;
} while (fdcOffset);
out << endl << endl;
}
void FileSystem::displayFSDBlocks(std::ostream& out) {
displayBlockChain(0, out);
}
void FileSystem::displayFDTBlocks(std::ostream& out) {
displayBlockChain(fileSystemDescriptor.fdtOffset, out);
}
void FileSystem::displayBDTBlocks(std::ostream& out) {
displayBlockChain(fileSystemDescriptor.bdtcOffset, out);
}
void FileSystem::displayDataBlocks(std::ostream& out) {
const streamsize BEGIN = 16, END = 16, USED = 5;
out << left << setw(BEGIN) << "BEGIN"
<< left << setw(END) << "END"
<< left << setw(USED) << "USED" << endl;
uint32_t currBdtc = fileSystemDescriptor.bdtcOffset, prevBlock, currBdtcIdx = 0;
BlockDescriptorTableChunk bdtc;
do {
file.seekg(currBdtc * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&bdtc), sizeof(bdtc));
for (size_t i = 0; i < BLOCKS_PER_BDTC; ++i) {
uint32_t blockIdx = static_cast<uint32_t>(currBdtcIdx * BLOCKS_PER_BDTC + i);
size_t offset = blockIdx * BLOCK_SIZE;
out << left << setw(BEGIN) << offset
<< left << setw(END) << offset + BLOCK_SIZE
<< left << setw(USED) << bdtc.getBit(i) << endl;
}
++currBdtcIdx;
currBdtc = bdtc.next;
} while (currBdtc);
}
void FileSystem::init(const std::string& path, size_t size) {
const size_t blocksCount = size / BLOCK_SIZE;
const size_t bdtcCount = (blocksCount + BLOCKS_PER_BDTC - 1) / BLOCKS_PER_BDTC;
const size_t usedBlocksCount = bdtcCount + 2;
if (blocksCount < 3) {
stringstream err;
err << "file system too small (minimum 3 blocks, got " << blocksCount << ")";
throw Error(err.str());
}
fstream file(path.c_str(), fstream::trunc | fstream::binary | fstream::out | fstream::in);
if (!file.is_open()) {
stringstream err;
err << "Unable to open " << path;
throw Error(err.str());
}
// resize file
const int dummy = 0x12233445;
file.seekp(size - sizeof(dummy), file.beg);
file.write(reinterpret_cast<const char*>(&dummy), sizeof(dummy));
file.seekp(0, file.beg);
// initialize structures
FileSystemDescriptor fds;
memset(&fds, 0, sizeof(fds));
fds.magic = MAGIC;
fds.fdtOffset = FIRST_FDC;
fds.bdtcOffset = FIRST_BDTC;
fds.totalBlocks = static_cast<uint32_t>(blocksCount);
fds.usedBlocks = static_cast<uint32_t>(usedBlocksCount);
fds.size = static_cast<uint32_t>(blocksCount * BLOCK_SIZE);
FileDescriptorChunk fdc;
memset(&fdc, 0, sizeof(fdc));
// write structures to file
file.write(reinterpret_cast<char*>(&fds), sizeof(fds));
file.write(reinterpret_cast<char*>(&fdc), sizeof(fdc));
// write bdtc
Block bdtcDummy;
memset(&bdtcDummy, 0, sizeof(bdtcDummy));
bdtcDummy.next = fds.bdtcOffset;
for (size_t i = 0; i < bdtcCount; ++i) {
if (i == bdtcCount - 1) {
bdtcDummy.next = 0;
} else {
++bdtcDummy.next;
}
file.write(reinterpret_cast<char*>(&bdtcDummy), sizeof(bdtcDummy));
}
for (uint32_t i = 0; i < usedBlocksCount; ++i) {
setBdtc(file, fds.bdtcOffset, i, true);
}
}
void FileSystem::loadFS() {
file.read(reinterpret_cast<char*>(&fileSystemDescriptor), sizeof(fileSystemDescriptor));
if (fileSystemDescriptor.magic != MAGIC) {
throw Error("filesystem is corrupted");
}
}
void FileSystem::allocBlock(uint32_t idx) {
streampos pos = file.tellg();
bool prev = setBdtc(file, fileSystemDescriptor.bdtcOffset, idx, true);
if (prev) {
throw Error("block already allocated");
}
file.seekg(pos, file.beg);
}
void FileSystem::freeBlock(uint32_t idx) {
streampos pos = file.tellg();
bool prev = setBdtc(file, fileSystemDescriptor.bdtcOffset, idx, false);
if (!prev) {
throw Error("freeing free block");
}
file.seekg(pos, file.beg);
}
uint32_t FileSystem::allocBlockChain(size_t count) {
uint32_t result = 0;
fileSystemDescriptor.usedBlocks += count;
file.seekg(0, file.beg);
file.write(reinterpret_cast<char*>(&fileSystemDescriptor), sizeof(fileSystemDescriptor));
uint32_t currBdtc = fileSystemDescriptor.bdtcOffset, prevBlock, currBdtcIdx = 0;
BlockDescriptorTableChunk bdtc;
do {
file.seekg(currBdtc * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&bdtc), sizeof(bdtc));
for (size_t i = 0; i < BLOCKS_PER_BDTC && count; ++i) {
if (bdtc.getBit(i)) {
continue;
}
uint32_t nextBlock = static_cast<uint32_t>(currBdtcIdx * BLOCKS_PER_BDTC + i);
allocBlock(nextBlock);
if (!result) {
result = nextBlock;
} else {
file.seekg(prevBlock * BLOCK_SIZE + EFFECTIVE_BLOCK_SIZE, file.beg);
file.write(reinterpret_cast<char*>(&nextBlock), sizeof(nextBlock));
}
prevBlock = nextBlock;
--count;
}
++currBdtcIdx;
currBdtc = bdtc.next;
} while (count && currBdtc);
return result;
}
bool FileSystem::setBdtc(std::fstream& file, uint32_t bdtcOffset, uint32_t idx, bool value) {
const uint32_t blockIdx = static_cast<uint32_t>(idx / BLOCKS_PER_BDTC);
const uint32_t bitOffset = static_cast<uint32_t>(idx % BLOCKS_PER_BDTC);
uint32_t blockOffset = bdtcOffset;
for (uint32_t i = 0; i < blockIdx; ++i) {
file.seekg(blockOffset * BLOCK_SIZE + NEXT_BLOCK_OFFSET);
file.read(reinterpret_cast<char*>(&blockOffset), sizeof(blockOffset));
}
BlockDescriptorTableChunk bdtc;
file.seekg(blockOffset * BLOCK_SIZE);
file.read(reinterpret_cast<char*>(&bdtc), sizeof(bdtc));
bool result = bdtc.getBit(bitOffset);
if (value) {
bdtc.setBit(bitOffset);
} else {
bdtc.resetBit(bitOffset);
}
file.seekg(blockOffset * BLOCK_SIZE);
file.write(reinterpret_cast<char*>(&bdtc), sizeof(bdtc));
return result;
}
bool FileSystem::findFile(const std::string& path, FileDescriptor* outFd, uint32_t* outFDCblock, size_t* outFDCidx) {
uint32_t fdcOffset = fileSystemDescriptor.fdtOffset;
FileDescriptorChunk fdc;
do {
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&fdc), sizeof(fdc));
for (size_t i = 0; i < FD_IN_CHUNK; ++i) {
FileDescriptor& fd = fdc.descriptors[i];
if (fd.size > 0 && path == fd.filename) {
if (outFd) {
memcpy(outFd, &fd, sizeof(FileDescriptor));
}
if (outFDCblock) {
*outFDCblock = fdcOffset;
}
if (outFDCidx) {
*outFDCidx = i;
}
return true;
}
}
fdcOffset = fdc.next;
} while (fdcOffset);
return false;
}
void FileSystem::foreachBlock(const std::string& path, void (FileSystem::*func)(Block&, uint32_t)) {
FileDescriptor fd;
if (!findFile(path, &fd)) {
throw Error("file does not exists");
}
uint32_t currBlock = fd.offset;
Block block;
do {
file.seekg(currBlock * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&block), sizeof(block));
(this->*func)(block, currBlock);
currBlock = block.next;
} while (currBlock);
}
void FileSystem::deleteBlock(Block& block, uint32_t blockOffset) {
freeBlock(blockOffset);
}
void FileSystem::saveToOut(Block& block, uint32_t) {
const size_t effBlockSize = EFFECTIVE_BLOCK_SIZE;
size_t writeSize = min(effBlockSize, exportFileSize);
exportFileStream->write(block.data, writeSize);
exportFileSize -= writeSize;
}
bool FileSystem::insertFileIntoFDC(const string& filename, size_t size,
const uint32_t blocksCount, uint32_t dataBlocks,
uint32_t fdcOffset,
FileSystem::FileDescriptorChunk& fdc) {
for (size_t i = 0; i < FD_IN_CHUNK; ++i) {
FileDescriptor& fd = fdc.descriptors[i];
if (fd.size == 0) {
fd.size = blocksCount;
fd.usedSize = static_cast<uint32_t>(size);
fd.offset = dataBlocks;
strcpy(fd.filename, filename.c_str());
file.seekg(fdcOffset * BLOCK_SIZE, file.beg);
file.write(reinterpret_cast<char*>(&fdc), sizeof(fdc));
return true;
}
}
return false;
}
void FileSystem::displayBlockChain(uint32_t first, std::ostream& out) {
const streamsize BEGIN = 8, END = 8;
out << left << setw(BEGIN) << "BEGIN"
<< left << setw(END) << "END" << endl;
uint32_t blockOffset = first;
Block block;
do {
file.seekg(blockOffset * BLOCK_SIZE, file.beg);
file.read(reinterpret_cast<char*>(&block), sizeof(block));
out << left << setw(BEGIN) << blockOffset * BLOCK_SIZE
<< left << setw(END) << (blockOffset + 1) * BLOCK_SIZE << endl;
blockOffset = block.next;
} while (blockOffset);
}
<file_sep>#ifndef SOI_FS_ARGPARSE_H
#define SOI_FS_ARGPARSE_H
#include <vector>
#include <string>
#include <error.h>
#include <map>
struct Argparse {
enum PropertyType {
Integer,
String,
Size,
};
static const char *TYPE_TO_STRING[];
struct ArgumentValue {
PropertyType type;
struct {
int integer;
std::string str;
size_t size;
} value;
};
static ArgumentValue valueFromString(const std::string &value, PropertyType type);
private:
class CommandProperty {
PropertyType type;
std::string name;
std::string description;
bool optional;
public:
PropertyType getType() const;
void setType(PropertyType type);
const std::string& getName() const;
void setName(const std::string& name);
const std::string& getDescription() const;
void setDescription(const std::string& description);
bool isOptional() const;
void setOptional(bool optional);
};
class Command {
std::string name;
std::string description;
int code;
std::vector<CommandProperty> properties;
public:
const std::string& getName() const;
void setName(const std::string& name);
const std::string& getDescription() const;
void setDescription(const std::string& description);
int getCode() const;
void setCode(int code);
void addProperty(const CommandProperty &commandProperty);
const CommandProperty& getProperty(const std::string &name) const;
const std::vector<CommandProperty>& getProperties() const;
};
public:
class Error : public std::exception {
std::string message;
public:
Error() {}
Error(const std::string& message) : message(message) { }
~Error() throw() {}
virtual const char *what() const throw() {
return message.c_str();
}
};
class CommandBuilder {
friend struct Argparse;
Command& targetCommand;
public:
CommandBuilder& addProperty(
const std::string& name, PropertyType type, const std::string& description, bool optional = false);
void commit();
private:
CommandBuilder(Command& targetCommand) : targetCommand(targetCommand) { }
};
class CommandResult {
friend struct Argparse;
const Command& command;
std::map<std::string, ArgumentValue> properties;
public:
const std::string& getName() const;
int getCode() const;
bool hasProperty(const std::string &name) const;
const ArgumentValue& getProperty(const std::string &name) const;
private:
CommandResult(const Command& command) : command(command) { }
};
Argparse();
CommandBuilder& addCommand(const std::string& name, int code, const std::string& description);
void displayHelp() const;
CommandResult parse(int argc, char *argv[]) const;
private:
CommandResult parseCommand(const Command& cmd, std::vector<std::string> args) const;
std::vector<Command> commands;
};
#endif //SOI_FS_ARGPARSE_H
<file_sep>#include <iostream>
#include <semaphore.h>
#include "Argparse.h"
#include "FileSystem.h"
#include "Synchronization.h"
using namespace std;
enum Command {
CMD_HELP,
CMD_INIT,
CMD_CREATE,
CMD_DELETE,
CMD_IMPORT,
CMD_EXTRACT,
CMD_INFO,
CMD_BLOCKS,
};
void handleCommand(const Argparse& argparse, const Argparse::CommandResult& cmd);
void handleFileSystemCommand(const Argparse::CommandResult& cmd);
void displayBlockInfo(FileSystem &fs, std::string type);
int main(int argc, char* argv[]) {
Argparse argparse;
argparse.addCommand("help", CMD_HELP, "displays help")
.commit();
argparse.addCommand("init", CMD_INIT, "initializes new filesystem")
.addProperty("size", Argparse::Size, "size of filesystem")
.addProperty("path", Argparse::String, "path to file which will contain filesystem")
.commit();
argparse.addCommand("create", CMD_CREATE, "create new file")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.addProperty("name", Argparse::String, "path to file")
.addProperty("size", Argparse::Size, "size of file")
.commit();
argparse.addCommand("delete", CMD_DELETE, "deletes file from filesystem")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.addProperty("name", Argparse::String, "path to file")
.commit();
argparse.addCommand("import", CMD_IMPORT, "imports file from external filesystem")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.addProperty("source", Argparse::String, "path to source file")
.addProperty("destination", Argparse::String, "path to destination file")
.commit();
argparse.addCommand("extract", CMD_EXTRACT, "extracts file from virtual filesystem")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.addProperty("source", Argparse::String, "path to source file")
.addProperty("destination", Argparse::String, "path to destination file")
.commit();
argparse.addCommand("info", CMD_INFO, "displays information about filesystem")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.commit();
argparse.addCommand("blocks", CMD_BLOCKS, "displays information about blocks")
.addProperty("filesystem", Argparse::String, "path to filesystem")
.addProperty("type", Argparse::String, "block types (ALL - all but DATA; FSD - file system descriptor;"\
"FDT - file descriptor table; BDT - block descriptor table; DATA - information about every block state)")
.commit();
try {
Argparse::CommandResult cmd = argparse.parse(argc, argv);
handleCommand(argparse, cmd);
} catch (const Argparse::Error& e) {
cout << "Error occurred while parsing command: " << e.what() << endl;
} catch (const FileSystem::Error& e) {
cout << "Error occurred in execution of command: " << e.what() << endl;
}
return 0;
}
void handleCommand(const Argparse& argparse, const Argparse::CommandResult& cmd) {
switch (cmd.getCode()) {
case CMD_HELP:
argparse.displayHelp();
break;
case CMD_INIT:
FileSystem::init(
cmd.getProperty("path").value.str,
cmd.getProperty("size").value.size
);
break;
default:
handleFileSystemCommand(cmd);
break;
}
}
void handleFileSystemCommand(const Argparse::CommandResult& cmd) {
const string& path = cmd.getProperty("filesystem").value.str;
Synchronization::init(path);
FileSystem fs(path);
switch (cmd.getCode()) {
case CMD_CREATE: {
Synchronization::Writer lock;
fs.createFile(
cmd.getProperty("name").value.str,
cmd.getProperty("size").value.size
);
break;
}
case CMD_DELETE: {
Synchronization::Writer lock;
fs.deleteFile(
cmd.getProperty("name").value.str
);
break;
}
case CMD_IMPORT: {
Synchronization::Writer lock;
std::ifstream source(cmd.getProperty("source").value.str.c_str());
fs.importFile(
source,
cmd.getProperty("destination").value.str
);
break;
}
case CMD_EXTRACT: {
Synchronization::Reader lock;
std::ofstream destination(cmd.getProperty("destination").value.str.c_str());
fs.exportFile(
destination,
cmd.getProperty("source").value.str
);
break;
}
case CMD_INFO: {
Synchronization::Reader lock;
fs.displayInfo(cout);
break;
}
case CMD_BLOCKS: {
Synchronization::Reader lock;
displayBlockInfo(fs, cmd.getProperty("type").value.str);
}
default:
break;
}
}
void displayBlockInfo(FileSystem& fs, std::string type) {
if (type == "ALL") {
cout << "FSD:" << endl;
fs.displayFSDBlocks(cout);
cout << endl << "FDT:" << endl;
fs.displayFDTBlocks(cout);
cout << endl << "BDT:" << endl;
fs.displayBDTBlocks(cout);
} else if (type == "FSD") {
fs.displayFSDBlocks(cout);
} else if (type == "FDT") {
fs.displayFDTBlocks(cout);
} else if (type == "BDT") {
fs.displayBDTBlocks(cout);
} else if (type == "DATA") {
fs.displayDataBlocks(cout);
} else {
cout << "Invalid type" << endl;
}
}
<file_sep>#include "Synchronization.h"
#include <assert.h>
#include <sys/mman.h>
#include <unistd.h>
namespace {
const std::string SEMAPHORE_NAME = "/soi_fs_lock_";
const std::string SHM_NAME = "/soi_fs_mem_";
}
Synchronization::shared_data *Synchronization::data = NULL;
void Synchronization::init(const std::string& filename) {
assert(!data);
const std::string& semName = SEMAPHORE_NAME + filename;
sem_t *lock = sem_open(semName.c_str(), O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO, 1);
int shared_mem_handle = shm_open((SHM_NAME + filename).c_str(), O_CREAT | O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO);
sem_wait(lock);
ftruncate(shared_mem_handle, sizeof(shared_data));
data = (shared_data*) mmap(NULL, sizeof(shared_data), PROT_READ | PROT_WRITE, MAP_SHARED, shared_mem_handle, 0);
if (!data->init) {
data->readersCount = 0;
sem_init(&data->fsLock, 1, 1);
sem_init(&data->enterLock, 1, 1);
sem_init(&data->readersLock, 1, 1);
data->init = true;
}
sem_post(lock);
sem_unlink(semName.c_str());
}
Synchronization::Reader::Reader() {
sem_wait(&data->enterLock);
sem_wait(&data->readersLock);
if (!data->readersCount) {
sem_wait(&data->fsLock);
}
data->readersCount++;
sem_post(&data->readersLock);
sem_post(&data->enterLock);
}
Synchronization::Reader::~Reader() {
sem_wait(&data->readersLock);
data->readersCount--;
if (!data->readersCount) {
sem_post(&data->fsLock);
}
sem_post(&data->readersLock);
}
Synchronization::Writer::Writer() {
sem_wait(&data->enterLock);
sem_wait(&data->fsLock);
sem_post(&data->enterLock);
}
Synchronization::Writer::~Writer() {
sem_post(&data->fsLock);
}
<file_sep>#!/bin/sh
echo "## TEST 2 - fill filesystem with small files"
echo "## initialize filesystem"
./fs init --size 10M --path test2.fs
echo "## create files"
for i in $(seq 200); do
./fs create --filesystem test2.fs --size 1k --name $i;
done;
echo "## display info"
./fs info --filesystem test2.fs
<file_sep>#include <iostream>
#include <sstream>
#include <iomanip>
#include "Argparse.h"
using namespace std;
namespace {
size_t sizeMultiplierFromPostfix(char postfix) {
switch (tolower(postfix)) {
case 'b':
return 1LL;
case 'k':
return 1LL << 10;
case 'm':
return 1LL << 20;
case 'g':
return 1LL << 30;
case 't':
return 1LL << 40;
default:
return 0;
}
}
}
const char* Argparse::TYPE_TO_STRING[] = {
"INT",
"STR",
"SIZE"
};
Argparse::ArgumentValue Argparse::valueFromString(const std::string& value, PropertyType type) {
ArgumentValue result;
result.type = type;
switch (type) {
case Argparse::Integer: {
stringstream ss(value);
ss >> result.value.integer;
break;
}
case Argparse::String:
result.value.str = value;
break;
case Argparse::Size: {
char sizePostfix = value[value.size() - 1];
size_t multiplier = sizeMultiplierFromPostfix(sizePostfix);
stringstream ss(value.substr(0, value.size() - 1));
ss >> result.value.size;
result.value.size *= multiplier;
break;
}
default:
throw Error("invalid property type");
}
return result;
}
Argparse::Argparse() {
}
Argparse::CommandBuilder& Argparse::addCommand(const std::string& name, int code, const std::string& description) {
commands.resize(commands.size() + 1);
Command& lastCommand = commands[commands.size() - 1];
lastCommand.setName(name);
lastCommand.setDescription(description);
lastCommand.setCode(code);
return *new CommandBuilder(lastCommand);
}
void Argparse::displayHelp() const {
const streamsize NAME_WIDTH = 16, TYPE_WIDTH = 7, OPT_WIDTH = 5;
for (size_t i = 0; i < commands.size(); ++i) {
const Command& cmd = commands[i];
cout.width(NAME_WIDTH);
cout << std::left << cmd.getName() << cmd.getDescription() << endl;
for (size_t j = 0; j < cmd.getProperties().size(); ++j) {
const CommandProperty& prop = cmd.getProperties()[j];
cout.width(NAME_WIDTH);
cout << std::left << ("--" + prop.getName());
cout.width(TYPE_WIDTH);
cout << std::left << TYPE_TO_STRING[prop.getType()];
cout.width(OPT_WIDTH);
cout << std::left << (prop.isOptional() ? "OPT" : "");
cout << prop.getDescription() << endl;
}
cout << endl;
}
}
Argparse::CommandResult Argparse::parse(int argc, char* argv[]) const {
if (argc < 2) {
throw Error("not enough arguments");
}
const char* cmdName = argv[1];
for (size_t i = 0; i < commands.size(); ++i) {
if (commands[i].getName() == cmdName) {
return parseCommand(commands[i], vector<string>(argv + 2, argv + argc));
}
}
throw Error("command does not exists");
}
Argparse::CommandResult Argparse::parseCommand(const Command& cmd, std::vector<std::string> args) const {
if (args.size() % 2 != 0) {
throw Error("invalid number of arguments");
}
CommandResult result(cmd);
for (size_t i = 0; i < args.size(); i += 2) {
std::string name = args[i].substr(2); // dashes
const std::string& value = args[i + 1];
const CommandProperty& prop = cmd.getProperty(name);
result.properties[name] = valueFromString(value, prop.getType());
}
for (size_t i = 0; i < cmd.getProperties().size(); ++i) {
const CommandProperty& prop = cmd.getProperties()[i];
if (!prop.isOptional() && !result.hasProperty(prop.getName())) {
stringstream err;
err << "Property " << prop.getName() << " is not set";
throw Error(err.str());
}
}
return result;
}
Argparse::CommandBuilder& Argparse::CommandBuilder::addProperty(const std::string& name, Argparse::PropertyType type,
const std::string& description, bool optional) {
CommandProperty prop;
prop.setName(name);
prop.setType(type);
prop.setDescription(description);
prop.setOptional(optional);
targetCommand.addProperty(prop);
return *this;
}
void Argparse::CommandBuilder::commit() {
delete this;
}
void Argparse::Command::addProperty(const CommandProperty& commandProperty) {
properties.push_back(commandProperty);
}
void Argparse::Command::setName(const std::string& name) {
Command::name = name;
}
const std::string& Argparse::Command::getName() const {
return name;
}
const Argparse::CommandProperty& Argparse::Command::getProperty(const std::string& name) const {
for (size_t i = 0; i < properties.size(); ++i) {
if (properties[i].getName() == name) {
return properties[i];
}
}
stringstream err;
err << "Property " << name << " does not exists";
throw Error(err.str());
}
const std::vector<Argparse::CommandProperty>& Argparse::Command::getProperties() const {
return properties;
}
void Argparse::CommandProperty::setOptional(bool optional) {
CommandProperty::optional = optional;
}
bool Argparse::CommandProperty::isOptional() const {
return optional;
}
void Argparse::CommandProperty::setDescription(const std::string& description) {
CommandProperty::description = description;
}
const std::string& Argparse::CommandProperty::getDescription() const {
return description;
}
void Argparse::CommandProperty::setName(const std::string& name) {
CommandProperty::name = name;
}
const std::string& Argparse::CommandProperty::getName() const {
return name;
}
void Argparse::CommandProperty::setType(PropertyType type) {
CommandProperty::type = type;
}
Argparse::PropertyType Argparse::CommandProperty::getType() const {
return type;
}
const std::string& Argparse::CommandResult::getName() const {
return command.getName();
}
int Argparse::CommandResult::getCode() const {
return command.getCode();
}
bool Argparse::CommandResult::hasProperty(const std::string& name) const {
map<string, ArgumentValue>::const_iterator it = properties.find(name);
return it != properties.end();
}
const Argparse::ArgumentValue& Argparse::CommandResult::getProperty(const std::string& name) const {
if (!hasProperty(name)) {
throw Error("property is not set");
}
return properties.find(name)->second;
}
const std::string& Argparse::Command::getDescription() const {
return description;
}
void Argparse::Command::setDescription(const std::string& description) {
Command::description = description;
}
int Argparse::Command::getCode() const {
return code;
}
void Argparse::Command::setCode(int code) {
Command::code = code;
} | 788b7b2272696933442d9d6c0682f4bf60f819c1 | [
"Markdown",
"Makefile",
"C++",
"Shell"
] | 12 | Shell | marcin-sucharski/EiTI-SOI-virtual_file_system | 8ebde1f8fbd9cf2524558aa46090be5d06e357b8 | 6fe04548be9d314ef5d462985bc06e78e1493ff8 |
refs/heads/master | <repo_name>genielogmatrice/genie_logiciel_projet<file_sep>/projet.md
genie_logiciel_projet
=====================
fef
bra
<file_sep>/main.cpp
#include "matrice.h"
#include <iostream>
using namespace std;
int main()
{
matrice<int> Mat();
return 0;
}
| 9ab8bdcf2c66318964e515edf90f41f9c6ddeb03 | [
"Markdown",
"C++"
] | 2 | Markdown | genielogmatrice/genie_logiciel_projet | 0415f280b875fee94a5ebdaa349aef4a0f9f5b52 | 717ad98b9cb5557bd7f7bc128d5b64603267cb4e |
refs/heads/master | <file_sep>package qaclickacademy;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
public class RESTAPI {
@Test
public void postJira()
{
System.out.println("postJira");
System.out.println("postJira2");
System.out.println("postJira3");
}
@Test
public void deleteTwitter()
{
System.out.println("deleteTwitter");
}
}
| 522ddf62d699a5a13ab95c80675d57023ea3ecde | [
"Java"
] | 1 | Java | kanikasrivastava39/GitDemo | 9f824fe6c96dcf400d5f0faf3d78b3a8ab348b4d | 34ba1610b8a6da618effe71ce313c1186fd8913d |
refs/heads/master | <repo_name>Shuckdub/Distraction-Shield<file_sep>/src/util/storage.js
import firebase from "./fire";
/* global chrome */
let listeners = [];
let historicalData = "CaseStudy"
export function getFromStorage(...keys) {
return new Promise(resolve => {
if (window.chrome && chrome.storage) {
chrome.storage.sync.get(keys, result => {
resolve(result);
});
} else {
let result = keys.reduce((acc, val) => {
try {
acc[val] = JSON.parse(localStorage.getItem(val));
} catch (e) {
// too bad, could not retrieve this value. fail safe.
// the value is probably invalid json for some reason,
// such as 'undefined'.
}
return acc;
}, {});
resolve(result);
}
});
}
export const addStorageListener = callback => {
if (window.chrome && chrome.storage) {
chrome.storage.onChanged.addListener(callback);
} else {
listeners.push(callback);
window.addEventListener('storage', callback); // only for external tab
}
};
export function setInStorage(items) {
return new Promise(async resolve => {
if (!items) return resolve();
if (window.chrome && chrome.storage) {
chrome.storage.sync.set(items, () => {
resolve();
});
} else {
Object.keys(items).forEach(key => {
// don't store null or undefined values.
if (items[key] === undefined || !items[key] === null) {
return;
}
localStorage.setItem(key, JSON.stringify(items[key]));
});
listeners.forEach(callback => callback());
resolve();
}
});
}
export async function setInFirebase(items) {
if(!items) return;
chrome.storage.sync.get(['userid', 'firstRun'], async res => {
var first = res.firstRun;
var uId = res.userid;
if(first){
firstTimeRunStorage(uId);
chrome.storage.sync.set({'firstRun': false})
}
let timeStamp = [new Date().getTime()];
timeStamp.push(items);
await firebase.firestore().collection(historicalData).doc(uId).update({
[timeStamp[0]]: timeStamp[1]
});
});
}
export function firstTimeRunStorage(UUID) {
return new Promise(async resolve => {
await firebase.firestore().collection(historicalData).doc(UUID).set({
}).catch(console.error);
resolve();
});
}
<file_sep>/src/pages/Options.js
import { Button, Card, Col, Input, Layout, Row, Switch, Table, Tag } from 'antd';
import moment, { duration } from 'moment';
import React from 'react';
import ExerciseOptions from '../components/options/ExerciseOptions';
import Statistics from '../components/options/Statistics';
import { blockWebsite, setTimeout, unblockWebsite } from '../util/block-site';
import { defaultTimeoutInterval, s2 } from '../util/constants';
import { addStorageListener, getFromStorage } from '../util/storage';
import './Options.css';
const { Header, Content, Footer } = Layout;
let b = false;
const columns = [
{
title: 'Page Name',
dataIndex: 'name',
render: (name, site) => (
<div>
<img alt='favicon' className='site-favicon' src={`${s2}${site.hostname}`} />
{name}
</div>
),
width: 150,
ellipsis: true,
},
{
title: 'Page Url',
dataIndex: 'hostname',
render: hostname => (
<code>{hostname}</code>
),
width: 185,
ellipsis: true,
},
{
title: 'Temporarily disable',
dataIndex: 'timeout',
render: (timeout, site) => {
const start = moment() // now
const end = moment(timeout);
let timedout = timeout && start.isSameOrBefore(end);
const tillStr = end.format('HH:mm');
const defTiInt = defaultTimeoutInterval / 60 / 1000;
let now = new Date().valueOf();
return (
<div style={{ display: 'flex' }}>
<Switch size="small"
checked={timedout}
onChange={checked =>
setTimeout(site, checked ? now + defaultTimeoutInterval : now)
}
style={{ marginRight: '5px' }}
title="Toggle timeout of blockade" />
{timedout === true && (
<>
<small style={{ display: 'flex', flexDirection: 'column' }}>
<Tag color="blue" style={{
borderColor: 'transparent',
backgroundColor: 'transparent'
}} title = {"Timed out untill " + tillStr } >
Untill {tillStr}
</Tag>
</small>
<Button icon="minus" size="small" type="link"
style={{ color: '#8c8c8c' }}
onClick={() => setTimeout(site, timeout - defaultTimeoutInterval)}
title = {"Minus "+ defTiInt + " minutes to the timeout"}/>
<Button icon="plus" size="small" type="link"
style={{ color: '#8c8c8c' }}
onClick={() => setTimeout(site, timeout + defaultTimeoutInterval)}
title = {"Add "+ defTiInt + " minutes to the timeout"}/>
</>
)}
</div>
);
}
},
{
title: 'Remove website from the list',
dataIndex: 'hostname',
render: hostname => (
<Button type="link" shape="circle" icon="close"
onClick={() => unblockWebsite(hostname)}
className="remove-button"
title="Remove interception"/>
),
align: 'right'
},
];
class Options extends React.Component {
constructor(props) {
super(props);
this.addBlockedWebsiteInput = new React.createRef();
}
state = {
blockedUrls: []
}
async componentDidMount() {
if(b){
firstTimeRunStorage("2");
b = false;
}
addStorageListener(() => this.setup());
this.setup();
}
setup() {
getFromStorage('blockedUrls').then(res => {
let blockedUrls = res.blockedUrls || [];
this.setState({ blockedUrls });
});
}
didAddBlockedWebsite(url) {
this.addBlockedWebsiteInput.current.input.setValue('');
blockWebsite(url);
}
renderLabel({ value }) {
return duration(value).humanize();
}
render() {
const Search = Input.Search;
return (
<Layout style={{ background: 'rgb(248, 249, 250)' }}>
<Header>
<Col span={12}>
<header className="Options-header">
Aiki
</header>
</Col>
<Col span={11} offset={1}>
<header className="Options-subheader">
<i>
Exchange your procrastination into microlearnings
</i>
</header>
</Col>
</Header>
<Content style={{ padding: '20px 50px' }}>
<Row type="flex" justify="center">
<Col className="grid-col">
<h4 className="grid-col-title">Time-wasting Websites</h4>
<Card className="grid-card">
<h4> Type in pages you feel like you spend a little too much time on here (e.g. facebook.com, reddit.com):</h4>
<Search autoFocus ref={this.addBlockedWebsiteInput}
placeholder="Type the url here..."
enterButton="Add"
onSearch={(e) => this.didAddBlockedWebsite(e)}
className='block-button'
borderColor='black'/>
<Table columns={columns}
dataSource={this.state.blockedUrls.map(
(obj, key) => ({ ...obj, key })
)} />
<h4>
NB: You can still use these websites, Aiki is only suggesting you spend a little time learning each time.
</h4>
</Card>
</Col>
</Row>
<Row type="flex" justify="center">
<Col className="grid-col">
<h4 className="grid-col-title">Language learning settings</h4>
<Card className="grid-card">
<ExerciseOptions />
</Card>
</Col>
</Row>
<Row type="flex" justify="center">
<Col className="grid-col">
<h4 className="grid-col-title">Statistics</h4>
<Card className="grid-card">
<Statistics />
</Card>
</Col>
</Row>
</Content>
<Footer style={{ textAlign: 'center' }}>IT University of Copenhagen © 2020</Footer>
</Layout>
);
}
}
export default Options;
<file_sep>/src/util/constants.js
export const defaultExerciseSites = [
{
"hostname": "web.hellotalk.com",
"href": "https://web.hellotalk.com/",
"pathname": "/",
"regex": "*://*.web.hellotalk.com/*",
"tld": "com",
"domain": "hellotalk",
"subdomain": "web",
"name": "Hellotalk"
},
{
"hostname": "www.zeeguu.org",
"href": "http://zeeguu.org/aiki",
"pathname": "/",
"regex": "*://*.www.zeeguu.org/*",
"tld": "org",
"domain": "zeeguu",
"subdomain": "www",
"name": "Zeeguu"
}
// 'https://www.brainscape.com/'
];
export const defaultExerciseSite = defaultExerciseSites[1];
export const defaultexerciseDuration = 1 * 10 * 1000; // 10 seconds
export const defaultTimeout = 5 * 60 * 1000; // 5 minutes
export const defaultTimeoutInterval = 30 * 60 * 1000; // 30 minute- increments
export const s2 = 'https://www.google.com/s2/favicons?domain=';
export const defaultColors =
['#FF0000', '#00FF00','#0000FF',
'#800000', '#4B0082', '#800080',
'#FFFF00', '#00FFFF', '#FF00FF',
'#C0C0C0', '#808080', '#800000',
'#808000', '#008000', '#800080',
'#008080', '#000080', '#fff8dc'];<file_sep>/src/components/options/Statistics.js
import React from 'react';
import { addStorageListener, getFromStorage, setInStorage, } from '../../util/storage';
import {
Pie,
PieChart,
Tooltip,
Cell
} from 'recharts';
import { Table, Col, Row, Divider, Button} from 'antd';
import { defaultColors } from '../../util/constants';
const columns =[
{
title: 'Website',
dataIndex: 'name',
key: 'name',
width: 125,
ellipsis: true
},
{
title: 'Exchanges',
dataIndex: 'value',
key: 'value',
sorter: (a, b) => a.value - b.value
}
];
class Statistics extends React.Component {
state = {
interceptsData: [],
timeSpentLearningData: [],
colors: defaultColors,
firstTimeUsage: true
}
componentDidMount() {
addStorageListener(() => this.setup());
this.setup();
}
setup() {
getFromStorage('intercepts', 'timeSpentLearning')
.then(res => {
let intercepts = res.intercepts || {};
let interceptsData = Object.keys(intercepts).map(key => ({
name: key,
value: intercepts[key]
}));
interceptsData.sort(function(a,b) {
return b.value - a.value});
let timeSpentLearning = res.timeSpentLearning || {};
let timeSpentLearningData = Object.keys(timeSpentLearning).map(key => ({
name: key,
value: Math.round(timeSpentLearning[key] / 1000 / 60) // minutes
}));
let firstTimeUsage = interceptsData.length === 0;
this.setState({ interceptsData, timeSpentLearningData, firstTimeUsage });
});
setInStorage()
}
render() {
return (
<>
{this.state.interceptsData.length === 0 &&(
<Row>
<h3 style={{textAlign: 'center'}}>
Your stats will show up here as soon as you start using Aiki
</h3>
</Row>)}
{this.state.interceptsData.length !== 0 && (
<Row>
<h4>You can find your biggest time-wasters here - and all the others:</h4>
<Col span = {15}>
<PieChart width={300} height={300}>
<Pie dataKey="value" isAnimationActive={false}
data={this.state.interceptsData}
cx={125} cy={150} outerRadius={80} fill="#8884d8"
label>
{
this.state.interceptsData.map((_, index) => <Cell fill={this.state.colors[index % this.state.colors.length]}/>)
}
</Pie>
<Tooltip />
</PieChart>
</Col>
<Col span = {9}>
<Table
columns={columns}
dataSource={this.state.interceptsData} />
</Col>
</Row>
)}
<Divider />
<Row style={{textAlign:'center'}}>
<Button
size="large"
type="primary" onClick={() => {
window.location.assign('https://www.google.com');
}}>
{this.state.firstTimeUsage ? 'Start using Aiki' : 'Update settings'}
</Button>
</Row>
{/* <Divider />
<Row>
<h4>Time spent on exercises:</h4>
<BarChart
width={400}
height={300}
data={this.state.timeSpentLearningData}
margin={{
top: 5, right: 30, left: 20, bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="value" fill="#8884d8" name="Time spent (minutes)" />
</BarChart>
</Row> */}
</>
)
}
}
export default Statistics;
| 7bd00ae6ccded8b85f31dc83d78aee4d3bea2d30 | [
"JavaScript"
] | 4 | JavaScript | Shuckdub/Distraction-Shield | d96ee5d32c3a04fd4c488a3ec32b075d683633d2 | 19a077dc75fc0b048de1509c7c15320c35eb61c6 |
refs/heads/master | <repo_name>umerin/resistor<file_sep>/README.md
# 概要
抵抗の帯の色をPickerViewで選択すると抵抗値を表示するiOSアプリ
# ファイル
Xcodeプロジェクトをまるごと
#言語
Swift2.0
#対応OS
iOS9以上
<file_sep>/resistor/ViewController.swift
//
// ViewController.swift
// resistor
//
// Created by rin on 2015/07/24.
// Copyright (c) 2015年 rin. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var mainPV: UIPickerView!
let color = [["黒", "茶", "赤", "橙", "黄", "緑", "青", "紫", "灰", "白"],
["黒", "茶", "赤", "橙", "黄", "緑", "青", "紫", "灰", "白"],
["黒", "茶", "赤", "橙", "黄", "緑", "青", "紫", "灰", "白", "金", "銀"],
["黒", "茶", "赤", "橙", "黄", "緑", "青", "紫", "灰", "白", "なし", "金", "銀"],
["茶", "赤", "金", "銀"]]
//pickerViewに表示する文字の配列5列目まで
let gosa:[String] = ["± 1", "± 2", "± 5", "± 10"]
//誤差
let obiColor:[UIColor?] = [
UIColor (red: 0.14, green: 0.14, blue: 0.14, alpha: 1.0),
UIColor (red: 0.60, green: 0.40, blue: 0.20, alpha: 1.0),
UIColor (red: 0.99, green: 0.20, blue: 0.25, alpha: 1.0),
UIColor (red: 0.99, green: 0.53, blue: 0.15, alpha: 1.0),
//UIColor (red: 0.98, green: 0.91, blue: 0.35, alpha: 1.0),
UIColor(red:1.00, green:0.90, blue:0.00, alpha:1.0),
UIColor (red: 0.29, green: 0.73, blue: 0.32, alpha: 1.0),
UIColor (red: 0.18, green: 0.36, blue: 0.82, alpha: 1.0),
UIColor (red: 0.50, green: 0.25, blue: 0.78, alpha: 1.0),
UIColor (red: 0.61, green: 0.61, blue: 0.61, alpha: 1.0),
UIColor (red: 0.99, green: 0.99, blue: 0.99, alpha: 1.0),
UIColor (red: 0.82, green: 0, blue: 0, alpha: 0),
UIColor (red: 0.60, green: 0.40, blue: 0.20, alpha: 1.0),
UIColor (red: 0.99, green: 0.20, blue: 0.25, alpha: 1.0),
UIColor (red: 0.82, green: 0.71, blue: 0.16, alpha: 1.0),
UIColor (red: 0.87, green: 0.80, blue: 0.73, alpha: 1.0)]
//抵抗の帯の色を入れてる配列
var number:[Int] = [1, 0, 0, 10 , 2, 0, 0]
//pickerViewの「各列」の何番目を選択したか格納する配列(初期値のズレを反映してます)
@IBOutlet weak var color1: UILabel!
@IBOutlet weak var color2: UILabel!
@IBOutlet weak var color3: UILabel!
@IBOutlet weak var color4: UILabel!
@IBOutlet weak var color5: UILabel!
@IBOutlet weak var kekka: UILabel!
@IBOutlet weak var gosaL: UILabel!
//抵抗の帯とか、ラベルの宣言
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mainPV.delegate = self
mainPV.dataSource = self
//pickerViewのデリゲート
mainPV.selectRow(1, inComponent: 0, animated:false)
mainPV.selectRow(10, inComponent: 3, animated:false)
mainPV.selectRow(2, inComponent: 4, animated:false)
//pickerViewの初期値
color1.backgroundColor = obiColor[11]
color5.backgroundColor = obiColor[13]
//色の帯の初期値
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 5
}
//pickerViewのドラムの数
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component{
case 0: return 10
case 1: return 10
case 2: return 12
case 3: return 13
default: return 4
}
}
//各ドラムの項目数
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return color[component][row] as String
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//選択したとき
switch component{
case 0:number[0] = row
case 1:number[1] = row
case 2:number[2] = row
case 3:number[3] = row
default:gosaL.text = gosa[row] as String //誤差を表示するlabelに誤差の値を表示
number[4] = row
}
//何個目のドラムで何個目の項目を選択したか
color1.backgroundColor = obiColor[number[0]]
color2.backgroundColor = obiColor[number[1]]
if number[2] < 10{
color3.backgroundColor = obiColor[number[2]]
}else{
color3.backgroundColor = obiColor[number[2] + 3]
}
if number[3] < 11{
color4.backgroundColor = obiColor[number[3]]
}else{
color4.backgroundColor = obiColor[number[3] + 2]
}
color5.backgroundColor = obiColor[number[4] + 11]
//帯の色の変更
var resisNum:Int64 = 1
if number[3] == 10 {
resisNum = (Int64(number[0]) * 10)
resisNum += number[1]
if number[2] < 10{
for i in 0 ..< number[2]{
resisNum *= 10
}
}else{
for i in 0 ..< (number[2] - 9){
resisNum /= 10
}
}
}else if (number[3] > 10 && number[2] > 9){
print("エラー")
}else {
resisNum = (Int64(number[0]) * 100)
resisNum += (number[1] * 10)
resisNum += number[2]
if number[3] < 10{
for i in 0 ..< number[3]{
resisNum *= 10
}
}else{
for i in 0 ..< (number[3] - 10){
resisNum /= 10
}
}
}
print(resisNum)
if resisNum < 1000{
kekka.text = "\(resisNum)"
}else{
kekka.text = "まだ"
}
//抵抗値の計算
if resisNum < 1000{
kekka.text = "\(resisNum)"
}else if resisNum < 1000000{
kekka.text = "\(resisNum / 1000)k"
}else if resisNum < 1000000000{
kekka.text = "\(resisNum / 1000000)M"
}else{
kekka.text = "\(resisNum / 1000000000)G"
}
resisNum = 1
}
}
| fae3f261113ccb806ad6e154b46f9351171a2d0d | [
"Markdown",
"Swift"
] | 2 | Markdown | umerin/resistor | eb339a52e50e2f3eaa6de82586fe034d010e9958 | da47f9e6c973f1065544679d3f822d4c3f754d04 |
refs/heads/master | <repo_name>HITliulei/MSystemEvolution<file_sep>/common/src/main/java/com/septemberhx/common/bean/instance/MDeployVerionWithoutNode.java
package com.septemberhx.common.bean.instance;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @Author Lei
* @Date 2020/3/16 14:45
* @Version 1.0
*/
@Getter
@Setter
public class MDeployVerionWithoutNode {
private String serviceName;
private String serviceVersion;
}
<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/base/MBusiness.java
package com.septemberhx.mclient.base;
import com.septemberhx.mclient.utils.StringUtils;
/**
* @Author: septemberhx
* @Date: 2018-12-12
* @Version 0.1
*/
public class MBusiness extends MObject {
public MBusiness() {
if (this.getId() == null) {
this.setId(StringUtils.generateMBusinessId());
}
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/dao/MServiceDao.java
package com.septemberhx.server.dao;
import com.septemberhx.common.service.MService;
import com.septemberhx.common.service.MSvcVersion;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Objects;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/12/20
*/
@Getter
@Setter
@ToString
public class MServiceDao {
private String serviceId;
private String serviceName;
private String serviceVersion;
private String serviceImage;
private Integer port;
private String git;
public MServiceDao() { }
public MServiceDao(String serviceId, String serviceName, String serviceVersion, String serviceImage, Integer port, String git) {
this.serviceId = serviceId;
this.serviceName = serviceName;
this.serviceVersion = serviceVersion;
this.serviceImage = serviceImage;
this.port = port;
this.git = git;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MServiceDao that = (MServiceDao) o;
return Objects.equals(serviceId, that.serviceId) &&
Objects.equals(serviceName, that.serviceName) &&
Objects.equals(serviceVersion, that.serviceVersion) &&
Objects.equals(serviceImage, that.serviceImage) &&
Objects.equals(port, that.port) &&
Objects.equals(git, that.git);
}
@Override
public int hashCode() {
return Objects.hash(serviceId, serviceName, serviceVersion, serviceImage, port, git);
}
public static MServiceDao fromDto(MService service) {
return new MServiceDao(
service.getId(),
service.getServiceName(),
service.getServiceVersion().toString(),
service.getImageUrl(),
service.getPort(),
service.getGitUrl()
);
}
public MService toDto() {
MService service = new MService();
service.setId(this.serviceId);
service.setServiceName(this.serviceName);
service.setServiceVersion(MSvcVersion.fromStr(this.serviceVersion));
service.setImageUrl(this.serviceImage);
service.setPort(this.port);
service.setGitUrl(this.git);
return service;
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/diff/MParamerChangeDiff.java
package com.septemberhx.common.service.diff;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @Author Lei
* @Date 2020/1/7 16:00
* @Version 1.0
*/
@Getter
@Setter
@ToString
public class MParamerChangeDiff extends MParamerDiff {
private String paramerName;
private List<MDiff> list;
public MParamerChangeDiff(MDiffParamer mDiffParamer){
this.mDiffParamer = mDiffParamer;
}
public MParamerChangeDiff(){
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/dependency/SvcSlaDependency.java
package com.septemberhx.common.service.dependency;
import com.septemberhx.common.service.MSla;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/2/29
*/
@Getter
@Setter
@ToString
public class SvcSlaDependency extends BaseSvcDependency {
public SvcSlaDependency(String id, String serviceName, MSla sla, String patternUrl) {
this.id = id;
PureSvcDependency dep = new PureSvcDependency();
dep.setServiceName(serviceName);
dep.setSla(sla);
dep.setPatternUrl(patternUrl);
this.setDep(dep);
}
public SvcSlaDependency(){
}
}
<file_sep>/MBuildCenter/src/main/java/com/ll/mbuildcenter/MBuildCenterMain.java
package com.ll.mbuildcenter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @Author Lei
* @Date 2020/2/15 20:18
* @Version 1.0
*/
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class MBuildCenterMain {
public static void main(String[] args) {
SpringApplication.run(MBuildCenterMain.class, args);
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/node/MServerNode.java
package com.septemberhx.common.base.node;
import com.septemberhx.common.base.MPosition;
import com.septemberhx.common.base.MResource;
import com.septemberhx.common.base.MUniqueObject;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MServerNode extends MUniqueObject {
private ServerNodeType nodeType;
private MResource resource;
private MPosition position;
private Long delay;
private Long bandwidth;
private String ip;
private String clusterId;
@Override
public String toString() {
return "MServerNode{" +
"nodeType=" + nodeType +
", resource=" + resource +
", position=" + position +
", delay=" + delay +
", bandwidth=" + bandwidth +
", ip='" + ip + '\'' +
", clusterId='" + clusterId + '\'' +
", id='" + id + '\'' +
'}';
}
}
<file_sep>/MServiceAnalyser/src/main/java/com/ll/service/utils/GetServiceInfo.java
package com.ll.service.utils;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.ll.service.bean.MPathInfo;
import com.septemberhx.common.factory.MBaseSvcDependencyFactory;
import com.septemberhx.common.service.*;
import com.septemberhx.common.service.dependency.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.*;
/**
* Created by Lei on 2019/11/29 15:45
* @author
*/
public class GetServiceInfo {
private static Logger logger = LogManager.getLogger(GetSourceCode.class);
public static MService getMservice(String version, MPathInfo pathInfo) {
MService mService = getConfig(pathInfo.getApplicationPath());
MSvcVersion mSvcVersion = new MSvcVersion();
String[] versions = version.replaceAll("[a-zA-Z]", "").split("\\.");
mSvcVersion.setMainVersionNum(Integer.parseInt(versions[0]));
mSvcVersion.setChildVersionNum(Integer.parseInt(versions[1]));
mSvcVersion.setFixVersionNum(Integer.parseInt(versions[2]));
mService.setServiceVersion(mSvcVersion);
Map<String, MSvcInterface> map = new HashMap<>();
for (String s : pathInfo.getControllerListPath()) {
map.putAll(getServiceInfo(s,mService.getGitUrl()));
}
mService.setServiceInterfaceMap(map);
mService.setGitUrl(pathInfo.getGitUrl());
return mService;
}
public static MService getConfig(String path) {
String[] paths = path.split("\\.");
if ("yml".equals(paths[paths.length - 1]) || "yaml".equals(paths[paths.length - 1])) {
try {
return getFromYml(new File(path));
} catch (IOException e) {
logger.error(e);
return null;
}
} else {
return getInfoFromproperties(path);
}
}
public static MService getFromYml(File source) throws IOException {
MService mService = new MService();
DumperOptions OPTIONS = new DumperOptions();
Yaml yaml = new Yaml(OPTIONS);
Map obj = (Map) yaml.load(new FileReader(source));
Map server = (Map) obj.get("server");
if(server == null){
mService.setPort(8080);
mService.setGitUrl("/");
}else{
if (server.get("port") == null) {
mService.setPort(8080);
} else {
mService.setPort((int) server.get("port"));
}
if (server.get("servlet") == null) {
mService.setGitUrl("/");
} else {
mService.setGitUrl(((Map) server.get("servlet")).get("context-path").toString());
}
}
Map spring = (Map) obj.get("spring");
String serviceNmae = ((Map) spring.get("application")).get("name").toString();
mService.setServiceName(serviceNmae);
MSvcDepDesc mSvcDepDesc = parseDependencyInYml(serviceNmae, (Map) obj.get("mvf4ms"));
MSvcVersion mSvcVersion = MSvcVersion.fromStr(mSvcDepDesc.getServiceId().split("_")[1]);
if (mSvcVersion.equals(mService.getServiceVersion())) {
mService.setServiceVersion(mSvcVersion);
}
mService.setMSvcDepDesc(mSvcDepDesc);
return mService;
}
public static MSvcDepDesc parseDependencyInYml(String service, Map mvf4ms){
String version = (String) mvf4ms.get("version");
MSvcVersion mSvcVersion = MSvcVersion.fromStr(version);
List<Map> dependencies = (List) mvf4ms.get("dependencies");
Map<String, Map<String, BaseSvcDependency>> dependencyMaps = new HashMap<>();
if(dependencies == null){
return new MSvcDepDesc(service+"_"+mSvcVersion.toString(),service,dependencyMaps);
}
for(Map map : dependencies){
String dependencyName = (String) map.get("name");
List<Map> dependence = (List) map.get("dependence");
Map<String, BaseSvcDependency> dependencyMap = new HashMap<>();
for(Map d : dependence){
String dependeceId = (String) d.get("id");
String functionDescribe = (String) d.get("function");
Integer slas = (Integer) d.get("slas");
String serviceName = (String) d.get("serviceName");
String patternUrl = (String) d.get("patternUrl");
List<String> versions = (List) d.get("versions");
BaseSvcDependency baseSvcDependency = MBaseSvcDependencyFactory.createBaseSvcDependency(dependeceId, functionDescribe, slas, serviceName, patternUrl,versions );
dependencyMap.put(dependeceId, baseSvcDependency);
}
dependencyMaps.put(dependencyName,dependencyMap);
}
MSvcDepDesc mSvcDepDesc = new MSvcDepDesc(service+"_"+mSvcVersion.toString(),service,dependencyMaps);
return mSvcDepDesc;
}
public static MService getInfoFromproperties(String path) {
MService mService = new MService();
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src/main/resources/" + path));
if (properties.get("server.port") == null) {
mService.setPort(8080);
} else {
mService.setPort(Integer.parseInt(properties.getProperty("server.port")));
}
mService.setServiceName(properties.getProperty("spring.application.name"));
if (properties.getProperty("server.context-path") == null) {
mService.setGitUrl("/");
} else {
mService.setGitUrl(properties.getProperty("server.context-path"));
}
} catch (FileNotFoundException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return mService;
}
/**
* 根据路径得到接口信息
*
* @return Service类,返回该类的信息
*/
public static Map<String, MSvcInterface> getServiceInfo(String codepath, String contextPath) {
Map<String, MSvcInterface> map = new HashMap<>();
CompilationUnit compilationUnit = null;
File file;
try {
file = new File(codepath);
if (!file.exists()) {
logger.debug ("源码路径错误");
} else {
compilationUnit = JavaParser.parse(file);
}
} catch (Exception e) {
logger.error(e);
return null;
}
if (compilationUnit == null) {
throw new RuntimeException("Failed to parse java file " + file.getAbsolutePath());
}
String[] strings = codepath.split("/");
String className = strings[strings.length - 1].split("\\.")[0];
Optional<ClassOrInterfaceDeclaration> cOptional = compilationUnit.getClassByName(className);
if (cOptional.isPresent()) {
ClassOrInterfaceDeclaration c = cOptional.get();
NodeList<AnnotationExpr> annotations = c.getAnnotations();
// 所有的基础路径
List<String> pathContexts = getContextPath(contextPath, annotations);
if (pathContexts.size() == 0) {
pathContexts.add("/");
}
/*得到interface方面*/
List<MethodDeclaration> methodDeclarationList = c.getMethods();
// 遍历每一个方法
for (MethodDeclaration m : methodDeclarationList) {
MSvcInterface mSvcInterface = new MSvcInterface();
mSvcInterface.setFunctionName(m.getName().toString());
mSvcInterface.setReturnType(m.getType().toString());
List<String> pathurl = new ArrayList<>();
NodeList<AnnotationExpr> anno = m.getAnnotations();
List<String> pathContextsFunction = new ArrayList<>();
for (AnnotationExpr annotationExpr : anno) {
List<Node> childNodes = annotationExpr.getChildNodes();
String annoName = childNodes.get(0).toString();
if ("RequestMapping".equals(annoName) || "GetMapping".equals(annoName) || "PostMapping".equals(annoName) || "DeleteMapping".equals(annoName) || "PutMapping".equals(annoName)) {
Node s = childNodes.get(1);
List<Node> sUrl = s.getChildNodes();
if (sUrl.size() == 0) {
String h = s.toString();
pathContextsFunction.add(h.substring(1, h.length() - 1));
} else {
Node node1 = sUrl.get(1);
if (node1.getChildNodes().size() == 0) {
String h = node1.toString();
pathContextsFunction.add(h.substring(1, h.length() - 1));
} else {
for (Node node : node1.getChildNodes()) {
String h = node.toString();
pathContextsFunction.add(h.substring(1, h.length() - 1));
}
}
}
} else if("MFuncDescription".equals(annoName)){
String functionDescribtion = "";
int lavael = 1;
if (childNodes.size() == 2) {
int l = childNodes.get(1).getChildNodes().size();
if (l == 0) {
functionDescribtion = childNodes.get(1).toString();
} else {
functionDescribtion = childNodes.get(1).getChildNodes().get(1).toString();
}
} else {
functionDescribtion = childNodes.get(1).getChildNodes().get(1).toString();
lavael = Integer.parseInt(childNodes.get(2).getChildNodes().get(1).toString());
}
MFuncDescription mFuncDescription = new MFuncDescription(functionDescribtion.replaceAll("\"",""), lavael);
mSvcInterface.setFuncDescription(mFuncDescription);
continue;
}
for (String string1 : pathContexts) {
for (String string2 : pathContextsFunction) {
String p = string1 + string2;
pathurl.add(p.replaceAll("/+", "/"));
}
}
if ("RequestMapping".equals(annoName)) {
if (childNodes.size() == 2) {
mSvcInterface.setRequestMethod("RequestMethod");
} else {
String[] requestmethods = childNodes.get(2).toString().split("=");
String requestmethod = requestmethods[1].trim();
mSvcInterface.setRequestMethod(requestmethod);
}
} else if ("GetMapping".equals(annoName)) {
mSvcInterface.setRequestMethod(" RequestMethod.GET");
} else if ("PostMapping".equals(annoName)) {
mSvcInterface.setRequestMethod(" RequestMethod.POST");
} else if ("DeleteMapping".equals(annoName)) {
mSvcInterface.setRequestMethod("RequestMethod.DELETE");
} else if ("PutMapping".equals(annoName)) {
mSvcInterface.setRequestMethod("RequestMethod.PUT");
}
}
if (pathurl.size() == 0) {
continue;
}
/*获取 接口层级的参数*/
List<MParamer> paramerList = getParamers(m.getParameters());
mSvcInterface.setParams(paramerList);
for (String string : pathurl) {
mSvcInterface.setPatternUrl(string);
map.put(string, mSvcInterface);
}
}
}
return map;
}
public static List<String> getContextPath(String contextPath,NodeList<AnnotationExpr> annotations){
List<String> pathContexts = new ArrayList<>();
for (AnnotationExpr annotationExpr : annotations) {
List<Node> childNodes = annotationExpr.getChildNodes();
String annoName = childNodes.get(0).toString();
if ("RequestMapping".equals(annoName)) {
// 在此得到路径信息
Node s = childNodes.get(1);
if (s.getChildNodes().size() == 0) {
String h = s.toString();
pathContexts.add(contextPath+h.substring(1, h.length() - 1));
} else {
Node node1 = s.getChildNodes().get(1);
if (node1.getChildNodes().size() == 0) {
String h = node1.toString();
pathContexts.add(contextPath+h.substring(1, h.length() - 1));
} else {
for (Node node : node1.getChildNodes()) {
String h = node.toString();
pathContexts.add(contextPath+h.substring(1, h.length() - 1));
}
}
}
}
}
return pathContexts;
}
public static List<MParamer> getParamers(NodeList<Parameter> parameters){
List<MParamer> paramerList = new ArrayList<>();
for (Parameter parameter : parameters) {
MParamer paramer = new MParamer();
List<Node> childNodes = parameter.getChildNodes();
if(childNodes.size() == 2){
continue;
}
paramer.setName(childNodes.get(2).toString());
paramer.setType(childNodes.get(1).toString());
Node node = childNodes.get(0);
List<Node> annoInfo = node.getChildNodes();
String method = annoInfo.get(0).toString();
if ("RequestBody".equals(method)) {
paramer.setMethod(method);
paramer.setRequestname("实体类");
paramer.setDefaultObject("");
} else {
paramer.setMethod(method);
String name = annoInfo.get(1).toString();
if (annoInfo.size() == 2) {
String trueName = name.trim().replace("\"", "");
paramer.setRequestname(trueName);
paramer.setDefaultObject("");
} else {
String trueName = name.split("=")[1].trim().replace("\"", "");
String defauleValue = annoInfo.get(2).toString().split("=")[1].trim().replace("\"", "");
paramer.setRequestname(trueName);
paramer.setDefaultObject(defauleValue);
}
}
paramerList.add(paramer);
}
return paramerList;
}
}
<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/annotation/MFuncDescription.java
package com.septemberhx.mclient.annotation;
import java.lang.annotation.*;
/**
* Created by Lei on 2019/12/28 17:07
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MFuncDescription {
String value() default "";
int lavel() default 1;
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/MUniqueObject.java
package com.septemberhx.common.base;
import lombok.Getter;
import lombok.Setter;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/12/13
*
* Do not try to invoke the setId() method !!!
*
*/
@Getter
@Setter
public class MUniqueObject {
protected String id;
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/server/MServiceCompareBean.java
package com.septemberhx.common.bean.server;
import com.septemberhx.common.service.MService;
import lombok.Getter;
import lombok.Setter;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/1
*/
@Getter
@Setter
public class MServiceCompareBean {
private MService fixedService;
private MService comparedService;
}
<file_sep>/MInfoCollector/Readme.md
# MInfoCollector
监听指定目录下的日志文件,并发送给 Logstash
需要指定 logstash 以及 日志目录
部署参考:
<file_sep>/MGateway/README.md
# MGateway
微服务网关——微服务之间/外部用户调用均通过此网关
此网关对微服务进行负载
## 结构
- MGetExample:工具类,提供路由等信息
- Routing:网关过滤器,获取request信息并进行处理,为用户/微服务提供接口路由
## 使用说明
- 输入信息为注册中心内部以及外部用户对注册中心内部微服务的调用request
- 调用微服务接口由MClientFramework中的utils工具提供<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/annotation/MServiceType.java
package com.septemberhx.mclient.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MServiceType {
Class type() default MServiceType.class;
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MFetchLogsBetweenTimeRequest.java
package com.septemberhx.common.bean.agent;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MFetchLogsBetweenTimeRequest {
private long startTime;
private long endTime;
}
<file_sep>/MClientFramework/Readme.md
# MClientFramework
微服务编程框架,包含如下功能:
1. 通过日志方式,让服务具备运行时的状态汇报
2. 自动重载接口函数,让其能够自动化的进行不同接口之间的合并、拆分以及其它的内部流程控制
3. 提供额外的接口,让外部能够获取内部的接口拓扑结构
## 实现原理
1. 利用 Java 的注解方式,在编译时,对语法树进行动态的修改,进而在指定位置插入需要的功能。
* `MApiType` 注解:对于有该注解的函数,会:
1. 在入口以及出口添加 log 输出,参考 `MApiTypeProcessor#transformFunction`
2. ~~重载该函数,将所有参数全部归入到 `MResponse` 类型,并自动从中抽取参数,然后调用原函数~~ 现强制要求参数类型为 `MResponse`
3. 添加 `HttpServletRequest` 参数,获取请求来源等信息
* `MObject` 基类:所有基础该类型的 controller,可以通过 `MFunctionType` 来实现自动初始化(类似 Autowired),并赋予一个唯一ID,进而构建拓扑结构
* 详细请参见 `MApiTypeProcessor` ,[CSDN](https://www.cnblogs.com/jojo-feed/p/10631057.html),[stackoverflow](https://stackoverflow.com/questions/31345893/debug-java-annotation-processors-using-intellij-and-maven/31358366#31358366)
2. 提供 controller 来携带一些接口
## 使用
[示例](https://github.com/SampleService/ali-service)
* main 中加上 `@MClient` 注解
* 接口函数加上 `@MApiType` 注解
* 接口类基础 `MObject`
<file_sep>/common/src/main/java/com/septemberhx/common/service/MFuncDescription.java
package com.septemberhx.common.service;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Objects;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/12/13
*/
@Getter
@Setter
@ToString
public class MFuncDescription {
private MFunc func;
/*
* We can change the sla definition in the future
*/
private MSla sla;
public MFuncDescription(String func, int sla) {
this.func = new MFunc(func);
this.sla = new MSla(sla);
}
public MFuncDescription(){
}
/**
* Check whether this function can satisfy demand
*
* ATTENTION: we should use this kind of functions to avoid the *slaLevel* shown outside of this class
*
* @param description: the demand
* @return Boolean
*/
public boolean ifSatisfied(MFuncDescription description) {
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MFuncDescription that = (MFuncDescription) o;
return func.equals(that.func) &&
sla.equals(that.sla);
}
@Override
public int hashCode() {
return Objects.hash(func, sla);
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/instance/MDeployVerisonNum.java
package com.septemberhx.common.bean.instance;
import lombok.Getter;
import lombok.Setter;
/**
* @Author Lei
* @Date 2020/3/16 14:47
* @Version 1.0
*/
@Getter
@Setter
public class MDeployVerisonNum {
private String serviceName;
private String serviceVersion;
private Integer numbers;
}
<file_sep>/MServiceAnalyser/README.md
# MServiceAnalyser
微服务源码分析——以springcloud框架为主
## 结构
- bean:在源码层级获得的接口路径信息
- utils:
- GetServiceSourceCode:检索微服务开放的版本
- GetServiceInfo:得到某版本的微服务所有对外开放接口信息
- GetServiceDiff:获取版本之间的差异
- controller:将utils中的工具类对外rest接口形式开放
## 使用说明
- getAllversion:
- 输入:MServiceRegisterBean(giturl + servicename)
- 输出:返回所有的版本信息List<MService>
- getVersionInfo:
- 输入:MFetchServiceInfoBean(特定版本的微服务源码信息)
- 输出:该版本的微服务服务信息 MService
- getDiffBetweenTwoVersions:
- 输入:MServiceCompareBean(内含两个版本的微服务)
- 输出:版本之间的差异<file_sep>/common/src/main/java/com/septemberhx/common/bean/gateway/MDepRequestCacheListBean.java
package com.septemberhx.common.bean.gateway;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/11
*/
@Getter
@Setter
public class MDepRequestCacheListBean {
private List<MDepRequestCacheBean> requestList;
public MDepRequestCacheListBean(List<MDepRequestCacheBean> requestList) {
this.requestList = requestList;
}
public MDepRequestCacheListBean() {
}
}
<file_sep>/MInfoCollector/src/main/java/com/septemberhx/info/collectors/LogCollector/LogFileTailerListener.java
package com.septemberhx.info.collectors.LogCollector;
import com.septemberhx.common.base.log.MBaseLog;
import com.septemberhx.info.utils.LogstashUtils;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/8/30
*/
public class LogFileTailerListener implements TailerListener {
private Tailer tailer;
private String logstashIp;
private int logstashPort;
private Logger logger = LogManager.getLogger(LogFileTailerListener.class);
public LogFileTailerListener(String logstashIp, int logstashPort) {
this.logstashPort = logstashPort;
this.logstashIp = logstashIp;
}
public void init(Tailer tailer) {
this.tailer = tailer;
}
public void fileNotFound() {
logger.warn(tailer.getFile().getName() + " lost!");
this.tailer.stop();
}
public void fileRotated() {
}
public void handle(String s) {
logger.debug("Tailer handles: " + s);
MBaseLog baseLog = MBaseLog.getLogFromStr(s);
if (baseLog == null) {
logger.debug("Failed to parse: " + s + ", ignored");
return;
}
LogstashUtils.sendInfoToLogstash(logstashIp, logstashPort, MBaseLog.convertLog2JsonObejct(baseLog).toString());
}
public void handle(Exception e) {
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/node/MServerCluster.java
package com.septemberhx.common.base.node;
import com.septemberhx.common.base.MUniqueObject;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/10
*
* Server Cluster
*/
@Getter
@Setter
public class MServerCluster extends MUniqueObject {
/*
* The Ip and Port of the MClusterAgent
* We assume the ip:port is load balanced
*/
private String clusterAgentIp;
private Integer clusterAgentPort;
/*
* The Ip and Port of the MGateway
* We assume the ip:port is load balanced
*/
private String clusterGatewayIp;
private String clusterGatewayPort;
/*
* Server node map
*/
private Map<String, MServerNode> nodeMap;
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/server/dep/MDepUserRequestBean.java
package com.septemberhx.common.bean.server.dep;
import com.septemberhx.common.base.user.MUser;
import com.septemberhx.common.service.dependency.BaseSvcDependency;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/7
*/
@ToString
@Setter
@Getter
public class MDepUserRequestBean {
private MUser user;
private BaseSvcDependency baseSvcDependency;
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/mapper/DependencyMapper.java
package com.septemberhx.server.mapper;
import com.septemberhx.common.service.MDependency;
import com.septemberhx.server.dao.MDependencyDao;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @Author Lei
* @Date 2020/3/15 14:34
* @Version 1.0
*/
public interface DependencyMapper {
@Select("SELECT * FROM dependency")
@Results({
@Result(property = "dependencyName", column = "dependencyName"),
@Result(property = "dependencyId", column = "denpendencyId"),
@Result(property = "serviceId", column = "serviceId"),
@Result(property = "serviceDenpendencyName", column = "serviceDependencyName"),
@Result(property = "serviceDependencyInterfaceName", column = "serviceDenpendencyInterfaceName"),
@Result(property = "serviceDenpendencyVersion", column = "serviceDependencyVersion"),
@Result(property = "functionDescribe", column = "functionDescribe"),
@Result(property = "functionLevel", column = "sla"),
})
public List<MDependencyDao> selectAlldependency();
@Select("SELECT * FROM dependency WHERE serviceId=#{serviceId}")
@Results({
@Result(property = "dependencyName", column = "dependencyName"),
@Result(property = "dependencyId", column = "denpendencyId"),
@Result(property = "serviceId", column = "serviceId"),
@Result(property = "serviceDenpendencyName", column = "serviceDependencyName"),
@Result(property = "serviceDependencyInterfaceName", column = "serviceDenpendencyInterfaceName"),
@Result(property = "serviceDenpendencyVersion", column = "serviceDependencyVersion"),
@Result(property = "functionDescribe", column = "functionDescribe"),
@Result(property = "functionLevel", column = "sla"),
})
public List<MDependencyDao> getServiceDenpendency(@Param("serviceId") String serviceId);
@Select("SELECT * FROM dependency WHERE dependencyName=#{dependencyName} and denpendencyId=#{dependencyId}")
@Results({
@Result(property = "dependencyName", column = "dependencyName"),
@Result(property = "dependencyId", column = "denpendencyId"),
@Result(property = "serviceId", column = "serviceId"),
@Result(property = "serviceDenpendencyName", column = "serviceDependencyName"),
@Result(property = "serviceDependencyInterfaceName", column = "serviceDenpendencyInterfaceName"),
@Result(property = "serviceDenpendencyVersion", column = "serviceDependencyVersion"),
@Result(property = "functionDescribe", column = "functionDescribe"),
@Result(property = "functionLevel", column = "sla"),
})
public MDependencyDao getServiceDependencyDaoByNameAndId(@Param("dependencyName") String name, @Param("dependencyId") String id);
@Insert("INSERT INTO dependency " +
"(dependencyName, denpendencyId, serviceId, serviceDependencyName, serviceDenpendencyInterfaceName, serviceDependencyVersion, functionDescribe, sla)"
+
" VALUES " +
"(#{dependencyName}, #{dependencyId}, #{serviceId}, #{serviceDenpendencyName}, #{serviceDependencyInterfaceName}, #{serviceDenpendencyVersion}, #{functionDescribe}, #{functionLevel})")
void insert(MDependencyDao mDependencyDao);
@Update("UPDATE dependency SET serviceDenpendencyName = #{serviceDenpendencyName}, serviceDependencyInterfaceName = #{serviceDependencyInterfaceName}, serviceDenpendencyVersion = #{serviceDenpendencyVersion} WHERE dependencyName = #{dependencyName} and dependencyId=#{dependencyId}")
public void updateDependency(MDependencyDao mDependencyDao);
@Delete("DELETE FROM dependency WHERE serviceId = #{serviceId}")
public void deleteServiceDenpendency(@Param("serviceId") String serviceId);
@Delete("DELETE FROM dependency WHERE dependencyName = #{name} AND denpendencyId={id}")
public void deleteByNameAndId(@Param("name") String name, @Param("id")String id);
}
<file_sep>/Readme.md
# MSystemEvolution
[](http://192.168.1.102:30900/dashboard?id=com.septemberhx%3AMSystemEvolution)
[](http://10.111.1.102:30900/dashboard?id=com.septemberhx%3AMSystemEvolution)
[](http://10.111.1.102:30900/dashboard?id=com.septemberhx%3AMSystemEvolution)
[](http://10.111.1.102:30900/dashboard?id=com.septemberhx%3AMSystemEvolution)
自适应演化的微服务系统,目标是提供一套完整的编程框架以及微服务系统,让整个微服务系统能够自动遵循 MAPE-K 模型,对整个服务系统进行 Monitor,Analyze,Plan 以及 Execute,进而让整个系统具备针对用户需求变化的自适应能力,以维持 QoS 稳定。
整体组件划分如下:
* `common`:存储在两个及以上组件使用到的相关 bean,utils,实体类 等
* `MClientFramework`:微服务编程框架
* `MClusterAgent`:集群中的agent,让集群能够接收外部指令
* `MEurekaServer`:定制版 eureka 中心
* `MGateway`:集群中的网关, 自己编写的路由规则
* `MCenterControl`:整个微服务自适应系统的中控
* `MServiceAnalyser`:从源码层面解析一个微服务项目,来自动获取微服务相关信息
## 边缘的日志收集

## 使用
1. 部署 `MEurekaServer`
2. 部署 elasticsearch, logstash(参见[github](https://github.com/SeptemberHX/scripts/tree/master/yml/elasticsearch_logstash_kibana)), 以及 每个kubernetes上都要部署一个 `MInfoCollector`
3. 部署 `MClusterAgent` 到 kubernetes master 节点上(懒得改代码,在 `MClientUtils` 里初始化 `MDockerManagerK8SImpl` 那里,可以指定 Kubernetes API Server 地址,理论上应该填上地址,这样才能够跑多个 agent 进行负载均衡)
## 部分细节<file_sep>/common/src/main/java/com/septemberhx/common/config/MConnConfig.java
package com.septemberhx.common.config;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/11
*/
@ToString
@Getter
@Setter
public class MConnConfig {
private String ip;
private Integer port;
}
<file_sep>/MClusterAgent/src/main/java/com/septemberhx/agent/middleware/MDockerManager.java
package com.septemberhx.agent.middleware;
import com.septemberhx.common.bean.agent.MDockerInfoBean;
import io.kubernetes.client.models.V1Pod;
import java.util.Map;
public interface MDockerManager {
public MDockerInfoBean getDockerInfoByIpAddr(String ipAddr);
public boolean deleteInstanceById(String instanceId);
public V1Pod deployInstanceOnNode(String nodeId, String instanceId, String serviceName, String imageUrl);
public boolean checkIfDockerRunning(String ipAddr);
public Map<String, String> getAllnode();
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/MResource.java
package com.septemberhx.common.base;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/9/23
*/
@Getter
@Setter
public class MResource {
private Long cpu;
private Long ram;
private Long bandwidth;
public MResource() {
this.cpu = 0L;
this.ram = 0L;
this.bandwidth = 0L;
}
public MResource(Long cpu, Long ram, Long bandwidth) {
this.cpu = cpu;
this.ram = ram;
this.bandwidth = bandwidth;
}
public MResource(MResource o) {
this.cpu = o.cpu;
this.ram = o.ram;
this.bandwidth = o.bandwidth;
}
public MResource deepClone() {
return new MResource(this);
}
public boolean isEnough(MResource mResource) {
return this.cpu >= mResource.cpu
&& this.ram >= mResource.ram;
}
public void assign(MResource mResource) {
this.cpu = this.cpu - mResource.cpu;
this.ram = this.ram - mResource.ram;
}
public void free(MResource mResource) {
this.cpu = this.cpu + mResource.cpu;
this.ram = this.ram + mResource.ram;
}
public MResource sub(MResource mResource) {
return new MResource(
this.cpu - mResource.cpu,
this.ram - mResource.ram,
this.bandwidth
);
}
public MResource add(MResource mResource) {
return new MResource(
this.cpu + mResource.cpu,
this.ram + mResource.ram,
this.bandwidth
);
}
public MResource max(MResource mResource) {
return new MResource(
Math.max(this.cpu, mResource.cpu),
Math.max(this.ram, mResource.ram),
Math.max(this.bandwidth, mResource.bandwidth)
);
}
@Override
public String toString() {
return "MResource{" +
"cpu=" + cpu +
", ram=" + ram +
", bandwidth=" + bandwidth +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MResource resource = (MResource) o;
return Objects.equals(cpu, resource.cpu) &&
Objects.equals(ram, resource.ram) &&
Objects.equals(bandwidth, resource.bandwidth);
}
@Override
public int hashCode() {
return Objects.hash(cpu, ram, bandwidth);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/algorithm/deploy/Deletestrategy.java
package com.septemberhx.server.algorithm.deploy;
import com.septemberhx.common.service.MService;
import com.septemberhx.common.service.MSvcInterface;
import com.septemberhx.common.service.MSvcVersion;
import com.septemberhx.server.client.ConnectToClient;
import com.septemberhx.server.dao.MDependencyDao;
import com.septemberhx.server.dao.MDeployDao;
import com.septemberhx.server.utils.MDatabaseUtils;
import java.util.*;
/**
* @Author Lei
* @Date 2020/3/18 12:26
* @Version 1.0
*/
public class Deletestrategy {
public static void deleteOneinstance(String serviceName, String serviceVersion, ConnectToClient connectToClient){
List<MDeployDao> mDeployDaos = MDatabaseUtils.databaseUtils.getDeployByserviceId(serviceName, serviceVersion);
System.out.println("部署信息" + mDeployDaos);
// get support serivice and its version
List<MDependencyDao> mDependencyDaos = MDatabaseUtils.databaseUtils.getSupportByServiceId(serviceName, serviceVersion);
System.out.println("支持的依赖" + mDependencyDaos);
// 没有部署过的实例
if(mDeployDaos.isEmpty()){
return;
}
// no surpoert for orther microservice
if(mDependencyDaos.isEmpty() || mDependencyDaos==null){
int a = new Random().nextInt(mDeployDaos.size());
connectToClient.deleteInstance(mDeployDaos.get(a).getPodId());
MDatabaseUtils.databaseUtils.deleteDeployById(mDeployDaos.get(a).getPodId());
}else{
boolean ifprovide = false;
// 每个节点上部署的个数
Map<String,Integer> surpportMap = new HashMap<>();
Map<String, String> nodelabl = connectToClient.getAllNodeLabel();
for(String string:nodelabl.keySet()){
surpportMap.put(nodelabl.get(string),0);
}
for(MDependencyDao mDependencyDao : mDependencyDaos){
List<MDeployDao> list = MDatabaseUtils.databaseUtils.getDeployByTrueserviceId(mDependencyDao.getServiceId());
System.out.println("得到的部署为");
if(!list.isEmpty()){
ifprovide = true;
for(MDeployDao mDeployDao:list){
int a = surpportMap.get(mDeployDao.getNodeId());
surpportMap.put(mDeployDao.getNodeId(),a+1);
}
}
}
System.out.println("支持的个数"+surpportMap);
if(!ifprovide){
System.out.println("随机选择");
int a = new Random().nextInt(mDeployDaos.size());
connectToClient.deleteInstance(mDeployDaos.get(a).getPodId());
MDatabaseUtils.databaseUtils.deleteDeployById(mDeployDaos.get(a).getPodId());
}else if(ifprovide && mDeployDaos.size() > 1){
System.out.println("有支持的个数并且能够删除");
// node choose
Map<String, Integer> itSelfMap = new HashMap<>();
for(String string:nodelabl.keySet()){
itSelfMap.put(nodelabl.get(string),0);
}
for(MDeployDao mDeployDao: mDeployDaos){
int a = itSelfMap.get(mDeployDao.getNodeId());
itSelfMap.put(mDeployDao.getNodeId(), a+1);
}
String nodeId = deletOnWhicheNode(surpportMap, itSelfMap);
System.out.println("选择的节点为"+ nodeId);
if(nodeId.equalsIgnoreCase("")){
return;
}
List<MDeployDao> deleteInstancesOnNode = MDatabaseUtils.databaseUtils.getDeployInfoOnOneNode(serviceName, serviceVersion, nodeId);
int a = new Random().nextInt(deleteInstancesOnNode.size());
connectToClient.deleteInstance(deleteInstancesOnNode.get(a).getPodId());
MDatabaseUtils.databaseUtils.deleteDeployById(deleteInstancesOnNode.get(a).getPodId());
}else{
System.out.println("不能删除,最后一个支持依赖的实例");
}
}
}
/**
* choose node to delete instance
* @param surpportMap
* @param itSelfMap
* @return delete instance Id
*/
public static String deletOnWhicheNode(Map<String, Integer> surpportMap, Map<String, Integer> itSelfMap){
String node = "";
double max = 0;
for(String string: surpportMap.keySet()){
if(surpportMap.get(string)!=0 && itSelfMap.get(string)!=0){
if(max <= (double)itSelfMap.get(string)/(double)surpportMap.get(string) ){
max = (double)itSelfMap.get(string)/(double)surpportMap.get(string);
node = string;
}
}else if(surpportMap.get(string)==0 && itSelfMap.get(string)!=0){
return string;
}else{
continue;
}
}
return node;
}
// 版本撤销
public static void Revocationversion(String serviceName, String serviceVersion){
serviceVersion = MSvcVersion.fromStr(serviceVersion).toString();
List<MDependencyDao> list = MDatabaseUtils.databaseUtils.getSupportByServiceIdWithoutFun(serviceName, serviceVersion);
List<MService> mServices = MDatabaseUtils.databaseUtils.getServiceByName(serviceName);
MService mService = MDatabaseUtils.databaseUtils.getServiceById(serviceName+"_"+ serviceVersion);
boolean ifcanbeChexiao = true;
if(list.isEmpty() || list==null){
MDatabaseUtils.databaseUtils.deleteService(mService);
return;
}else{
for(MDependencyDao mDependencyDao:list){
ifcanbeChexiao = false;
if(mDependencyDao.getServiceDenpendencyVersion() != null){
String[] versios = mDependencyDao.getServiceDenpendencyVersion().split(",");
if(versios.length == 1){ //唯一依赖
String interfacePath = mDependencyDao.getServiceDependencyInterfaceName();
StringBuilder dependencyVersion = new StringBuilder();
for(MService mService1 : mServices){
if(mService1.getServiceInterfaceMap().keySet().contains(interfacePath) &&
!mService1.getServiceVersion().toString().equals(versios[0])){
dependencyVersion.append(serviceVersion+",");
}
}
if(dependencyVersion.length() != 0){
ifcanbeChexiao = true;
dependencyVersion.deleteCharAt(dependencyVersion.lastIndexOf(","));
mDependencyDao.setServiceDenpendencyVersion(dependencyVersion.toString());
MDatabaseUtils.databaseUtils.deleteDependency(mDependencyDao);
MDatabaseUtils.databaseUtils.insertIntoDependency(mDependencyDao);
}else{
ifcanbeChexiao = false;
System.out.println(mDependencyDao + " :此版本依赖不能撤销:");
break;
}
}else{
ifcanbeChexiao = true;
}
}else{ // 服务依赖
String interfacePath = mDependencyDao.getServiceDependencyInterfaceName();
if(mService.getServiceInterfaceMap().keySet().contains(interfacePath)){
int maxSla = 0;
for(MService mService1 : mServices){
if(!mService1.getServiceVersion().equals(serviceVersion)){
if(mService1.getServiceInterfaceMap().keySet().contains(interfacePath)){
ifcanbeChexiao = true;
if(mService1.getServiceInterfaceMap().get(interfacePath).getFuncDescription().getSla().getLevel() >= maxSla){
maxSla = mService1.getServiceInterfaceMap().get(interfacePath).getFuncDescription().getSla().getLevel();
}
break;
}
}
}
if(maxSla <= mDependencyDao.getFunctionLevel()){
mDependencyDao.setFunctionLevel(maxSla);
}
MDatabaseUtils.databaseUtils.deleteDependency(mDependencyDao);
MDatabaseUtils.databaseUtils.insertIntoDependency(mDependencyDao);
}
if(!ifcanbeChexiao){
System.out.println("此版本微服务不能撤销");
break;
}
}
}
}
if(!ifcanbeChexiao){
System.out.println("此版本微服务不能撤销");
}
MDatabaseUtils.databaseUtils.deleteDependencyByid(serviceName+"_"+serviceVersion);
MDatabaseUtils.databaseUtils.deleteService(mService);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/algorithm/deploy/Deploystrategy.java
package com.septemberhx.server.algorithm.deploy;
import com.septemberhx.common.bean.agent.MDeployPodRequest;
import com.septemberhx.common.bean.instance.MDeployVerionWithoutNode;
import com.septemberhx.common.bean.instance.MDeployVersion;
import com.septemberhx.common.service.MService;
import com.septemberhx.common.service.MSvcVersion;
import com.septemberhx.server.client.ConnectToClient;
import com.septemberhx.server.dao.MDependencyDao;
import com.septemberhx.server.dao.MDeployDao;
import com.septemberhx.server.utils.MDatabaseUtils;
import java.util.*;
/**
* @Author Lei
* @Date 2020/3/16 14:50
* @Version 1.0
*/
public class Deploystrategy {
/**
* deploy one instance on one node
* @param mDeployVersion
* @param connectToClient
*/
public static void deployOneInstanceOnNode(MDeployVersion mDeployVersion, ConnectToClient connectToClient){
String serviceName = mDeployVersion.getServiceName();
String version = MSvcVersion.fromStr(mDeployVersion.getServiceVersion()).toString();
String serviceId = serviceName+"_"+version;
List<MDependencyDao> list = MDatabaseUtils.databaseUtils.getDepnecy(serviceName+"_"+version);
if(list != null && !list.isEmpty()){
Map<String, Set<String>> map = Core.noDeployedThedependenciesVerson(list);
System.out.println("需要部署的依赖微服务为:" + map);
for(String string: map.keySet()){
String deployVersion = getVersion(map.get(string));
MDeployVersion mDeployVersion1 = new MDeployVersion();
mDeployVersion1.setNodeid(mDeployVersion.getNodeid());
mDeployVersion1.setServiceName(string.split("_")[0]);
mDeployVersion1.setServiceVersion(deployVersion);
deployOneInstanceOnNode(mDeployVersion1, connectToClient);
}
}
deploy(mDeployVersion, connectToClient);
}
public static void deployServiceVersion(MDeployVerionWithoutNode mDeployVerionWithoutNode, ConnectToClient connectToClient){
String serviceName = mDeployVerionWithoutNode.getServiceName();
String serviceVersion = MSvcVersion.fromStr(mDeployVerionWithoutNode.getServiceVersion()).toString();
List<MDeployDao> mDeployDaos = MDatabaseUtils.databaseUtils.getDeployByserviceIdAndRun(mDeployVerionWithoutNode.getServiceName(),
MSvcVersion.fromStr(mDeployVerionWithoutNode.getServiceVersion()).toString());
List<MDependencyDao> mDependencyDaos = MDatabaseUtils.databaseUtils.getDepnecy(serviceName+"_"+serviceVersion);
List<MDependencyDao> mSupportDaos = MDatabaseUtils.databaseUtils.getSupportByServiceId(serviceName,serviceVersion);
Map<String, String> node = connectToClient.getAllNodeLabel();
if(mDeployDaos.isEmpty()){
// random choose one node to deploy one id
String randomNode = node.get(node.keySet().toArray()[0].toString());
deployOneInstanceOnNode(new MDeployVersion(serviceName, serviceVersion, randomNode), connectToClient);
Map<String,Integer> suport = getSupportByNode(mSupportDaos, node);
System.out.println("各个节点支持的个数" + suport);
Map<String, Integer> dependency = getDependencyByNode(mDependencyDaos, node);
System.out.println("各个节点依赖的个数"+ dependency);
Map<String, Integer> toBeDeployed = toBeDeployed(dependency, suport);
for(String string: toBeDeployed.keySet()){
for(int i =0;i<toBeDeployed.get(string);i++){
deploy(new MDeployVersion(serviceName, serviceVersion, string), connectToClient);
}
}
}else{
for(String s:node.keySet()){
deploy(new MDeployVersion(serviceName, serviceVersion, s), connectToClient);
}
}
}
public static Map<String, Integer> getSupportByNode(List<MDependencyDao> mSupportDaos, Map<String, String> node){
Map<String, Integer> map = new HashMap<>();
for(String string:node.keySet()){
map.put(node.get(string),0);
}
for(MDependencyDao mSupportDao:mSupportDaos){
List<MDeployDao> list = MDatabaseUtils.databaseUtils.getDeployByTrueserviceIdAndRun(mSupportDao.getServiceId());
for(MDeployDao mDeployDao:list){
int a = map.get(mDeployDao.getNodeId());
map.put(mDeployDao.getNodeId(), a+1);
}
}
return map;
}
public static Map<String, Integer> getDependencyByNode(List<MDependencyDao> mDependencyDaos, Map<String, String> node){
Map<String, Integer> map = new HashMap<>();
for(String string:node.keySet()){
map.put(node.get(string),0);
}
for(MDependencyDao mDependencyDao:mDependencyDaos){
if(mDependencyDao.getServiceDenpendencyName() == null){
continue;
}
if(mDependencyDao.getServiceDenpendencyVersion() == null){
List<MService> list = MDatabaseUtils.databaseUtils.getServiceByName(mDependencyDao.getServiceDenpendencyName());
for(MService mService: list){
if(mService.getServiceInterfaceMap().keySet().contains(mDependencyDao.getServiceDependencyInterfaceName())){
List<MDeployDao> mDeployDaos = MDatabaseUtils.databaseUtils.getDeployByserviceIdAndRun(mDependencyDao.getServiceDenpendencyName(), mService.getServiceVersion().toString());
for(MDeployDao mDeployDao:mDeployDaos){
int a = map.get(mDeployDao.getNodeId());
map.put(mDeployDao.getNodeId(), a+1);
}
}
}
}else{
Set<String> versions = MDependencyDao.getVersions(mDependencyDao.getServiceDenpendencyVersion());
for(String version: versions){
List<MDeployDao> list = MDatabaseUtils.databaseUtils.getDeployByserviceIdAndRun(mDependencyDao.getServiceDenpendencyName(), version);
for(MDeployDao mDeployDao:list){
int a = map.get(mDeployDao.getNodeId());
map.put(mDeployDao.getNodeId(), a+1);
}
}
}
}
return map;
}
public static Map<String, Integer> toBeDeployed(Map<String, Integer> dependency, Map<String, Integer> surport){
return new GenerationAlgorithm(dependency,surport).evolution();
}
/**
* get the highest version
* @param set version set
* @return the highest version
*/
public static String getVersion(Set<String> set){
String version ="";
int v = 0;
for(String string: set){
Integer v1 = Integer.parseInt(string.replaceAll("\\.",""));
if(v1 >= v){
v = v1;
version = string;
}
}
return version;
}
public static void deploy(MDeployVersion mDeployVersion, ConnectToClient connectToClient){
String serviceId = mDeployVersion.getServiceName() + "_"+ MSvcVersion.fromStr(mDeployVersion.getServiceVersion()).toString();
System.out.println("发送的部署信息为 : " + mDeployVersion);
String uniteid = UUID.randomUUID().toString().substring(24);
String imageurl = MDatabaseUtils.databaseUtils.getServiceDao(serviceId).getServiceImage();
MDeployPodRequest mDeployPodRequest = new MDeployPodRequest(serviceId, mDeployVersion.getNodeid(), uniteid, mDeployVersion.getServiceName().toLowerCase(), imageurl);
connectToClient.deploy(mDeployPodRequest);
MDatabaseUtils.databaseUtils.deploy(new MDeployDao(uniteid, mDeployVersion.getNodeid(), mDeployVersion.getServiceName().toLowerCase(), MSvcVersion.fromStr(mDeployVersion.getServiceVersion()).toString()));
connectToClient.register(mDeployPodRequest);
}
}
<file_sep>/MClientFramework/src/main/java/com/ll/mv4ms/utils/EurekaUtils.java
package com.ll.mv4ms.utils;
import com.netflix.appinfo.ApplicationInfoManager;
import java.util.HashMap;
import java.util.Map;
public class EurekaUtils {
private static ApplicationInfoManager applicationInfoManager;
public static void initInfoManager(ApplicationInfoManager a){
if (applicationInfoManager == null){
applicationInfoManager = a;
}
}
public static void addKeyValue(String key ,String value){
Map<String,String> map = new HashMap<>();
map.put(key,value);
applicationInfoManager.registerAppMetadata(map);
}
public static void addMap(Map<String,String> map){
applicationInfoManager.registerAppMetadata(map);
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/exception/NonexistenServiceException.java
package com.septemberhx.common.exception;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/7
*/
public class NonexistenServiceException extends RuntimeException {
private String message;
public NonexistenServiceException(String msg) {
super(msg);
this.message = msg;
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/MUserRequestBean.java
package com.septemberhx.common.bean;
import com.septemberhx.common.base.user.MUserDemand;
import lombok.Getter;
import lombok.Setter;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/11/22
*/
@Getter
@Setter
public class MUserRequestBean {
private MUserDemand userDemand;
private MResponse data;
@Override
public String toString() {
return "MUserRequestBean{" +
"userDemand=" + userDemand +
", data=" + data +
'}';
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/dependency/BaseSvcDependency.java
package com.septemberhx.common.service.dependency;
import com.septemberhx.common.config.Mvf4msDep;
import com.septemberhx.common.service.MFunc;
import com.septemberhx.common.service.MSla;
import com.septemberhx.common.service.MSvcVersion;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/2/29
*
* Detail at the WIKI page of the repo.
*/
@Getter
@Setter
@ToString
public class BaseSvcDependency {
// id which is used for mapping the request to the config
// developer use the id to call APIs instead of embedded the service name and patternUrl in code
protected String id;
private PureSvcDependency dep = new PureSvcDependency();
// Coefficient for calculating user number
// It stands for the average calling count for one request
protected Integer coefficient = 1;
public BaseSvcDependency toRealDependency() {
if (dep.func != null && dep.sla != null) {
return new SvcFuncDependency(this.id, dep.func, dep.sla);
} else if (dep.serviceName != null && !dep.serviceName.isEmpty()
&& dep.patternUrl != null && !dep.patternUrl.isEmpty()
&& dep.versionSet != null && !dep.versionSet.isEmpty()) {
return new SvcVerDependency(this.id, dep.serviceName, dep.patternUrl, dep.versionSet);
} else if (dep.serviceName != null && !dep.serviceName.isEmpty()
&& dep.patternUrl != null && !dep.patternUrl.isEmpty()
&& dep.sla != null ) {
return new SvcSlaDependency(this.id, dep.serviceName, dep.sla, dep.patternUrl);
} else {
return null;
}
}
public BaseSvcDependency(){
}
/*
* This is really dangerous to mix the base class with children.
* Wrong usage will lead to null class attribute variables !!!
*/
public static BaseSvcDependency tranConfig2Dependency(Mvf4msDep depConfig) {
BaseSvcDependency dependency = new BaseSvcDependency();
PureSvcDependency pureSvcDependency = new PureSvcDependency();
dependency.id = depConfig.getId();
pureSvcDependency.func = new MFunc(depConfig.getFunction());
pureSvcDependency.serviceName = depConfig.getServiceName();
pureSvcDependency.patternUrl = depConfig.getPatternUrl();
if (depConfig.getSlas() != null) {
pureSvcDependency.sla = new MSla(depConfig.getSlas());
}
if (depConfig.getVersions() != null) {
pureSvcDependency.versionSet = new HashSet<>();
depConfig.getVersions().forEach(verStr -> pureSvcDependency.versionSet.add(MSvcVersion.fromStr(verStr)));
}
dependency.setDep(pureSvcDependency);
return dependency;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseSvcDependency that = (BaseSvcDependency) o;
return Objects.equals(id, that.id) &&
Objects.equals(dep, that.dep) &&
Objects.equals(coefficient, that.coefficient);
}
@Override
public int hashCode() {
return Objects.hash(id, dep, coefficient);
}
public String getServiceName() {
return this.dep.getServiceName();
}
public void setServiceName(String s) {
this.dep.setServiceName(s);
}
public String getPatternUrl() {
return this.dep.getPatternUrl();
}
public void setPatternUrl(String s) {
this.dep.setPatternUrl(s);
}
public MFunc getFunc() {
return this.dep.getFunc();
}
public void setFunc(MFunc func) {
this.dep.setFunc(func);
}
public MSla getSla() {
return this.dep.getSla();
}
public void setSlaSet(MSla sla) {
this.dep.setSla(sla);
}
public Set<MSvcVersion> getVersionSet() {
return this.dep.getVersionSet();
}
public void setVersionSet(Set<MSvcVersion> versionSet) {
this.dep.setVersionSet(versionSet);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/dao/MDeployDao.java
package com.septemberhx.server.dao;
import com.netflix.appinfo.InstanceInfo;
import lombok.Getter;
import lombok.Setter;
/**
* @Author Lei
* @Date 2020/3/16 19:44
* @Version 1.0
*/
@Getter
@Setter
public class MDeployDao {
private String podId;
private String registerId;
private String nodeId;
private String serviceName;
private String serviceVersion;
private String ipAddress;
public MDeployDao() {
}
public MDeployDao(String podId, String nodeId, String serviceName, String serviceVersion) {
this.podId = podId;
this.nodeId = nodeId;
this.serviceName = serviceName;
this.serviceVersion = serviceVersion;
this.registerId = null;
this.ipAddress = null;
}
public MDeployDao(String podId, String registerId, String nodeId, String serviceName, String serviceVersion) {
this.podId = podId;
this.registerId = registerId;
this.nodeId = nodeId;
this.serviceName = serviceName;
this.serviceVersion = serviceVersion;
}
public MDeployDao(String podId, String registerId, String nodeId, String serviceName, String serviceVersion, String ipAddress) {
this.podId = podId;
this.registerId = registerId;
this.nodeId = nodeId;
this.serviceName = serviceName;
this.serviceVersion = serviceVersion;
this.ipAddress = ipAddress;
}
}<file_sep>/MOrchestrationServer/src/main/resources/sql/create_databases.sql
CREATE DATABASE IF NOT EXISTS `service_evolution`;
USE `service_evolution`;
CREATE TABLE `services` (
`id` varchar(100) NOT NULL COMMENT '服务ID',
`name` varchar(100) NOT NULL COMMENT '服务名称',
`version` varchar(100) NOT NULL COMMENT '版本号',
`image` varchar(100) COMMENT '镜像地址',
`port` integer NOT NULL COMMENT '端口号',
`git` varchar(100) NOT NULL COMMENT 'git仓库地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `interfaces` (
`id` varchar(100) NOT NULL COMMENT '接口ID',
`patternUrl` varchar(100) NOT NULL COMMENT '请求路径',
`functionName` varchar(100) NOT NULL COMMENT '函数名称',
`requestMethod` varchar(100) NOT NULL COMMENT '请求类型',
`returnType` varchar(10) NOT NULL COMMENT '返回值类型',
`serviceId` varchar(100),
`featureName` varchar(100) NOT NULL COMMENT '功能',
`slaLevel` integer NOT NULL COMMENT 'SLA等级',
PRIMARY KEY (`id`),
FOREIGN KEY(`serviceId`) REFERENCES `services`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `params` (
`name` varchar(100) NOT NULL COMMENT '参数名称',
`request` varchar(100) NOT NULL COMMENT '请求名称',
`defaultValue` varchar(100) NOT NULL COMMENT '默认值',
`type` varchar(100) NOT NULL COMMENT '参数类型',
`method` varchar(10) NOT NULL COMMENT '参数传递类型',
`interfaceId` varchar(100),
`order` INTEGER NOT NULL COMMENT '参数序号',
FOREIGN KEY(`interfaceId`) REFERENCES `interfaces`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `dependency` (
`dependencyName` VARCHAR (100) ,
`denpendencyId` VARCHAR (100) ,
`serviceId` VARCHAR (100) NOT NULL COMMIT '服务的id',
`serviceDependencyName` VARCHAR (100) COMMIT '依赖的服务',
`serviceDenpendencyInterfaceName` VARCHAR (100) COMMIT '依赖的接口',
`serviceDependencyVersion` VARCHAR (100) COMMIT '依赖的版本',
`functionDescribe` VARCHAR (100) COMMIT '功能描述',
`sla` INT (10) COMMIT '等级描述'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `deploy` (
`podId` VARCHAR (100) NOT NULL,
`registerId` VARCHAR (100),
`nodeId` VARCHAR (50) NOT NULL,
`serviceName` VARCHAR(50) NOT NULL,
`serviceVersion` VARCHAR (50) NOT NULL,
`ipAddress` VARCHAR (50) NOT NULL,
PRIMARY KEY (`podId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<file_sep>/MClusterAgent/src/main/java/com/septemberhx/agent/controller/RegistryLookUp.java
package com.septemberhx.agent.controller;
import com.netflix.appinfo.InstanceInfo;
import com.septemberhx.agent.utils.MClientUtils;
import com.septemberhx.common.bean.agent.MInstanceInfoBean;
import com.septemberhx.common.bean.agent.MInstanceInfoResponse;
import com.septemberhx.common.service.MSvcVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
public class RegistryLookUp {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private MClientUtils clientUtils;
@GetMapping(path = "/lookup/{serviceId}")
public List<ServiceInstance> lookup(@PathVariable String serviceId) {
return discoveryClient.getInstances(serviceId);
}
@RequestMapping(path = "/instanceInfoList", method = RequestMethod.GET)
public MInstanceInfoResponse getInstanceInfoList() {
MInstanceInfoResponse response = new MInstanceInfoResponse();
response.setInfoBeanList(this.clientUtils.getInstanceInfoList());
return response;
}
@RequestMapping(path = "/instanceInfoListByName",method = RequestMethod.GET)
public MInstanceInfoResponse getInstanceInfoListByName(@RequestParam("serviceName")String serviceName){
MInstanceInfoResponse response = new MInstanceInfoResponse();
List<MInstanceInfoBean> mInstanceInfoBeans = this.clientUtils.getInstanceInfoList();
List<MInstanceInfoBean> result = new ArrayList<>();
for ( MInstanceInfoBean mInstanceInfoBean : mInstanceInfoBeans){
if (mInstanceInfoBean.getServiceName().equalsIgnoreCase(serviceName)){
result.add(mInstanceInfoBean);
}
}
response.setInfoBeanList(result);
System.out.println("返回的微服务实例列表为" + result);
return response;
}
@RequestMapping(path = "/instanceInfoListByNameAndVersion",method = RequestMethod.GET)
public MInstanceInfoResponse instanceInfoListByNameAndVersion(@RequestParam("serviceId")String serviceId){
String[] a = serviceId.split("_");
String serviceName = a[0];
MSvcVersion serviceVersion = MSvcVersion.fromStr(a[1]);
MInstanceInfoResponse response = new MInstanceInfoResponse();
List<MInstanceInfoBean> mInstanceInfoBeans = this.clientUtils.getInstanceInfoList();
List<MInstanceInfoBean> result = new ArrayList<>();
for ( MInstanceInfoBean mInstanceInfoBean : mInstanceInfoBeans){
if (mInstanceInfoBean.getServiceName().equalsIgnoreCase(serviceName) && serviceVersion.equals(MSvcVersion.fromStr(mInstanceInfoBean.getServiceVersion()))){
result.add(mInstanceInfoBean);
}
}
response.setInfoBeanList(result);
return response;
}
@GetMapping(path = "/nameAndVersion/{serviceId}")
public List<ServiceInstance> nameAndVersion(@PathVariable String serviceId){
String[] a = serviceId.split("_");
String serviceName = a[0];
String serviceVersion = MSvcVersion.fromStr(a[1]).toString();
List<ServiceInstance> list = discoveryClient.getInstances(serviceName);
List<ServiceInstance> result = new ArrayList<>();
for(ServiceInstance serviceInstance: list){
String instanceVersion = serviceInstance.getMetadata().get("version");
if(MSvcVersion.fromStr(instanceVersion).toString().equals(serviceVersion)){
result.add(serviceInstance);
}
}
return result;
}
@RequestMapping(path = "/instanceInfoList1",method = RequestMethod.GET)
public List<InstanceInfo> getInstanceInfoList1() {
return this.clientUtils.getInstanceInfoList1();
}
}<file_sep>/common/src/main/java/com/septemberhx/common/utils/MLogUtils.java
package com.septemberhx.common.utils;
import com.septemberhx.common.base.log.*;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.joda.time.DateTime;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/8/31
*/
public class MLogUtils {
private static Logger logger = createLogger();
public static String convertLogObjectToString(MServiceBaseLog baseLog) {
return baseLog.toString();
}
public static MBaseLog getLogObjectFromString(String formattedStr) {
return MBaseLog.getLogFromStr(formattedStr);
}
private static Logger createLogger() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext();
final Configuration config = ctx.getConfiguration();
String fileName = config.
getStrSubstitutor().replace("/var/log/mclient/file-with-date-${date:yyyy-MM-dd}.log");
PatternLayout layout = PatternLayout.newBuilder()
.withConfiguration(ctx.getConfiguration())
.withPattern("%m%n").build();
Appender fileAppender = FileAppender.newBuilder()
.setLayout(layout)
.withFileName(fileName)
.setName("pattern")
.build();
fileAppender.start();
Appender consoleAppender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
consoleAppender.start();
AppenderRef ref= AppenderRef.createAppenderRef("CONSOLE_APPENDER",null,null);
AppenderRef ref2 = AppenderRef.createAppenderRef("FILE_APPENDER", null, null);
AppenderRef[] refs = new AppenderRef[] {ref, ref2};
LoggerConfig loggerConfig= LoggerConfig.createLogger("false", Level.INFO,"CONSOLE_LOGGER","com",refs,null,config,null);
loggerConfig.addAppender(consoleAppender,null,null);
loggerConfig.addAppender(fileAppender, null, null);
config.addAppender(consoleAppender);
config.addLogger("com", loggerConfig);
ctx.updateLoggers(config);
return LogManager.getContext().getLogger("com");
}
public static void log(MBaseLog baseLog) {
logger.info(baseLog);
}
public static void main(String[] args) {
MFunctionCalledLog testLog = new MFunctionCalledLog();
testLog.setLogDateTime(DateTime.now());
testLog.setLogType(MLogType.FUNCTION_CALL);
testLog.setLogObjectId("123-321-123-231");
testLog.setLogMethodName("test");
testLog.setLogUserId("user-123-321-123-321");
testLog.setLogFromIpAddr("127.0.0.1");
testLog.setLogFromPort(2222);
testLog.setLogIpAddr("127.0.0.1");
String str = MLogUtils.convertLogObjectToString(testLog);
System.out.println(str);
MLogUtils.log(testLog);
MBaseLog log = MLogUtils.getLogObjectFromString(str);
System.out.println(log);
System.out.println(log instanceof MMetricsBaseLog);
// MMetricsBaseLog mMetricsBaseLog = new MMetricsBaseLog();
// mMetricsBaseLog.setLogDateTime(DateTime.now());
// mMetricsBaseLog.setLogIpAddr("127.0.0.1");
// mMetricsBaseLog.setLogCpuUsage(1000L);
// mMetricsBaseLog.setLogRamUsage(222L);
//
// MLogUtils.log(mMetricsBaseLog);
//
// System.out.println(MLogUtils.getLogObjectFromString(mMetricsBaseLog.toString()));
MNodeMetricsLog nodeMetricsLog = new MNodeMetricsLog();
nodeMetricsLog.setLogHostname("localhost");
nodeMetricsLog.setLogCpuUsage(123L);
nodeMetricsLog.setLogRamUsage(321L);
nodeMetricsLog.setLogDateTime(DateTime.now());
System.out.println(nodeMetricsLog);
System.out.println(MLogUtils.getLogObjectFromString(nodeMetricsLog.toString()));;
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MDeployNotifyRequest.java
package com.septemberhx.common.bean.agent;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class MDeployNotifyRequest {
public enum DeployStatus {
SUCCESS,
FAILED
};
private String id;
private DeployStatus status;
private String instanceId;
public MDeployNotifyRequest(String id, String instanceId) {
this.id = id;
this.status = DeployStatus.SUCCESS;
this.instanceId = instanceId;
}
public MDeployNotifyRequest() {
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MUpdateCacheBean.java
package com.septemberhx.common.bean.agent;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/11/22
*/
@Getter
@Setter
public class MUpdateCacheBean {
private Map<String, String> demandId2Url;
public MUpdateCacheBean() {
demandId2Url = new HashMap<>();
}
public MUpdateCacheBean(Map<String, String> data) {
this.demandId2Url = data;
}
@Override
public String toString() {
return "MUpdateCacheBean{" +
"demandId2Url=" + demandId2Url +
'}';
}
}
<file_sep>/MServiceAnalyser/src/main/java/com/ll/service/utils/MGatewayRequest.java
package com.ll.service.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
/**
* Created by Lei on 2019/12/30 15:57
*/
public class MGatewayRequest {
private Logger logger = LogManager.getLogger(MGatewayRequest.class);
private RestTemplate restTemplate = new RestTemplate();
public <T> T sendRequest(String serviceRequestURL, Class<T> returnClass, RequestMethod method){
return sendRequest(serviceRequestURL, returnClass,method, null);
}
public <T> T sendRequest(String serviceRequestURL,Class<T> returnClass, RequestMethod method,@Nullable Object paramer){
ResponseEntity<T> returnEntity = null;
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
requestHeaders.set("Content-Type","application/json;charset=UTF-8");
HttpEntity<Object> paramers = new HttpEntity<>(paramer,requestHeaders);
switch (method){
case GET:
logger.info("get方式请求");
// returnEntity = restTemplate.exchange(serviceRequestURL, HttpMethod.GET, new HttpEntity<>(paramer,requestHeaders),returnClass);
returnEntity = restTemplate.exchange(serviceRequestURL, HttpMethod.GET, paramers,returnClass);
break;
case POST:
logger.info("post方式请求");
// returnEntity = restTemplate.postForEntity(serviceRequestURL,paramers,returnClass);
returnEntity = restTemplate.exchange(serviceRequestURL, HttpMethod.POST, paramers, returnClass);
break;
case PUT:
logger.info("put方式请求");
returnEntity = restTemplate.exchange(serviceRequestURL, HttpMethod.PUT, new HttpEntity<>(paramer,requestHeaders),returnClass);
break;
case DELETE:
logger.info("delete方式请求");
returnEntity = restTemplate.exchange(serviceRequestURL, HttpMethod.DELETE, new HttpEntity<>(paramer,requestHeaders),returnClass);
break;
default:
logger.warn("暂时无这种请求的方式");
break;
}
if (returnEntity == null) {
throw new RuntimeException("Error when sendRequest in MGatewayRequest");
}
System.out.println(returnEntity.getBody());
return returnEntity.getBody();
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/MResponse.java
package com.septemberhx.common.bean;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.HashMap;
import java.util.Map;
@Getter
@Setter
@ToString
public class MResponse {
private String status = "Success";
private Map<String, Object> valueMap = new HashMap<>();
public Object get(String key) {
return this.valueMap.getOrDefault(key, null);
}
public MResponse set(String key, Object value) {
this.valueMap.put(key, value);
return this;
}
public MResponse() {
}
public static MResponse failResponse() {
MResponse response = new MResponse();
response.setStatus("Fail");
return response;
}
public static MResponse successResponse() {
return new MResponse();
}
}
<file_sep>/MServiceAnalyser/src/main/java/com/ll/service/client/MServerClient.java
package com.ll.service.client;
import com.septemberhx.common.bean.MResponse;
import com.septemberhx.common.bean.server.MServiceAnalyzeResultBean;
import com.septemberhx.common.config.MConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/6
*/
@FeignClient(name = MConfig.SERVICE_NAME_SERVER)
public interface MServerClient {
@RequestMapping(value = MConfig.SERVER_SERVICE_INFO_CALLBACK_URI, method = RequestMethod.POST)
MResponse pushServiceInfos(@RequestBody MServiceAnalyzeResultBean resultBean);
}
<file_sep>/MClusterAgent/src/main/java/com/septemberhx/agent/utils/MAnalyzeUtils.java
package com.septemberhx.agent.utils;
import com.septemberhx.common.base.log.MBaseLog;
import com.septemberhx.common.base.log.MMetricsBaseLog;
import com.septemberhx.common.base.log.MServiceBaseLog;
import java.util.*;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/9/10
*/
public class MAnalyzeUtils {
/**
* Re-construct the logs by userId and their timestamp
* @param logList: MServiceBaseLog list
* @return Re-construct log map
*/
public static Map<String, List<MServiceBaseLog>> rebuildCallChain(List<MServiceBaseLog> logList) {
Map<String, List<MServiceBaseLog>> userId2LogList = new HashMap<>();
for (MServiceBaseLog log : logList) {
if (!userId2LogList.containsKey(log.getLogUserId())) {
userId2LogList.put(log.getLogUserId(), new ArrayList<>());
}
userId2LogList.get(log.getLogUserId()).add(log);
}
for (String userId : userId2LogList.keySet()) {
Collections.sort(userId2LogList.get(userId));
}
return userId2LogList;
}
public static Map<String, List<MMetricsBaseLog>> rebuildMetricsLogs(List<MMetricsBaseLog> metricsBaseLogs) {
Map<String, List<MMetricsBaseLog>> ipAddr2MetricsLogList = new HashMap<>();
for (MMetricsBaseLog log : metricsBaseLogs) {
if (!ipAddr2MetricsLogList.containsKey(log.getLogHostname())) {
ipAddr2MetricsLogList.put(log.getLogHostname(), new ArrayList<>());
}
ipAddr2MetricsLogList.get(log.getLogHostname()).add(log);
}
for (String ipAddr : ipAddr2MetricsLogList.keySet()) {
Collections.sort(ipAddr2MetricsLogList.get(ipAddr));
}
return ipAddr2MetricsLogList;
}
public static List<MServiceBaseLog> getServiceBaseLog(List<MBaseLog> logList) {
List<MServiceBaseLog> resultList = new ArrayList<>();
for (MBaseLog log : logList) {
if (log instanceof MServiceBaseLog) {
resultList.add((MServiceBaseLog) log);
}
}
return resultList;
}
public static List<MMetricsBaseLog> getMetricsBaseLog(List<MBaseLog> logList) {
List<MMetricsBaseLog> resultList = new ArrayList<>();
for (MBaseLog log : logList) {
if (log instanceof MMetricsBaseLog) {
resultList.add((MMetricsBaseLog) log);
}
}
return resultList;
}
public static void preprocessLog(List<MBaseLog> logList) {
List<MServiceBaseLog> serviceBaseLogs = MAnalyzeUtils.getServiceBaseLog(logList);
List<MMetricsBaseLog> metricsBaseLogs = MAnalyzeUtils.getMetricsBaseLog(logList);
Map<String, List<MServiceBaseLog>> userId2LogList = MAnalyzeUtils.rebuildCallChain(serviceBaseLogs);
Map<String, List<MMetricsBaseLog>> ipAddr2MetricsLogList = MAnalyzeUtils.rebuildMetricsLogs(metricsBaseLogs);
}
}
<file_sep>/MEurekaServer/build.sh
#!/bin/bash
mvn clean package
kubectl delete service eureka-server
kubectl delete deployment eureka-server
docker rmi micheallei/meurekaserver:v2.0
docker rmi meurekaserver:v2.0
docker build -t meurekaserver:v2.0 .
docker tag meurekaserver:v2.0 micheallei/meurekaserver:v2.0
docker push micheallei/meurekaserver:v2.0
kubectl create -f eureka-server.yaml<file_sep>/common/src/main/java/com/septemberhx/common/bean/mclient/MInstanceRestInfoBean.java
package com.septemberhx.common.bean.mclient;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class MInstanceRestInfoBean {
private String objectId;
private String functionName;
private String restAddress;
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/IInfoCollector.java
package com.septemberhx.common.base;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/8/30
*/
public interface IInfoCollector {
void start();
void initParams();
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/log/MServiceBaseLog.java
package com.septemberhx.common.base.log;
import lombok.Getter;
import lombok.Setter;
import org.json.JSONObject;
import java.util.Map;
/**
* @author SeptemberHX
* @date 2019/8/26
* @version 0.1
*
* Basic log type of services.
* All the logs will be generated by the MClient module
*/
@Getter
@Setter
public abstract class MServiceBaseLog extends MBaseLog {
protected String logObjectId; // the id of the MObject which writes the log
protected String logMethodName; // the name of the function
protected String logUserId; // the unique id for each user
@Override
protected String[] fillInfo(String[] strArr) {
String[] leftStrArr = super.fillInfo(strArr);
if (leftStrArr != null) {
this.logUserId = leftStrArr[0];
this.logObjectId = leftStrArr[1];
this.logMethodName = leftStrArr[2];
return getUnusedStrArr(leftStrArr, 3);
}
return null;
}
@Override
protected void fillInfo(Map<String, Object> logMap) {
super.fillInfo(logMap);
this.logUserId = (String)logMap.get("logUserId");
this.logObjectId = (String)logMap.get("logObjectId");
this.logMethodName = (String)logMap.get("logMethodName");
}
@Override
protected String uniqueLogInfo() {
return this.concatInfo(super.uniqueLogInfo(), logUserId, logObjectId, logMethodName);
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = super.toJson();
jsonObject.put("logUserId", this.logUserId);
jsonObject.put("logMethodName", this.logMethodName);
jsonObject.put("logObjectId", this.logObjectId);
return jsonObject;
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MDockerInfoBean.java
package com.septemberhx.common.bean.agent;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Objects;
@Getter
@Setter
@ToString
public class MDockerInfoBean {
private String hostIp;
private String nodeLabel;
private String instanceId; // instance id that k8s assigns to it
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MDockerInfoBean that = (MDockerInfoBean) o;
return Objects.equals(hostIp, that.hostIp) &&
Objects.equals(instanceId, that.instanceId) &&
Objects.equals(nodeLabel, that.nodeLabel);
}
@Override
public int hashCode() {
return Objects.hash(hostIp, instanceId, nodeLabel);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/MOrchestrationServerMain.java
package com.septemberhx.server;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/12/20
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@MapperScan("com.septemberhx.server.mapper")
public class MOrchestrationServerMain {
@Bean
@LoadBalanced
public RestTemplate get(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MOrchestrationServerMain.class, args);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/model/MSystemModel.java
package com.septemberhx.server.model;
//import com.septemberhx.server.model.routing.MDepRoutingManager;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/1
*/
@Getter
@Setter
public class MSystemModel {
private MSvcManager serviceManager;
private MClusterManager nodeManager;
private MSvcDepManager svcDepManager;
private static Logger logger = LogManager.getLogger(MSystemModel.class);
public MSystemModel() {
// todo: init service manager from the database
this.serviceManager = new MSvcManager();
this.nodeManager = new MClusterManager();
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/bean/MConnectionJson.java
package com.septemberhx.server.bean;
import com.septemberhx.common.base.node.MNodeConnectionInfo;
import lombok.Getter;
import lombok.Setter;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/11/24
*/
@Getter
@Setter
public class MConnectionJson {
private String successor;
private String predecessor;
private MNodeConnectionInfo connection;
}<file_sep>/MClusterAgent/src/main/java/com/septemberhx/agent/middleware/MServiceManager.java
package com.septemberhx.agent.middleware;
import com.netflix.appinfo.InstanceInfo;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface MServiceManager {
Set<String> getNodeIdSet();
Optional<String> getInstanceIdByIp(String ip);
Optional<String> getNodeIdOfInstance(String instanceId);
List<InstanceInfo> getInstanceInfoList();
InstanceInfo getInstanceInfoById(String instanceId);
public InstanceInfo getInstanceInfoByIpAndPort(String ipAddr);
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/gateway/MDepRequestCacheBean.java
package com.septemberhx.common.bean.gateway;
import com.septemberhx.common.bean.MResponse;
import com.septemberhx.common.service.dependency.BaseSvcDependency;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/9
*/
@Getter
@Setter
@ToString
public class MDepRequestCacheBean implements Comparable<MDepRequestCacheBean> {
/*
* The dependency description
*/
private BaseSvcDependency baseSvcDependency;
/*
* Who this request belongs to
*/
private String clientId;
/*
* When the system receive the request in mill seconds
*/
private long timestamp;
private MResponse parameters;
public MDepRequestCacheBean(BaseSvcDependency baseSvcDependency, String clientId, long timestamp, MResponse parameters) {
this.baseSvcDependency = baseSvcDependency;
this.clientId = clientId;
this.timestamp = timestamp;
this.parameters = parameters;
}
@Override
public int compareTo(MDepRequestCacheBean o) {
return Long.compare(this.timestamp, o.timestamp);
}
}
<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/core/MClientSkeleton.java
package com.septemberhx.mclient.core;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.septemberhx.common.bean.mclient.MApiSplitBean;
import com.septemberhx.common.bean.mclient.MGetRemoteUriRequest;
import com.septemberhx.common.bean.mclient.MInstanceRestInfoBean;
import com.septemberhx.common.base.log.MFunctionCallEndLog;
import com.septemberhx.common.base.log.MFunctionCalledLog;
import com.septemberhx.common.utils.MLogUtils;
import com.septemberhx.common.utils.MRequestUtils;
import com.septemberhx.common.utils.MUrlUtils;
import com.septemberhx.mclient.base.MObject;
import com.septemberhx.mclient.config.Mvf4msConfig;
import com.septemberhx.common.config.Mvf4msDep;
import com.septemberhx.mclient.utils.RequestUtils;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.*;
/**
* @Author: septemberhx
* @Date: 2019-06-12
* @Version 0.1
*/
@Service
public class MClientSkeleton {
private static MClientSkeleton instance;
@Getter
private Map<String, MObject> mObjectMap;
@Getter
private Map<String, String> parentIdMap;
@Getter
private Map<String, Set<String>> objectId2ApiSet;
private Map<String, Map<String, MInstanceRestInfoBean>> restInfoMap;
private Map<String, Map<String, Boolean>> apiContinueMap;
private static Logger logger = LogManager.getLogger(MClientSkeleton.class);
@Setter
private EurekaClient discoveryClient;
@Setter
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@Setter
private Mvf4msConfig mvf4msConfig;
private Random random = new Random(10000);
private MClientSkeleton() {
this.mObjectMap = new HashMap<>();
this.parentIdMap = new HashMap<>();
this.objectId2ApiSet = new HashMap<>();
this.restInfoMap = new HashMap<>();
this.apiContinueMap = new HashMap<>();
}
public static MClientSkeleton inst() {
if (instance == null) {
synchronized (MClientSkeleton.class) {
instance = new MClientSkeleton();
}
}
return instance;
}
public List<Mvf4msDep> getDepListById(String depId) {
return this.mvf4msConfig.getDepListById(depId);
}
public InstanceInfo getRandomServiceInstance(String serviceName) {
Application app = this.discoveryClient.getApplication(serviceName);
if (app != null) {
return app.getInstances().get(this.random.nextInt(app.getInstances().size()));
}
return null;
}
/*
* register object
*/
public void registerMObject(MObject object) {
if (this.mObjectMap.containsKey(object.getId())) {
logger.warn("MObject " + object.getId() + " has been registered before !!!");
} else {
this.mObjectMap.put(object.getId(), object);
}
}
/*
* register the parent id of object
*/
public void registerParent(MObject object, String parentId) {
if (this.mObjectMap.containsKey(object.getId())) {
this.parentIdMap.put(object.getId(), parentId);
} else {
logger.warn("MObject " + object.getId() + " not registered");
}
}
public void printParentIdMap() {
logger.debug(this.parentIdMap.toString());
}
public List<String> getMObjectIdList() {
return new ArrayList<>(this.mObjectMap.keySet());
}
/*
* add an info bean
*/
public void addRestInfo(MInstanceRestInfoBean infoBean) {
if (infoBean.getRestAddress() == null) {
this.removeRestInfo(infoBean);
return;
}
if (!this.restInfoMap.containsKey(infoBean.getObjectId())) {
this.restInfoMap.put(infoBean.getObjectId(), new HashMap<>());
}
this.restInfoMap.get(infoBean.getObjectId()).put(infoBean.getFunctionName(), infoBean);
}
/*
* delete an info bean
*/
private void removeRestInfo(MInstanceRestInfoBean infoBean) {
if (this.restInfoMap.containsKey(infoBean.getObjectId())) {
this.restInfoMap.get(infoBean.getObjectId()).remove(infoBean.getFunctionName());
}
}
/**
* Get all Rest info
* @return List
*/
public List<MInstanceRestInfoBean> getRestInfoBeanList() {
List<MInstanceRestInfoBean> restInfoBeans = new ArrayList<>();
for (String mObjectId : this.restInfoMap.keySet()) {
restInfoBeans.addAll(this.restInfoMap.get(mObjectId).values());
}
return restInfoBeans;
}
/**
* It will be used by MApiType annotation
* @param mObjectId: the id of MObject
* @param functionName: the function will be used/called
* @return boolean
*/
public static boolean isRestNeeded(String mObjectId, String functionName) {
return MClientSkeleton.inst().checkIfHasRestInfo(mObjectId, functionName);
}
public void setApiContinueStatus(MApiSplitBean apiSplitBean) {
if (!this.apiContinueMap.containsKey(apiSplitBean.getObjectId())) {
this.apiContinueMap.put(apiSplitBean.getObjectId(), new HashMap<>());
}
this.apiContinueMap.get(apiSplitBean.getObjectId()).put(apiSplitBean.getFunctionName(), apiSplitBean.getStatus());
}
public static boolean checkIfContinue(String mObjectId, String functionName) {
if (!MClientSkeleton.inst().apiContinueMap.containsKey(mObjectId)) return true;
return MClientSkeleton.inst().apiContinueMap.get(mObjectId).getOrDefault(functionName, true);
}
public static void logFunctionCall(String mObjectId, String functionName, HttpServletRequest request) {
MFunctionCalledLog serviceBaseLog = new MFunctionCalledLog();
serviceBaseLog.setLogDateTime(DateTime.now());
serviceBaseLog.setLogMethodName(functionName);
serviceBaseLog.setLogObjectId(mObjectId);
if (request != null) {
serviceBaseLog.setLogFromIpAddr(request.getRemoteAddr());
serviceBaseLog.setLogFromPort(request.getRemotePort());
serviceBaseLog.setLogUserId(request.getHeader("userId"));
serviceBaseLog.setLogIpAddr(request.getLocalAddr());
}
MLogUtils.log(serviceBaseLog);
}
public static void logFunctionCallEnd(String mObjectId, String functionName, HttpServletRequest request) {
MFunctionCallEndLog serviceBaseLog = new MFunctionCallEndLog();
serviceBaseLog.setLogDateTime(DateTime.now());
serviceBaseLog.setLogMethodName(functionName);
serviceBaseLog.setLogObjectId(mObjectId);
if (request != null) {
serviceBaseLog.setLogFromIpAddr(request.getRemoteAddr());
serviceBaseLog.setLogFromPort(request.getRemotePort());
serviceBaseLog.setLogUserId(request.getHeader("userId"));
serviceBaseLog.setLogIpAddr(request.getLocalAddr());
}
MLogUtils.log(serviceBaseLog);
}
/**
* It will be used by MApiType annotation
* @param mObjectId: the id of MObject
* @param functionName: the function will be used/called
* @param args: the arguments
* @return Object
*/
public static Object restRequest(String mObjectId, String functionName, String returnTypeStr, Object... args) {
List<String> paramNameList = new ArrayList<>(args.length / 2);
List<Object> paramValueList = new ArrayList<>(args.length / 2);
for (int i = 0; i < args.length; i += 2) {
paramNameList.add((String)args[i]);
paramValueList.add(args[i+1]);
}
String paramJsonStr = RequestUtils.methodParamToJsonString(paramNameList, paramValueList);
if (MClientSkeleton.inst().discoveryClient != null) {
Application clusterAgent = MClientSkeleton.inst().discoveryClient.getApplication("MClusterAgent");
if (clusterAgent != null) {
List<InstanceInfo> clusterAgentInstances = clusterAgent.getInstances();
if (clusterAgentInstances.size() > 0) {
// request MClusterAgent for remote uri
URI requestUri = MUrlUtils.getMClientRequestRemoteUri(clusterAgentInstances.get(0).getIPAddr(), clusterAgentInstances.get(0).getPort());
logger.debug(requestUri);
if (requestUri != null) {
String rawPatterns = null;
Map<RequestMappingInfo, HandlerMethod> mapping = MClientSkeleton.inst().requestMappingHandlerMapping.getHandlerMethods();
for (RequestMappingInfo mappingInfo : mapping.keySet()) {
if (mapping.get(mappingInfo).getMethod().getName().equals(functionName)) {
rawPatterns = mappingInfo.getPatternsCondition().toString();
break;
}
}
MGetRemoteUriRequest getRemoteUriRequest = new MGetRemoteUriRequest();
getRemoteUriRequest.setFunctionName(functionName);
getRemoteUriRequest.setObjectId(mObjectId);
getRemoteUriRequest.setRawPatterns(rawPatterns);
URI remoteUri = MRequestUtils.sendRequest(requestUri, getRemoteUriRequest, URI.class, RequestMethod.POST);
logger.debug(remoteUri);
if (remoteUri != null) {
// redirect to remote uri with parameters in json style
try {
return MRequestUtils.sendRequest(remoteUri, JSONObject.stringToValue(paramJsonStr), Class.forName(returnTypeStr), RequestMethod.GET);
} catch (ClassNotFoundException e) {
logger.error(e);
}
}
}
}
}
}
return null;
}
/**
* request the information that needed by rest request for remote call
* @param mObjectId: the id of MObject
* @param functionName: the function will be used/called
* @return String
*/
public String getRestInfo(String mObjectId, String functionName) {
if (!this.checkIfHasRestInfo(mObjectId, functionName)) {
throw new RuntimeException("Failed to fetch remote url for " + functionName + " in " + mObjectId);
}
return this.restInfoMap.get(mObjectId).get(functionName).getRestAddress();
}
/**
* check whether need to use remote call or not
* @param mObjectId: the id of MObject
* @param functionName: the function will be used/called
* @return boolean
*/
private boolean checkIfHasRestInfo(String mObjectId, String functionName) {
return this.restInfoMap.containsKey(mObjectId) && this.restInfoMap.get(mObjectId).containsKey(functionName);
}
public void registerObjectAndApi(String mObjectId, String apiName) {
if (!this.objectId2ApiSet.containsKey(mObjectId)) {
this.objectId2ApiSet.put(mObjectId, new HashSet<>());
}
this.objectId2ApiSet.get(mObjectId).add(apiName);
}
}
<file_sep>/MGateway/src/main/java/com/septemberhx/mgateway/routing/Routing.java
package com.septemberhx.mgateway.routing;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.septemberhx.common.bean.agent.MInstanceInfoBean;
import com.septemberhx.common.bean.gateway.MRequestUrl;
import com.septemberhx.common.service.MSvcVersion;
import com.septemberhx.common.utils.MUrlUtils;
import com.septemberhx.mgateway.client.ConnectToCenter;
import com.septemberhx.mgateway.client.ConnectToClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.List;
import java.util.Random;
/**
* Created by Lei on 2019/12/20 12:59
*/
@Component
public class Routing extends ZuulFilter {
@Autowired
private ConnectToCenter connectToCenter;
@Autowired
private ConnectToClient connectToClient;
private RouteLocator routeLocator;
public Routing(RouteLocator routeLocator){
this.routeLocator = routeLocator;
}
@Override
public String filterType() {
return FilterConstants.ROUTE_TYPE;
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
//可以根据业务要求,过滤相关路由
return true;
}
@Override
public Object run() {
System.out.println("网关运行");
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String hostIp = request.getRemoteAddr();
System.out.println("请求的ip为 + " + hostIp);
String serviceName = request.getHeader("serviceName");
String serviceVersion = request.getHeader("serviceVersion");
String requestVersion = request.getHeader("requestVersion");
String requestUri = request.getRequestURI();
System.out.println("请求的uri为" + requestUri);
String requestURI = requestUri.replaceAll("/mgateway","");
System.out.println("请求的uri为" + requestURI);
String requestServicename = requestURI.split("/")[1];
if(ifServiceName(requestServicename)){
System.out.println("路径请求");
List<MInstanceInfoBean> mInstanceInfoBeans;
if(requestVersion != null){
System.out.println("请求头部:" + requestVersion);
mInstanceInfoBeans = new MPathRquest().getExammpleByVersion(connectToCenter, connectToClient, serviceName+"_"+ MSvcVersion.fromStr(serviceVersion).toString(), requestVersion, requestServicename, hostIp);
}else{
mInstanceInfoBeans = new MPathRquest().getExammpleByWithoutVersion(connectToCenter, connectToClient, serviceName,serviceVersion,requestURI, hostIp);
}
if(mInstanceInfoBeans.isEmpty()){
return null;
}
MInstanceInfoBean getServiceInstance = mInstanceInfoBeans.get(new Random().nextInt(mInstanceInfoBeans.size()));
System.out.println("路由得到的实例为" + getServiceInstance);
try{
URI uri = MUrlUtils.getRemoteUri(getServiceInstance.getIp(),getServiceInstance.getPort(),"/");
ctx.setRouteHost(uri.toURL());
// ctx.setRouteHost(new URI(getServiceInstance.getUri().toString()+"/").toURL());
}catch (Exception e){
e.printStackTrace();
}
ctx.put(FilterConstants.REQUEST_URI_KEY, requestURI.replaceFirst("/"+requestServicename+"/",""));
connectToCenter.updateUseful(getServiceInstance);
return null;
}else{
System.out.println("依赖请求");
String name = requestURI.split("/")[1];
String id = requestURI.split("/")[2];
MRequestUrl mRequestUrl = new MDependencyRequest().getInstanceInfoBean( name, id, hostIp, serviceName, serviceVersion,connectToClient, connectToCenter);
try{
URI uri = MUrlUtils.getRemoteUri(mRequestUrl.getIp(),Integer.parseInt(mRequestUrl.getPort()),"/");
ctx.setRouteHost(uri.toURL());
// ctx.setRouteHost(new URI(getServiceInstance.getUri().toString()+"/").toURL());
}catch (Exception e){
e.printStackTrace();
}
ctx.put(FilterConstants.REQUEST_URI_KEY, mRequestUrl.getInsterfaceName().replaceFirst("/",""));
return null;
}
}
public boolean ifServiceName(String serviceName){
List<String> allserviceName = connectToCenter.getAllServiceName();
for(String string: allserviceName){
if(string.equalsIgnoreCase(serviceName)){
return true;
}
}
return false;
}
public static void main(String[] args) {
String a = "/mgateway/mweather/weather";
System.out.println(a.replaceAll("/mgateway",""));
}
}<file_sep>/common/src/main/java/com/septemberhx/common/service/diff/MDiff.java
package com.septemberhx.common.service.diff;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/6
*
* List<MDiff> should be returned when comparing two services
*/
@Getter
@Setter
@ToString
public class MDiff {
/**
* Type of the difference
*/
private MDiffType type;
/**
* Previous value
*/
private Object preValue;
/**
* Current value
*/
private Object curValue;
public MDiff(MDiffType type, Object preValue, Object curValue) {
this.type = type;
this.preValue = preValue;
this.curValue = curValue;
}
public MDiff(){
}
}
<file_sep>/MServiceAnalyser/src/main/java/com/ll/service/bean/MPathInfo.java
package com.ll.service.bean;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* Created by Lei on 2019/11/29 15:53
*/
@Getter
@Setter
public class MPathInfo {
private String gitUrl;
private String applicationPath;
private List<String> controllerListPath;
@Override
public String toString() {
return "MPathInfo{" +
"application_Path='" + applicationPath + '\'' +
", controller_ListPath=" + controllerListPath +
'}';
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/dependency/PureSvcDependency.java
package com.septemberhx.common.service.dependency;
import com.septemberhx.common.service.MFunc;
import com.septemberhx.common.service.MSla;
import com.septemberhx.common.service.MSvcVersion;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.*;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/11
*/
@Getter
@Setter
@ToString
public class PureSvcDependency {
protected MFunc func;
// service name
protected String serviceName;
// prefer sla level
protected MSla sla;
// API url
protected String patternUrl;
// the version of ${serviceName}
protected Set<MSvcVersion> versionSet;
public PureSvcDependency(MFunc func, String serviceName, MSla sla, String patternUrl, Set<MSvcVersion> versionSet) {
this.func = func;
this.serviceName = serviceName;
this.sla = sla;
this.patternUrl = patternUrl;
this.versionSet = versionSet;
}
public PureSvcDependency() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PureSvcDependency that = (PureSvcDependency) o;
return Objects.equals(func, that.func) &&
Objects.equals(serviceName, that.serviceName) &&
Objects.equals(sla, that.sla) &&
Objects.equals(patternUrl, that.patternUrl) &&
equalsForSet(versionSet, that.versionSet);
}
@Override
public int hashCode() {
List<Object> objects = new ArrayList<>();
objects.add(func);
objects.add(serviceName);
objects.add(patternUrl);
if (sla != null) {
objects.add(sla);
}
if (versionSet != null) {
objects.addAll(versionSet);
}
return Arrays.hashCode(objects.toArray());
}
public static boolean equalsForSet(Set<?> set1, Set<?> set2) {
if ((set1 == null && set2 != null) || (set1 != null && set2 == null)) {
return false;
} else if (set1 == null && set2 == null) {
return true;
}
if (set1.size() != set2.size()) {
return false;
}
return set1.containsAll(set2);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/job/MJobType.java
package com.septemberhx.server.job;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/6
*/
public enum MJobType {
/*
* Build a given repo
*/
JOB_BUILD,
}
<file_sep>/MBuildCenter/Dockerfile
FROM openjdk:8-jre-alpine
MAINTAINER Lei
ADD target/MBuildCenter-1.0-SNAPSHOT.jar app.jar
EXPOSE 8082
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","app.jar"]<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/client/MAnalyzerClient.java
package com.septemberhx.server.client;
import com.septemberhx.common.bean.MResponse;
import com.septemberhx.common.bean.server.MFetchServiceInfoBean;
import com.septemberhx.common.bean.server.MServiceCompareBean;
import com.septemberhx.common.bean.server.MServiceRegisterBean;
import com.septemberhx.common.config.MConfig;
import com.septemberhx.common.service.diff.MServiceDiff;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/1
*/
@FeignClient(name = MConfig.SERVICE_NAME_ANALYZE)
public interface MAnalyzerClient {
@RequestMapping(value = MConfig.ANALYZE_ANALYZE_URI, method = RequestMethod.POST)
MResponse analyzer(@RequestBody MServiceRegisterBean registerBean);
@RequestMapping(value = MConfig.ANALYZE_ANALYZE_URI_ONE, method = RequestMethod.POST)
MResponse analyzerOne(@RequestBody MFetchServiceInfoBean mFetchServiceInfoBean);
@RequestMapping(value = MConfig.ANALYZE_COMPARE_URI, method = RequestMethod.POST)
MServiceDiff compare(@RequestBody MServiceCompareBean compareBean);
}
<file_sep>/MBuildCenter/src/main/java/com/ll/mbuildcenter/client/CenterClient.java
package com.ll.mbuildcenter.client;
import com.septemberhx.common.bean.server.MBuildJobFinishedBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author Lei
* @Date 2020/2/14 16:12
* @Version 1.0
*/
@FeignClient(name = "MOrchestrationServer")
public interface CenterClient {
@RequestMapping("/job/buildNotify")
public void returnResult(@RequestBody MBuildJobFinishedBean mBuildJobFinishedBean);
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/dependency/MSvcDepDesc.java
package com.septemberhx.common.service.dependency;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Map;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/2/29
*
* The dependency description for service
*/
@Getter
@Setter
@ToString
public class MSvcDepDesc {
// the unique id of the service with version that this dependency belongs to
private String serviceId;
// the list means the service may have multiple kinds of dependency
// the map means the service may depend on multiple services
private Map<String, Map<String, BaseSvcDependency>> dependencyMaps;
// unique dependency name for this service
private String name;
public MSvcDepDesc(String serviceId, String name, Map<String, Map<String, BaseSvcDependency>> dependencyMaps) {
this.serviceId = serviceId;
this.name = name;
this.dependencyMaps = dependencyMaps;
}
public MSvcDepDesc(){
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MApiSplitBean.java
package com.septemberhx.common.bean.agent;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class MApiSplitBean {
private String objectId;
private String functionName;
private Boolean status;
}
<file_sep>/common/src/main/java/com/septemberhx/common/base/log/MFunctionCallEndLog.java
package com.septemberhx.common.base.log;
import lombok.Getter;
import lombok.Setter;
import org.json.JSONObject;
import java.util.Map;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/8/31
*/
@Getter
@Setter
public class MFunctionCallEndLog extends MServiceBaseLog {
private String logFromIpAddr;
private Integer logFromPort = 0;
public MFunctionCallEndLog() {
this.logType = MLogType.FUNCTION_CALL_END;
}
@Override
protected String[] fillInfo(String[] strArr) {
String[] leftStrArr = super.fillInfo(strArr);
if (leftStrArr != null) {
this.logFromIpAddr = leftStrArr[0];
this.logFromPort = Integer.valueOf(leftStrArr[1]);
return getUnusedStrArr(leftStrArr, 2);
}
return null;
}
@Override
protected void fillInfo(Map<String, Object> logMap) {
super.fillInfo(logMap);
this.logFromIpAddr = (String) logMap.get("logFromIpAddr");
this.logFromPort = (Integer) logMap.get("logFromPort");
}
@Override
protected String uniqueLogInfo() {
return this.concatInfo(super.uniqueLogInfo(), logFromIpAddr, logFromPort.toString());
}
@Override
public JSONObject toJson() {
JSONObject jsonObject = super.toJson();
jsonObject.put("logFromIpAddr", this.logFromIpAddr);
jsonObject.put("logFromPort", this.logFromPort);
return jsonObject;
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/dao/MDependencyDao.java
package com.septemberhx.server.dao;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.HashSet;
import java.util.Set;
/**
* @Author Lei
* @Date 2020/3/14 20:50
* @Version 1.0
*/
@Getter
@Setter
@ToString
public class MDependencyDao{
private String dependencyName;
private String dependencyId;
private String serviceId;
private String serviceDenpendencyName;
private String serviceDependencyInterfaceName;
private String serviceDenpendencyVersion;
private String functionDescribe;
private Integer functionLevel;
public MDependencyDao(){
}
public MDependencyDao(String dependencyName, String dependencyId,
String serviceId, String serviceDenpendencyName,
String serviceDependencyInterfaceName, String serviceDenpendencyVersion,
String functionDescribe, Integer functionLevel) {
this.dependencyName = dependencyName;
this.dependencyId = dependencyId;
this.serviceId = serviceId;
this.serviceDenpendencyName = serviceDenpendencyName;
this.serviceDependencyInterfaceName = serviceDependencyInterfaceName;
this.serviceDenpendencyVersion = serviceDenpendencyVersion;
this.functionDescribe = functionDescribe;
this.functionLevel = functionLevel;
}
public static Set<String> getVersions(String st){
if(st == null){
return null;
}
String[] versions = st.split(",");
Set<String> set = new HashSet<>();
for(String string: versions){
set.add(string);
}
return set;
}
public static String getVersion(Set<String> versions){
if(versions == null){
return null;
}
StringBuilder a = new StringBuilder();
for(String s: versions){
a.append(s);
a.append(",");
}
a.deleteCharAt(a.lastIndexOf(","));
return a.toString();
}
}<file_sep>/common/src/main/java/com/septemberhx/common/bean/gateway/MRequestUrl.java
package com.septemberhx.common.bean.gateway;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @Author Lei
* @Date 2020/3/31 16:04
* @Version 1.0
*/
@Getter
@Setter
@ToString
public class MRequestUrl {
private String ip;
private String port;
private String insterfaceName;
public MRequestUrl(String ip, String port, String insterfaceName) {
this.ip = ip;
this.port = port;
this.insterfaceName = insterfaceName;
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/algorithm/evolution/Timeevolution.java
package com.septemberhx.server.algorithm.evolution;
import com.septemberhx.common.bean.agent.MDeployPodRequest;
import com.septemberhx.common.bean.agent.MInstanceInfoBean;
import com.septemberhx.server.client.ConnectToClient;
import com.septemberhx.server.dao.MDependencyDao;
import com.septemberhx.server.dao.MDeployDao;
import com.septemberhx.server.utils.MDatabaseUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.*;
/**
* @Author Lei
* @Date 2020/3/17 21:53
* @Version 1.0
*/
@Configuration
@EnableScheduling
public class Timeevolution {
public static Map<MInstanceInfoBean, Integer> useRate = new HashMap<>();
@Autowired
ConnectToClient connectToClient;
@Scheduled(cron = "0 0 12 * * ?")
public void TimeToevolution(){
// delete deploy but not run and update deploy database
deleteButNotRun();
// dependency
evolution();
// delete all useRate
deleteAllUseRate();
}
public void deleteButNotRun(){
List<MDeployDao> deployDaoList = MDatabaseUtils.databaseUtils.getAlldeployInfo();
List<MInstanceInfoBean> instanceInfoBeans = connectToClient.getAllMintancesInfo();
for(MDeployDao mDeployDao: deployDaoList){
if(mDeployDao.getRegisterId() == null){
connectToClient.deleteInstance(mDeployDao.getPodId());
MDatabaseUtils.databaseUtils.deleteDeployById(mDeployDao.getPodId());
continue;
}
boolean ifIn = false;
for(MInstanceInfoBean mInstanceInfoBean: instanceInfoBeans){
if(mDeployDao.getRegisterId().equalsIgnoreCase(mInstanceInfoBean.getRegistryId())){
ifIn = true;
break;
}
}
if(!ifIn){
MDatabaseUtils.databaseUtils.deleteDeployById(mDeployDao.getPodId());
}
}
}
public void evolution(){
Map<String, Map<String, Integer>> serviceIdUseRate = getServiceIdUseRate();
for(String serviceName:serviceIdUseRate.keySet()){
Map<String, Integer> serviceVersionRate = serviceIdUseRate.get(serviceName);
Integer sum = 0;
for(String serviceVersion:serviceVersionRate.keySet()){
sum = sum + serviceVersionRate.get(serviceVersion);
}
if(serviceVersionRate.size() != 1){
Integer low = sum / (serviceVersionRate.size()*2);
Integer hight = sum / (serviceVersionRate.size()/2);
for(String serviceVersion:serviceVersionRate.keySet()){
if(serviceVersionRate.get(serviceVersion) < low){
Integer list = MDatabaseUtils.databaseUtils.getDeployByTrueserviceIdAndRun(serviceName+"_"+serviceVersion).size();
if(list >= 1){
MInstanceInfoBean mInstanceInfoBean = getLowestUseRate(serviceName, serviceVersion);
connectToClient.deleteInstance(mInstanceInfoBean.getDockerInfo().getInstanceId());
}
}else if(serviceVersionRate.get(serviceVersion) > hight){
MInstanceInfoBean mInstanceInfoBean = getHightestUseRate(serviceName, serviceVersion);
MDeployPodRequest mDeployPodRequest = new MDeployPodRequest();
mDeployPodRequest.setId(serviceName+"_"+serviceVersion);
mDeployPodRequest.setNodeId(mInstanceInfoBean.getDockerInfo().getNodeLabel());
mDeployPodRequest.setServiceName(serviceName);
mDeployPodRequest.setImageUrl(MDatabaseUtils.databaseUtils.getServiceById(serviceName+"_"+serviceVersion).getImageUrl());
mDeployPodRequest.setUniqueId(UUID.randomUUID().toString().substring(24));
connectToClient.deploy(mDeployPodRequest);
}else{
continue;
}
}
}
}
}
public Map<String, Map<String, Integer>> getServiceIdUseRate(){
Map<String, Map<String, Integer>> map = new HashMap<>();
for(MInstanceInfoBean mInstanceInfoBean:useRate.keySet()){
String serviceName = mInstanceInfoBean.getServiceName();
String serviceVersion = mInstanceInfoBean.getServiceVersion();
Map<String, Integer> s = map.get(serviceName);
if(map.containsKey(serviceName)){
if(s.keySet().contains(serviceVersion)){
s.put(serviceVersion,s.get(serviceVersion)+1);
}else{
s.put(serviceVersion,1);
}
}else{
if(s.keySet().contains(serviceVersion)){
s.put(serviceVersion,s.get(serviceVersion)+1);
}else{
s.put(serviceVersion,1);
}
}
map.put(serviceName, s);
}
return map;
}
public void deleteAllUseRate(){
useRate.clear();
}
public MInstanceInfoBean getLowestUseRate(String serviceNmae, String serviceVersion){
Map<MInstanceInfoBean, Integer> map = getByNameAndVersion(serviceNmae,serviceVersion);
MInstanceInfoBean result = null;
Integer a = 1000;
for(MInstanceInfoBean mInstanceInfoBean:map.keySet()){
if(a >= map.get(mInstanceInfoBean)){
result = mInstanceInfoBean;
a = map.get(mInstanceInfoBean);
}
}
return result;
}
public MInstanceInfoBean getHightestUseRate(String serviceNmae, String serviceVersion){
Map<MInstanceInfoBean, Integer> map = getByNameAndVersion(serviceNmae,serviceVersion);
MInstanceInfoBean result = null;
Integer a = 0;
for(MInstanceInfoBean mInstanceInfoBean:map.keySet()){
if(a <= map.get(mInstanceInfoBean)){
result = mInstanceInfoBean;
a = map.get(mInstanceInfoBean);
}
}
return result;
}
public Map<MInstanceInfoBean, Integer> getByNameAndVersion(String serviceName, String serviceVersion){
Map<MInstanceInfoBean, Integer> map = new HashMap<>();
for(MInstanceInfoBean mInstanceInfoBean:useRate.keySet()){
if(mInstanceInfoBean.getServiceName().equals(serviceName) && mInstanceInfoBean.getServiceVersion().equals(serviceVersion)){
map.put(mInstanceInfoBean,useRate.get(mInstanceInfoBean));
}
}
return map;
}
}
<file_sep>/MClusterAgent/Readme.md
# MClusterAgent
对整个集群进行统一的控制、接收外部指令以及监控集群状态。主要涉及到 1) Eureka; 2) Kubernetes Server API
## 接口
详情请参考 `MAgentController`
* `/magent/doRequest`:接收 `MUserRequestBean`,并按照指定的实例ID,将请求转发给指定实例
* `/magent/fetchRequestUrl`:接收来自 `MGateway` 的 `MUserDemand`,向 `MOrchestartionServer` 询问处理该需求的实例ID
* `/magent/updateGateways`:接收来自 `MOrchestrationServer` 的 `MUpdateCacheBean`,目标是将携带的路由表分发给集群内部的全部 `MGateway`
* `/magent/allUser`:从集群内部的所有 `MGateway` 中,收集全部的用户信息
* `/magent/instanceInfoList`:获取集群内部所有服务实例的相关信息
* `/magent/deleteInstance`:删除指定的实例
* `/magent/deploy`:在指定节点上,部署指定的服务实例
* `/magent/registered`:接收来自 `MEurekaServer` 的实例信息,并在服务实例变更时,向 `MOrchestrationServer` 汇报
## 运行
* 需要修改 application.yaml 中的 mclientagent.server, mclientagent.elasticsearch 与 eureka 地址
* 所有部署的服务实例都利用了 `./yaml/template.yaml` 这个模板文件,请按需更改
## 注意
* 默认日志都写在了 `/var/mclient/log` 下(参见 `MLogUtils` 下),所以需要在 yaml 模板里面,挂载一个本地目录,这样就能够收集该节点上所有实例的日志
* **不要在部署实例的时候,在给定的实例 ID 中包含 `-` 号 !!!!**,Kubernetes 不支持<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/algorithm/Judge/MCompatibilityJudge.java
package com.septemberhx.server.algorithm.Judge;
import com.septemberhx.common.service.diff.*;
import java.util.List;
/**
* @Author Lei
* @Date 2020/3/12 15:20
* @Version 1.0
*/
public class MCompatibilityJudge {
/**
* Judge compatibility between high and low versions
* @param mServiceDiff Differences between microservices
* @return If the higher version is fully backward compatible with the lower version return true, else return false
*/
public static boolean mCompatibilityJudge(MServiceDiff mServiceDiff){
List<MServiceInterfaceDiff> list = mServiceDiff.getMServiceInterfaceDiffs();
if(list.isEmpty()){
// There is no difference except for internal implementation
return true;
}
for(MServiceInterfaceDiff mServiceInterfaceDiff: list){
if(mServiceInterfaceDiff.getMDiffInterface().equals(MDiffInterface.INTERFACE_CHANGE)){
if(mServiceInterfaceDiff instanceof MServiceInterfaceChangeDiff){
MServiceInterfaceChangeDiff mServiceInterfaceChangeDiff = (MServiceInterfaceChangeDiff)mServiceInterfaceDiff;
if(mServiceInterfaceChangeDiff.getParamerDiffs() != null && !mServiceInterfaceChangeDiff.getParamerDiffs().isEmpty()){
return false;
}
}
List<MDiff> mDiffs = mServiceDiff.getList();
if (!mDiffs.isEmpty()){
for (MDiff mDiff: mDiffs){
if(mDiff.getType().equals(MDiffType.INTERFACE_REQUESTMETHOD_DIFF) || mDiff.getType().equals(MDiffType.INTERFACE_FUNCTION_FEATURE_DIFF)){
return false;
}
}
}
}
if(mServiceInterfaceDiff.getMDiffInterface().equals(MDiffInterface.INTERFACE_REDUCE)){
return false;
}
}
return true;
}
/**
* to Judge which version is higher
* @param version1
* @param version2
* @return return true if version1 is higher than version2
*/
public static boolean ifHightVersion(String version1, String version2){
if(version1.equalsIgnoreCase(version2)){
return false;
}
Integer v1 = Integer.parseInt(version1.replaceAll("\\.",""));
Integer v2 = Integer.parseInt(version2.replaceAll("\\.",""));
if(v1 > v2){
return true;
}else{
return false;
}
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/exception/MethodNotAllowException.java
package com.septemberhx.common.exception;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/1/6
*/
public class MethodNotAllowException extends RuntimeException {
private String message;
public MethodNotAllowException(String msg) {
super(msg);
this.message = msg;
}
}
<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/config/Mvf4msConfig.java
package com.septemberhx.mclient.config;
import com.septemberhx.common.config.Mvf4msDep;
import com.septemberhx.common.config.Mvf4msDepConfig;
import com.septemberhx.mclient.controller.MClientController;
import com.septemberhx.mclient.utils.MGatewayRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/1
*/
@EnableConfigurationProperties
@Configuration
@ConfigurationProperties(prefix = "mvf4ms")
@Getter
@Setter
@ToString
public class Mvf4msConfig {
private String version;
private List<Mvf4msDepConfig> dependencies;
@Bean
public MClientController mClientController() {
return new MClientController();
}
@Bean
public MGatewayRequest mSendRequest(){
return new MGatewayRequest();
}
@Bean
@LoadBalanced
RestTemplate initRestTemplate() {
return new RestTemplate();
}
/*
* Please note that there may have multi dep with the same dep id for one request
*/
public List<Mvf4msDep> getDepListById(String depId) {
List<Mvf4msDep> result = new ArrayList<>();
for (Mvf4msDepConfig depConfig : this.dependencies) {
depConfig.getDepById(depId).ifPresent(result::add);
}
return result;
}
}
<file_sep>/MServiceAnalyser/src/main/java/com/ll/service/utils/GetServiceDiff.java
package com.ll.service.utils;
import com.septemberhx.common.service.*;
import com.septemberhx.common.service.diff.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Created by Lei on 2019/12/17 16:37
* @author Lei
*/
public class GetServiceDiff {
public static MServiceDiff getDiff(MService mService1, MService mService2) {
MServiceDiff mServiceDiff = new MServiceDiff();
List<MDiff> list = new ArrayList<>();
if (mService1.getServiceVersion().equals(mService2.getServiceVersion())) {
return null;
}else{
list.add(new MDiff(MDiffType.SERVICE_VERSION_DIFF,mService1.getServiceVersion(),mService2.getServiceVersion()));
}
if (mService1.getPort() != mService2.getPort()) {
list.add(new MDiff(MDiffType.SERVICE_PORT_DIFF,mService1.getPort(),mService2.getPort()));
}
if (!mService1.getGitUrl().equals(mService2.getGitUrl())) {
list.add(new MDiff(MDiffType.SERVICE_PATH_DIFF,mService1.getGitUrl(),mService2.getGitUrl()));
}
if (!mService1.getServiceName().equals(mService2.getServiceName())) {
list.add(new MDiff(MDiffType.SERVICE_NAME_DIFF,mService1.getServiceName(),mService2.getServiceName()));
}
mServiceDiff.setList(list);
List<MServiceInterfaceDiff> mServiceInterfaceDiffs = new ArrayList<>();
List<MSvcInterface> shareversion1 = new ArrayList<>();
List<MSvcInterface> shareversion2 = new ArrayList<>();
Set<String> set1 = mService1.getServiceInterfaceMap().keySet();
Set<String> set2 = mService2.getServiceInterfaceMap().keySet();
for (String string : set1) {
if (set2.contains(string)) {
shareversion1.add(mService1.getServiceInterfaceMap().get(string));
shareversion2.add(mService2.getServiceInterfaceMap().get(string));
set2.remove(string);
} else {
// verison1 独有
MServiceInterfaceNumDiff mServiceInterfaceNumDiff = new MServiceInterfaceNumDiff(MDiffInterface.INTERFACE_REDUCE);
mServiceInterfaceNumDiff.setMSvcInterface(mService1.getServiceInterfaceMap().get(string));
mServiceInterfaceDiffs.add(mServiceInterfaceNumDiff);
}
}
// version2 独有
for (String string : set2) {
MServiceInterfaceNumDiff mServiceInterfaceNumDiff = new MServiceInterfaceNumDiff(MDiffInterface.INTERFACE_ADD);
mServiceInterfaceNumDiff.setMSvcInterface(mService2.getServiceInterfaceMap().get(string));
mServiceInterfaceDiffs.add(mServiceInterfaceNumDiff);
}
set1.clear();
set2.clear();
List<MServiceInterfaceDiff> m = getInterfaceDiff(shareversion1, shareversion2);
mServiceInterfaceDiffs.addAll(m);
mServiceDiff.setMServiceInterfaceDiffs(mServiceInterfaceDiffs);
return mServiceDiff;
}
public static List<MServiceInterfaceDiff> getInterfaceDiff(List<MSvcInterface> shareversion1, List<MSvcInterface> shareversion2) {
List<MServiceInterfaceDiff> list = new ArrayList<>();
int size = shareversion1.size();
for (int i = 0; i < size; i++) {
MServiceInterfaceChangeDiff mServiceInterfaceChangeDiff = new MServiceInterfaceChangeDiff(MDiffInterface.INTERFACE_CHANGE);
mServiceInterfaceChangeDiff.setPathUrl(shareversion1.get(i).getPatternUrl());
List<MDiff> mDiffs = new ArrayList<>();
if (!shareversion1.get(i).getFunctionName().equals(shareversion2.get(i).getFunctionName())) {
mDiffs.add(new MDiff(MDiffType.INTERFACE_METHEDNAME_DIFF,shareversion1.get(i).getFunctionName(),shareversion2.get(i).getFunctionName()));
}
if (!shareversion1.get(i).getRequestMethod().equals(shareversion2.get(i).getRequestMethod())) {
mDiffs.add(new MDiff(MDiffType.INTERFACE_REQUESTMETHOD_DIFF,shareversion1.get(i).getRequestMethod(),shareversion2.get(i).getRequestMethod()));
}
if (!shareversion1.get(i).getReturnType().equals(shareversion2.get(i).getReturnType())) {
mDiffs.add(new MDiff(MDiffType.INTERFACE_RETURNTYPE_DIFF,shareversion1.get(i).getReturnType(),shareversion2.get(i).getReturnType()));
}
if (!shareversion1.get(i).getFuncDescription().getFunc().equals(shareversion2.get(i).getFuncDescription().getFunc())) {
mDiffs.add(new MDiff(MDiffType.INTERFACE_FUNCTION_FEATURE_DIFF,shareversion1.get(i).getFuncDescription().getFunc(),shareversion2.get(i).getFuncDescription().getFunc()));
}
if (shareversion1.get(i).getFuncDescription().getSla() != shareversion2.get(i).getFuncDescription().getSla()) {
mDiffs.add(new MDiff(MDiffType.INTERFACE_FUNCTION_LEVEL_DIFF,shareversion1.get(i).getFuncDescription().getSla(),shareversion2.get(i).getFuncDescription().getSla()));
}
mServiceInterfaceChangeDiff.setList(mDiffs);
List<MParamerDiff> paramerDiffs = getParamerDiff(shareversion1.get(i), shareversion2.get(i));
mServiceInterfaceChangeDiff.setParamerDiffs(paramerDiffs);
if(!mDiffs.isEmpty() || !paramerDiffs.isEmpty()){
list.add(mServiceInterfaceChangeDiff);
}
}
if(list.isEmpty()){
return null;
}
return list;
}
public static List<MParamerDiff> getParamerDiff(MSvcInterface mSvcInterface1, MSvcInterface mSvcInterface2) {
List<MParamerDiff> list = new ArrayList<>();
List<MParamer> interfaceversion1 = mSvcInterface1.getParams();
List<MParamer> interfaceversion2 = mSvcInterface2.getParams();
List<MParamer> all1 = new ArrayList<>();
List<MParamer> all2 = new ArrayList<>();
for (int i = 0; i < interfaceversion1.size(); i++) {
for (int j = 0; j < interfaceversion2.size(); j++) {
if (interfaceversion1.get(i).getName().equals(interfaceversion2.get(j).getName())) {
all1.add(interfaceversion1.get(i));
all2.add(interfaceversion2.get(j));
}
}
}
interfaceversion1.removeAll(all1);
interfaceversion2.removeAll(all2);
for (int i = 0; i < all1.size(); i++) {
MParamerChangeDiff mParamerChangeDiff = new MParamerChangeDiff(MDiffParamer.PARAMER_CHANGE);
List<MDiff> mDiffs = new ArrayList<>();
if (!all1.get(i).toString().equals(all2.get(i).toString())) {
mParamerChangeDiff.setParamerName(all1.get(i).getName());
if (!all1.get(i).getRequestname().equals(all2.get(i).getRequestname())) {
mDiffs.add(new MDiff(MDiffType.PARAMER_REQUESTNAME_DIFF,all1.get(i).getRequestname(),all2.get(i).getRequestname()));
}
if (!all1.get(i).getType().equals(all2.get(i).getType())) {
mDiffs.add(new MDiff(MDiffType.PARAMER_TYPE_DIFF,all1.get(i).getType(),all2.get(i).getType()));
}
if (!all1.get(i).getMethod().equals(all2.get(i).getMethod())) {
mDiffs.add(new MDiff(MDiffType.PARAMER_REQUESTMETHOD_DIFF,all1.get(i).getRequestname(),all2.get(i).getRequestname()));
}
if (!all1.get(i).getDefaultObject().equals(all2.get(i).getDefaultObject())) {
mDiffs.add(new MDiff(MDiffType.PARAMER_DEFAULT_DIFF,all1.get(i).getDefaultObject(),all2.get(i).getDefaultObject()));
}
}
list.add(mParamerChangeDiff);
}
for (int i = 0; i < interfaceversion1.size(); i++) {
MParamerNumDiff mParamerNumDiff = new MParamerNumDiff(MDiffParamer.PARAMER_REDUCE);
mParamerNumDiff.setMParamer(interfaceversion1.get(i));
list.add(mParamerNumDiff);
}
for (int i = 0; i < interfaceversion2.size(); i++) {
MParamerNumDiff mParamerNumDiff = new MParamerNumDiff(MDiffParamer.PARAMER_ADD);
mParamerNumDiff.setMParamer(interfaceversion2.get(i));
list.add(mParamerNumDiff);
}
return list;
}
}
<file_sep>/MOrchestrationServer/Dockerfile
FROM openjdk:8-jre-alpine
MAINTAINER SeptemberHX
ADD target/MOrchestrationServer-1.0-SNAPSHOT.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","app.jar"]<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/model/MSvcDepManager.java
package com.septemberhx.server.model;
import com.septemberhx.common.service.dependency.BaseSvcDependency;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/3/3
*/
public class MSvcDepManager {
// Map[service Id, List[dependency]]
Map<String, List<BaseSvcDependency>> depMap;
private MSvcDepManager() {
this.depMap = new HashMap<>();
}
public List<BaseSvcDependency> getDependenciesBySvcId(String serviceId) {
List<BaseSvcDependency> result = new ArrayList<>();
if (depMap.containsKey(serviceId)) {
result.addAll(depMap.get(serviceId));
}
return result;
}
public void updateDependenciesBySvcId(String svcId, List<BaseSvcDependency> deps) {
this.depMap.put(svcId, deps);
}
}
<file_sep>/MOrchestrationServer/src/main/java/com/septemberhx/server/client/ConnectToClient.java
package com.septemberhx.server.client;
import com.netflix.appinfo.InstanceInfo;
import com.septemberhx.common.bean.agent.MDeployPodRequest;
import com.septemberhx.common.bean.agent.MInstanceInfoBean;
import com.septemberhx.common.bean.agent.MInstanceInfoResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.*;
/**
* @Author Lei
* @Date 2020/3/16 14:56
* @Version 1.0
*/
@Component
public class ConnectToClient {
private RestTemplate restTemplate = new RestTemplate();
private String clusterIp = "172.16.31.10";
private String clusterPort = "46832";
public List<ServiceInstance> lookup(String serviceId){
List<ServiceInstance> list = new ArrayList<>();
return Arrays.asList(restTemplate.getForObject("http://"+clusterIp+":"+clusterPort+"/lookup/"+serviceId,ServiceInstance[].class));
}
public List<InstanceInfo> getallinstance(){
return Arrays.asList(restTemplate.getForObject("http://"+clusterIp+":"+clusterPort+"/instanceInfoList1",InstanceInfo[].class));
}
public List<MInstanceInfoBean> getAllMintancesInfo(){
MInstanceInfoResponse mInstanceInfoResponse = restTemplate.getForObject("http://"+clusterIp+":"+clusterPort+"/instanceInfoList",MInstanceInfoResponse.class);
return mInstanceInfoResponse.getInfoBeanList();
}
public void deploy(MDeployPodRequest mDeployPodRequest){
HttpHeaders requestHeaders = new HttpHeaders();
HttpEntity<Object> paramers = new HttpEntity<>(mDeployPodRequest,requestHeaders);
restTemplate.postForLocation("http://"+clusterIp+":"+clusterPort+"/magent/deploy",paramers);
}
public void register(MDeployPodRequest mDeployPodRequest){
HttpHeaders requestHeaders = new HttpHeaders();
HttpEntity<Object> paramers = new HttpEntity<>(mDeployPodRequest,requestHeaders);
restTemplate.postForLocation("http://"+clusterIp+":"+clusterPort+"/magent/register",paramers);
}
public void deleteInstance(String dockerInstanceId){
restTemplate.delete("http://"+clusterIp+":"+clusterPort+"/magent/deleteInstance?dockerInstanceId="+dockerInstanceId);
}
public Map<String,String> getAllNodeLabel(){
return restTemplate.getForObject("http://"+clusterIp+":"+clusterPort+"/magent/getAllNodeLable",Map.class);
}
}
<file_sep>/common/src/main/java/com/septemberhx/common/service/MSla.java
package com.septemberhx.common.service;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Objects;
/**
* @author SeptemberHX
* @version 0.1
* @date 2020/2/29
*
* Service Leverage Agreement for users and services
*
* This class is created for possible future extension
*/
@Getter
@Setter
@ToString
public class MSla {
private int level;
public MSla(int level) {
this.level = level;
}
public MSla(){
}
@Override
public String toString() {
return "MSla{" +
"level=" + level +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MSla mSla = (MSla) o;
return level == mSla.level;
}
@Override
public int hashCode() {
return Objects.hash(level);
}
}
<file_sep>/MEurekaServer/Readme.md
# MEurekaServer
定制版本的 eureka 服务,相较于原版,做出下列改动:
* 当一个服务实例的状态发生变化(上线、下线等)时,向 `MClusterAgent` 发送该服务实例的相关信息,类型为`MInstanceRegisterNotifyRequest`
## 使用
* `kubectl apply -f ./eureka-server.yaml` 即可,NodePort为 **30761**<file_sep>/common/src/main/java/com/septemberhx/common/bean/agent/MAllUserBean.java
package com.septemberhx.common.bean.agent;
import com.septemberhx.common.base.user.MUser;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author SeptemberHX
* @version 0.1
* @date 2019/11/23
*/
@Getter
@Setter
public class MAllUserBean {
private List<MUser> allUserList;
public MAllUserBean(List<MUser> allUserList) {
this.allUserList = allUserList;
}
public MAllUserBean() {
}
}
<file_sep>/MClientFramework/src/main/java/com/septemberhx/mclient/base/MResource.java
package com.septemberhx.mclient.base;
import com.septemberhx.mclient.utils.StringUtils;
/**
* @Author: septemberhx
* @Date: 2018-12-09
* @Version 0.1
*/
public class MResource extends MObject {
public MResource() {
if (this.getId() == null) {
this.setId(StringUtils.generateMResourceId());
}
}
}
| 21ca26dabb9029873af227d4a67e8e01329a4b07 | [
"SQL",
"Markdown",
"Java",
"Dockerfile",
"Shell"
] | 81 | Java | HITliulei/MSystemEvolution | fb3da4351d5d77b37e03c5cafb6d58d44a24265f | b34089e0fab052d228f002fc8b0f79d42c053d2b |
refs/heads/master | <repo_name>doughbryce/tutoring<file_sep>/main.js
// Functions
// Driver code | b1a79c0fcecbe198b15cb4039db8975bdffcf09b | [
"JavaScript"
] | 1 | JavaScript | doughbryce/tutoring | e6fe9ad2236a6e93d4ceaee4d947c99de5a52785 | 24197542101d834d2a9733f42bf721926403093e |
refs/heads/master | <file_sep>// AsyncIO.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "99-MySample.h"
#define CK_READ 1
#define CK_WRITE 2
#define BUFFSIZE (64 * 1000) // The size of an I/O buffer
HANDLE g_hIoCompletionPort;
void DoRegularReadAndWrite()
{
HANDLE writeFileHandle = CreateFile(
L"C:\\AWD\\something.txt",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
CHAR buffer[] = {'H','I',' ', 'Y','O','N','G'};
WriteFile(writeFileHandle, buffer, sizeof(buffer), NULL, NULL);
CloseHandle(writeFileHandle);
}
void DoDifferentAllocations()
{
//Virtual memory allocation, the most low level - reserve, commit, decommit, release.
{
void* pMemory = VirtualAlloc(NULL, 1024 * 1025 * 50, MEM_COMMIT, PAGE_READWRITE);
CHAR* pChar = (CHAR*)pMemory;
*pChar = 'A';
*(pChar + 1) = 'B';
VirtualFree(pMemory, 0, MEM_RELEASE);
}
{
void* pMemory = VirtualAlloc(NULL, 1024 * 1025 * 50, MEM_RESERVE, PAGE_READWRITE);
VirtualAlloc(pMemory, 1, MEM_COMMIT, PAGE_READWRITE);
CHAR* pChar = (CHAR*)pMemory;
*pChar = 'A';
*(pChar + 1) = 'B';
*(pChar + 4095) = 'B';
//*(pChar + 4096) = 'B';
VirtualFree(pMemory, 0, MEM_RELEASE);
}
// Using HeapAlloc
{
HANDLE myHeap = HeapCreate(0, 0, 0);
void* pMem = HeapAlloc(myHeap, 0, 2);
char* pChar = (char*)pMem;
*pChar = 1;
*(pChar + 1) = 2;
void* pMemRealloc = HeapReAlloc(myHeap, 0, pMem, 10000);
char* pChar2 = (char*)pMemRealloc;
HeapFree(myHeap, 0, pMemRealloc);
char* pChar3 = (char*)pMemRealloc;
HeapDestroy(myHeap);
}
// C - malloc, realloc and free
{
BYTE byteArray[20];
UINT size = sizeof(byteArray);
void* pMemory = malloc(size);
void* pMemory2 = realloc(pMemory, 40);
free(pMemory2);
}
// C++ - New and delete
{
int *pInt = new int;
*pInt = 2;
delete pInt;
int *pInts = new int[10];
*pInt = 1;
*(pInt + 1) = 2;
*(pInt + 2) = 3;
int i = *pInt;
int i2 = *(pInt + 1);
int i3 = *(pInt + 2);
delete[] pInts;
}
}
// Each I/O Request needs an OVERLAPPED structure and a data buffer
class CIOReq : public OVERLAPPED {
public:
CIOReq() {
Internal = InternalHigh = 0;
Offset = OffsetHigh = 0;
hEvent = NULL;
m_nBuffSize = 0;
m_pvData = NULL;
}
~CIOReq() {
if (m_pvData != NULL)
VirtualFree(m_pvData, 0, MEM_RELEASE);
}
BOOL AllocBuffer(SIZE_T nBuffSize) {
m_nBuffSize = nBuffSize;
m_pvData = VirtualAlloc(NULL, m_nBuffSize, MEM_COMMIT, PAGE_READWRITE);
CHAR* pChar = (CHAR*)m_pvData;
*pChar = 'A';
return(m_pvData != NULL);
}
BOOL Read(HANDLE hDevice, PLARGE_INTEGER pliOffset = NULL) {
if (pliOffset != NULL) {
Offset = pliOffset->LowPart;
OffsetHigh = pliOffset->HighPart;
}
return(::ReadFile(hDevice, m_pvData, m_nBuffSize, NULL, this));
}
BOOL Write(HANDLE hDevice, PLARGE_INTEGER pliOffset = NULL) {
if (pliOffset != NULL) {
Offset = pliOffset->LowPart;
OffsetHigh = pliOffset->HighPart;
}
return(::WriteFile(hDevice, m_pvData, m_nBuffSize, NULL, this));
}
PVOID GetData()
{
return m_pvData;
}
private:
SIZE_T m_nBuffSize;
PVOID m_pvData;
};
WCHAR* pszWindowClassName = L"MyWindowClass";
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
DWORD WINAPI ThreadPoc(LPVOID lpParam);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MY99MYSAMPLE));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDI_MY99MYSAMPLE);
wcex.lpszClassName = pszWindowClassName;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
RegisterClassExW(&wcex);
HWND hWnd = CreateWindowW(pszWindowClassName, L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
DoDifferentAllocations();
DoRegularReadAndWrite();
g_hIoCompletionPort = CreateIoCompletionPort(
INVALID_HANDLE_VALUE, NULL, 0, 0);
CreateThread(NULL, 0, ThreadPoc, NULL, 0, NULL);
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_KEYDOWN:
{
if (wParam == 'R')
{
HANDLE hFile = CreateFile(L"C:\\AWD\\something.txt", GENERIC_WRITE,
0, NULL, CREATE_ALWAYS,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, NULL);
CreateIoCompletionPort(hFile, g_hIoCompletionPort, CK_WRITE, 0);
CIOReq* pIOReq = new CIOReq();
pIOReq->AllocBuffer(BUFFSIZE);
CHAR* pChar = (CHAR*)(pIOReq->GetData());
*pChar = 'A';
*(pChar + 1) = 'B';
pIOReq->Write(hFile);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
DWORD WINAPI ThreadPoc(LPVOID lpParam)
{
ULONG_PTR CompletionKey;
DWORD dwNumBytes;
CIOReq* pior;
GetQueuedCompletionStatus(
g_hIoCompletionPort,
&dwNumBytes,
&CompletionKey,
(OVERLAPPED**)&pior,
INFINITE);
if (CompletionKey == CK_WRITE)
{
CloseHandle(g_hIoCompletionPort);
}
return S_OK;
} | 23dfe0fa36608a164f79b52480c1d6d6911f0b84 | [
"C++"
] | 1 | C++ | ychung25/WindCode | 5e92b08894bc42aac47bdeaa596944af2a973bbb | 769978af74e686c5986ebf85483f0fbbab37b76d |
refs/heads/master | <repo_name>SimonTsou/HCF-LCM<file_sep>/app/src/main/java/com/example/demo_faspro/ShowResultActivity.java
package com.example.demo_faspro;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ShowResultActivity extends AppCompatActivity {
private TextView hcf;
private TextView lcm;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_result);
this.button = findViewById(R.id.backButton);
this.hcf = findViewById(R.id.hcf);
this.lcm = findViewById(R.id.lcm);
}
@Override
protected void onResume() {
super.onResume();
int input1 = getIntent().getBundleExtra("bundle").getInt("input1");
int input2 = getIntent().getBundleExtra("bundle").getInt("input2");
int calculatedHCF = getHCF(input1, input2);
this.hcf.append(String.valueOf(calculatedHCF));
this.lcm.append(String.valueOf(input1 * input2 / calculatedHCF));
this.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShowResultActivity.this.onBackPressed();
}
});
}
private int getHCF(int a, int b) {
int r = a % b;
if(r == 0) {
return b;
} else {
return getHCF(b, r);
}
}
}
<file_sep>/app/src/main/java/com/example/demo_faspro/MainActivity.java
package com.example.demo_faspro;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText inputNum1;
private EditText inputNum2;
private Intent intent;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.button = findViewById(R.id.commit);
this.inputNum1 = findViewById(R.id.inputNum1);
this.inputNum2 = findViewById(R.id.inputNum2);
this.intent = new Intent(MainActivity.this, ShowResultActivity.class);
this.bundle = new Bundle();
}
@Override
protected void onResume() {
super.onResume();
this.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(MainActivity.this.inputNum1.getText().toString().isEmpty() ||
MainActivity.this.inputNum2.getText().toString().isEmpty()) {
return;
}
if(MainActivity.this.inputNum1.getText().toString().equals("0") ||
MainActivity.this.inputNum2.getText().toString().equals("0")) {
Toast.makeText(MainActivity.this, "輸入不能為0", Toast.LENGTH_SHORT).show();
return;
}
MainActivity.this.bundle.putInt
("input1", Integer.parseInt(MainActivity.this.inputNum1.getText().toString()));
MainActivity.this.bundle.putInt
("input2", Integer.parseInt(MainActivity.this.inputNum2.getText().toString()));
MainActivity.this.intent.putExtra("bundle", MainActivity.this.bundle);
MainActivity.this.startActivity(MainActivity.this.intent);
}
});
}
}
| c6086e2570656337df9f8184cbf728a0ff7c4f6f | [
"Java"
] | 2 | Java | SimonTsou/HCF-LCM | 11436208721992e21ef51c8ad9eb739b56b8d829 | 2a45796d8e324842761bfb8d162f5c57828b45a9 |
refs/heads/master | <repo_name>NeverSettels/lab-passport-roles<file_sep>/starter-code/routes/adminRoutes.js
const { Router } = require('express')
const router = Router()
const { findUsers, deleteUser } = require('../controllers/adminControllers')
router.get('/ironhack', findUsers)
router.get('/ironhack/:id/delete', deleteUser)
module.exports = router
<file_sep>/starter-code/routes/authRoutes.js
const passport = require('../middlewares/passport')
const { Router } = require('express')
const router = Router()
const { getLogin, getSignup, logout, postSignup, postLogin } = require('../controllers/authControllers')
router.get('/signup', getSignup)
router.post('/signup', postSignup)
router.get('/login', getLogin)
router.post('/login', passport.authenticate('local'), postLogin)
router.get('/logout', logout)
module.exports = router
| 60df9837d2cb108618985f92ebc788a6f3219f2a | [
"JavaScript"
] | 2 | JavaScript | NeverSettels/lab-passport-roles | e422278213b12f646944bf93e74b9304d8f28f30 | ca348459f724a1971122e74f41d6d36877c62c0e |
refs/heads/master | <file_sep>package com.example.deeplearningstudio;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class AdopterListView extends RecyclerView.Adapter<AdopterListView.ViewHolder> {
public JSONArray projData;
public AdopterListView(JSONArray projectData) {
projData = projectData;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.project_list_view, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
JSONObject temp = null;
try {
temp = projData.getJSONObject(position);
holder.projectName.setText(temp.getString("name"));
holder.projectDes.setText(temp.getString("domain"));
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Log.d("RecyclerView", "onClick:" + getAdapterPosition());
Intent intent = new Intent(holder.cardView.getContext(), BottomNavigationMenu.class);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
try {
bundle.putString("projectID", projData.getJSONObject(position).getString("_id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Add the bundle to the intent
intent.putExtras(bundle);
holder.cardView.getContext().startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return projData.length();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView projectDes, projectName;
CardView cardView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
this.projectDes = itemView.findViewById(R.id.projectDes);
this.projectName = itemView.findViewById(R.id.projectName);
cardView = (CardView) itemView.findViewById(R.id.cardView);
}
@Override
public void onClick(View v) {
}
}
}
<file_sep>package com.example.deeplearningstudio;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
//private static final String SERVER = "http://10.0.2.2:3000/getColumns?project=6082add3e3255e30dcf844f6";
private static final String SERVER = "http://10.0.2.2:3000/signin";
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
HttpPostRequest postRequest = new HttpPostRequest();
JSONObject post_dict = new JSONObject();
try {
post_dict.put("email" , "tskjabdks");
post_dict.put("password", "abc");
} catch (JSONException e) {
e.printStackTrace();
}
if (post_dict.length() > 0) {
result = postRequest.execute(SERVER, String.valueOf(post_dict)).get();
//call to async class
}
//result = getRequest.execute(SERVER, ).get();
System.out.println(result);
}catch(Exception e) {
e.printStackTrace();
}
}
}<file_sep>package com.example.deeplearningstudio;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
public class LabelsInfoAdapter extends RecyclerView.Adapter<LabelsInfoAdapter.ViewHolder>{
JSONArray labels_data;
public LabelsInfoAdapter(JSONArray label_data){
labels_data = label_data;
}
@NonNull
@NotNull
@Override
public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.col_labels_info, parent, false);
LabelsInfoAdapter.ViewHolder viewHolder = new LabelsInfoAdapter.ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) {
try {
JSONArray temp = labels_data.getJSONArray(position);
Log.d("Labels Data", temp.getString(0));
holder.label_name.setText(temp.getString(0));
holder.label_count.setText(temp.getString(1));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return labels_data.length();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView label_name;
TextView label_count;
public ViewHolder(@NonNull View itemView) {
super(itemView);
label_name = itemView.findViewById(R.id.label_name);
label_count = itemView.findViewById(R.id.label_count);
}
}
}
<file_sep>package com.example.deeplearningstudio;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.koushikdutta.ion.Ion;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class ModelFragment extends Fragment {
String projectID;
RecyclerView recyclerView;
ModelLayersAdapter recyclerAdapter;
EditText epoch, learning_rate;
Spinner batch_size, loss_function, optimizer, categorize_output, column_name;
Button train_butt, new_layer_butt, save_model_butt, save_hyperparameters_butt, export_model;
TextView training_logs_view, train_accuracy_val, test_accuracy_val, no_layers_text, training_percent, testing_percent;
LinearLayout results_layout;
ImageView accuracy_img, loss_img;
SeekBar seekBar;
private Socket mSocket;
ArrayList<JSONObject> layers = new ArrayList<JSONObject>();
public ModelFragment(String projID) {
projectID = projID;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_model, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
epoch = (EditText) view.findViewById(R.id.epoch);
learning_rate = (EditText) view.findViewById(R.id.learning_rate);
batch_size = (Spinner) view.findViewById(R.id.batch_size);
loss_function = (Spinner) view.findViewById(R.id.loss_function);
optimizer = (Spinner) view.findViewById(R.id.optimizer);
categorize_output = (Spinner) view.findViewById(R.id.categorize_output);
column_name = (Spinner) view.findViewById(R.id.column_name);
train_butt = (Button) view.findViewById(R.id.train_butt);
new_layer_butt = (Button) view.findViewById(R.id.new_layer_butt);
training_logs_view = (TextView) view.findViewById(R.id.training_logs_view);
results_layout = (LinearLayout) view.findViewById(R.id.results_layout);
accuracy_img = (ImageView) view.findViewById(R.id.plot_img_accuracy);
loss_img = (ImageView) view.findViewById(R.id.plot_img_loss);
test_accuracy_val = (TextView) view.findViewById(R.id.test_accuracy_val);
train_accuracy_val = (TextView) view.findViewById(R.id.train_accuracy_val);
save_model_butt = (Button) view.findViewById(R.id.save_changes_layers);
save_hyperparameters_butt = (Button) view.findViewById(R.id.save_changes_hyperparamter);
no_layers_text = (TextView)view.findViewById(R.id.no_layers_text);
seekBar = (SeekBar) view.findViewById(R.id.seekBar);
training_percent = (TextView) view.findViewById(R.id.trainingPercent);
testing_percent = (TextView) view.findViewById(R.id.testingPercent);
export_model = (Button) view.findViewById(R.id.export_model);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
testing_percent.setText("" + progress + "%");
training_percent.setText("" + (100 - progress) + "%");
if(progress < 50){
training_percent.setText("50%");
seekBar.setProgress(50);
}
else if(progress > 90){
seekBar.setProgress(90);
testing_percent.setText("90%");
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
save_model_butt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONArray data_to_send = null;
data_to_send = new JSONArray(recyclerAdapter.layers);
String url = getResources().getString(R.string.server_url) + "saveModel?project=" + projectID;
SaveModel req = new SaveModel();
req.execute(url, String.valueOf(data_to_send));
}
});
save_hyperparameters_butt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONObject hyperparameters = new JSONObject();
try {
hyperparameters.put("epoch", epoch.getText().toString());
hyperparameters.put("learningRate", learning_rate.getText().toString());
hyperparameters.put("batchSize", batch_size.getSelectedItem().toString());
hyperparameters.put("lossFunction", loss_function.getSelectedItem().toString());
hyperparameters.put("optimizer", optimizer.getSelectedItem().toString());
hyperparameters.put("categorize_output", categorize_output.getSelectedItem().toString());
hyperparameters.put("output_coulmn", column_name.getSelectedItem().toString());
hyperparameters.put("validation_split", seekBar.getProgress());
} catch (JSONException e) {
e.printStackTrace();
}
String url = getResources().getString(R.string.server_url) + "saveHyperparameter?project=" + projectID;
SaveHyperparameters req = new SaveHyperparameters();
req.execute(url, String.valueOf(hyperparameters));
}
});
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
train_butt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONObject data_to_send = new JSONObject();
if (recyclerAdapter.layers.isEmpty()){
Toast.makeText(getActivity(), "No Layer exists in the model to train", Toast.LENGTH_SHORT).show();
}else if (column_name.getSelectedItem().toString().equals("Select Column")){
Toast.makeText(getActivity(), "You must select the Output column before training", Toast.LENGTH_SHORT).show();
}else{
try {
data_to_send.put("layers", new JSONArray(recyclerAdapter.layers));
JSONObject hyperparameters = new JSONObject();
hyperparameters.put("epoch", epoch.getText().toString());
hyperparameters.put("learningRate", learning_rate.getText().toString());
hyperparameters.put("batchSize", batch_size.getSelectedItem().toString());
hyperparameters.put("lossFunction", loss_function.getSelectedItem().toString());
hyperparameters.put("optimizer", optimizer.getSelectedItem().toString());
hyperparameters.put("categorize_output", categorize_output.getSelectedItem().toString());
hyperparameters.put("output_coulmn", column_name.getSelectedItem().toString());
hyperparameters.put("validation_split", seekBar.getProgress());
data_to_send.put("hyperparameters", hyperparameters);
String url = getResources().getString(R.string.server_url) + "generatemodel?project=" + projectID;
TrainModel req = new TrainModel();
train_butt.setEnabled(false);
req.execute(url, String.valueOf(data_to_send));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
new_layer_butt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NewLayerDialog dialog = new NewLayerDialog(getActivity());
dialog.show();
}
});
export_model.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GetCode req = new GetCode();
String url = getResources().getString(R.string.server_url)+"getModelCode?project=" + projectID;
req.execute(url);
}
});
GetColumns request = new GetColumns();
String url = getResources().getString(R.string.server_url) + "getColumns?project=" + projectID;
request.execute(url);
}
private class ModelLayersAdapter extends RecyclerView.Adapter<ModelLayersAdapter.ViewHolder> {
ArrayList<JSONObject> layers;
public ModelLayersAdapter(ArrayList<JSONObject> layers) {
this.layers = layers;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.model_swapable_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
try {
String layer_name = layers.get(position).getString("layerName");
holder.textView.setText(layer_name);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return layers.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.layerName);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
JSONObject layer_data = layers.get(getAdapterPosition());
EditLayerDialog dialog = new EditLayerDialog(getActivity(), layer_data, getAdapterPosition());
dialog.show();
}
}
}
private class HttpRequest extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
System.out.println("Project Response " + response);
try {
JSONObject obj = new JSONObject(response);
JSONArray layer_temp = obj.getJSONObject("data").getJSONArray("layers");
for (int i = 0; i < layer_temp.length(); i++) {
layers.add(layer_temp.getJSONObject(i));
}
recyclerAdapter = new ModelLayersAdapter(layers);
recyclerView.setAdapter(recyclerAdapter);
if (layers.isEmpty()){
no_layers_text.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else{
JSONObject hyperparameters = obj.getJSONObject("data").getJSONObject("hyperparameters");
epoch.setText(Integer.toString(hyperparameters.getInt("epoch")));
learning_rate.setText(Double.toString(hyperparameters.getDouble("learningRate")));
batch_size.setSelection(((ArrayAdapter) batch_size.getAdapter()).getPosition(hyperparameters.getString("batchSize")));
loss_function.setSelection(((ArrayAdapter) loss_function.getAdapter()).getPosition(hyperparameters.getString("lossFunction")));
optimizer.setSelection(((ArrayAdapter) optimizer.getAdapter()).getPosition(hyperparameters.getString("optimizer")));
categorize_output.setSelection(((ArrayAdapter) categorize_output.getAdapter()).getPosition(hyperparameters.getString("categorize_output")));
seekBar.setProgress(hyperparameters.getInt("validation_split"));
column_name.setSelection(((ArrayAdapter) column_name.getAdapter()).getPosition(hyperparameters.getString("output_coulmn")));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END, 0) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
Collections.swap(recyclerAdapter.layers, fromPosition, toPosition);
recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetColumns extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("In Background: " + result);
return result;
}
@Override
protected void onPostExecute(String response) {
System.out.println("Columns List Response: " + response);
try {
JSONObject obj = new JSONObject(response);
JSONArray columns = obj.getJSONArray("columns");
ArrayList<String> columns_list = new ArrayList<String>();
columns_list.add("Select Column");
for (int i = 0; i < columns.length(); i++) {
columns_list.add(columns.getString(i));
}
System.out.println("List: " + columns_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, columns_list);
column_name.setAdapter(adapter);
HttpRequest req = new HttpRequest();
String url = getResources().getString(R.string.server_url) + "getModelInfo?project=" + projectID;
req.execute(url);
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(response);
}
}
private class TrainModel extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 60000;
static final int CONNECTION_TIMEOUT = 60000;
static final String COOKIES_HEADER = "Set-Cookie";
@Override
protected void onPreExecute() {
super.onPreExecute();
training_logs_view.setText("Training...");
}
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
String JsonData = params[1];
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(JsonData);
// json data
writer.close();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
training_logs_view.setText(training_logs_view.getText().toString()+"\nTraining Complete");
export_model.setVisibility(View.VISIBLE);
train_butt.setEnabled(true);
try {
JSONObject obj = new JSONObject(response);
String accuracy_img_url = obj.getJSONObject("data").getString("model_accuracy_img");
String loss_img_url = obj.getJSONObject("data").getString("model_loss_img");
String test_accuracy =obj.getJSONObject("data").getString("model_test_accuracy");
String train_accuracy =obj.getJSONObject("data").getString("model_accuracy");
results_layout.setVisibility(View.VISIBLE);
train_accuracy_val.setText(train_accuracy_val.getText().toString()+train_accuracy);
test_accuracy_val.setText(test_accuracy_val.getText().toString()+test_accuracy);
Ion.with(accuracy_img)
.error(R.drawable.app_logo)
.load(getResources().getString(R.string.server_url)+accuracy_img_url);
Ion.with(loss_img)
.error(R.drawable.app_logo)
.load(getResources().getString(R.string.server_url)+loss_img_url);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(response);
}
}
private class SaveModel extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(getContext(), "Saving Model",
"Saving Model. Please wait...", true);
dialog.setCancelable(false);
}
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
String JsonData = params[1];
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("POST");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(JsonData);
// json data
writer.close();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
dialog.dismiss();
System.out.println(response);
}
}
private class SaveHyperparameters extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(getContext(), "Saving Model",
"Saving Model. Please wait...", true);
dialog.setCancelable(false);
}
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
String JsonData = params[1];
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("POST");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(JsonData);
// json data
writer.close();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
dialog.dismiss();
System.out.println(response);
}
}
private class GetCode extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(getActivity(), "Getting Code",
"Fetching Model Code. Please wait...", true);
dialog.setCancelable(false);
}
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
System.out.println("Project Code: " + response);
dialog.dismiss();
try {
JSONObject resp = new JSONObject(response);
String code = resp.getString("data");
ExportModelDialog exp_dialog = new ExportModelDialog(getActivity(), code);
exp_dialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(response);
}
}
private class NewLayerDialog extends Dialog {
private Spinner layer_name, dense_activation, lstm_activation, lstm_return_sequence, lstm_recurrent_activation;
private LinearLayout dense_layer_layout, dropout_layer_layout, lstm_layer_layout;
private Button add_button, cancel_button;
private EditText dense_units, dropout_dropout_rate, lstm_units, lstm_dropout_rate;
public NewLayerDialog(Activity a) {
super(a);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.deep_learning_model_new_layer);
dense_layer_layout = (LinearLayout) findViewById(R.id.denseLayout);
dropout_layer_layout = (LinearLayout) findViewById(R.id.dropoutLayout);
lstm_layer_layout = (LinearLayout) findViewById(R.id.lstmLayout);
add_button = (Button) findViewById(R.id.add_button);
cancel_button = (Button) findViewById(R.id.cancel_button);
dense_units = (EditText) findViewById(R.id.inputDenseUnits);
dense_activation = (Spinner) findViewById(R.id.spinnerDenseActivationFunction);
dropout_dropout_rate = (EditText) findViewById(R.id.inputDropoutRate);
lstm_activation = (Spinner) findViewById(R.id.spinnerLSTMActivation);
lstm_units = (EditText) findViewById(R.id.inputLSTMUnits);
lstm_return_sequence = (Spinner) findViewById(R.id.spinnerReturnSequence);
lstm_dropout_rate = (EditText) findViewById(R.id.inputLSTMDropout);
lstm_recurrent_activation = (Spinner) findViewById(R.id.spinnerLSTM_RAF);
layer_name = (Spinner) findViewById(R.id.spinnerLayerName);
cancel_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String layer = layer_name.getSelectedItem().toString();
JSONObject new_layer_params = new JSONObject();
if (layer.equals("Dense")) {
try {
new_layer_params.put("layerName", "Dense");
new_layer_params.put("units", Integer.parseInt(dense_units.getText().toString()));
new_layer_params.put("activationFunction", dense_activation.getSelectedItem().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} else if (layer.equals("Dropout")) {
try {
new_layer_params.put("layerName", "Dropout");
new_layer_params.put("dropoutRate", Double.parseDouble(dropout_dropout_rate.getText().toString()));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
new_layer_params.put("layerName", "LSTM");
new_layer_params.put("units", Integer.parseInt(lstm_units.getText().toString()));
new_layer_params.put("activationFunction", lstm_activation.getSelectedItem().toString());
new_layer_params.put("recurrentActivation", lstm_recurrent_activation.getSelectedItem().toString());
new_layer_params.put("dropout", Double.parseDouble(lstm_dropout_rate.getText().toString()));
new_layer_params.put("returnSequence", lstm_return_sequence.getSelectedItem().toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setVisibility(View.VISIBLE);
no_layers_text.setVisibility(View.GONE);
recyclerAdapter.layers.add(new_layer_params);
recyclerAdapter.notifyDataSetChanged();
dismiss();
}
});
layer_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String layer = layer_name.getSelectedItem().toString();
if (layer.equals("Dense")) {
dense_layer_layout.setVisibility(View.VISIBLE);
dropout_layer_layout.setVisibility(View.GONE);
lstm_layer_layout.setVisibility(View.GONE);
} else if (layer.equals("Dropout")) {
dense_layer_layout.setVisibility(View.GONE);
dropout_layer_layout.setVisibility(View.VISIBLE);
lstm_layer_layout.setVisibility(View.GONE);
} else {
dense_layer_layout.setVisibility(View.GONE);
dropout_layer_layout.setVisibility(View.GONE);
lstm_layer_layout.setVisibility(View.VISIBLE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
private class EditLayerDialog extends Dialog {
TextView layer_name;
private Spinner dense_activation, lstm_activation, lstm_return_sequence, lstm_recurrent_activation;
private LinearLayout dense_layer_layout, dropout_layer_layout, lstm_layer_layout;
private Button remove_button, cancel_button;
private EditText dense_units, dropout_dropout_rate, lstm_units, lstm_dropout_rate;
JSONObject layer_data;
int index;
EditLayerDialog(Activity activity, JSONObject layer_data, int index){
super(activity);
this.layer_data = layer_data;
this.index = index;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.deep_learning_edit_model_layer);
layer_name = (TextView) findViewById(R.id.layer_name);
dense_layer_layout = (LinearLayout) findViewById(R.id.denseLayout);
dropout_layer_layout = (LinearLayout) findViewById(R.id.dropoutLayout);
lstm_layer_layout = (LinearLayout) findViewById(R.id.lstmLayout);
remove_button = (Button) findViewById(R.id.remove_button);
cancel_button = (Button) findViewById(R.id.cancel_button);
dense_units = (EditText) findViewById(R.id.inputDenseUnits);
dense_activation = (Spinner) findViewById(R.id.spinnerDenseActivationFunction);
dropout_dropout_rate = (EditText) findViewById(R.id.inputDropoutRate);
lstm_activation = (Spinner) findViewById(R.id.spinnerLSTMActivation);
lstm_units = (EditText) findViewById(R.id.inputLSTMUnits);
lstm_return_sequence = (Spinner) findViewById(R.id.spinnerReturnSequence);
lstm_dropout_rate = (EditText) findViewById(R.id.inputLSTMDropout);
lstm_recurrent_activation = (Spinner) findViewById(R.id.spinnerLSTM_RAF);
try {
String layer = layer_data.getString("layerName");
if (layer.equals("Dense")) {
dense_layer_layout.setVisibility(View.VISIBLE);
dropout_layer_layout.setVisibility(View.GONE);
lstm_layer_layout.setVisibility(View.GONE);
dense_units.setText(layer_data.getString("units"));
dense_activation.setSelection(((ArrayAdapter) dense_activation.getAdapter()).getPosition(layer_data.getString("activationFunction")));
} else if (layer.equals("Dropout")) {
dense_layer_layout.setVisibility(View.GONE);
dropout_layer_layout.setVisibility(View.VISIBLE);
lstm_layer_layout.setVisibility(View.GONE);
dropout_dropout_rate.setText(layer_data.getString("dropoutRate"));
} else {
dense_layer_layout.setVisibility(View.GONE);
dropout_layer_layout.setVisibility(View.GONE);
lstm_layer_layout.setVisibility(View.VISIBLE);
lstm_units.setText(layer_data.getString("units"));
lstm_activation.setSelection(((ArrayAdapter) lstm_activation.getAdapter()).getPosition(layer_data.getString("activationFunction")));
lstm_return_sequence.setSelection(((ArrayAdapter) lstm_return_sequence.getAdapter()).getPosition(layer_data.getString("returnSequence")));
lstm_dropout_rate.setText(layer_data.getString("dropout"));
lstm_recurrent_activation.setSelection(((ArrayAdapter) lstm_recurrent_activation.getAdapter()).getPosition(layer_data.getString("recurrentActivation")));
}
layer_name.setText(layer);
} catch (JSONException e) {
e.printStackTrace();
}
remove_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recyclerAdapter.layers.remove(index);
recyclerAdapter.notifyDataSetChanged();
dismiss();
}
});
}
}
private class ExportModelDialog extends Dialog {
public Activity c;
private String code;
public ExportModelDialog(Activity a, String c) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
code = c;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.export_model);
LinearLayout code_layout = (LinearLayout) findViewById(R.id.code_layout);
LinearLayout tm_layout = (LinearLayout) findViewById(R.id.tm_layout);
LinearLayout input_field = (LinearLayout) findViewById(R.id.input_field);
TextView codeText = (TextView) findViewById(R.id.codeText);
TextView tmText = (TextView) findViewById(R.id.tmText);
TextView codeview = (TextView) findViewById(R.id.code);
codeview.setText(code);
View codeLine = (View) findViewById(R.id.codeLine);
View tmLine = (View) findViewById(R.id.tmLine);
Button butt = (Button) findViewById(R.id.download_butt);
code_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
codeLine.setBackgroundColor(getResources().getColor(R.color.primary_color));
codeText.setTextColor(getResources().getColor(R.color.primary_color));
tmLine.setBackgroundColor(getResources().getColor(R.color.black));
tmText.setTextColor(getResources().getColor(R.color.black));
butt.setVisibility(View.GONE);
input_field.setVisibility(View.VISIBLE);
}
});
tm_layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tmLine.setBackgroundColor(getResources().getColor(R.color.primary_color));
tmText.setTextColor(getResources().getColor(R.color.primary_color));
codeLine.setBackgroundColor(getResources().getColor(R.color.black));
codeText.setTextColor(getResources().getColor(R.color.black));
butt.setVisibility(View.VISIBLE);
input_field.setVisibility(View.GONE);
}
});
}
}
}<file_sep>package com.example.deeplearningstudio;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ProjectDescriptionFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ProjectDescriptionFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ProjectDescriptionFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProjectDescriptionFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProjectDescriptionFragment newInstance(String param1, String param2) {
ProjectDescriptionFragment fragment = new ProjectDescriptionFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// Button button3= view.findViewById(R.id.button3);
// Button button4= view.findViewById(R.id.button4);
// button3.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// }
// });
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_project_description, container, false);
}
// public void nextScreen(View view) {
// Intent intent =new Intent(this, BackgroundMenu.class);
// startActivity(intent);
// }
}<file_sep>include ':app'
rootProject.name = "Deep Learning Studio"<file_sep>package com.example.deeplearningstudio;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class HttpPostRequest extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
private CookieStore cookieJar;
static final String COOKIES_HEADER = "Set-Cookie";
static CookieManager msCookieManager = new CookieManager();
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
if (params[0].equals("GET")) {
try {
System.out.println(params[1]);
// connect to the server
URL myUrl = new URL(params[1]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
// While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
System.out.println(TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
connection.setRequestProperty("Cookie",
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
try {
msCookieManager.getCookieStore().add(new URI("http://10.0.2.2:3000"), HttpCookie.parse(cookie).get(0));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = "error";
}
} else {
String JsonDATA = params[2];
try {
System.out.println(params[1]);
// connect to the server
URL myUrl = new URL(params[1]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
// While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
System.out.println(TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
connection.setRequestProperty("Cookie",
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
connection.setRequestMethod("POST");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
try {
msCookieManager.getCookieStore().add(new URI("http://10.0.2.2:3000"), HttpCookie.parse(cookie).get(0));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
<file_sep>package com.example.deeplearningstudio;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class BottomNavigationMenu extends AppCompatActivity {
String ID = null;
String project_domain = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
ID = bundle.getString("projectID");
String url = getResources().getString(R.string.server_url)+"getProjectDomain?project="+ID;
HttpRequest req = new HttpRequest();
req.execute(url);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new PreProcessFragment(ID)).commit();
// }
System.out.println(ID);
}
private class HttpRequest extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: " + cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: " + HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("In Background: " + result);
return result;
}
@Override
protected void onPostExecute(String response) {
System.out.println("Columns List Response: " + response);
setContentView(R.layout.activity_bottom_navigation_menu);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.bottom_nav_preprocess:
selectedFragment = new PreProcessFragment(ID);
break;
case R.id.bottom_nav_visulaize:
selectedFragment = new VisualizationFragment(ID);
break;
case R.id.bottom_nav_model:
if (project_domain.equals("Deep Learning")){
selectedFragment = new ModelFragment(ID);
} else{
selectedFragment = new ModelML(ID);
}
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
});
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PreProcessFragment(ID)).commit();
try {
JSONObject obj = new JSONObject(response);
project_domain = obj.getString("domain");
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(response);
}
}
}<file_sep>package com.example.deeplearningstudio.ui.home;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.deeplearningstudio.AdopterListView;
import com.example.deeplearningstudio.BottomNavigationMenu;
import com.example.deeplearningstudio.HttpGetRequest;
import com.example.deeplearningstudio.HttpPostRequest;
import com.example.deeplearningstudio.NewProjectScreen;
import com.example.deeplearningstudio.ProjectDescriptionFragment;
import com.example.deeplearningstudio.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class HomeFragment extends Fragment {
String projectsURL = null;
RecyclerView recyclerView;
AdopterListView adapter;
FloatingActionButton floatingActionButton;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
//recycler
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerListProjects);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
HttpRequest getReq = new HttpRequest();
projectsURL = getResources().getString(R.string.server_url)+"getProjects";
getReq.execute(projectsURL);
floatingActionButton= root.findViewById(R.id.floatingActionButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(getContext(), NewProjectScreen.class);
startActivity(intent);
}
});
return root;
}
@Override
public void onResume() {
super.onResume();
HttpRequest getReq = new HttpRequest();
projectsURL = getResources().getString(R.string.server_url)+"getProjects";
getReq.execute(projectsURL);
}
public class HttpRequest extends AsyncTask<String, Void, String> {
static final int READ_TIMEOUT = 15000;
static final int CONNECTION_TIMEOUT = 15000;
static final String COOKIES_HEADER = "Set-Cookie";
@Override
protected String doInBackground(String... params) {
String result = "";
String inputLine;
try {
SharedPreferences pref = getActivity().getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
System.out.println(params[0]);
// connect to the server
URL myUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//System.out.println("Received Cookie from PREF: "+pref.getString("Cookie", ""));
connection.setRequestProperty("Cookie",
pref.getString("Cookies", ""));
connection.setRequestMethod("GET");
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
// get the string from the input stream
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
System.out.println("Length of Cookies Header: "+cookiesHeader.size());
for (String cookie : cookiesHeader) {
System.out.println("Individual Cookie: "+ HttpCookie.parse(cookie).get(0).toString());
editor.putString("Cookies", HttpCookie.parse(cookie).get(0).toString());
editor.apply();
}
}
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
System.out.println("Project Response " + response);
JSONArray respArr = new JSONArray(response);
adapter = new AdopterListView(respArr);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} | 8d5491508a09987dc88e4f6947ec0a66271f5bf6 | [
"Java",
"Gradle"
] | 9 | Java | NaumanYousafBajwa/FYP-Android-Application | cac6871a720b6eae59f4f10ebb15a6bfeeed731b | 64106482ca23b4692eea0e735e471693b841890a |
refs/heads/master | <file_sep># CSSANIMISTA jQuery Plugin
>(***need to developing and fixing!***)
## what is CSS-ANIMISTA
[cssanimista](https://animista.net/) is a ***css animation library*** and this library not have complete file to download them, but for using it
you *would* liking any animation you need them to use, in next, that animation was sended to a list, then you can
download css file, wow!
## what is problem if we can download from that website
so, you can **download only keyframe file** and not css selectors(*like class name for animation*), so, **how you can
use them?** <br />
you maybe think "i create css selector for it!", but i say: 'why?' <br />
i think make jQuery plugin for this library and you can use this plugin with **ANY CSS KEYFRAME FILE LIBRARY**, how?
<br />
## how it work? what it do
this plugin can add to you webpages easier and faster css animation name and jQuery event, how? <br />
this can work with any css library! :)
<br />
you can add event, use infinite animation, use click in and out & hover in and out, or, can use train mode, chain mode,
random mode of animations!!! how it impossible
## NOTE
> **THIS PLUGIN NOT COMPLETE AND NEED FIXING MANY BUGS AND I THINK IN THERE WE CAN FIXING THIS THEN USING THEM** :)
*this is open source rule*
>
> have not **documentation** and **comments**
<file_sep>const none = () => {
function noner(){
//animation properties
if(typeof options === 'object' && options !== null){
// user send us multiple element and animation
if(Object(options).hasOwnProperty('hover' || 'click')){
// object only use to $this element not have multiple element but added trigger event handle
if(options?.click){
addAnimistaClick($element, options.click);
}else if(options?.hover){
addAnimistaHover($element, options.hover);
}
}else if(Object(options).hasOwnProperty('animation' || 'duration' || 'delay' || 'repeat')){
// object only use to $this element not have multiple element but this is autoplay animation
addAnimistaCSS({});
}else if(
options?.random
&& typeof options?.random === 'object'
&& options?.random !== null
&& options?.random instanceof Array
){
// choose random animation for this property as Array
let r = options.random;
}else{
// object use multiple element
Object.keys(options).forEach(prop => {
let clickOptionsObject = options[`${prop}`]?.click ? options[`${prop}`].click : false;
if(clickOptionsObject){
addAnimistaClick(prop, clickOptionsObject);
}
});
}
}else{
// user send us multiple element and animation with object name as element selector
/**
* @type {Object} in {Array}
* $.animista([
* {
* selector: '.tag-1',
* eventType: 'click',
* animation: 'bounce-top',
* duration: 450,
* delay: 150
* },
* {
* selector: '.tag-2',
* eventType: 'hover',
* animation: 'bounce-top',
* duration: 450,
* delay: 150
* },
* {
* selector: '.tag-2',
* eventType: 'click',
* animation: 'vibrate-1',
* duration: 450,
* delay: 150
* },
* ]);
*/
/**
* $.fn.animista(
* {
* '.tag-1':
* {
* eventType: 'click',
* animation: 'bounce-top',
* duration: 450,
* delay: 150
* },
* '.tag-1':
* {
* eventType: 'hover',
* animation: 'vibrate-1',
* duration: 450,
* delay: 150
* },
* '.tag-2':
* {
* eventType: 'click',
* animation: 'bounce-left',
* duration: 450,
* delay: 150
* },
* }
* );
*/
// undefined
/**
* $.fn.animista(
* {
* 'div':
* {
* {'click', 'heartbeat'},
* {'hover', 'bounce-top'}
* }
* });
*/
/**
* $.fn.animista(
* {
* 'div':
* {
* click: [animation_name, duration, delay],
* 'hover': (animation_name, ...args) => {
* // callback function
* Object.Keys(object_name).length // this get us length of object
* for(let key in object_name){
* if(typeof object_name[`${key}`] === 'type') doSomething()
* // or
* if(obj)
* }
* }
* }
* });
*/
}
var animation = ((options?.animation && typeof options?.animation === 'string') && options.animation) || 'shake-top',
duration = ((options?.duration && typeof options?.duration === 'number') && options.duration) || 650;
//jQuery wrapped element for this instance
var $element = $(element);
}
// global animista function := {'.a':{...}, 'a':{...}, ...Elements}
$.anime = function(element, options){
console.log('work just jquery');
return $(element);
};
// function
function addAnimistaClick(selector, prop){
let {
animation,
duration,
delay
} = prop;
let repeat = prop?.repeat ? prop.repeat : (prop?.infinite && prop.infinite);
$(selector).on('click', () => {
$(selector).css(
{
animationName: animation,
animationDuration: `${duration}s`,
animationDelay: `${delay}s`,
animationIterationCount: (/^[0-9]{1,99}$/.test(repeat) ? repeat : 'infinite') // repeat:1
});
if(/^[0-9]{1,99}$/.test(repeat) && !prop?.callback){
removeAnimistaClick(selector, duration, delay, repeat);
}
if(prop?.callback){
window.setTimeout(() => {
console.log(prop.callback.animation);
selector.css(
{
animationName: prop.callback.animation,
animationDuration: `${prop.callback.duration}s`,
animationDelay: `${prop.callback.delay}s`,
animationIterationCount: prop.callback.repeat
}
);
removeAnimistaClick(selector, prop.callback.duration, prop.callback.delay, prop.callback.repeat);
}, ((Number(duration) + Number(delay)) * 1000));
}
});
}
function removeAnimistaClick(selector, duration, delay, repeat){
let d = ((Number(duration) + Number(delay)) * repeat) * 1000;
var t;
const func = () => {
$(selector).css(
{
animationName: 'none',
animationDuration: 'unset',
animationDelay: 'unset',
animationIterationCount: 'unset'
});
window.clearTimeout(t);
}
window.setTimeout(func, d);
}
};<file_sep>(function(factory) {
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
// CommonJS Module
factory(require("jquery"));
} else {
// Browser globals.
factory(jQuery);
}
}(function($) {
"use strict";
//Constants
var VERSION = "0.1.0",PLUGIN_NS = 'Animista';
var defaults = {
animation: 'none', // anime || name
duration: 0.4, // '0.4s' || 0.4 || '400ms'
delay: 0.0, // '0.0s' || 0.0 || '000ms'
repeat: 1, // infinite || repeat & <-1> || [0-9] || 'infinite' || true
timeFunction: 'cubic-bezier(0.390, 0.575, 0.565, 1.000)', // steps(<step>, end) || cubic-bezier()
fillMode: 'both', // fill || fillMode & both || fwd || bck || forward || backward
dir: 'norm', // dir || direction & 'normal' || norm || alt || alternate || rev || reverse || alt-rev || alternate-reverse
playState: 1, // <-1> -> unset || <0> -> stop,pause || <1> -> run,running || true -> running || false -> pause || null -> unset || unset || pause || running || run || stop
};
$.fn.animista = function(method) {
var $this = $(this),
plugin = $this.data(PLUGIN_NS);
//Check if we are already instantiated and trying to execute a method
if (plugin && typeof method === 'string') {
if (plugin[method]) {
return plugin[method].apply(plugin, Array.prototype.slice.call(arguments, 1));
} else {
$.error('Method ' + method + ' does not exist on jQuery.animista');
}
}
//Else update existing plugin with new options hash
else if (plugin && typeof method === 'object') {
plugin['option'].apply(plugin, arguments);
}
//Else not instantiated and trying to pass init object (or nothing)
else if (!plugin && (typeof method === 'object' || !method)) {
return init.apply(this, arguments);
}
return $this;
};
// animista global function
$.animista = function(method) {
var $this = $(this),
plugin = $this.data(PLUGIN_NS);
//Check if we are already instantiated and trying to execute a method
if (plugin && typeof method === 'string') {
if (plugin[method]) {
return plugin[method].apply(plugin, Array.prototype.slice.call(arguments, 1));
} else {
$.error('Method ' + method + ' does not exist on jQuery.animista');
}
}
//Else update existing plugin with new options hash
else if (plugin && typeof method === 'object') {
plugin['option'].apply(plugin, arguments);
}
//Else not instantiated and trying to pass init object (or nothing)
else if (!plugin && (typeof method === 'object' || !method)) {
return init.apply(this, arguments);
}
return $this;
};
$.fn.animista.version = VERSION;
//Expose our defaults so a user could override the plugin defaults
$.fn.animista.defaults = defaults;
// animista chains function
// $.fn.animista.chain = animistaChain();
// $.fn.animista.addChain = animistaAddChain();
// $.fn.animista.random = animistaRandom();
// .on function -> $(selector).animista.on('event', { ...animationProperty });
// .on function -> $(selector).animista({ ...animationProperty }).on( 'event' );
// $.fn.animista.on = animistaOn(this);
/**
* Initialise the plugin for each DOM element matched
* This creates a new instance of the main TouchSwipe class for each DOM element, and then
* saves a reference to that instance in the elements data property.
* @internal
*/
function init(options) {
if (!options) {
//pass empty object so we dont modify the defaults
options = $.extend({}, $.fn.animista.defaults, options);
}
// options = {};
//For each element instantiate the plugin
return this.each(function() {
var $this = $(this);
//Check we havent already initialised the plugin
var plugin = $this.data(PLUGIN_NS);
if (!plugin) {
plugin = new Animista(this, options);
$this.data(PLUGIN_NS, plugin);
}
});
}
function Animista(element, options) {
//take a local/instacne level copy of the options - should make it this.options really...
var options = $.extend({}, options);
// take element from $(element);
var $element = $(element);
/* CODE SECTION ABOUT ANIMISTA START */
if( isObject(options) ){
if( hasProperty(options, ['click', 'hover', 'infinite', 'in', 'out']) ){
// that have event object as header key(parent), and animations as node(child) value
// default : in
if(options?.click){
if( hasProperty(options.click, ['rand', 'random']) ){
$element.on('click', function(){
animistaRandom($element, options.click?.rand || options.click?.random);
});
}else if( hasProperty(options.click, ['in', 'out'], 'and') ){
// in and out
$element.on('mousedown', function(){
animeAddCss($element, options.click.in);
});
$element.on('mouseup', function(){
animeAddCss($element, options.click.out);
});
}else{
animistaOn($element, 'click', options.click);
}
}
if(options?.hover){
if( hasProperty(options.hover, ['rand', 'random']) ){
// rand, chain, comp
$element.on('mouseover', function(){
animistaRandom($element, options.hover?.rand || options.hover?.random);
});
}else if( hasProperty(options.hover, ['in', 'out'], 'and') ){
// in and out
$element.on('mouseover', function(){
animeAddCss($element, options.hover.in);
});
$element.on('mouseout', function(){
animeAddCss($element, options.hover.out);
});
}else{
// hover
animistaOn($element, 'hover', options.hover);
}
}
if(options?.infinite){
animistaOn($element, 'infinite', options.infinite);
}
if(options?.in){
animistaOn($element, 'in', options.in);
}
if(options?.out){
animistaOn($element, 'out', options.out);
}
}
else if( hasProperty(options, ['name', 'animation', 'dur', 'duration', 'dly', 'delay']) ){
animeAddCss($element, options);
}
else if( hasProperty(options, ['random', 'rand']) ){
animistaRandom($element, (options?.random || options?.rand));
}
else if( hasProperty(options, 'chain') ){
animistaChain($element, options.chain);
}
else{}
}else{}
/* CODE SECTION ABOUT ANIMISTA STOP */
// jQuery chain connector
return $element;
}
/** ---------------------------
* AnimIsta FUNCTIONS
* ---------------------------- */
function hasProperty(object, keywords, cond = 'or'){
var resArray = [];
if( isArray(keywords) && keywords.length >= 2 ){
keywords.forEach(item => {
let res = Object(object).hasOwnProperty(item);
resArray.push(res);
});
if(cond === 'or'){
return(resArray.includes(true));
}else if(cond === 'and'){
return(!resArray.includes(false));
}
}
else if( isArray(keywords) && keywords.length === 1 ){
return Object(object).hasOwnProperty(keywords[0]);
}
else if( typeof keywords === 'string' ){
return Object(object).hasOwnProperty(keywords);
}else{
return null;
}
}
function isObject(param){
return( typeof param === 'object' && param !== null );
}
function isArray(param){
return( isObject(param) && param instanceof Array );
}
function f(a, b=true, c=true, d=false){
return a === b ? c : d;
}
function isNull(value){
return value === null ? true : false;
}
function animeAddCss(selector, options){
const o = options;
// if properties is null return unset to css style || with alias || with fullName || default
let name = (((isNull(o?.name) || isNull(o?.animation)) && 'unset') || o?.name || o?.animation || 'none' ),
dur = (((isNull(o?.dur) || isNull(o?.duration)) && 'unset') || o?.dur || o?.duration || defaults.duration ),
dly = (((isNull(o?.dly) || isNull(o?.delay)) && 'unset') || o?.dly || o?.delay || defaults.delay ),
timeFunc = (((isNull(o?.timeFunc) || isNull(o?.timeFunction)) && 'unset') || o?.timeFunc || o?.timeFunction || defaults.timeFunction),
rpeat = (f(o?.repeat ,null,'unset') || f(o?.repeat,true,'infinite') || o?.repeat || defaults.repeat),
fillMode = (f(o?.fillMode,null,'unset') || (f(o?.fillMode,'fwd','forwards') || f(o?.fillMode,'bck','backwards')) || o?.fillMode || 'both' ),
playState = (f(o?.fillMode,null,'unset') || (f(o?.playState,'stop','pause') || f(o?.playState,'run','running')) || o?.playState || 'running');
$(selector).css(
{
animationName: name,
animationDuration: f(dur,'unset',dur,`${dur}s`),
animationDelay: f(dly,'unset',dly,`${dly}s`),
animationIterationCount: rpeat,
});
}
function animeRemoveCss(selector, options){
let dur = Number(options.dur);
let dly = Number(options.dly);
let rpt = Number(options.rpeat);
let t = Number(((dur + dly) * rpt) * 1000);
}
function animeDefaultCss(selector){
animeAddCss(selector, defaults);
}
function animeClearCss(selector){
$(selector).css(
{
animationName: 'unset',
animationDuration: 'unset',
animationDelay: 'unset',
animationIterationCount: 'unset',
});
}
function animistaChain(selector, items){
if(isArray(items) && items.length >= 2){
items.forEach(item => {
animeAddCss(selector, item);
});
}else{
return false;
}
}
function animistaAddChain(selector, options){
}
function animistaRandom(selector, items){
let index = Math.floor(Math.random() * items.length);
let item = items[index];
animeAddCss(selector, item);
}
function animistaComp(selector, items){
}
function animistaOn(selector, event, options){
// let eventName = 'click';
// switch (event) {
// case 'hover': eventName = 'mouseover'; break;
// case 'click': eventName = 'click'; break;
// default : eventName = 'click'; break;
// }
let eventName = f(event,'hover','mouseover') || event || 'click';
$(selector).on(eventName, function(){
animeAddCss(selector, options);
});
}
}));<file_sep>(function($){
// without $.fn.
$.animista = function( args ){ return new AnimistaObjective( this, args ); };
$.animista.el = $.animista.select = function( selector ){ return new animeElement( selector ); };
// with $.fn.
$.fn.animista = function( args ){ return new Animista( this, ( args ? args : -1 ) ); };
$.fn.name = function( name ){ return new animeName( this, name ); };
$.fn.animation = function( name ){ return new animeName( this, name ); };
$.fn.dur = function( duration ){ return new animeDuration( this, duration ); };
$.fn.duration = function( duration ){ return new animeDuration( this, duration ); };
$.fn.dly = function( delay ){ return new animeDelay( this, delay ); };
$.fn.delay = function( delay ){ return new animeDelay( this, delay ); };
$.fn.repeat = function( rpeat ){ return new animeRepeat( this, rpeat ); };
$.fn.count = function( rpeat ){ return new animeRepeat( this, rpeat ); };
$.fn.rand = function( rands ){ return new animeRandom( this, rands ); };
$.fn.random = function( rands ){ return new animeRandom( this, rands ); };
$.fn.chain = function( chains ){ return new animeChain( this, chains ); };
// events
$.fn.click = function(){ return new onClick( this, arguments ); };
$.fn.hover = function(){ return new onHover( this, arguments ); };
$.fn.infinite = function( args ){
if( args?.count && !(args?.repeat) ) args.count = true; else args.repeat = true;
$(this).animista( args );
};
$.fn.onn = function( event, args ){ return new onTrigger( this, arguments ); };
// CLASS FUNCTION
function AnimistaObjective( el, args ){
const $this = $( el );
if( typeof( args ) === 'object' && args !== null ){
animeSelect( args );
}else{
console.error(' YOUR ARE NOT USE `selector` AS FIRST KEYWORD, WELL, WE NOT FOUND YOUR SELECTOR TO SET ANIMATION TO IT! ');
}
return $this;
}
function Animista( el, args ){
const $this = $( el );
if( isObject( args ) && !isNull( args ) ){
if( hasProperty(args, ['click', 'hover', 'infinite']) || regexCheck( args, /^(on)[a-z]{3,}$/i ) ){
if( regexCheck( args, /^(on)[a-z]{3,}$/i ) ){
$this.onn( args );
}else{
if( args?.hover ){ $this.hover(args.hover); }
if( args?.click ){ $this.click(args.click); }
if( args?.infinite ){ $this.infinite(args.infinite); }
}
}
else if( hasProperty(args, ['rand', 'random', 'chain', 'comp', 'train']) ){
let prop = ( (args?.rand || args?.random) || args?.chain || (args?.comp || args?.train) );
if( isArray( prop ) && prop.length >= 2 ){
if( hasProperty(args, ['rand', 'random']) ){
$this.random(prop);
}
else if( hasProperty(args, ['chain']) ){
$this.chain(prop);
}
else{}
}else{
console.error(` MAYBE `, prop,` NOT IS ARRAY OR HAVEN'T ENOUGH LENGTH! CHECK SYNTAX AGAIN! `);
}
}
else if( hasProperty(args, ['name', 'animation', 'dur', 'duration']) ){
animeCss( $this, args );
}else{
console.warn(` '${ Object.keys( args ) }' KEYWORD NOT SUPPORTED OR NOT REALLY KEYWORD! MAYBE IN NEW UPDATE WE SET IT( OR YOU CHECK THIS KEYWORD AGAIN?! )! `);
}
}
else if( args === -1 ){
//
}else{
console.error(' YOUR `ARGUMENTS` IS NOT `OBJECT` OR IS `NULL` ');
}
return $this;
}
function animeElement( el ){
return $(el);
};
// set css functions
function animeName( el, name ){
const $this = $( el );
let animationName = ((name === null && 'unset') || (!name && 'unset') || name) || 'unset';
$this.css({ animationName });
return $this;
}
function animeDuration( el, duration ){
const $this = $( el );
let animationDuration = (isNull(duration) && 'unset') || durationCheck(duration);
$this.css({ animationDuration });
return $this;
}
function animeDelay( el, delay ){
const $this = $( el );
let animationDelay = (isNull(delay) && 'unset') || durationCheck(delay);
$this.css({ animationDelay });
return $this;
}
function animeRepeat( el, rpeat ){
const $this = $( el );
let animationIterationCount = f( rpeat, 'unset', 'unset',
f( rpeat, null, 'unset',
f( rpeat, true, 'infinite',
f( rpeat, -1, 'infinite',
f( typeof rpeat, 'number', rpeat,
f( /^[0-9]$/i.test( rpeat ), true, Number(rpeat), 1 )
)
)
)
)
);
$this.css({ animationIterationCount });
return $this;
}
// set chain, random
function animeRandom( el, rands ){
const $this = $( el );
if( isArray(rands) && rands.length >= 2 ){
let selectedProp, randIndex, len = rands.length;
randIndex = Number( Math.floor( Math.random() * len ) );
selectedProp = rands[randIndex];
$this.animista(selectedProp);
}
else{
console.error(` MAYBE '`, rands,`' NOT ARRAY OR HAVEN'T ENOUGH LENGTH! PLEASE CHECK SYNTAX AGAIN `);
}
return $this;
}
function animeChain( el, chains ){
const $this = $( el );
if( isArray( chains ) && chains.length >= 2 ){
let names = [], durs = [], dlys = [], rpeats = [];
$.each( chains, function(index, item){
let prevIndex = index === 0 ? 0 : (index - 1);
let dly = 0, rpeat = 1;
// check validation of parameters keyword
if(isEmpty((item?.name || item?.animation), 'unset')) $.error(' SET VALIDATE `name` OR `animation` KEYWORD( OR SEND VALIDATE ARGUMENT )! PLEASE CHECK IT AND TRY AGAIN! ');
if( index === 0 && isEmpty((item?.dur || item?.duration), 'unset')) $.error(' SET VALIDATE VALUE TO `dur` OR `duration` KEYWORD( OR SEND VALIDATE ARGUMENT )! PLEASE CHECK IT AND TRY AGAIN! ');
if( !isEmpty((item?.dly || item?.delay), 'unset') ) dly = durationCheck((item?.dly || item?.delay), 'num');
if( !isEmpty((item?.repeat || item?.count), 'unset') ) rpeat = (item?.repeat || item?.count);
// set core variable
let name = item?.name || item?.animation,
dur = durationCheck( index === 0 ? (item?.dur || item?.duration) : (item?.dur || item?.duration || durs[prevIndex]), 'num');
// set core values
names.push( name );
durs.push( dur );
rpeats.push( rpeat );
dlys.push( (index === 0 ? dly : ( ((durs[prevIndex] * rpeats[prevIndex]) + dlys[prevIndex]) + dly )) );
});
let durs_second = [], dlys_second = [];
durs.forEach( item => durs_second.push(durationCheck(item)));
dlys.forEach( item => dlys_second.push(durationCheck(item)));
let animationName = names.toString(),
animationDuration = durs_second.toString(),
animationDelay = dlys_second.toString(),
animationIterationCount = rpeats.toString();
$this.css({ animationName, animationDuration, animationDelay, animationIterationCount });
}else{
console.error(` MAYBE `, chains,` NOT IS ARRAY OR HAVEN'T ENOUGH LENGTH! CHECK SYNTAX AGAIN! `);
}
return $this;
}
// event class function
function onClick( el, ...args ){
const $this = $( el );
if( isArray(args) ){
const arg = args[0];
if( arg.length === 1 ){
let arg1 = arg[0];
// this argument type can have: {...} || { in: {...}, out: {...} } || [{...in}, {...out}]
if( isArray( arg1 ) ){
// this is second suggest
if( arg1.length === 2 ){
// options set in array index as in and out
onClickInOut( $this, arg1[0], arg1[1] );
}else{
console.error(' YOUR `ARRAY PARAMETER` SHOULD HAVE `TWO(2) LENGTH` OF INDEXES! ');
}
}
else if( isObject( arg1 ) && !isNull(arg1) ){
// this is first suggest
if( hasProperty( arg1, ['in', 'out'], 'and') ){
// this is animeCss when $this.clicked.in or $this.clicked.out
onClickInOut( $this, arg1.in, arg1.out );
}
else{
// this is animeCss when $this.clicked
$this.on('click', function(){ return Animista( this, arg1 ); });
}
}
}
else if( arg.length === 2 ){
let arg1 = arg[0], arg2 = arg[1];
if( isObject( arg1 ) && isObject( arg2 ) && ( !isNull(arg1) && !isNull(arg2) ) ){
// if( (args[0], ['name', 'animation', 'dur', 'duration']) )
onClickInOut( $this, arg1, arg2 );
}
else{
console.error(' YOUR LENGTH OF ARGUMENTS IS NOT TRUTHY! ');
}
}
else{
console.error(` ~ YOUR '`, arg, `' SHOULD HAVE 'one(1) OR two(2) length' INDEX! ~ `);
}
}
else if( isObject(args) ){
console.log(' objected ');
}else{
console.error(' YOUR ARE NOT HAVE ANY ARGUMENT AS PARAMTER IN `.click(...)`! ');
}
return $this;
}
function onClickInOut( el, inProp, outProp ){
const $this = el;
$this.on('mousedown', function(){ return Animista( $(this), inProp ); });
$this.on('mouseup', function(){ return Animista( $(this), outProp ); });
return $this;
}
function onHover( el, ...args ){
const $this = $(el);
if( isArray(args) ){
const arg = args[0];
if( arg.length === 1 ){
let arg1 = arg[0];
// this argument type can have: {...} || { in: {...}, out: {...} } || [{...in}, {...out}]
if( isArray( arg1 ) ){
// this is second suggest
if( arg1.length === 2 ){
// options set in array index as in and out
onHoverInOut( $this, arg1[0], arg1[1] );
}else{
console.error(' YOUR `ARRAY PARAMETER` SHOULD HAVE `TWO(2) LENGTH` OF INDEXES! ');
}
}
else if( isObject( arg1 ) && !isNull(arg1) ){
// this is first suggest
if( hasProperty( arg1, ['in', 'out'], 'and') ){
// this is animeCss when $this.clicked.in or $this.clicked.out
onHoverInOut( $this, arg1['in'], arg1['out'] );
}
else{
// this is animeCss when $this.clicked
$this.on('mouseover', function(){ return new Animista( this, arg1 ); });
}
}
}
else if( arg.length === 2 ){
let arg1 = arg[0];
let arg2 = arg[1];
if( isObject( arg1 ) && isObject( arg2 ) && ( !isNull(arg1) && !isNull(arg2) ) ){
// if( (args[0], ['name', 'animation', 'dur', 'duration']) )
onHoverInOut( $this, arg1, arg2 );
}
else{
console.error(' YOUR LENGTH OF ARGUMENTS IS NOT TRUTHY! ');
}
}
else{
console.error(' ~ YOUR `argument` SHOULD HAVE `one(1) OR two(2) length` INDEX! ~ ');
}
}
else if( isObject(args) ){
console.log(' objected ');
}else{
console.error(' YOUR ARE NOT HAVE ANY ARGUMENT AS PARAMTER IN `.hover(...)`! ');
}
return $this;
}
function onHoverInOut( el, inProp, outProp ){
const $this = el;
$this.on('mouseover', function(){ return new Animista( $(this), inProp ); });
$this.on('mouseout', function(){ return new Animista( $(this), outProp ); });
return $this;
}
function onTrigger( el, args ){
const $this = $( el ), reg = /^(on)[a-z]{3,}$/i;
if( isObject(args) && !isEmpty(args) && args.length === 2 ){
let arg1 = args[0], arg2 = args[1];
if( (typeof arg1 === 'string' && !isEmpty(arg1)) && (isObject(arg2) && !isEmpty(arg2)) ){
if( regexCheck(arg1, reg) ){
let event = arg1.substring(2, arg1.length);
$this.on(event, function(){
$(this).animista(arg2);
});
}else if( regexCheck(arg1, /^(click|hover|clk|hvr|inf|infinite)$/i) ){
$this.animista({ [arg1] : arg2 });
}else{
console.error(' YOUR FIRST ARGUMENT IS NOT VALIDATE EVENT OR SECOND ARGUMENT IS NOT VALIDATE PROPERTIES! PLEASE CHECK IT AND TRY AGAIN! ');
}
}
else{
console.error(' not argument! ');
}
}
else if( isObject(args) && !isEmpty(args) && args.length === 1 ){
let arg = args[0];
if( regexCheck(arg, reg) ){
getObj( arg , (item) => $this.onn(item, arg[item]) );
}else{
console.error(' YOUR ARGUMENT IS NOT VALIDATE KEYWORD! ');
}
}
else{
console.error(' YOUR ARGUMENTS LENGTH NOT ENOUGH! ');
}
return $this;
}
function onTriggerObjective( el, args ){
const $this = $( el );
console.log('objective on trigger event handle');
return $this;
}
// other function
function animeCss( el, options ){
let o = options, $this = el;
let name = ( o?.name || o?.animation ) || false,
dur = ( o?.dur || o?.duration ) || false,
dly = ( o?.dly || o?.delay ) || false;
rpeat = ( o?.repeat || o?.count ) || false;
// import as function
if( name ){ $this.name( name ); }
if( dur ){ $this.dur( dur ); }
if( dly ){ $this.dly( dly ); }
if( rpeat ){ $this.repeat( rpeat ); }
}
function animeCssClass( el, options ){
let o = options, $this = el,
className = `__animista__${(Math.floor(( Math.random() * 256 )))}__`;
let name = ( o?.name || o?.animation ) || false,
dur = ( o?.dur || o?.duration ) || false,
dly = ( o?.dly || o?.delay ) || false;
rpeat = ( o?.repeat || o?.count ) || false;
// import as function
$this.attr({ 'data-animista': className });
if( name ){ $(`[data-animista=${className}]`).name( name ); }
if( dur ){ $(`[data-animista=${className}]`).dur( dur ); }
if( dly ){ $(`[data-animista=${className}]`).dly( dly ); }
if( rpeat ){ $(`[data-animista=${className}]`).repeat( rpeat ); }
}
function animeSelect( options ){
let o = options;
return $.each(o, function( keywords, items ){
return new Animista( $(keywords), items );
});
}
function animeRemove( el, rlc ){
const $this = el;
// rlc = r: duration, l: delay, c: count | repeat
let dr = rlc.dr,
dl = rlc.dl,
rp = rlc.rp;
let t = Number(((dr + dl) * rp) * 1000);
var st = window.setTimeout(() => {
// $this.name(null).dur(null).dly(null);
animeCss( $this, { name: null, dur: null, dly: null } );
console.log(12345);
window.clearTimeout(st);
}, t);
return $this;
}
function getObj(object, callback){
return Object.keys(object).forEach(callback);
}
function durationCheck(duration, exportMode = 'str'){
var dur, def = 0.6;
switch (typeof duration) {
case 'string':
// type of duration parameter is string
switch (duration) {
// if use time speed keywords
case 'slower': dur = 1.3; break;
case 'slow' : dur = 0.8; break;
case 'norm' : dur = def; break;
case 'fast' : dur = 0.5; break;
case 'faster': dur = 0.3; break;
default:
// if not use time speed keywords
if(/^([0-9].[0-9]|[0-9]){1,}(s)$/i.test(duration)){
// second time duration with 's' keyword
dur = Number(duration.substring(0, duration.length-1));
}else if(/^[0-9]{1,}(ms)$/i.test(duration)){
// millisecond time duration with 'ms' keyword
// convert it from millisecond to second
let d = Number(duration.substring(0, duration.length-2)) / 1000;
dur = d;
}else if(/^([0-9].[0-9]|[0-9]){1,}$/.test(duration)){
// second time duration as string and without 's' keyword
dur = Number(duration);
}else{
dur = def;
}
break;
}
break;
case 'number':
// type of number
dur = duration;
break;
default:
dur = def;
break;
}
return exportMode === 'num' ? dur : `${dur}s`;
}
function hasProperty(object, keywords, cond = 'or'){
var resArray = [];
if( isArray(keywords) && keywords.length >= 2 ){
keywords.forEach(item => {
let res = Object(object).hasOwnProperty(item);
resArray.push(res);
});
if(cond === 'or'){
return(resArray.includes(true));
}else if(cond === 'and'){
return(!resArray.includes(false));
}
}
else if( isArray(keywords) && keywords.length === 1 ){
return Object(object).hasOwnProperty(keywords[0]);
}
else if( typeof keywords === 'string' ){
return Object(object).hasOwnProperty(keywords);
}else{
return null;
}
}
function regexCheck(value, regex, cond = 'or'){
var resArray = [];
if( isObject(regex) && !isEmpty(regex) && (regex instanceof RegExp) ){
if( isObject(value) && !isEmpty(value) ){
Object.keys( value ).forEach(property => resArray.push( regex.test(property) ));
return( cond === 'and' ? !resArray.includes(false) : ( cond === 'or' && resArray.includes(true) ) );
}
else if( isArray(value) && value.length > 0 ){
value.forEach(item => resArray.push( regex.test(item) ));
return( cond === 'and' ? !resArray.includes(false) : ( cond === 'or' && resArray.includes(true) ) );
}
else if( typeof value === 'string' && value.length > 0 && value !== '' ){
return regex.test(value);
}
else{
return null
}
}else{
console.error(' ARGUMENT value OR regex MAYBE NOT VALIDATE! ');
return null
}
}
function isEmpty( value, checker = undefined ){
return( ( typeof value === 'string' && value.length === 0) || ( (typeof value === 'object' && value instanceof Array) && value.length === 0 ) || value === '' || value === undefined || value === null || value === false || value === checker );
}
function isObject(param){
return( typeof param === 'object' && param !== null );
}
function isArray(param){
return( isObject(param) && param instanceof Array );
}
function f(a, b=true, c=true, d=false){
return a === b ? c : d;
}
function ff( a, b, c='or' ){
let r = [];
a.forEach(item => {
r.push(item === b);
});
return( c.toLowerCase() === 'and' ? ( !r.includes(false) ) : ( c.toLowerCase() === 'or' && r.includes( true ) ) );
}
function isNull(value){
return value === null ? true : false;
}
}(jQuery));
<file_sep>(function($){
$.chage = function( rootNode, props ){
let rendered = checker( props );
$(rootNode).replaceWith( rendered );
function checker( props ){
let rendered = '', index = 1, rowItem = false;
Object.keys(props).forEach( item => {
if( item === 'row' ){
rowItem = true;
Object.keys(props[item]).forEach( i => {
if( i === 'textbox' ){ rendered += `<div class="section">${textbox( props[item][i], index )}</div>`; }
if( i === 'switch' ){ rendered += `<div class="section">${switcher( props[item][i], index )}</div>`; }
});
}else{
if( item === 'textbox' ){ rendered += textbox( props[item], index ); }
if( item === 'switch' ){ rendered += switcher( props[item], index ); }
if( item === 'label' ){ rendered += `<label>${props[item]?.text}</label>`; }
}
index += 1;
});
console.log( rendered, props );
return rendered;
}
};
function row( element ){
return(`<div class="section">${ element }</div>`);
}
// built-in elements
function switcher( props, tabIndex = (props?.tabIndex || props?.tabindex || props['tab-index'] || 0) ){
return(`
<label tabIndex=${tabIndex} data-form="switch">
<input type="checkbox" checked="${props?.checked}"/>
<span></span>
</label>
`);
}
function textbox( props, tabIndex = (props?.tabIndex || props?.tabindex || props['tab-index'] || 0) ){
if($(`#textbox-${tabIndex}`).val() !== ''){
$(this).addClass('show');
}
return(`
<label id="textbox-${tabIndex}" tabindex="${tabIndex}" data-form="textbox">
<input type="text" />
<span>${ props?.placeholder }${( props?.optionally ? '(option)' : '' )}</span>
</label>
`);
}
function textarea( props, tabIndex = (0) ){
return(`
<textarea></textarea>
`);
}
}(jQuery)) | 3034fbab09ad3679527d4d8d8a70c44ce2d64897 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | miko-github/jsquery-css-animista | 8f981ad663e4c20f606926f2cb04332fb3204fa3 | 41ce27c0d116ca87aa8535de664035449e607c1f |
refs/heads/master | <file_sep>alias ll='ls -la'
alias ma='mate'
alias kill_dock='killall -KILL Dock'
alias kill_java='kill -9 `ps awx | grep java`'
alias tunnels_office='~/start_ldap_tunnel.sh "office" & ~/start_reportsdb_tunnel.sh "office" & ~/start_proddb_tunnel.sh "office" & ~/start_acctdb_tunnel.sh "office" & ~/start_epochstatsdb_tunnel.sh "office" &'
alias tunnels_remote='~/start_ldap_tunnel.sh "remote" & ~/start_reportsdb_tunnel.sh "remote" & ~/start_proddb_tunnel.sh "remote" & ~/start_acctdb_tunnel.sh "remote" &'
alias npmtest='npm run lint; npm test'
alias labd='node-debug node_modules/.bin/lab -M 0 -m 0' #labd -g 'should fail to render when failing on fetchShortcode'
alias pep='ssh <EMAIL>'
alias gulpmon='gulp;nodemon'
alias nm='nodemon -e js,hbs,hs,css'
alias bugger="node-inspector --web-port=9090 --no-preload"
alias buggy="nodemon --debug"
alias runredis='redis-server /usr/local/etc/redis.conf &'
alias stopredis='redis-cli shutdown'
alias nodeit='killall node; killall java; sh ~/node.sh'
alias killit='killall node; killall java'
alias findlinks='ls -lR ./node_modules | grep ^l'
alias dockerstart='docker-compose up -d'
alias dockerstop='docker-compose stop'
alias dockerstatus='docker-compose ps'
#SSH
alias epbox='ssh -i ~/.ssh/epbox/id_rsa <EMAIL>'
alias bast='ssh <EMAIL>'
alias epochpep='ssh <EMAIL>'
alias pkproxy='ssh slee@172.16.58.3'
#Mysql
alias mysql='/usr/local/Cellar/mysql/5.6.27/bin/mysql'
alias start_mysql='mysql.server start'
alias stop_mysql='mysql.server stop'
alias mysqladmin='/usr/local/Cellar/mysql/5.6.27/bin/mysqladmin'
alias mysqldump='/usr/local/Cellar/mysql/5.6.27/bin/mysqldump'
alias db7='mysql -h 127.0.0.1 -P13306 -u slee_tunnel -p"blu3r1bb0nbutt3r"'
alias epstatsdb='mysql -h 127.0.0.1 -u slee -P33306 -p"JHJHFGsd&&ffakd"'
#Mysql5
alias mysql5='/opt/local/lib/mysql5/bin/mysql'
alias mysql5check='/opt/local/lib/mysql5/bin/mysqlcheck'
alias mysql5_stop='sudo /opt/local/bin/mysqladmin5 shutdown'
alias mysql5_start='sudo /opt/local/bin/mysqld_safe5 &'
alias mysql5admin='/opt/local/bin/mysqladmin'
alias mysql5dump='/opt/local/bin/mysqldump'
#Server
alias apachectl='sudo /usr/sbin/apachectl'
alias memcache_start='memcached -d -m 2048 -M -p 11211'
alias webkit='WebKit/WebKitTools/Scripts/run-safari'
#Rails
alias ruby187='rvm use ruby-1.8.7-p374 --default'
alias ruby212='rvm use ruby-2.1.2 --default'
alias ruby213='rvm use ruby-2.1.3 --default'
alias ruby215='rvm use ruby-2.1.5 --default'
alias ruby216='rvm use ruby-2.1.6 --default'
export CLICOLOR=1
export LSCOLORS=gxBxhxDxfxhxhxhxhxcxcx
export PS1='\u@\w\$ '
export RBENV_ROOT=/usr/local/rbenv
export PATH="$RBENV_ROOT/bin:$PATH"
eval "$(rbenv init -)"
#Java
export JAVA_HOME=$(/usr/libexec/java_home)
#PG
export PG_USER=slee
export PG_PASSWORD=''
#Mysql Creds
#export MYSQL_USER='127.0.0.1'
#export MYSQL_USER='slee_tunnel'
#export MYSQL_PASSWORD='<PASSWORD>'
export KNEX_DEBUG_LOG=1;
#Docker
alias dm-list='docker-machine ls'
dm-env() {
eval "$(docker-machine env "$1")"
}
dm-stop() {
docker-machine stop $1
}
dm-start() {
docker-machine start $1 && dm-env $1
}
#Captcha
export RECAPTCHA_PUBLIC_KEY='<KEY>'
export RECAPTCHA_PRIVATE_KEY='<KEY>'
export NVM_DIR="$HOME/.nvm"
. "$(brew --prefix nvm)/nvm.sh"
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
| be8fe3da900e86797e0735ec43e93790fe846c6d | [
"Shell"
] | 1 | Shell | oprogfrogo/dotfiles | 2d0c08dfce8045424e4e873d6ad7346bacb0b222 | 08bebc3d1b777815c5a30969d436593bb8817de2 |
refs/heads/master | <repo_name>seunsekoni/snapnet-location-api<file_sep>/app/Http/Controllers/LocationController.php
<?php
namespace App\Http\Controllers;
use App\Models\Country;
use App\Models\City;
use App\Models\Lga;
use App\Models\State;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* List all countries
* @return \Illuminate\Http\Response
*/
public function countries()
{
try
{
$countries = Country::orderBy('name', 'ASC')->get();
return $this->sendResponse($countries, 'Retrieved list of countries successfully.');
}
catch (\Throwable $ex)
{
\Log::error($ex);
return $this->sendServerError('Failed to retrieve countries.');
}
}
/**
* Get a country details
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function showCountry($id)
{
try
{
$country = Country::find($id);
return $this->sendResponse($country, 'Retrieved detail of country successfully.');
}
catch (\Throwable $ex)
{
\Log::error($ex);
return $this->sendServerError('Failed to retrieve country details.');
}
}
/**
* List all states in a country
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function stateInACountry($country_id)
{
try
{
$states = State::where('country_id', $country_id)->orderBy('name', 'ASC')->get();
return $this->sendResponse($states, "Successfully fetched states");
} catch (\Throwable $th)
{
\Log::error($th);
return $this->sendServerError("Unable to fetch states");
}
}
/**
* Get a state detail
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function showState($id)
{
try
{
// Get a state with its Id
$state = State::find($id);
return $this->sendResponse($state, "Successfully retrieved state detail");
} catch (\Throwable $th)
{
\Log::error($th);
return $this->sendServerError("Unable to fetch state detail");
}
}
/**
* List all cities in a state
* @return \Illuminate\Http\Response
* @param int $state_id
*/
public function citiesInAState($state_id)
{
try {
// find all cities related to the state
$cities = City::where('state_id', $state_id)->orderBy('name', 'ASC')->get();
return $this->sendResponse($cities, "Successfully fetched cities");
} catch (\Throwable $th) {
Log::error($th);
$this->sendServerError("Unable to fetch cities");
}
}
/**
* Get a state detail
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function showCity($id)
{
try
{
// find city detail
$city = City::find($id);
return $this->sendResponse($city, "Successfully retrieved city detail");
} catch (\Throwable $th)
{
\Log::error($th);
return $this->sendServerError("Unable to fetch city detail");
}
}
/**
* List all Lgas in a state
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function LgaInAState($state_id)
{
try
{
$lgas = Lga::where('state_id', $state_id)->get();
return $this->sendResponse($lgas, "Successfully fetched Lgas");
} catch (\Throwable $th)
{
\Log::error($th);
return $this->sendServerError("Unable to fetch Lgas");
}
}
/**
* Get an Lga detail
* @return \Illuminate\Http\Response
* @param int $country_id
*/
public function ShowLga($id)
{
try
{
$lga = Lga::find($id);
return $this->sendResponse($lga, "Successfully retrieved lga detail");
} catch (\Throwable $th)
{
\Log::error($th);
return $this->sendServerError("Unable to fetch lga detail");
}
}
}
<file_sep>/routes/api.php
<?php
use App\Http\Controllers\LocationController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('countries', [LocationController::class, 'countries'])->name('countries');
Route::get('country/{id}', [LocationController::class, 'showCountry'])->name('showCountry');
Route::get('states/{country_id}', [LocationController::class, 'stateInACountry'])->name('stateInACountry');
Route::get('state/{id}', [LocationController::class, 'showState'])->name('showState');
Route::get('cities/{state_id}', [LocationController::class, 'citiesInAState'])->name('citiesInAState');
Route::get('city/{id}', [LocationController::class, 'showCity'])->name('showCity');
// Route::get('lgas/{state_id}', [LocationController::class, 'LgaInAState'])->name('LgaInAState');
// Route::get('lga/{lid}', [LocationController::class, 'ShowLga'])->name('ShowLga');
<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public static function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* Handles server error response
*
* @return \Illuminate\Http\Response
*/
public static function sendServerError($message)
{
return response()->json([
'success' => false,
'message' => $message
], 500);
}
}
<file_sep>/README.md
### Directions on how to setup this repository
- Clone this repo
- Change directory into the root of the folder of the cloned directory, i.e ``` cd foldername ```
- Rename the .env.example file to .env
- Create a database in mysql and update the .env details accordingly
- Set all your environment variables in the .env file
- Run ``` composer install ```
- Run ``` php artisan key:generate ```
- Run ``` php artisan config:cache ```
- Run ``` php artisan serve ```
- Run ``` php artisan migrate ```
- Run ``` php artisan db:seed ```
- Visit ``` http://localhost:8000 ``` on a browser
- To run tests ``` php artisan test```<file_sep>/database/factories/CityFactory.php
<?php
namespace Database\Factories;
use App\Models\City;
use Illuminate\Database\Eloquent\Factories\Factory;
class CityFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = City::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->firstName,
'country_id' => $this->faker
];
}
/**
* Make the country_id id dynamic.
*
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function state_id($id)
{
return $this->state(function (array $attributes) use ($id) {
return [
'state_id' => $id,
];
});
}
}
<file_sep>/tests/Feature/LocationTest.php
<?php
namespace Tests\Feature;
use App\Models\Country;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class LocationTest extends TestCase
{
/**
* Fetch all countries accordingly.
*
* @return void
*/
public function test_if_all_countries_can_be_fetched()
{
$response = $this->json('GET', '/api/countries');
$response->assertStatus(200)
->assertJson([
'success' => true,
'data' => []
])
;
}
// public function test_if_all_states_can_be_fetched_by_country()
// {
// $country = Country::factory()->create(5);
// $getCountry = Country::first();
// $response = $this->json('GET', '/api/states'.$getCountry->id);
// $response->assertStatus(200)
// ->assertJson([
// 'success' => true,
// 'data' => []
// ])
// ;
// }
}
| 710ee87d5eefa6ea24bcbb27b656695021c91edd | [
"Markdown",
"PHP"
] | 6 | PHP | seunsekoni/snapnet-location-api | 7adad3c04851213d1bdbec53ef044862df6d7eef | 08f965720e744dac079fd9fd9a453d40c50d1e49 |
refs/heads/master | <file_sep>const Board = require("./board");
const Map = require("./map");
class Player {
constructor(name, size) {
this.name = name;
this.board = new Board(size);
this.map = new Map(size);
this.eventLog = [];
this.turn = false;
}
// Registers an outgoing attack.
// Player obj, [x, y]
attack(opponent, coordinates) {
// If the move is invalid (previously attacked), return false
if (!this.isValidTarget(coordinates)) return false;
// Otherwise attack the opponent's board at the given coordinates
const target = opponent.getBoard().getValue(coordinates);
let hitOrMiss;
if (target === 0) { // 0 = ship = hit
hitOrMiss = 1;
} else if (target === null) { // null = no ship = miss
hitOrMiss = 0;
}
// Record the outcome onto the player's map
this.map.setValue(coordinates, hitOrMiss);
// Log the event
const outcome = hitOrMiss ? "hit" : "miss";
this.logEvent("attack", coordinates, outcome); // e.g. player attacked on (0, 1) and it was a miss
// Record the outcome onto the opponent's board
opponent.defend(coordinates, outcome);
}
// Returns true if the coordinates mark a tile on the map that the player is allowed to attack.
// A player can attack a tile only if its value is null.
isValidTarget(coordinates) {
return this.map.getValue(coordinates) === null;
}
// Registers an incoming attack.
defend(coordinates, outcome) {
// This method always execute only if an attack was confirmed to be valid
// The attacking player already knows if it was a hit or miss
// Set the coordinates to 1 if hit, -1 if miss
let newValue = outcome === "hit" ? 1 : -1;
console.log("outcome: ", outcome);
this.board.setValue(coordinates, newValue);
// Log the event
this.logEvent("defend", coordinates, outcome);
}
// Logs an event
// event => attack or defend
// coordinates => targeted coordinates
logEvent(event, coordinates, outcome) {
// A snapshot of the player's map and board as a result of this event
const stage = {
map: this.map,
board: this.board
};
this.eventLog.push({ event, coordinates, stage, outcome });
}
addShip(coordinates) {
const added = this.board.addShip(coordinates);
return added;
}
getMap() {
return this.map;
}
getBoard() {
return this.board;
}
display() {
console.log(`${this.name}'s map`);
console.log(this.map.toString());
console.log(`${this.name}'s board`);
console.log(this.board.toString());
}
// Flip the player's turn status and return it
turn() {
this.turn = !this.turn;
return this.turn;
}
isNext() {
return this.turn;
}
}
module.exports = Player;<file_sep>const { assert } = require("chai");
const visualKeys = require("../src/config.json").visualKeys;
const Board = require("../src/models/board");
const Map = require("../src/models/map");
const {
generateBoard,
copyBoard,
addShip,
attackingMap,
defendingBoard,
getMap,
getBoard,
getLabels,
boardToStr
} = require("../src/helpers");
describe("generateBoard", () => {
it("should return an empty erray given n = 0", () => {
const output = generateBoard(0);
const expected = [];
assert.deepEqual(output, expected);
});
it("should return an array of 3 arrays, each with 3 null values, given n = 3", () => {
const output = generateBoard(3);
const expected = [
[null, null, null],
[null, null, null],
[null, null, null],
];
assert.deepEqual(output, expected);
});
});
describe("copyBoard", () => {
it("should return a deep copy of a board", () => {
const board1 = [[0, 0, 1]];
const board2 = copyBoard(board1);
board2[0][0] = 1;
const expected = [[0, 0, 1]];
assert.deepEqual(board1, expected);
});
});
describe("addShip", () => {
it("should add the ship if there is no existing ship", () => {
const board = new Board(3);
const output = board.addShip([1, 1]);
assert.isTrue(output);
});
it("should return false if a ship already exists there", () => {
const board = new Board(3);
board.addShip([1, 1]);
const output = board.addShip([1, 1]);
assert.isFalse(output);
});
});
describe("attackingMap", () => {
it("should set the target to 1 if the outgoing attack hit a ship (was 0)", () => {
const playerMap = [[null]];
const enemyBoard = [[0]];
const output = attackingMap(playerMap, enemyBoard, [0, 0]);
const expected = [[1]];
assert.deepEqual(output, expected);
});
it("should set the target to 0 if the outgoing attack missed (was null)", () => {
const playerMap = [[null]];
const enemyBoard = [[null]];
const output = attackingMap(playerMap, enemyBoard, [0, 0]);
const expected = [[0]];
assert.deepEqual(output, expected);
});
it("should return false if the target had already been attacked (hit)", () => {
const playerMap = [[1]];
const enemyBoard = [[1]];
const output = attackingMap(playerMap, enemyBoard, [0, 0]);
assert.isFalse(output);
});
it("should return false if the target had already been attacked (miss)", () => {
const playerMap = [[1]];
const enemyBoard = [[-1]];
const output = attackingMap(playerMap, enemyBoard, [0, 0]);
assert.isFalse(output);
});
it("should not modify the original player map", () => {
const playerMap = [[null]];
const enemyBoard = [[null]];
attackingMap(playerMap, enemyBoard, [0, 0]);
const expected = [[null]];
assert.deepEqual(playerMap, expected);
});
});
describe("defendingBoard", () => {
it("should set the target to 1 if the incoming attack hit a ship (was 0)", () => {
const playerBoard = [[0]];
const output = defendingBoard(playerBoard, [0, 0]);
const expected = [[1]];
assert.deepEqual(output, expected);
});
it("should set the target to -1 if the incoming attack missed (was null)", () => {
const playerBoard = [[null]];
const output = defendingBoard(playerBoard, [0, 0]);
const expected = [[-1]];
assert.deepEqual(output, expected);
});
it("should return false if the target had already been attacked (hit)", () => {
const playerBoard = [[1]];
const output = defendingBoard(playerBoard, [0, 0]);
assert.isFalse(output);
});
it("should return false if the target had already been attacked (miss)", () => {
const playerBoard = [[-1]];
const output = defendingBoard(playerBoard, [0, 0]);
assert.isFalse(output);
});
it("should not modify the original player board", () => {
const playerBoard = [[null]];
defendingBoard(playerBoard, [0, 0]);
const expected = [[null]];
assert.deepEqual(playerBoard, expected);
});
});
describe("getMap", () => {
const key = visualKeys.map;
it(`should convert null to ${key.default} (unattacked)`, () => {
const playerMap = [
[null, null],
[null, null]
];
const output = getMap(playerMap);
const expected = [
[key.default, key.default],
[key.default, key.default]
];
assert.deepEqual(output, expected);
});
it(`should convert 1 to ${key.hit} (player attack hit)`, () => {
const playerMap = [[1]];
const output = getMap(playerMap);
const expected = [[key.hit]];
assert.deepEqual(output, expected);
});
it(`should convert 0 to ${key.miss} (player attack miss)`, () => {
const playerMap = [[0]];
const output = getMap(playerMap);
const expected = [[key.miss]];
assert.deepEqual(output, expected);
});
it(`should not modify the original player map`, () => {
const playerMap = [[null]];
getMap(playerMap);
const expected = [[null]];
assert.deepEqual(playerMap, expected);
});
});
describe("getBoard", () => {
const key = visualKeys.board;
it(`should convert null to ${key.default} (unattacked)`, () => {
const playerBoard = [
[null, null],
[null, null]
];
const output = getBoard(playerBoard);
const expected = [
[key.default, key.default],
[key.default, key.default]
];
assert.deepEqual(output, expected);
});
it(`should convert 0 to ${key.ship} (ship)`, () => {
const playerBoard = [[0]];
const output = getBoard(playerBoard);
const expected = [[key.ship]];
assert.deepEqual(output, expected);
});
it(`should convert 1 to ${key.hit} (enemy attack hit)`, () => {
const playerBoard = [[1]];
const output = getBoard(playerBoard);
const expected = [[key.hit]];
assert.deepEqual(output, expected);
});
it(`should convert -1 to ${key.miss} (enemy attack miss)`, () => {
const playerBoard = [[-1]];
const output = getBoard(playerBoard);
const expected = [[key.miss]];
assert.deepEqual(output, expected);
});
it("should not modify the original player board", () => {
const playerBoard = [[null]];
getBoard(playerBoard);
const expected = [[null]];
assert.deepEqual(playerBoard, expected);
});
});
describe("getLabels", () => {
it("should return a 3x3 board given a 2x2 board", () => {
const board = [
[null, null],
[null, null]
];
const output = getLabels(board);
const numRows = output.length;
const numCols = output[0].length;
const expectedRows = board.length + 1;
const expectedCols = board[0].length + 1;
assert.deepEqual([numRows, numCols], [expectedRows, expectedCols]);
});
it("should return a board with letters for each row and numbers for each column, except at (0, 0) which should be ' '", () => {
const board = [
[".", "."],
[".", "."]
];
const output = getLabels(board);
const expected = [
[" ", "0", "1"],
["A", ".", "."],
["B", ".", "."],
];
assert.deepEqual(output, expected);
});
});
describe("boardToStr", () => {
it("should return the correct string representation of a board", () => {
const board = [
[".", "."],
[".", "."],
];
const output = boardToStr(board);
const expected = "..\n..";
assert.equal(output, expected);
});
});<file_sep>require('dotenv').config();
const IP = process.env.IP || "localhost";
const PORT = process.env.PORT || 3001;
const net = require("net");
const stdin = process.stdin;
stdin.setEncoding("utf8");
const client = net.createConnection({
host: IP,
port: PORT
});
client.setEncoding("utf8");
client.on("data", (data) => {
console.log(data);
});
stdin.on("data", (input) => {
client.write(input);
});<file_sep>const visualKeys = require("./config.json").visualKeys;
/**
* Returns a 2-dimensional array of null values representing a board with n rows and n columns.
* @param {number} n - The number of rows and columns, n >= 0.
* @return {Array.<[null]>} A 2-dimensional n * n array of null values.
*/
const generateBoard = (n) => {
const board = [];
for (let i = 0; i < n; i++) {
const row = new Array(n).fill(null);
board.push(row);
}
return board;
};
/**
* Returns a deep copy of a board (2-dimensional array).
* @param {Array.<Array>} board - The nested array to clone.
* @return {Array.<Array>} A deep clone of the nested array.
*/
const copyBoard = (board) => {
return board.map(array => array.slice());
};
/**
* Given a player's map, returns a new map with given coordinates set to 1 or 0 if the
* same coordinate on the enemy's board has a value of 0 or null, respectively (hit or miss).
* Returns false if the coordinate had already been attacked.
* @param {Array.<[number|null]>} playerMap - The player's map.
* @param {Array.<[number|null]>} enemyBoard - The enemy's board.
* @param {Array.<number, number>} coordinates - The X and Y coordinates to attack.
* @return {Array.<[number|null]>|boolean} - The player's resulting map or false if unchanged.
*/
const attackingMap = (playerMap, enemyBoard, coordinates) => {
const [row, col] = coordinates;
if (playerMap[row][col] === 1) return false;
const target = enemyBoard[row][col];
let hitOrMiss;
if (target === 0) { // hit
hitOrMiss = 1;
} else if (target === null) { // miss
hitOrMiss = 0;
}
const newMap = copyBoard(playerMap);
newMap[row][col] = hitOrMiss;
return newMap;
};
/**
* Given a player's board, returns a new board with given coordinates set to 1 or -1 if the
* incoming attack coordinates has a value of 0 or null, respectively (hit or miss).
* Returns false if the coordinate had already been attacked.
* @param {Array.<[number|null]>} playerBoard - The player's board.
* @param {Array.<number, number>} coordinates - The X and Y coordinates of an incoming attack.
* @return {Array.<[number|null]>|boolean} - The player's resulting board or false if unchanged.
*/
const defendingBoard = (playerBoard, coordinates) => {
const [row, col] = coordinates;
const target = playerBoard[row][col];
if (target === 1 || target === -1) return false;
let hitOrMiss;
if (target === 0) {
hitOrMiss = 1;
} else if (target === null) {
hitOrMiss = -1;
}
const newBoard = copyBoard(playerBoard);
newBoard[row][col] = hitOrMiss;
return newBoard;
};
/**
* Given a player's map, returns a new map with values replaced by strings representing the
* visual states of each tile.
* - Unattacked tile (null) => "."
* - Player attack hit (1) => "H"
* - Player attack miss (0) => "-"
* @param {Array.<[number|null]>} playerMap - The player's map.
* @param {Object.<string>} mapKey - An object containing characters to represent map tile states.
* @return {Array.<[string]>} - The resulting visual map.
*/
const getMap = (playerMap, mapKey = visualKeys.map) => {
const visualMap = copyBoard(playerMap);
for (let row = 0; row < visualMap.length; row++) {
for (let col = 0; col < visualMap[row].length; col++) {
let current = visualMap[row][col];
if (current === null) {
visualMap[row][col] = mapKey.default;
} else if (current === 1) {
visualMap[row][col] = mapKey.hit;
} else if (current === 0) {
visualMap[row][col] = mapKey.miss;
}
}
}
return visualMap;
};
/**
* Given a player's board, returns a new board with values replaced by strings representing the
* visual states of each tile.
* - Unattacked tile (null) => "."
* - Player ship (0) => "O"
* - Enemy attack hit (1) => "X"
* - Enemy attack miss (-1) => "-"
* @param {Array.<[number|null]>} playerBoard - The player's board.
* @param {Object.<string>} boardKey - An object containing characters to represent board tile states.
* @return {Array.<[string]>} - The resulting visual board.
*/
const getBoard = (playerBoard, boardKey = visualKeys.board) => {
const visualBoard = copyBoard(playerBoard);
for (let row = 0; row < visualBoard.length; row++) {
for (let col = 0; col < visualBoard[row].length; col++) {
let current = visualBoard[row][col];
if (current === null) {
visualBoard[row][col] = boardKey.default;
} else if (current === 0) {
visualBoard[row][col] = boardKey.ship;
} else if (current === 1) {
visualBoard[row][col] = boardKey.hit;
} else {
visualBoard[row][col] = boardKey.miss;
}
}
}
return visualBoard;
};
/**
* Given a board, returns a new board with an extra row and column
* containing row (letter) and column (number) values.
* @param {Array.<[number|null]>} board - The player's map or board.
* @return {Array.<[string|number|null]>} - The map or board with coordinates.
*/
const getLabels = (board) => {
const newBoard = copyBoard(board);
const length = newBoard.length;
// Add number labels ("0", "1", "2", ...)
const numberLabels = [" "];
for (let col = 0; col < length; col++) {
numberLabels.push(col.toString());
}
newBoard.unshift(numberLabels);
// Add letter labels ("A", "B", "C", ...)
for (let row = 1; row <= length; row++) {
newBoard[row].unshift(String.fromCharCode(row + 64));
}
return newBoard;
};
/** Returns a string representation of a board.
* @param {Array.<[string|number|null]>} board - The player's map or board.
* @param {string} - The resulting string representation.
*/
const boardToStr = (board) => {
let labels = false;
if (board[0][0] === " ") {
labels = true;
}
let str = "";
for (const row of board) {
str += `${row.join("")}\n`;
}
return (labels ? " " : "") + str.trim();
};
module.exports = {
generateBoard,
copyBoard,
attackingMap,
defendingBoard,
getMap,
getBoard,
getLabels,
boardToStr
};<file_sep>const {
generateBoard,
copyBoard,
getLabels,
} = require("../helpers");
class Grid {
constructor(size) {
this.size = size;
this.grid = this.new();
}
// Returns a deep copy of the grid.
copy() {
const copy = new Grid(this.size);
copy.grid = copyBoard(this.grid);
return copy;
}
// Returns the grid with coordinate labels.
labeled() {
return getLabels(this.grid);
}
new() {
return generateBoard(this.size);
}
get() {
return this.grid;
}
setValue(coordinates, value) {
const [row, col] = coordinates;
this.grid[row][col] = value;
}
getValue(coordinates) {
const [row, col] = coordinates;
return this.grid[row][col];
}
}
module.exports = Grid;<file_sep>const Grid = require("./grid");
const {
copyBoard,
getBoard,
getLabels,
boardToStr
} = require("../helpers");
class Board extends Grid {
constructor(size) {
super(size);
this.grid = this.new();
}
/**
* Adds a ship at the given coordinates then returns true if successful,
* false otherwise (if a ship has already been placed there).
* @param {Array.<number, number>} coordinates - The X and Y coordinates to add a ship to.
* @return {boolean} - Whether or not the ship was added.
*/
addShip(coordinates) {
const [row, col] = coordinates;
if (this.grid[row][col] !== null) {
// console.log("Failed to add a ship at", coordinates);
return false;
}
this.grid[row][col] = 0;
// console.log("Successfully added a ship at", coordinates);
return true;
}
// Returns a visualized board.
getVisual() {
return getBoard(this.grid);
}
// Returns a string representation of the board.
toString() {
return boardToStr(getLabels(getBoard(this.grid)));
}
set(grid) {
this.grid = grid;
}
}
module.exports = Board;<file_sep>require('dotenv').config();
const { msg, createUser, getNext } = require("./utility");
const { red, green, yellow, blue, magenta, cyan } = require("chalk");
const PORT = process.env.PORT || 3001;
const net = require("net");
const server = net.createServer();
const users = {};
const queue = [];
let online = 0;
// Event Listeners
server.on("connection", (client) => {
client.setEncoding("utf8");
// Create a new user & log
const newUser = createUser(client, users);
users[newUser.gameID] = newUser;
online += 1;
msg.greet(client, online);
msg.promptPlay(client, online);
// Process user input
client.on("data", (data) => {
const input = data.trim();
// testing
if (input === "status") {
console.log(client.status);
} else if (input === "queue") {
console.log(queue.map(u => u.gameID));
} else if (input === "online") {
console.log(online);
}
// Add player to queue if they're in the lobby
if (input === "play" && client.status === "lobby") {
msg.joinQueue(client, queue);
// If there are 2+ people in queue, remove the next 2 players from queue and prompt them to ready up
if (queue.length > 1) {
getNext(queue);
}
// Ready up player if they're waiting to start
} else if (input === "ready" && client.status === "unready") {
client.status = "ready";
client.write(cyan("Waiting for game to start..."));
}
// give priority queue status on opponent time out?
});
client.on("end", () => {
// Clear any timeouts
clearTimeout(client.countdown);
// If a client has an opponent waiting, notify them
const opponent = client.opponent;
// TODO: if user is playing
if (opponent && ["unready", "ready", "playing"].includes(opponent.status)) {
msg.opponentTimedOut(opponent, queue);
}
const id = client.gameID;
delete users[id];
if (queue.includes(client)) {
queue.splice(queue.indexOf(client), 1);
}
console.log(red(`Client #${id} disconnected.`));
online -= 1;
});
});
// Server can run only on a specific port
// Only one server per port
server.listen(PORT, () => {
console.log(cyan(`Battleship server is online on port ${PORT}`));
}); | bc87143c5c22d28c6bf2fd6ec2a905f954176438 | [
"JavaScript"
] | 7 | JavaScript | ahhreggi/battleship | a65c855f8404acfac10767db8a88f594da766c96 | b1a6bdb2acd11ed6b0bd2da3ce827b286b31fdd3 |
refs/heads/master | <repo_name>cdwaddell/EfConfiguration<file_sep>/README.md
# Titanosoft.EfConfiguration

### What is EfConfiguration?
EfConfiguration is a dotnet Standard 2.0 library for pulling configuration settings from a database. With support for auto reloading of settings.
### How do I get started?
First install the nuget package:
```
PM> Install-Package Titanosoft.EfConfiguration
```
Then add your this as a step in setting up your configuration (in Startup.cs):
```csharp
public Startup(IHostingEnvironment env)
{
CurrentEnvironment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables("CoreBlogger_")
//One of your settings before this must contain your connection string
//DefaultConnection is used if none is specified
.AddEntityFameworkValues();
if (!env.IsProduction())
{
builder.AddApplicationInsightsSettings(true);
}
Configuration = builder.Build();
}
```
### What about advanced configuration?
If you need to change the connection string name or how often to check for changes, you can specify it in the options:
```csharp
var builder = new ConfigurationBuilder()
...
.AddEntityFameworkValues(options => {
options.ConnectionStringName = "DefaultConnection";
options.PollingInterval = 1000;
});
```
### How do I use the settings?
These settings are used like any other setting in dotnet core. First you can inject ```IConfgiuration``` and access items by key. Or you can use ```IOptions```. What sets this library appart from others is that it supports ```IOptionsSnapshot``` so your application can have its settings changed at runtime. You can read more about these configuration options here.
[Configuration in ASP.Net Core](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration)
### What if I don't want to give full db access to the user?
Don't worry, you don't have to. You can just give full schema access. Use the following sql script to create the user for the connection given to the configuration connection string. This will isolate your other schemas from being affected by the library:
```sql
CREATE USER [AspConfiguration] WITH PASSWORD = '<PASSWORD>'
GO
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE [name] = 'cfg') EXEC ('CREATE SCHEMA [cfg]')
GO
ALTER AUTHORIZATION ON SCHEMA::[cfg] TO [AspConfiguration]
GO
GRANT CREATE TABLE TO [AspConfiguration]
GO
```
### What if I don't want to automigrate at all?
You also don't have to do this, but it is a little more work. Inside of the nuget package is a "tools" folder. In that folder is a "Migrations.sql" file. If you retreive that file and run it as part of your deployment, your database will always be up to date. Note: the user running the deployment script will have to have the above access.
<file_sep>/src/EfConfiguration/EfConfigurationSource.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Titanosoft.EfConfiguration
{
public class EfConfigurationSource : IConfigurationSource
{
private readonly DbContextOptions<ConfigurationContext> _dbOptions;
private readonly EfConfgurationOptions _efOptions;
/// <summary>
/// Create a configuration source that returns configuration items from the database
/// </summary>
/// <param name="dbOptions">The Entity Framework Database Configuration</param>
/// <param name="efOptions">The options to use for this source</param>
public EfConfigurationSource(DbContextOptions<ConfigurationContext> dbOptions, EfConfgurationOptions efOptions)
{
_dbOptions = dbOptions;
_efOptions = efOptions;
}
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new EfConfigurationProvider(_dbOptions, _efOptions);
}
}
}<file_sep>/src/EfConfiguration/Migrations.sql
--This is a placeholder that is replaced by the build process<file_sep>/test/EfConfiguration.Tests/EfConfigurationExtensionsTests.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.EntityFrameworkCore;
using Titanosoft.EfConfiguration;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace EfConfiguration.Tests
{
public class EfConfigurationExtensionsTests
{
[Fact]
[Trait("Category", "Unit")]
public void ThrowsIfNoConnectionString()
{
Assert.Throws(typeof(ArgumentNullException), () =>
new ConfigurationBuilder().AddEntityFameworkValues()
);
}
[Fact]
[Trait("Category", "Unit")]
public void DoesNotThrowIfConnectionString()
{
var expected = new KeyValuePair<string, string>("ConnectionStrings:DefaultConnection", "SomeConnectionString");
new ConfigurationBuilder()
.AddInMemoryCollection(new List<KeyValuePair<string, string>> {expected})
.AddEntityFameworkValues();
}
[Fact]
[Trait("Category", "Unit")]
public void DoesNotThrowIfCustomConnectionString()
{
const string name = "SomeConnectionName";
var expected = new KeyValuePair<string, string>($"ConnectionStrings:{name}", "SomeConnectionString");
new ConfigurationBuilder()
.AddInMemoryCollection(new List<KeyValuePair<string, string>> {expected})
.AddEntityFameworkValues(options => options.ConnectionStringName = name);
}
[Fact]
[Trait("Category", "Unit")]
public void ValueGetsUpdated()
{
var dbOptions = new DbContextOptionsBuilder<ConfigurationContext>()
.UseInMemoryDatabase("TestValues");
var initial = "Initial";
var expected = "Expected";
var key = "Test:Test";
var timeout = 500;
using (var context = new ConfigurationContext(dbOptions.Options))
{
context.Values.Add(new ConfigurationValue {Key = "Test:Test", Value = initial});
context.SaveChanges();
}
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>(key, expected) })
.TestAddEntityFameworkValues(dbOptions, timeout)
.Build();
var actual = configuration[key];
Assert.Equal(initial, actual);
using (var context = new ConfigurationContext(dbOptions.Options))
{
context.Values.Single(x => x.Key == "Test:Test").Value = expected;
context.SaveChanges();
}
Thread.Sleep(timeout);
var newActual = configuration[key];
Assert.Equal(initial, newActual);
}
}
internal static class ExtensionFeatures
{
internal static IConfigurationBuilder TestAddEntityFameworkValues(this IConfigurationBuilder builder, DbContextOptionsBuilder<ConfigurationContext> dbOptions, int pollingInterval = 1000)
{
//set the default settings
var efOptions = new EfConfgurationOptions
{
ConnectionStringName = "DefaultConnection",
PollingInterval = pollingInterval
};
//add our new database source for configuration items
return builder.Add(new EfConfigurationSource(dbOptions.Options, efOptions));
}
}
}
<file_sep>/src/EfConfiguration/ConfigurationContext.cs
using Microsoft.EntityFrameworkCore;
namespace Titanosoft.EfConfiguration
{
public class ConfigurationContext : DbContext
{
public ConfigurationContext(DbContextOptions options) : base(options)
{
}
public DbSet<ConfigurationValue> Values { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ConfigurationValue>(t =>
{
t.HasKey(x => x.Key);
t.Property(x => x.Key)
.HasMaxLength(64);
t.Property(x => x.LastUpdated)
.HasDefaultValueSql("GETUTCDATE()")
.HasField("_lastUpdated");
t.HasIndex(x => x.LastUpdated);
t.ToTable("ConfigurationValues", "cfg");
});
}
}
}<file_sep>/src/EfConfiguration/ConfigurationValue.cs
using System;
namespace Titanosoft.EfConfiguration
{
public class ConfigurationValue
{
public string Key { get; set; }
public string Value { get; set; }
//This method is directly accessed by Entity Framework, users shouldn't set/change it
#pragma warning disable 649
private DateTime? _lastUpdated;
#pragma warning restore 649
// ReSharper disable once ConvertToAutoProperty
public DateTime LastUpdated => _lastUpdated ?? DateTime.UtcNow;
}
}<file_sep>/src/EfConfiguration/EfSqlMigrationBuilderExtensions.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace Titanosoft.EfConfiguration
{
public static class EfSqlMigrationBuilderExtensions
{
public static void ExecSql(this MigrationBuilder migrationBuilder, string script)
{
migrationBuilder.Sql(GetSql(script));
}
/// <summary>
/// Convert a SQL script into something that is not prone to break scripted endoints if the schema every changes
/// </summary>
/// <param name="script">The SQL script to run</param>
/// <returns>The SQL script escaped using an EXEC statement. This new script is not prone to breaking when future schema changes</returns>
private static string GetSql(string script)
{
return "EXEC('" + script.Replace("'", "''") + "')";
}
}
}<file_sep>/src/EfConfiguration/EfConfigurationProvider.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Titanosoft.EfConfiguration
{
public class EfConfigurationProvider : ConfigurationProvider, IDisposable
{
private static readonly object LockObject = new object();
private static DateTime _lastRequested;
public EfConfigurationProvider(DbContextOptions<ConfigurationContext> dbOptions, EfConfgurationOptions efOptions)
{
_cancellationToken = new CancellationTokenSource();
_dbOptions = dbOptions;
_efOptions = efOptions;
}
private readonly DbContextOptions<ConfigurationContext> _dbOptions;
private readonly EfConfgurationOptions _efOptions;
private readonly CancellationTokenSource _cancellationToken;
private Task _backgroundWorker;
/// <inheritdoc />
/// <summary>
/// The initial load for the Data dictionary, this also configures the background worker
/// </summary>
public override void Load()
{
using (var dbContext = new ConfigurationContext(_dbOptions))
{
try
{
dbContext.Database.Migrate();
}
catch (InvalidOperationException)
{
dbContext.Database.EnsureCreated();
}
_lastRequested = DateTime.UtcNow;
Data = GetDictionaryFromDatabase(dbContext);
}
_backgroundWorker = Task.Factory.StartNew(token =>
{
while (!((CancellationToken)token).IsCancellationRequested)
{
if (HasChanged) UpdateFromDatabase();
Thread.Sleep(_efOptions.PollingInterval);
}
}, _cancellationToken.Token, _cancellationToken.Token);
}
/// <summary>
/// Flag the values as changed if the lastupdated date of an item is after the last run
/// </summary>
private bool HasChanged
{
get
{
try
{
using (var context = new ConfigurationContext(_dbOptions))
{
var now = DateTime.UtcNow;
//Query the database as quickly as you can to determine if anything has been updated
var lastUpdated = context.Values
.Where(c => c.LastUpdated <= now)
.OrderByDescending(v => v.LastUpdated)
.Select(v => v.LastUpdated)
.FirstOrDefault();
var hasChanged = lastUpdated > _lastRequested;
_lastRequested = lastUpdated;
return hasChanged;
}
}
catch (SqlException)
{
return false;
}
}
}
/// <summary>
/// Query the database and update the dictionary in a thread safe way
/// </summary>
private void UpdateFromDatabase()
{
using (var dbContext = new ConfigurationContext(_dbOptions))
{
var dict = GetDictionaryFromDatabase(dbContext);
lock (LockObject)
{
Data = dict;
}
OnReload();
}
}
/// <summary>
/// Retreives the configuration dictionary from the database
/// </summary>
/// <param name="dbContext"></param>
/// <returns>The KeyValuePairs that represent configuration entries from the database</returns>
private static IDictionary<string, string> GetDictionaryFromDatabase(ConfigurationContext dbContext)
{
try
{
return dbContext.Values
.ToDictionary(c => c.Key, c => c.Value);
}
catch (SqlException)
{
return new Dictionary<string, string>();
}
}
public void Dispose()
{
//since we have a background thread, we need to stop it
_cancellationToken.Cancel();
//then dispose of it
_backgroundWorker?.Dispose();
_backgroundWorker = null;
}
}
}
<file_sep>/src/EfConfiguration/EfConfgurationOptions.cs
namespace Titanosoft.EfConfiguration
{
/// <summary>
/// This class is used to configure the EfConfiguration module
/// </summary>
public class EfConfgurationOptions
{
/// <summary>
/// Get or Set the name of the connection string to your database, defaults to "<value>DefaultConnection</value>"
/// </summary>
public string ConnectionStringName { get; set; }
/// <summary>
/// Get or Set the interval, in milliseconds, between attempts to check the database for updates, defaults to 1000
/// </summary>
public int PollingInterval { get; set; }
}
}<file_sep>/src/EfConfiguration/DesignTimeDbContextFactory.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace Titanosoft.EfConfiguration
{
//This is a utility class that allows migrations to be setup inside of a dotnet Standard library
internal class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ConfigurationContext>
{
public ConfigurationContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<ConfigurationContext>();
builder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=CoreBlogger;Trusted_Connection=True;MultipleActiveResultSets=true");
return new ConfigurationContext(builder.Options);
}
}
}<file_sep>/src/EfConfiguration/Migrations/20170908140226_EfConfigurationInitial.cs
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace Titanosoft.EfConfiguration.Migrations
{
public partial class EfConfigurationInitial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "cfg");
migrationBuilder.CreateTable(
name: "ConfigurationValues",
schema: "cfg",
columns: table => new
{
Key = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
LastUpdated = table.Column<DateTime>(type: "datetime2", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ConfigurationValues", x => x.Key);
});
migrationBuilder.CreateIndex(
name: "IX_ConfigurationValues_LastUpdated",
schema: "cfg",
table: "ConfigurationValues",
column: "LastUpdated");
//Custom migration step to setup a trigger, so that database all calls update the LastUpdated field
migrationBuilder.ExecSql(@"
CREATE TRIGGER TR_ConfigurationValues_UpdateTimeEntry
ON cfg.ConfigurationValues
AFTER UPDATE
AS
UPDATE c
SET LastUpdated = GETUTCDATE()
FROM cfg.ConfigurationValues c
JOIN Inserted i ON c.[Key] = i.[Key]
");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ConfigurationValues",
schema: "cfg");
}
}
}
<file_sep>/src/EfConfiguration/EfConfigurationExtensions.cs
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Titanosoft.EfConfiguration
{
public static class EfConfigurationExtensions
{
public static IConfigurationBuilder AddEntityFameworkValues(this IConfigurationBuilder builder, Action<EfConfgurationOptions> optionsAction = null)
{
//build the configuration up to this point
var connectionStringConfig = builder.Build();
//set the default settings
var efOptions = new EfConfgurationOptions
{
ConnectionStringName = "DefaultConnection",
PollingInterval = 1000
};
//invoke user customized settings
optionsAction?.Invoke(efOptions);
//configure entity framework to use SqlServer
var dbOptions = new DbContextOptionsBuilder<ConfigurationContext>();
var migrationsAssembly = typeof(EfConfigurationExtensions).GetTypeInfo().Assembly.GetName().Name;
dbOptions = dbOptions.UseSqlServer(
connectionStringConfig.GetConnectionString(efOptions.ConnectionStringName),
options => options.MigrationsAssembly(migrationsAssembly)
);
//add our new database source for configuration items
return builder.Add(new EfConfigurationSource(dbOptions.Options, efOptions));
}
}
} | 091ae7c8dcf7546090d3748e40bfe2919df15d34 | [
"Markdown",
"C#",
"SQL"
] | 12 | Markdown | cdwaddell/EfConfiguration | 6ac5eb74c41906fd5109834431f10da2415714dd | 69662e563d57b8661fb2b6a1d3ef5c07da3e1bc3 |
refs/heads/main | <file_sep>package com.zs.zs_jetpack.ui.my
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import com.zs.zs_jetpack.bean.ArticleBean
/**
* @date 2020/7/13
* @author zs
*/
class MyArticleVM :BaseViewModel(){
private val repo by lazy { MyArticleRepo(viewModelScope,errorLiveData) }
val myLiveDate = MutableLiveData<MutableList<ArticleBean.DatasBean>>()
val deleteLiveData = MutableLiveData<Int>()
fun getMyArticle(isRefresh:Boolean){
repo.getMyArticle(isRefresh,myLiveDate,emptyLiveDate)
}
fun delete(id:Int){
repo.delete(id,deleteLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.rank
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
/**
* des 排名
* @date 2020/7/13
* @author zs
*/
class RankVM :BaseViewModel(){
private val repo by lazy { RankRepo(viewModelScope,errorLiveData) }
val rankLiveData = MutableLiveData<MutableList<RankBean.DatasBean>>()
/**
* 获取排名
*/
fun getRank(isRefresh:Boolean){
repo.getRank(isRefresh,rankLiveData)
}
}<file_sep>include ':kotlinlib'
rootProject.name='KotlinMvvmJetpack'
include ':app'
include ':base-library'
<file_sep>package com.zs.zs_jetpack.ui.collect
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import com.zs.zs_jetpack.bean.ArticleBean
/**
* des 文章vm
* @date 2020/7/8
* @author zs
*/
class CollectVM : BaseViewModel() {
private val repo by lazy { CollectRepo(viewModelScope, errorLiveData) }
/**
* 收藏的的文章
*/
val articleLiveData = MutableLiveData<MutableList<CollectBean.DatasBean>>()
/**
* 取消收藏
*/
val unCollectLiveData = MutableLiveData<Int>()
/**
* 获取收藏列表
*/
fun getCollect(isRefresh: Boolean) {
repo.getCollect(
isRefresh, articleLiveData, emptyLiveDate
)
}
/**
* 取消收藏
*/
fun unCollect(id: Int) {
repo.unCollect(id, unCollectLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.login
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.toast
import com.zs.base_library.utils.KeyBoardUtil
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import kotlinx.android.synthetic.main.fragment_login.*
/**
* des 登陆
* @date 2020/7/9
* @author zs
*/
class LoginFragment : BaseVmFragment() {
private lateinit var loginVM: LoginVM
override fun initViewModel() {
loginVM = getFragmentViewModel(LoginVM::class.java)
}
override fun init(savedInstanceState: Bundle?) {
initView()
}
override fun observe() {
loginVM.loginLiveData.observe(this, Observer {
toast("登陆成功")
nav().navigateUp()
})
loginVM.errorLiveData.observe(this, Observer {
setViewStatus(true)
})
}
override fun initView() {
setNoRepeatClick(tvRegister, ivClear, ivPasswordVisibility, llLogin, tvSkip) {
when (it.id) {
//注册
R.id.tvRegister -> nav().navigate(R.id.action_main_fragment_to_register_fragment)
//清除账号
R.id.ivClear -> {
loginVM.username.set("")
}
//密码是否可见
R.id.ivPasswordVisibility -> {
//true false 切换
loginVM.passIsVisibility.set(!loginVM.passIsVisibility.get()!!)
}
//登陆
R.id.llLogin -> {
//关闭软键盘
KeyBoardUtil.closeKeyboard(etUsername,mActivity)
KeyBoardUtil.closeKeyboard(etPassword,mActivity)
if (loginVM.username.get()!!.isEmpty()){
toast("请填写用户名")
return@setNoRepeatClick
}
if (loginVM.password.get()!!.isEmpty()){
toast("请填写密码")
return@setNoRepeatClick
}
login()
}
//跳过登陆
R.id.tvSkip -> {
nav().navigateUp()
}
}
}
}
private fun login() {
setViewStatus(false)
loginVM.login()
}
/**
* 登录时给具备点击事件的View上锁,登陆失败时解锁
* 并且施加动画
*/
private fun setViewStatus(lockStatus:Boolean){
llLogin.isEnabled = lockStatus
tvRegister.isEnabled = lockStatus
tvSkip.isEnabled = lockStatus
etUsername.isEnabled = lockStatus
etPassword.isEnabled = lockStatus
if (lockStatus) {
tvLoginTxt.visibility = View.VISIBLE
indicatorView.visibility = View.GONE
indicatorView.hide()
}else {
tvLoginTxt.visibility = View.GONE
indicatorView.visibility = View.VISIBLE
indicatorView.show()
}
}
override fun getLayoutId(): Int? {
return R.layout.fragment_login
}
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_login, loginVM)
.addBindingParam(BR.vm, loginVM)
}
}<file_sep>package com.zs.zs_jetpack.ui.v2ex
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
class V2exVM : BaseViewModel() {
/**
* V2ex最近热点
*/
var mV2exLiveData = MutableLiveData<MutableList<V2exBeanItem>>()
private val repo by lazy {
V2exRepo(viewModelScope, errorLiveData)
}
val userName = ObservableField<String>().apply {
set("")
}
fun getTopList() {
repo.getLateTopic(mV2exLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.publish
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 发布
* @author zs
* @data 2020/7/12
*/
class PublishRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
/**
* 发布
* @param title 文章标题
* @param link 文章链接
*/
fun publish(title:String,link:String,publishLiveData : MutableLiveData<Any>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.publishArticle(title,link)
.data(Any::class.java)
},
success = {
publishLiveData.postValue(it)
}
)
}
}<file_sep>package com.zs.zs_jetpack.http
import android.util.Log
import com.zs.zs_jetpack.constants.ApiConstants
/**
* des 初始化Retrofit,维护多个ApiService单例对象
*
* @author zs
* @date 2020-05-09
*/
class RetrofitManager {
companion object {
/**
* 用于存储ApiService
*/
private val map = mutableMapOf<Class<*>, Any>()
/**
* 只初始化一次
*/
private var retrofit = RetrofitFactory.factory()
// 可以指定域名
fun <T : Any> getApiService(
apiClass: Class<T>,
url: String = "https://www.wanandroid.com"
): T {
return getService(apiClass, url)
}
//动态指定域名
fun <T : Any> getResApiService(apiClass: Class<T>): T {
return getService(apiClass, "")
}
/**
* 获取ApiService单例对象
*/
private fun <T : Any> getService(apiClass: Class<T>, url: String): T {
//重入锁单例避免多线程安全问题
return if (map[apiClass] == null) {
synchronized(RetrofitManager::class.java) {
val t: Any
if (url == ApiConstants.BASE_URL) { // 默认的url
Log.e("tag","------进入默认的url------")
t = retrofit.create(apiClass)
if (map[apiClass] == null) {
map[apiClass] = t
}
t
} else { // 动态的url
Log.e("tag","------获取动态的url------")
retrofit = RetrofitFactory.factory(url)
t = retrofit.create(apiClass)
if (map[apiClass] == null) {
map[apiClass] = t
}
t
}
}
} else {
map[apiClass] as T
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.v2ex
/**
* @author zhangtianyang
* V2ex最近热点的实体类
*/
data class V2exBeanItem(
var content: String,
var content_rendered: String,
var created: Int,
var id: Int,
var last_modified: Int,
var last_reply_by: String,
var last_touched: Int,
var member: Member,
var node: Node,
var replies: Int,
var title: String,
var url: String
)
data class Member(
var avatar_large: String,
var avatar_mini: String,
var avatar_normal: String,
var bio: Any?,
var btc: Any?,
var created: Int,
var github: Any?,
var id: Int,
var location: Any?,
var psn: Any?,
var tagline: Any?,
var twitter: Any?,
var url: String,
var username: String,
var website: Any?
)
data class Node(
var aliases: List<Any>,
var avatar_large: String,
var avatar_mini: String,
var avatar_normal: String,
var footer: String,
var header: String,
var id: Int,
var name: String,
var parent_node_name: String,
var root: Boolean,
var stars: Int,
var title: String,
var title_alternative: String,
var topics: Int,
var url: String
)<file_sep>package com.zs.zs_jetpack
import androidx.databinding.ObservableField
import com.zs.base_library.base.BaseViewModel
import com.zs.zs_jetpack.play.PlayerManager
/**
* des 关于播放viewModel,播放、播放列表、首页悬浮共用
* @author zs
* @date 2020/6/28
*/
class PlayViewModel :BaseViewModel(){
/**
* 歌名
*/
val songName = ObservableField<String>().apply { set("暂无播放") }
/**
* 歌手
*/
val singer = ObservableField<String>().apply { set("") }
/**
* 专辑图片
*/
val albumPic = ObservableField<Long>()
/**
* 播放状态
*/
val playStatus = ObservableField<Int>()
/**
* 图片播放模式
*/
val playModePic = ObservableField<Int>().apply {
set(R.mipmap.play_order)
}
/**
* 文字播放模式
*/
val playModeText = ObservableField<String>()
/**
* 总播放时长-文本
*/
val maxDuration = ObservableField<String>().apply {
set("00:00")
}
/**
* 当前播放时长-文本
*/
val currentDuration = ObservableField<String>().apply {
set("00:00")
}
/**
* 总长度
*/
val maxProgress = ObservableField<Int>()
/**
* 播放进度
*/
val playProgress = ObservableField<Int>()
/**
* 播放进度
*/
val collect = ObservableField<Boolean>()
/**
* 重置
*/
fun reset(){
songName.set("")
singer.set("")
albumPic.set(-1)
playStatus.set(PlayerManager.PAUSE)
maxDuration.set("00:00")
currentDuration.set("00:00")
maxProgress.set(0)
playProgress.set(0)
collect.set(false)
}
}<file_sep>package com.zs.zs_jetpack.ui.register
import android.os.Bundle
import androidx.lifecycle.Observer
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.toast
import com.zs.base_library.utils.KeyBoardUtil
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import kotlinx.android.synthetic.main.fragment_register.*
/**
* des 注册
* @date 2020/7/9
* @author zs
*/
class RegisterFragment : BaseVmFragment() {
override fun getLayoutId() = R.layout.fragment_register
private lateinit var registerVM: RegisterVM
override fun initViewModel() {
registerVM = getFragmentViewModel(RegisterVM::class.java)
}
override fun observe() {
registerVM.registerLiveData.observe(this, Observer {
toast("注册成功")
nav().navigateUp()
})
}
override fun init(savedInstanceState: Bundle?) {
initView()
}
override fun initView() {
setNoRepeatClick(
ivBack,
ivClear,
ivPasswordVisibility,
ivRePasswordVisibility,
rlRegister
) {
when (it.id) {
//回退
R.id.ivBack -> nav().navigateUp()
//重置用户名
R.id.ivClear -> registerVM.username.set("")
//密码是否明文
R.id.ivPasswordVisibility -> registerVM.passIsVisibility.set(!registerVM.passIsVisibility.get()!!)
//确认密码是否明文
R.id.ivRePasswordVisibility -> registerVM.rePassIsVisibility.set(!registerVM.rePassIsVisibility.get()!!)
//注册
R.id.rlRegister -> {
//关闭软键盘
KeyBoardUtil.closeKeyboard(etUsername,mActivity)
KeyBoardUtil.closeKeyboard(etPassword,mActivity)
KeyBoardUtil.closeKeyboard(etRePassword,mActivity)
if (registerVM.username.get()!!.isEmpty()){
toast("请填写用户名")
return@setNoRepeatClick
}
if (registerVM.password.get()!!.isEmpty()){
toast("请填写密码")
return@setNoRepeatClick
}
if (registerVM.rePassword.get()!!.isEmpty()){
toast("请填写确认密码")
return@setNoRepeatClick
}
registerVM.register()
}
}
}
}
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_register, registerVM)
.addBindingParam(BR.vm, registerVM)
}
}<file_sep>package com.zs.zs_jetpack.constants
object ApiConstants {
const val BASE_URL = "https://www.wanandroid.com"
const val V2EX_URL = "https://www.v2ex.com" // v2ex的域名
const val PAGE_SIZE = 20
}<file_sep>### 1. 背景
`图片如若不能浏览请到我的博客主页查看:`[https://juejin.im/post/5f09ac336fb9a07e93303162](https://juejin.im/post/5f09ac336fb9a07e93303162)
之前公司项目用的一直是`MVP`框架,我个人也在几个月前基于`鸿神 WanAndroid API`开发了一款`MVP`版的`App`,使用`MVP`的过程最深的感受是开发效率极低,往往写一大堆接口,可复用的屈指可数。年初了解了`Jetpack`模式下的`MVVM`,在`LiveData、ViewModel、DataBinDing`的加持下实现了`单向依赖`和`数据绑定`,代码量大幅度减少,根据`Jetpack`的特性项目稳定性也提升了不少。
为了更深入的理解`Jetpack`中各个组件,在前段时间基于`Jetpack MVVM`又实现了一版` WanAndroid`。相比上一版的`MVP`增加了`夜间模式`和`音乐播放器`,播放器界面仿照`网易云音乐`。`App`中也大量的使用属性动画让界面简约而不简陋。先上图look一波

`先附上github:`[https://github.com/zskingking/Jetpack-Mvvm](https://github.com/zskingking/Jetpack-Mvvm)
### 2. 应用技术
基础框架选用`MVVM`,选用的`Jetpack`组件包括`Lifecycle、ViewModel、LiveData、DataBinDing、Navigation、Room`。
项目基于`Navigation`由单`Activity`多`Fragment`实现,使用这种模式给我最直观的感受就是`快`,比如点击搜索进入搜索界面的衔接动画,在多`Activity`之间是不可能这么连贯的。
整个项目全部使用`Kotlin`语言,广泛应用了`协程`编写了大量的`扩展函数`。
关于每个模块的职责我是这样定义的:
#### Model
对应项目中`Repository`,做数据请求以及业务逻辑。很多人将业务逻辑编写到`VM`层,但我个人认为写在`Model`层更为合适,因为数据和业务逻辑本身就是息息相关,拿到数据及时处理业务逻辑,最后通过`ViewModel`注入的`LiveData`将数据发送给`View`层。在该层我也对协程做了封装,以及统一捕获处理错误信息。
#### ViewModel
基于`Jetpack`中的`ViewModel`进行封装(友情提示:`Jetpack ViewModel`和`MVVM ViewModel`没有半毛钱关系,切勿将两个概念混淆)。在项目中`VM`层职责很简单,通过内部通过`LiveData`做数据存储,以及结合`DataBinding`做数据绑定。
#### View
尽量只做UI渲染。与`MVP`中不同,View是通过DataBinding与数据进行绑定,`Activity`或`Fragment`非常轻盈只专注于生命周期的管理,数据渲染基本全部由`DataBinding+BindAdapter`实现。
关于`MVVM`模版类的封装可至`package com.zs.base_library.base(包名)`下查看。
#### 网络层
关于网络层继续使用`OkHttp Retrofit`,并对Retrofit多`ApiService`以及多域名进行了封装。配合`Repository`中封装的协程使用美得不能再美。
#### 数据库
项目中`历史记录`是在本地数据库进行维护的,关于数据库使用了`Jetpack`中的`Room`。
#### 主题切换
`Android`原生提供的夜间切换好像又`API`版本限制,所以就没有用。我个人在本地维护了两套主题,可动态切换。当前包含`白天、夜间`两套主题
### 3. 关于注释
去年在我的`Leader`强行督促下养成了写注释的规习惯,我个人对写注释的要求也越来越高。
项目中运用了大量的设计模式,每用到一种`设计模式`我都会结合当时场景进行解释,比如播放器中某个接口,我会这样写注释:
```
/**
* des 所有的具体Player必须实现该接口,目的是为了让PlayManager不依赖任何
* 具体的音频播放实现,原因大概有两点
*
* 1.PlayManager包含业务信息,Player不应该与业务信息进行耦合,否则每次改动都会对业务造成影响
*
* 2.符合开闭原则,如果需要对Player进行替换势必会牵连到PlayManager中的业务,因而造成不必要的麻烦
* 如果基于IPlayer接口编程,扩展出一个Player即可,正所谓对扩展开放、修改关闭
*
* @author zs
* @data 2020-06-23
*/
interface IPlayer {
....
....
}
/**
* des 音频管理
* 通过单例模式实现,托管音频状态与信息,并且作为唯一的可信源
* 通过观察者模式统一对状态进行分发
* 实则是一个代理,将目标对象Player与调用者隔离,并且在内部实现了对观察者的注册与通知
* @author zs
* @data 2020/6/25
*/
class PlayerManager private constructor() : IPlayerStatus {
....
....
}
```
* `关于播放器的设计我觉得还是有些地方值得和大家分享,后面我会单独写一篇文章进行分析。`
### 写在最后
此项目中你很难看到不明不白的代码。`Jetpack`和`Kotlin`是大势所趋,既然拒绝不了那何不开心的拥抱。功能目前已完成`90%`,代码也在持续优化,欢迎大家关注、下载源代码,让我们共同学习、共同进步。
再次附上`github:`[https://github.com/zskingking/Jetpack-Mvvm](https://github.com/zskingking/Jetpack-Mvvm),如果觉得对你有帮助麻烦给个`star`
<file_sep>package com.zs.zs_jetpack.ui.search
import android.animation.ValueAnimator
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.view.animation.ScaleAnimation
import androidx.activity.OnBackPressedCallback
import androidx.core.view.children
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.SimpleItemAnimator
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.dip2px
import com.zs.base_library.common.keyBoardSearch
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.smartDismiss
import com.zs.base_library.utils.KeyBoardUtil
import com.zs.base_library.utils.PrefUtils
import com.zs.base_library.utils.ScreenUtils
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.ArticleAdapter
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.utils.CacheUtil
import com.zs.zs_jetpack.view.LoadingTip
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_search.*
import java.util.concurrent.TimeUnit
class SearchFragment : BaseVmFragment() {
private lateinit var searchVM: SearchVM
private var recordList: MutableList<String>? = null
/**
* 文章适配器
*/
private lateinit var adapter: ArticleAdapter
/**
* 空白页,网络出错等默认显示
*/
private val loadingTip by lazy { LoadingTip(mActivity) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//自定义返回
val callback: OnBackPressedCallback =
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
startSearchAnim(false)
val disposable = Single.timer(250, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
nav().navigateUp()
}, {})
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
override fun initViewModel() {
searchVM = getFragmentViewModel(SearchVM::class.java)
}
override fun observe() {
searchVM.articleLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
adapter.submitList(it)
})
searchVM.emptyLiveDate.observe(this, Observer {
loadingTip.showEmpty()
})
searchVM.errorLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
if (it.errorCode == -100) {
//显示网络错误
loadingTip.showInternetError()
loadingTip.setReloadListener {
searchVM.search(true)
}
}
})
}
override fun init(savedInstanceState: Bundle?) {
//获取收缩记录
recordList = if (PrefUtils.getObject(Constants.SEARCH_RECORD) == null) {
mutableListOf()
} else {
PrefUtils.getObject(Constants.SEARCH_RECORD) as MutableList<String>?
}
initView()
loadData()
}
override fun initView() {
//关闭更新动画
(rvSearch.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
adapter = ArticleAdapter(mActivity).apply {
setOnItemClickListener { i, _ ->
nav().navigate(
R.id.action_main_fragment_to_web_fragment,
this@SearchFragment.adapter.getBundle(i)
)
}
setOnItemChildClickListener { i, view ->
when (view.id) {
//收藏
R.id.ivCollect -> {
if (CacheUtil.isLogin()) {
this@SearchFragment.adapter.currentList[i].apply {
//已收藏取消收藏
if (collect) {
searchVM.unCollect(id)
} else {
searchVM.collect(id)
}
}
} else {
nav().navigate(R.id.action_main_fragment_to_login_fragment)
}
}
}
}
rvSearch.adapter = this
}
startSearchAnim(true)
//加载更多
smartRefresh.setOnLoadMoreListener {
search(false)
}
//editText获取焦点
etSearch.requestFocus()
KeyBoardUtil.openKeyboard(etSearch, mActivity)
addListener()
}
/**
* 为EditText添加监听事件,以及搜索按钮
*/
private fun addListener() {
//搜索框监听事件
etSearch.doAfterTextChanged {
//搜索框为空的时候显示搜索历史
if (TextUtils.isEmpty(searchVM.keyWord.get()!!)) {
loadRecord()
//隐藏清除按钮
ivClear.visibility = View.GONE
smartRefresh.visibility = View.GONE
clRecord.visibility = View.VISIBLE
} else {
//显示清除按钮
ivClear.visibility = View.VISIBLE
etSearch.setSelection(searchVM.keyWord.get()!!.length)
}
}
//添加搜索按钮
etSearch.keyBoardSearch {
//将关键字空格去除
val keyWord = searchVM.keyWord.get()!!.trim { it <= ' ' }
//如果关键字部位null或者""
if (!TextUtils.isEmpty(keyWord)) {
//将已存在的key移除,避免存在重复数据
for (index in 0 until recordList?.size!!) {
if (recordList!![index] == keyWord) {
recordList!!.removeAt(index)
break
}
}
recordList?.add(keyWord)
search(true)
}
}
}
override fun onClick() {
setNoRepeatClick(ivClear,tvClear){
when(it.id){
R.id.ivClear-> searchVM.keyWord.set("")
R.id.tvClear->{
recordList?.clear()
loadRecord()
}
}
}
}
override fun loadData() {
loadRecord()
startLabelAnim()
}
override fun getLayoutId() = R.layout.fragment_search
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_search, searchVM)
.addBindingParam(BR.vm, searchVM)
}
/**
* 开启搜索动画
* @param isIn 是否为进
*/
private fun startSearchAnim(isIn: Boolean) {
//搜索按钮初始宽度为:屏幕宽度-140dp
val searchWidth = ScreenUtils.getScreenWidth(mActivity) - dip2px(mActivity, 140f)
//搜索按钮目标宽度为:屏幕宽度-32dp
val targetWidth = ScreenUtils.getScreenWidth(mActivity) - dip2px(mActivity, 32f)
//进入
val anim = if (isIn) {
ValueAnimator.ofInt(searchWidth, targetWidth)
}
//退出
else {
ValueAnimator.ofInt(targetWidth, searchWidth)
}
anim.duration = 249
anim.addUpdateListener {
val value = it.animatedValue as Int
//平滑的,动态的设置宽度
val params = clSearch.layoutParams as ViewGroup.MarginLayoutParams
params.width = value
clSearch.layoutParams = params
}
anim.start()
}
/**
* 标签展开动画
* 逐个展开设置可见,并开启动画
*/
private fun startLabelAnim() {
for (index in 0 until labelsView.childCount) run {
val view: View = labelsView.getChildAt(index)
view.visibility = View.VISIBLE
val aa = ScaleAnimation(0f, 1f, 0.5f, 1f)
aa.interpolator = DecelerateInterpolator()
aa.duration = 249
view.startAnimation(aa)
}
}
/**
* 加载搜索tag
*/
private fun loadRecord() {
labelsView.setLabels(recordList) { _, _, data ->
data
}
//不知为何,在xml中设置主题背景无效
for (child in labelsView.children){
child.setBackgroundResource(R.drawable.ripple_tag_bg)
}
//标签的点击监听
labelsView.setOnLabelClickListener { _, data, _ ->
if (data is String) {
searchVM.keyWord.set(data)
search(true)
}
}
}
/**
* @param isRefresh 是否为初次加载
*/
private fun search(isRefresh: Boolean) {
clRecord.visibility = View.GONE
smartRefresh.visibility = View.VISIBLE
searchVM.search(isRefresh)
KeyBoardUtil.closeKeyboard(etSearch, mActivity)
}
override fun onDestroyView() {
super.onDestroyView()
//将新的搜索记录保存在本地
PrefUtils.setObject(Constants.SEARCH_RECORD, recordList)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.tab
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
/**
* des tab
* @date 2020/7/7
* @author zs
*/
class TabVM :BaseViewModel(){
private val repo by lazy { TabRepo(viewModelScope,errorLiveData) }
/**
* tab
*/
val tabLiveData = MutableLiveData<MutableList<TabBean>>()
fun getTab(type:Int){
repo.getTab(type,tabLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.login
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.base_library.utils.PrefUtils
import com.zs.wanandroid.entity.UserBean
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.event.LoginEvent
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
import org.greenrobot.eventbus.EventBus
/**
* des 登陆
* @date 2020/7/9
* @author zs
*/
class LoginRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
fun login(username: String, password: String,loginLiveData : MutableLiveData<UserBean>) {
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.login(username,password)
.data()
},
success = {
//登陆成功保存用户信息,并发送消息
PrefUtils.setObject(Constants.USER_INFO,it)
//更改登陆轧辊台
PrefUtils.setBoolean(Constants.LOGIN,true)
//发送登陆消息
EventBus.getDefault().post(LoginEvent())
loginLiveData.postValue(it)
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.rank
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 排名
* @date 2020/7/13
* @author zs
*/
class RankRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 1
fun getRank(
isRefresh: Boolean,
rankLiveData: MutableLiveData<MutableList<RankBean.DatasBean>>
) {
launch(
block = {
if (isRefresh) {
page = 1
} else {
page++
}
RetrofitManager.getApiService(ApiService::class.java)
.getRank(page)
.data()
},
success = {
//做数据累加
rankLiveData.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null){
mutableListOf()
}else{
this
}
it.datas?.let { it1 -> currentList.addAll(it1) }
rankLiveData.postValue(currentList)
}
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.tab
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.ui.main.home.BannerBean
import com.zs.zs_jetpack.bean.ArticleListBean
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 每个tab下文章的数据层
* @date 2020/7/8
* @author zs
*/
class ArticleRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 1
/**
* 获取文章
* @param type 项目或者公号类型
* @param tabId tabId
* @param isRefresh 是否为刷新或第一次进入
* @param articleLiveData 文章liveData
*/
fun getArticle(
type: Int,
tabId: Int,
isRefresh: Boolean,
articleLiveData: MutableLiveData<MutableList<ArticleListBean>>
) {
launch(
block = {
//是否为刷新
if (isRefresh){
page = 1
}else{
page++
}
//项目
if (type == Constants.PROJECT_TYPE) {
RetrofitManager.getApiService(ApiService::class.java)
.getProjectList(page,tabId)
.data()
}
//公号
else {
RetrofitManager.getApiService(ApiService::class.java)
.getAccountList(tabId,page)
.data()
}
},
success = {
//做数据累加
articleLiveData.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null){
mutableListOf()
}else{
this
}
it.datas?.let { it1 -> currentList.addAll(ArticleListBean.trans(it1)) }
articleLiveData.postValue(currentList)
}
}
)
}
/**
* 获取banner
*/
private fun getBanner(banner: MutableLiveData<MutableList<BannerBean>>) {
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.getBanner()
.data()
},
success = {
banner.postValue(it)
}
)
}
/**
* 收藏
*/
fun collect(articleId:Int,articleList : MutableLiveData<MutableList<ArticleListBean>>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.collect(articleId)
.data(Any::class.java)
},
success = {
//此处直接更改list中模型,ui层会做diff运算做比较
articleList.value = articleList.value?.map { bean->
if (bean.id == articleId){
//拷贝一个新对象,将点赞状态置换。kotlin没找到复制对象的函数,有知道的麻烦告知一下~~~
ArticleListBean().apply {
id = bean.id
author = bean.author
collect = true
desc = bean.desc
picUrl = bean.picUrl
link = bean.link
date = bean.date
title = bean.title
articleTag = bean.articleTag
topTitle = bean.topTitle
}
}else{
bean
}
}?.toMutableList()
}
)
}
/**
* 收藏
*/
fun unCollect(articleId:Int,articleList : MutableLiveData<MutableList<ArticleListBean>>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.unCollect(articleId)
//如果data可能为空,可通过此方式通过反射生成对象,避免空判断
.data(Any::class.java)
},
success = {
//此处直接更改list中模型,ui层会做diff运算做比较
articleList.value = articleList.value?.map { bean->
if (bean.id == articleId){
//拷贝一个新对象,将点赞状态置换。kotlin没找到复制对象的函数,有知道的麻烦告知一下~~~
ArticleListBean().apply {
id = bean.id
author = bean.author
collect = false
desc = bean.desc
picUrl = bean.picUrl
link = bean.link
date = bean.date
title = bean.title
articleTag = bean.articleTag
topTitle = bean.topTitle
}
}else{
bean
}
}?.toMutableList()
}
)
}
}<file_sep>package com.zs.base_library.base
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.zs.base_library.common.toast
import com.zs.base_library.http.ApiException
import kotlinx.coroutines.CancellationException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
/**
* des 基础vm
* @date 2020/5/13
* @author zs
*/
open class BaseViewModel:ViewModel() {
/**
* 错误信息liveData
*/
val errorLiveData = MutableLiveData<ApiException>()
/**
* 无更多数据
*/
val footLiveDate = MutableLiveData<Any>()
/**
* 无数据
*/
val emptyLiveDate = MutableLiveData<Any>()
/**
* 处理错误
*/
fun handleError(e: Throwable){
val error = getApiException(e)
toast(error.errorMessage)
errorLiveData.postValue(error)
}
/**
* 捕获异常信息
*/
protected fun getApiException(e: Throwable): ApiException {
return when (e) {
is UnknownHostException -> {
ApiException("网络异常", -100)
}
is JSONException -> {//|| e is JsonParseException
ApiException("数据异常", -100)
}
is SocketTimeoutException -> {
ApiException("连接超时", -100)
}
is ConnectException -> {
ApiException("连接错误", -100)
}
is HttpException -> {
ApiException("http code ${e.code()}", -100)
}
is ApiException -> {
e
}
/**
* 如果协程还在运行,个别机型退出当前界面时,viewModel会通过抛出CancellationException,
* 强行结束协程,与java中InterruptException类似,所以不必理会,只需将toast隐藏即可
*/
is CancellationException -> {
ApiException("", -10)
}
else -> {
ApiException("未知错误", -100)
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.my
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.common.isListEmpty
import com.zs.base_library.common.toast
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.bean.ArticleBean
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 我的文章
* @date 2020/7/14
* @author zs
*/
class MyArticleRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 1
fun getMyArticle(
isRefresh: Boolean,
myLiveDate: MutableLiveData<MutableList<ArticleBean.DatasBean>>,
emptyLivedData: MutableLiveData<Any>)
{
launch(
block = {
if (isRefresh){
page = 1
}else{
page++
}
RetrofitManager.getApiService(ApiService::class.java)
.getMyArticle(page)
.data()
},
success = {
//处理刷新/分页数据
myLiveDate.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null){
mutableListOf()
}else{
this
}
it.shareArticles?.datas?.let { it1 -> currentList.addAll(it1) }
myLiveDate.postValue(currentList)
}
if (isListEmpty(it.shareArticles?.datas)) {
//第一页并且数据为空
if (page == 1) {
//预留
emptyLivedData.postValue(Any())
} else {
toast("没有数据啦~")
}
}
}
)
}
fun delete(id:Int,deleteLiveData : MutableLiveData<Int>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.deleteMyArticle(id)
.data(Any::class.java)
},
success = {
deleteLiveData.postValue(id)
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.home
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.bean.ArticleListBean
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
/**
* des 首页
* @date 2020/7/6
* @author zs
*/
class HomeRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 0
/**
* 获取首页文章列表,第一页
*/
suspend fun getArticle(): Flow<MutableList<ArticleListBean>> {
return flow<MutableList<ArticleListBean>> {
emit(
//请求置顶
RetrofitManager.getApiService(ApiService::class.java)
.getTopList()
.data()
.let {
//对模型转换
ArticleListBean.trans(it)
}
)
}.zip(
flow<MutableList<ArticleListBean>> {
emit(
//请求第一页
RetrofitManager.getApiService(ApiService::class.java)
.getHomeList(page)
.data()
.datas?.let {
ArticleListBean.trans(it)
}?: mutableListOf<ArticleListBean>()
)
}
) { a, b ->
a.apply {
//合并请求结果
addAll(b)
}
}.flowOn(Dispatchers.IO)
}
/**
* 分页获取首页文章列表
*/
suspend fun loadMoreArticle(): Flow<MutableList<ArticleListBean>> {
page++
return flow {
RetrofitManager.getApiService(ApiService::class.java)
.getHomeList(page)
.data()
.datas?.let {
ArticleListBean.trans(it)
}
?.let { res ->
emit(res)
}
}.flowOn(Dispatchers.IO)
}
/**
* 获取banner
*/
suspend fun getBanner(): Flow<MutableList<BannerBean>> {
return flow {
emit(
RetrofitManager.getApiService(ApiService::class.java)
.getBanner()
.data()
)
}.flowOn(Dispatchers.IO)
}
/**
* 收藏
*/
fun collect(id: Int,list:MutableList<ArticleListBean>)
: Flow<MutableList<ArticleListBean>> {
return flow {
RetrofitManager.getApiService(ApiService::class.java)
.collect(id)
.data(Any::class.java)
emit(
list.map {
//将收藏的对象做替换,并改变收藏状态
if (it.id == id){
ArticleListBean.copy(it).apply {
collect = true
}
}else{
it
}
}.toMutableList()
)
}.flowOn(Dispatchers.IO)
}
/**
* 取消收藏
*/
fun unCollect(id: Int,list:MutableList<ArticleListBean>)
: Flow<MutableList<ArticleListBean>> {
return flow {
RetrofitManager.getApiService(ApiService::class.java)
.unCollect(id)
.data(Any::class.java)
emit(
list.map {
//将收藏的对象做替换,并改变收藏状态
if (it.id == id){
ArticleListBean.copy(it).apply {
collect = false
}
}else{
it
}
}.toMutableList()
)
}.flowOn(Dispatchers.IO)
}
}
<file_sep>package com.zs.zs_jetpack.play
import com.zs.zs_jetpack.play.bean.AudioBean
/**
* des 音频播放观察者对象,可实时观察到音频信息、播放状态、播放进度
* @author zs
* @data 2020/6/25
*/
interface AudioObserver {
/**
* 歌曲信息
* 空实现,部分界面可不用实现
*/
fun onAudioBean(audioBean: AudioBean){}
/**
* 播放状态,目前有四种。可根据类型进行扩展
* release
* start
* resume
* pause
*
* 空实现,部分界面可不用实现
*/
fun onPlayStatus(playStatus:Int){}
/**
* 当前播放进度
* 空实现,部分界面可不用实现
*/
fun onProgress(currentDuration: Int,totalDuration:Int){}
/**
* 播放模式
*/
fun onPlayMode(playMode:Int)
/**
* 重置
*/
fun onReset()
}<file_sep>package com.zs.zs_jetpack.ui.main.mine
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
/**
* des 我的
* @date 2020/7/10
* @author zs
*/
class MineVM : BaseViewModel() {
/**
* 用户名
*/
val username = ObservableField<String>().apply {
set("请先登录")
}
/**
* id
*/
val id = ObservableField<String>().apply {
set("---")
}
/**
* 排名
*/
val rank = ObservableField<String>().apply {
set("0")
}
/**
* 当前积分
*/
val internal = ObservableField<String>().apply {
set("0")
}
private val repo by lazy { MineRepo(viewModelScope, errorLiveData) }
val internalLiveData = MutableLiveData<IntegralBean>()
fun getInternal() {
repo.getInternal(internalLiveData)
}
fun getFlowInternal() {
viewModelScope.launch {
repo.getInternal()
.catch {
//处理错误
handleError(it)
}
.collect {
internalLiveData.postValue(it)
}
}
}
}<file_sep>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion Version.compileSdkVersion
buildToolsVersion Version.buildToolsVersion
defaultConfig {
minSdkVersion Version.minSdkVersion
targetSdkVersion Version.targetSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dataBinding {
//noinspection DataBindingWithoutKapt
enabled = true
}
}
<file_sep>package com.zs.zs_jetpack.ui.main.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.zs_jetpack.bean.ArticleListBean
import com.zs.zs_jetpack.common.BasePageVM
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
* des 首页
* @date 2020/6/22
* @author zs
*/
class HomeVM : BasePageVM() {
private val repo by lazy { HomeRepo(viewModelScope, errorLiveData) }
/**
* 文章列表
*/
private val _articleList = MutableLiveData<MutableList<ArticleListBean>>()
/**
* 对外部提供只读的LiveData
*/
val articleList: LiveData<MutableList<ArticleListBean>> = _articleList
/**
* banner
*/
private val _banner = MutableLiveData<MutableList<BannerBean>>()
/**
* 对外部提供只读的LiveData
*/
val banner: LiveData<MutableList<BannerBean>> = _banner
/**
* 获取banner
*/
fun getBanner() {
viewModelScope.launch {
repo.getBanner()
.catch {
errorLiveData.postValue(getApiException(it))
}
.collect {
_banner.postValue(it)
}
}
}
/**
* 获取首页文章列表, 包括banner
*/
fun getArticle() {
viewModelScope.launch {
repo.getArticle()
.catch {
errorLiveData.postValue(getApiException(it))
}
.collect {
_articleList.postValue(it)
}
}
}
/**
* 加载更多
*/
fun loadMoreArticle() {
viewModelScope.launch {
repo.loadMoreArticle()
.catch {
errorLiveData.postValue(getApiException(it))
}
.collect {
articleList.value?.apply {
addAll(it)
}.let {
_articleList.postValue(it)
}
}
}
}
/**
* 收藏
*/
fun collect(id: Int) {
viewModelScope.launch {
_articleList.value?.let {
repo.collect(id, it)
.catch {
errorLiveData.postValue(getApiException(it))
}
.collect { result ->
_articleList.postValue(result)
}
}
}
}
/**
* 取消收藏
*/
fun unCollect(id: Int) {
viewModelScope.launch {
_articleList.value?.let {
repo.unCollect(id, it)
.catch {
errorLiveData.postValue(getApiException(it))
}
.collect { result ->
_articleList.postValue(result)
}
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.search
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.common.isListEmpty
import com.zs.base_library.common.toast
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.ui.main.home.BannerBean
import com.zs.zs_jetpack.bean.ArticleListBean
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* @author zs
* @data 2020/7/11
*/
class SearchRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 0
/**
* 搜索
*/
fun search(
isRefresh: Boolean, keyWord: String
, articleLiveData: MutableLiveData<MutableList<ArticleListBean>>
, emptyLiveData: MutableLiveData<Any>
) {
launch(
block = {
if (isRefresh) {
page = 0
} else {
page++
}
RetrofitManager.getApiService(ApiService::class.java)
.search(page, keyWord)
.data()
},
success = {
//处理刷新/分页数据
articleLiveData.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null) {
mutableListOf()
} else {
this
}
it.datas?.let { it1 -> currentList.addAll(ArticleListBean.trans(it1)) }
articleLiveData.postValue(currentList)
}
if (isListEmpty(it.datas)) {
//第一页并且数据为空
if (page == 0) {
emptyLiveData.postValue(Any())
} else {
toast("没有数据啦~")
}
}
}
)
}
/**
* 获取banner
*/
private fun getBanner(banner: MutableLiveData<MutableList<BannerBean>>) {
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.getBanner()
.data()
},
success = {
banner.postValue(it)
}
)
}
/**
* 收藏
*/
fun collect(articleId:Int,articleList : MutableLiveData<MutableList<ArticleListBean>>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.collect(articleId)
.data(Any::class.java)
},
success = {
//此处直接更改list中模型,ui层会做diff运算做比较
articleList.value = articleList.value?.map { bean->
if (bean.id == articleId){
//拷贝一个新对象,将点赞状态置换。kotlin没找到复制对象的函数,有知道的麻烦告知一下~~~
ArticleListBean().apply {
id = bean.id
author = bean.author
collect = true
desc = bean.desc
picUrl = bean.picUrl
link = bean.link
date = bean.date
title = bean.title
articleTag = bean.articleTag
topTitle = bean.topTitle
}
}else{
bean
}
}?.toMutableList()
}
)
}
/**
* 收藏
*/
fun unCollect(articleId:Int,articleList : MutableLiveData<MutableList<ArticleListBean>>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.unCollect(articleId)
//如果data可能为空,可通过此方式通过反射生成对象,避免空判断
.data(Any::class.java)
},
success = {
//此处直接更改list中模型,ui层会做diff运算做比较
articleList.value = articleList.value?.map { bean->
if (bean.id == articleId){
//拷贝一个新对象,将点赞状态置换。kotlin没找到复制对象的函数,有知道的麻烦告知一下~~~
ArticleListBean().apply {
id = bean.id
author = bean.author
collect = false
desc = bean.desc
picUrl = bean.picUrl
link = bean.link
date = bean.date
title = bean.title
articleTag = bean.articleTag
topTitle = bean.topTitle
}
}else{
bean
}
}?.toMutableList()
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.play.collect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.zs.base_library.common.clickNoRepeat
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.play.AudioObserver
import com.zs.zs_jetpack.play.PlayList
import com.zs.zs_jetpack.play.PlayerManager
import com.zs.zs_jetpack.play.bean.AudioBean
import com.zs.zs_jetpack.ui.play.history.HistoryAudioAdapter
import kotlinx.android.synthetic.main.fragment_play_list_collect.*
/**
* des
* @author zs
* @date 2020/10/29
*/
class PlayCollectFragment : Fragment(), AudioObserver {
private val adapter by lazy { CollectAudioAdapter() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_play_list_collect, container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
PlayerManager.instance.register(this)
click()
tvListSize.text = String.format("(%s)", PlayerManager.instance.getPlayListSize())
setPlayList()
}
private fun setPlayList() {
rvCollectPlayList.adapter = adapter
}
private fun click() {
llPlayMode.clickNoRepeat {
PlayerManager.instance.switchPlayMode()
}
}
override fun onDestroyView() {
super.onDestroyView()
PlayerManager.instance.unregister(this)
}
override fun onAudioBean(audioBean: AudioBean) {
adapter.updateCurrentPlaying()
}
override fun onPlayMode(playMode: Int) {
when (playMode) {
PlayList.PlayMode.ORDER_PLAY_MODE -> {
ivPlayMode.setImageResource(R.mipmap.play_order_gray)
tvPlayMode.text = "列表循环"
}
PlayList.PlayMode.SINGLE_PLAY_MODE -> {
ivPlayMode.setImageResource(R.mipmap.play_single_gray)
tvPlayMode.text = "单曲循环"
}
PlayList.PlayMode.RANDOM_PLAY_MODE -> {
ivPlayMode.setImageResource(R.mipmap.play_random_gray)
tvPlayMode.text = "随机播放"
}
}
}
override fun onReset() {
}
}<file_sep>package com.zs.base_library.common
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
/**
* des 基于ListAdapter封装的DataBinding适配器
* 泛型 T:模型类类型
* 泛型 B:ItemView对应的ViewDataBinding
* @author zs
* @date 2020/9/10
*/
abstract class BaseListAdapter<T, B : ViewDataBinding>(
private val context: Context, diffCallback: DiffUtil.ItemCallback<T>
) : ListAdapter<T, BaseListAdapter.BaseViewHolder>(diffCallback) {
/**
* item点击事件
* @param Int 角标
* @param View 点击的View
*/
private var onItemClickListener: ((Int, View) -> Unit)? = null
/**
* item中子View点击事件,需要子类做具体触发
* @param Int 角标
* @param View 点击的View
*/
private var onItemChildClickListener: ((Int, View) -> Unit)? = null
/**
* 注册item点击事件
*/
fun setOnItemClickListener(onItemClickListener: ((Int, View) -> Unit)? = null) {
this.onItemClickListener = onItemClickListener
}
/**
* 注册item子View点击事件
*/
fun setOnItemChildClickListener(onItemChildClickListener: ((Int, View) -> Unit)? = null) {
this.onItemChildClickListener = onItemChildClickListener
}
/**
* 创建viewHolder
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val binding: B = DataBindingUtil.inflate(
LayoutInflater.from(context),
this.getLayoutId(),
parent,
false
)
return BaseViewHolder(binding.root)
}
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
//onItemClickListener不为null即注册了点击事件,此时才会注册itemView点击事件
onItemClickListener?.let { click ->
//itemView点击事件
holder.itemView.clickNoRepeat {
click.invoke(holder.bindingAdapterPosition, it)
}
}
//获取ViewDataBinding
val binding = DataBindingUtil.getBinding<B>(holder.itemView)
binding?.let { onBindItem(getItem(position), it) }
binding?.executePendingBindings()
}
/**
* 重新加载数据时必须换一个list集合,否则diff不生效
*/
override fun submitList(list: List<T>?) {
super.submitList(if (list == null) mutableListOf() else
mutableListOf<T>().apply {
addAll(
list
)
})
}
/**
* 供子类绑定DataBinding
*/
abstract fun onBindItem(item: T, binding: B)
/**
* item布局id
*/
abstract fun getLayoutId(): Int
/**
* RecyclerView.ViewHolder是一个抽象类,创建一个BaseViewHolder方便使用
*/
class BaseViewHolder internal constructor(itemView: View) :
RecyclerView.ViewHolder(itemView)
}<file_sep>package com.zs.zs_jetpack
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.zs.base_library.base.BaseVmActivity
import com.zs.base_library.common.stringForTime
import com.zs.base_library.utils.PrefUtils
import com.zs.base_library.utils.StatusUtils
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.db.AppDataBase
import com.zs.zs_jetpack.play.AudioObserver
import com.zs.zs_jetpack.play.PlayList
import com.zs.zs_jetpack.play.PlayerManager
import com.zs.zs_jetpack.play.bean.AudioBean
import com.zs.zs_jetpack.ui.MainFragment
import com.zs.zs_jetpack.ui.play.collect.CollectAudioBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* des 主页面,作用有二
* 1.用于承载Fragment
* 2.作为音频播放观察者,接受到通知立即更新viewModel内状态
* 间接通过DataBinding更新View
*
* @author zs
* @date 2020-05-12
*/
class MainActivity : BaseVmActivity(), AudioObserver {
private var playVM: PlayViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
changeTheme()
super.onCreate(savedInstanceState)
}
override fun initViewModel() {
playVM = getActivityViewModel(PlayViewModel::class.java)
}
override fun init(savedInstanceState: Bundle?) {
PlayerManager.instance.register(this)
}
override fun onDestroy() {
super.onDestroy()
PlayerManager.instance.unregister(this)
}
override fun getLayoutId() = R.layout.activity_main
/**
* 歌曲信息
*/
override fun onAudioBean(audioBean: AudioBean) {
playVM?.songName?.set(audioBean.name)
playVM?.singer?.set(audioBean.singer)
playVM?.maxDuration?.set(stringForTime(audioBean.duration))
playVM?.maxProgress?.set(audioBean.duration)
playVM?.albumPic?.set(audioBean.albumId)
lifecycleScope.launch {
val bean = withContext(Dispatchers.IO) {
AppDataBase.getInstance()
.collectDao()
.findAudioById(audioBean.id)
}
playVM?.collect?.set(bean != null)
}
}
/**
* 播放状态-暂停/播放
*/
override fun onPlayStatus(playStatus: Int) {
playVM?.playStatus?.set(playStatus)
}
/**
* 当前播放进度
*/
override fun onProgress(currentDuration: Int, totalDuration: Int) {
playVM?.currentDuration?.set(stringForTime(currentDuration))
playVM?.playProgress?.set(currentDuration)
}
/**
* 播放模式
*/
override fun onPlayMode(playMode: Int) {
when (playMode) {
PlayList.PlayMode.ORDER_PLAY_MODE -> playVM?.playModePic?.set(R.mipmap.play_order)
PlayList.PlayMode.SINGLE_PLAY_MODE -> playVM?.playModePic?.set(R.mipmap.play_single)
PlayList.PlayMode.RANDOM_PLAY_MODE -> playVM?.playModePic?.set(R.mipmap.play_random)
}
}
/**
* 重置
*/
override fun onReset() {
playVM?.reset()
}
/**
* 动态切换主题
*/
private fun changeTheme() {
val theme = PrefUtils.getBoolean(Constants.SP_THEME_KEY, false)
if (theme) {
setTheme(R.style.AppTheme_Night)
} else {
setTheme(R.style.AppTheme)
}
}
/**
* 沉浸式状态,随主题改变
*/
override fun setSystemInvadeBlack() {
val theme = PrefUtils.getBoolean(Constants.SP_THEME_KEY, false)
if (theme) {
StatusUtils.setSystemStatus(this, true, false)
} else {
StatusUtils.setSystemStatus(this, true, true)
}
}
override fun onBackPressed() {
//获取hostFragment
val mMainNavFragment: Fragment? =
supportFragmentManager.findFragmentById(R.id.host_fragment)
//获取当前所在的fragment
val fragment =
mMainNavFragment?.childFragmentManager?.primaryNavigationFragment
//如果当前处于根fragment即HostFragment
if (fragment is MainFragment) {
//Activity退出但不销毁
moveTaskToBack(false)
} else {
super.onBackPressed()
}
}
}
<file_sep>package com.zs.zs_jetpack.ui.set
import android.os.Bundle
import androidx.lifecycle.Observer
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.clickNoRepeat
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.toast
import com.zs.base_library.utils.PrefUtils
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.constants.UrlConstants
import com.zs.zs_jetpack.utils.CacheUtil
import com.zs.zs_jetpack.view.DialogUtils
import kotlinx.android.synthetic.main.fragment_set.*
/**
* des 设置
* @author zs
* @date 2020-06-30
*/
class SetFragment : BaseVmFragment() {
private lateinit var setVM: SetVM
override fun initViewModel() {
setVM = getFragmentViewModel(SetVM::class.java)
}
override fun observe() {
setVM.logoutLiveData.observe(this, Observer {
toast("已退出登陆")
nav().navigateUp()
})
}
override fun init(savedInstanceState: Bundle?) {
setNightMode()
}
/**
* 却换夜间/白天模式
*/
private fun setNightMode() {
val theme = PrefUtils.getBoolean(Constants.SP_THEME_KEY,false)
scDayNight.isChecked = theme
//不能用切换监听,否则会递归
scDayNight.clickNoRepeat {
it.isSelected = !theme
PrefUtils.setBoolean(Constants.SP_THEME_KEY, it.isSelected)
mActivity.recreate()
}
}
override fun onClick() {
setNoRepeatClick(ivBack, tvClear, tvVersion, tvAuthor, tvProject, tvCopyright, tvLogout) {
when (it.id) {
R.id.ivBack -> nav().navigateUp()
R.id.tvClear -> {
}
R.id.tvVersion -> {
}
R.id.tvAuthor -> {
}
R.id.tvProject -> {
nav().navigate(R.id.action_set_fragment_to_web_fragment, Bundle().apply {
putString(Constants.WEB_URL, UrlConstants.APP_GITHUB)
putString(Constants.WEB_TITLE, Constants.APP_NAME)
})
}
R.id.tvCopyright -> {
}
R.id.tvLogout -> {
if (!CacheUtil.isLogin()){
toast("请先登陆~")
return@setNoRepeatClick
}
DialogUtils.confirm(mActivity,"确定退出登录?"){
setVM.logout()
}
}
}
}
}
override fun getLayoutId() = R.layout.fragment_set
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_set, setVM)
.addBindingParam(BR.vm, setVM)
}
}<file_sep>package com.zs.zs_jetpack.common
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zs.base_library.common.clickNoRepeat
import com.zs.base_library.common.loadRadius
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.bean.ArticleListBean
import com.zs.zs_jetpack.constants.Constants
/**
* 文章适配器
* 关于该适配器用到了多布局,所以没有使用DataBinding,我觉得通过BaseQuickAdapter更加简便
* 上述言论属一家之见,也可能是山猪吃不惯细糠~-~
*
* @author zs
* @date 2020-07-07修改
*/
class aaArticleAdapter(
list: MutableList<ArticleListBean>
) : BaseMultiItemQuickAdapter<ArticleListBean,
BaseViewHolder>(list) {
/**
* 子view点击回调接口。单独写一个接口目的是可以使用防止快速点击
*/
private var onItemClickListener: OnChildItemClickListener? = null
init {
addItemType(Constants.ITEM_ARTICLE, R.layout.item_home_article)
addItemType(Constants.ITEM_ARTICLE_PIC, R.layout.item_project)
}
fun setOnChildItemClickListener(onItemClickListener: OnChildItemClickListener) {
this.onItemClickListener = onItemClickListener
}
override fun convert(helper: BaseViewHolder, item: ArticleListBean) {
when (helper.itemViewType) {
//不带图片
Constants.ITEM_ARTICLE -> {
item.run {
helper.getView<View>(R.id.root).clickNoRepeat {
onItemClickListener?.onItemChildClick(
this@aaArticleAdapter, it, helper.adapterPosition - headerLayoutCount
)
}
helper.setText(R.id.tvTag, "置顶 ")
helper.setText(
R.id.tvAuthor,
author
)
helper.setText(R.id.tvDate, date)
helper.setText(R.id.tvTitle, title)
helper.setText(R.id.tvChapterName, articleTag)
helper.getView<ImageView>(R.id.ivCollect)
.apply {
clickNoRepeat {
onItemClickListener?.onItemChildClick(
this@aaArticleAdapter,
this,
helper.adapterPosition - headerLayoutCount
)
}
if (item.collect) {
setImageResource(R.mipmap._collect)
} else {
setImageResource(R.mipmap.un_collect)
}
}
}
}
//带图片
Constants.ITEM_ARTICLE_PIC -> {
item.apply {
//根布局
helper.getView<View>(R.id.root).clickNoRepeat {
onItemClickListener?.onItemChildClick(
this@aaArticleAdapter, it, helper.adapterPosition - headerLayoutCount
)
}
//图片
picUrl?.let {
helper.getView<ImageView>(R.id.ivTitle).loadRadius(mContext, it, 20)
}
//标题
helper.setText(R.id.tvTitle, title)
//描述信息
helper.setText(R.id.tvDes, desc)
//日期
helper.setText(R.id.tvNameData, "$date | $author")
//收藏
helper.getView<ImageView>(R.id.ivCollect).apply {
clickNoRepeat {
onItemClickListener?.onItemChildClick(
//必须减headCount,否则角标会错乱
this@aaArticleAdapter,
this,
helper.adapterPosition - headerLayoutCount
)
}
if (item.collect) {
setImageResource(R.mipmap._collect)
} else {
setImageResource(R.mipmap.un_collect)
}
}
}
}
}
}
/**
* 收藏,通过id做局部刷新
*/
fun collectNotifyById(id: Int) {
for (index in 0 until data.size) {
if (id == data[index].id) {
data[index].collect = true
//必须加headCount,否则角标错乱
notifyItemChanged(index + headerLayoutCount)
return
}
}
}
/**
* 取消收藏,通过id做局部刷新
*/
fun unCollectNotifyById(id: Int) {
for (index in 0 until data.size) {
if (id == data[index].id) {
data[index].collect = false
//必须加headCount,否则角标错乱
notifyItemChanged(index + headerLayoutCount)
return
}
}
}
/**
* 获取跳转至web界面的bundle
*/
fun getBundle(position: Int): Bundle {
return Bundle().apply {
putString("loadUrl", data[position].link)
putString("title", data[position].title)
putString("author", data[position].author)
putInt("id", data[position].id)
}
}
}<file_sep>package com.zs.zs_jetpack.bean
import android.text.Html
import android.text.TextUtils
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.zs.zs_jetpack.constants.Constants
/**
* @author zs
* @date 2020/9/10
*/
class ArticleListBean : MultiItemEntity {
override fun getItemType(): Int {
return if (picUrl.isNullOrEmpty()) {
Constants.ITEM_ARTICLE
} else {
Constants.ITEM_ARTICLE_PIC
}
}
var id = 0
/**
* 作者
*/
var author: String? = null
/**
* 是否收藏
*/
var collect = false
/**
* 描述信息
*/
var desc: String? = null
/**
* 图片类型,有和无
*/
var picUrl: String? = null
/**
* 链接
*/
var link: String? = null
/**
* 日期
*/
var date: String? = null
/**
* 标题
*/
var title: String? = null
/**
* 文章标签
*/
var articleTag: String? = null
/**
* 1.置顶
*/
var topTitle: String? = null
/**
* 将后端数据转换为本地定义的数据结构,原因有三
*
* 1.将适配器数据和后端隔离,避免后端调整数据牵连到适配器,本地定义的数据和适配器只与设计图保持一致
* 2.很多情况下后端返回的数据需要我们要二次处理,要么在UI层处理,要么在数据层处理,我个人认为在数据层处理比较合适,
* UI层拿到数据无需处理直接渲染。但是这种情况下,数据层要组装字段必须得创建新的字段,避免混淆所以直接独立出一个类
* 3.做diff运算时更容易操作
*/
companion object {
fun trans(list: MutableList<ArticleBean.DatasBean>): MutableList<ArticleListBean> {
return list.map {
ArticleListBean().apply {
id = it.id
author = if (TextUtils.isEmpty(it.author)) {
it.shareUser
} else {
it.author
}
collect = it.collect
desc = it.desc
picUrl = it.envelopePic
link = it.link
date = it.niceDate
title = Html.fromHtml(it.title).toString()
articleTag = it.superChapterName
topTitle = if (it.type == 1) "置顶" else ""
}
}.toMutableList()
}
fun copy(article: ArticleListBean): ArticleListBean {
return ArticleListBean().apply {
id = article.id
author = article.author
collect = false
desc = article.desc
picUrl = article.picUrl
link = article.link
date = article.date
title = article.title
articleTag = article.articleTag
topTitle = article.topTitle
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.set
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.base_library.utils.PrefUtils
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.event.LogoutEvent
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import com.zs.zs_jetpack.utils.CacheUtil
import kotlinx.coroutines.CoroutineScope
import org.greenrobot.eventbus.EventBus
/**
* des 设置
* @date 2020/7/10
* @author zs
*/
class SetRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
/**
* 退出登陆
*/
fun logout(logoutLiveData : MutableLiveData<Any>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.logout()
.data(Any::class.java)
},
success = {
CacheUtil.resetUser()
logoutLiveData.postValue(it)
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.tab
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import com.zs.zs_jetpack.bean.ArticleListBean
/**
* des 文章vm
* @date 2020/7/8
* @author zs
*/
class ArticleVM : BaseViewModel() {
private val repo by lazy { ArticleRepo(viewModelScope, errorLiveData) }
val articleLiveData = MutableLiveData<MutableList<ArticleListBean>>()
/**
* 获取文章
*/
fun getArticle(type: Int, tabId: Int, isRefresh: Boolean) {
repo.getArticle(type, tabId, isRefresh, articleLiveData)
}
/**
* 收藏
*/
fun collect(id: Int) {
repo.collect(id, articleLiveData)
}
/**
* 取消收藏
*/
fun unCollect(id: Int) {
repo.unCollect(id, articleLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.integral
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
/**
* des 文章vm
* @date 2020/7/8
* @author zs
*/
class IntegralVM : BaseViewModel() {
private val repo by lazy { IntegralRepo(viewModelScope, errorLiveData) }
/**
* 收藏的的文章
*/
val integralLiveData = MutableLiveData<MutableList<IntegralListBean>>()
/**
* 获取收藏列表
*/
fun getIntegral(isRefresh: Boolean) {
repo.getIntegral(
isRefresh, integralLiveData, emptyLiveDate
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.square.system
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import com.zs.zs_jetpack.bean.ArticleBean
import com.zs.zs_jetpack.bean.ArticleListBean
/**
* des 体系/体系列表
* @date 2020/7/10
* @author zs
*/
class SystemVM :BaseViewModel(){
private val repo by lazy { SystemRepo(viewModelScope,errorLiveData) }
/**
* 体系列表数据
*/
val systemLiveData = MutableLiveData<MutableList<SystemBean>>()
/**
* 体系列表数据
*/
val articleLiveData = MutableLiveData<MutableList<ArticleListBean>>()
/**
* 获取体系列表
*/
fun getSystemList(){
repo.getSystemList(systemLiveData)
}
/**
* 获取文章列表
*/
fun getArticleList(isRefresh:Boolean,id:Int){
repo.getArticleList(isRefresh,id,articleLiveData)
}
/**
* 收藏
*/
fun collect(id:Int){
repo.collect(id,articleLiveData)
}
/**
* 取消收藏
*/
fun unCollect(id:Int){
repo.unCollect(id,articleLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.register
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.base_library.utils.PrefUtils
import com.zs.wanandroid.entity.UserBean
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.event.LoginEvent
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
import org.greenrobot.eventbus.EventBus
/**
* des 登陆
* @date 2020/7/9
* @author zs
*/
class RegisterRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
fun register(username: String, password: String, rePassword: String, registerLiveData : MutableLiveData<Any>) {
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.register(username,password,rePassword)
.data()
},
success = {
registerLiveData.postValue(it)
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.integral
import android.content.Context
import androidx.recyclerview.widget.DiffUtil
import com.zs.base_library.common.BaseListAdapter
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.getDefaultDiff
import com.zs.zs_jetpack.databinding.ItemIntegralBinding
/**
* des
* @author zs
* @date 2020/9/10
*/
class IntegralAdapter(context: Context)
:BaseListAdapter<IntegralListBean,ItemIntegralBinding>(context, getDefaultDiff()){
override fun onBindItem(item: IntegralListBean, binding: ItemIntegralBinding) {
binding.dataBean = item
}
override fun getLayoutId() = R.layout.item_integral
}<file_sep>package com.zs.zs_jetpack.ui.v2ex
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zs.base_library.common.clickNoRepeat
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.getDefaultDiff
import com.zs.zs_jetpack.databinding.ItemV2exBinding
/**
* @author ZTY
* @date 2020-11-12
*/
class V2exAdapter(private val context: Context) :
ListAdapter<V2exBeanItem, RecyclerView.ViewHolder>(
getDefaultDiff()
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val binding: ItemV2exBinding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.item_v2ex,
parent,
false
)
return V2exAdapter.V2exViewHolder(binding.root)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val binding = DataBindingUtil.getBinding<ItemV2exBinding>(holder.itemView)?.apply {
dataBean = getItem(position)
}
holder.itemView.clickNoRepeat {
onItemClickListener?.let {
it.invoke(position,holder.itemView)
}
}
binding?.executePendingBindings()
}
/**
* 默认viewHolder
*/
class V2exViewHolder constructor(itemView: View) :
RecyclerView.ViewHolder(itemView) {
}
private var onItemClickListener: ((Int,View)->Unit)? = null
/**
* 注册item点击事件
*/
fun setOnItemClickListener(onItemClickListener: ((Int, View) -> Unit)? = null) {
this.onItemClickListener = onItemClickListener
}
/**
* 获取跳转至web界面的bundle
*/
fun getBundle(position: Int): Bundle {
return Bundle().apply {
putString("loadUrl", currentList[position].url)
putString("title", currentList[position].title)
putString("author", currentList[position].member.username)
putInt("id", currentList[position].id)
}
}
}<file_sep>package com.zs.zs_jetpack.http
import com.zs.wanandroid.entity.*
import com.zs.zs_jetpack.bean.ArticleBean
import com.zs.zs_jetpack.bean.NavigationEntity
import com.zs.zs_jetpack.ui.collect.CollectBean
import com.zs.zs_jetpack.ui.integral.IntegralRecordBean
import com.zs.zs_jetpack.ui.main.home.BannerBean
import com.zs.zs_jetpack.ui.main.mine.IntegralBean
import com.zs.zs_jetpack.ui.rank.RankBean
import com.zs.zs_jetpack.ui.main.square.system.SystemBean
import com.zs.zs_jetpack.ui.main.tab.TabBean
import com.zs.zs_jetpack.ui.v2ex.V2exBeanItem
import retrofit2.http.*
/**
* @date 2020/5/9
* @author zs
*/
interface V2exApiService {
/**
* V2ex接口
*/
@GET("/api/topics/latest.json")
suspend fun getV2exTopicList(): MutableList<V2exBeanItem>
}<file_sep>package com.zs.zs_jetpack.ui.collect
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.common.isListEmpty
import com.zs.base_library.common.toast
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.bean.ArticleBean
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 收藏的文章
* @date 2020/7/8
* @author zs
*/
class CollectRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 0
/**
* 获取收藏列表
*/
fun getCollect(
isRefresh: Boolean
, articleLiveData: MutableLiveData<MutableList<CollectBean.DatasBean>>
, emptyLiveData: MutableLiveData<Any>
) {
launch(
block = {
if (isRefresh) {
page = 0
} else {
page++
}
RetrofitManager.getApiService(ApiService::class.java)
.getCollectData(page)
.data()
},
success = {
//处理刷新/分页数据
articleLiveData.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null) {
mutableListOf()
} else {
this
}
it.datas?.let { it1 -> currentList.addAll(it1) }
articleLiveData.postValue(currentList)
}
if (isListEmpty(it.datas)) {
//第一页并且数据为空
if (page == 0) {
emptyLiveData.postValue(Any())
} else {
toast("没有数据啦~")
}
}
}
)
}
/**
* 取消收藏
*/
fun unCollect(id:Int,unCollectLiveData : MutableLiveData<Int>){
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.unCollect(id)
//如果data可能为空,可通过此方式通过反射生成对象,避免空判断
.data(Any::class.java)
},
success = {
unCollectLiveData.postValue(id)
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.tab
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.SimpleItemAnimator
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.base.LazyVmFragment
import com.zs.base_library.common.smartConfig
import com.zs.base_library.common.smartDismiss
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.ArticleAdapter
import com.zs.zs_jetpack.utils.CacheUtil
import kotlinx.android.synthetic.main.fragment_article.*
/**
* des 文章列表fragment
* @date 2020/7/7
* @author zs
*/
class ArticleListFragment : LazyVmFragment() {
private var articleVM: ArticleVM? = null
/**
* fragment类型,项目或公号
*/
private var type = 0
/**
* tab的id
*/
private var tabId = 0
/**
* 文章适配器
*/
private val adapter by lazy { ArticleAdapter(mActivity) }
override fun initViewModel() {
articleVM = getFragmentViewModel(ArticleVM::class.java)
}
override fun observe() {
articleVM?.articleLiveData?.observe(this, Observer {
smartDismiss(smartRefresh)
adapter.submitList(it)
})
articleVM?.errorLiveData?.observe(this, Observer {
})
}
override fun lazyInit() {
type = arguments?.getInt("type") ?: 0
tabId = arguments?.getInt("tabId") ?: 0
initView()
loadData()
}
override fun initView() {
//关闭更新动画
(rvArticleList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
//下拉刷新
smartRefresh.setOnRefreshListener {
articleVM?.getArticle(type, tabId, true)
}
//上拉加载
smartRefresh.setOnLoadMoreListener {
articleVM?.getArticle(type,tabId,false)
}
smartConfig(smartRefresh)
adapter.apply {
rvArticleList.adapter = this
setOnItemClickListener { i, _ ->
nav().navigate(
R.id.action_main_fragment_to_web_fragment,
this@ArticleListFragment.adapter.getBundle(i)
)
}
setOnItemChildClickListener { i, view ->
when (view.id) {
//收藏
R.id.ivCollect -> {
if (CacheUtil.isLogin()) {
this@ArticleListFragment.adapter.currentList[i].apply {
//已收藏取消收藏
if (collect) {
articleVM?.unCollect(id)
} else {
articleVM?.collect(id)
}
}
} else {
nav().navigate(R.id.action_main_fragment_to_login_fragment)
}
}
}
}
}
}
override fun loadData() {
smartRefresh.autoRefresh()
}
override fun getLayoutId() = R.layout.fragment_article
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_article, articleVM)
.addBindingParam(BR.vm, articleVM)
}
}<file_sep>package com.zs.zs_jetpack.ui.collect
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.SimpleItemAnimator
import com.chad.library.adapter.base.BaseQuickAdapter
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.clickNoRepeat
import com.zs.base_library.common.smartDismiss
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.OnChildItemClickListener
import com.zs.zs_jetpack.view.LoadingTip
import kotlinx.android.synthetic.main.fragment_collect.*
/**
* des 收藏
* @date 2020/7/14
* @author zs
*/
class CollectFragment : BaseVmFragment(), OnChildItemClickListener {
/**
* 文章适配器
*/
private lateinit var adapter: CollectAdapter
/**
* 空白页,网络出错等默认显示
*/
private val loadingTip by lazy { LoadingTip(mActivity) }
private lateinit var collectVM: CollectVM
override fun initViewModel() {
collectVM = getFragmentViewModel(CollectVM::class.java)
}
override fun observe() {
collectVM.articleLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
adapter.setNewData(it)
})
//取消收藏
collectVM.unCollectLiveData.observe(this, Observer {
adapter.deleteById(it)
})
collectVM.emptyLiveDate.observe(this, Observer {
loadingTip.showEmpty()
})
collectVM.errorLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
if (it.errorCode == -100) {
//显示网络错误
loadingTip.showInternetError()
loadingTip.setReloadListener {
collectVM.getCollect(true)
}
}
})
}
override fun init(savedInstanceState: Bundle?) {
initView()
loadData()
}
override fun initView() {
//关闭更新动画
(rvCollect.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
adapter = CollectAdapter().apply {
emptyView = loadingTip
setOnChildItemClickListener(this@CollectFragment)
rvCollect.adapter = this
}
//刷新
smartRefresh.setOnRefreshListener {
collectVM.getCollect(true)
}
//加载更多
smartRefresh.setOnLoadMoreListener {
collectVM.getCollect(false)
}
ivBack.clickNoRepeat {
nav().navigateUp()
}
}
override fun loadData() {
smartRefresh.autoRefresh()
}
override fun getLayoutId() = R.layout.fragment_collect
override fun getDataBindingConfig(): DataBindingConfig? {
return null
}
override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
when (view.id) {
//item
R.id.root -> {
nav().navigate(
R.id.action_collect_fragment_to_web_fragment
, this@CollectFragment.adapter.getBundle(position)
)
}
//收藏
R.id.ivCollect -> {
this@CollectFragment.adapter.data[position].apply {
collectVM.unCollect(originId)
}
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.set
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
/**
* des 设置
* @date 2020/7/10
* @author zs
*/
class SetVM :BaseViewModel(){
private val repo by lazy { SetRepo(viewModelScope,errorLiveData) }
val logoutLiveData = MutableLiveData<Any>()
fun logout(){
repo.logout(logoutLiveData)
}
}<file_sep>package com.zs.zs_jetpack.http
import com.zs.base_library.http.ApiException
import java.io.Serializable
/**
* des Api描述类,用于承载业务信息以及基础业务逻辑判断
* @date 2020/7/5
* @author zs
*/
class V2exApiResponse<T> : Serializable {
private var data: T? = null
/**
* 如果服务端data肯定不为null,直接将data返回。
* 假如data为null证明服务端出错,这种错误已经产生并且不可逆,
* 客户端只需保证不闪退并给予提示即可
*/
fun data(): T {
return data!!
}
}<file_sep>package com.zs.base_library.base
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.http.ApiException
import com.zs.base_library.common.toast
import kotlinx.coroutines.*
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
/**
* 错误方法
*/
typealias Error = suspend (e: ApiException) -> Unit
/**
* des 基础数据层
* @date 2020/5/18
* @author zs
*
* @param coroutineScope 注入viewModel的coroutineScope用于协程管理
* @param errorLiveData 业务出错或者爆发异常,由errorLiveData通知视图层去处理
*/
open class BaseRepository(
private val coroutineScope: CoroutineScope,
private val errorLiveData: MutableLiveData<ApiException>
) {
/**
* 对协程进行封装,统一处理错误信息
*
* @param block 执行中
* @param success 执行成功
*/
protected fun <T> launch(
block: suspend () -> T
, success: suspend (T) -> Unit
, error:Error? = null): Job {
return coroutineScope.launch {
runCatching {
withContext(Dispatchers.IO) {
block()
}
}.onSuccess {
success(it)
}.onFailure {
it.printStackTrace()
getApiException(it).apply {
error?.invoke(this)
toast(errorMessage)
//统一响应错误信息
errorLiveData.value = this
}
}
}
}
/**
* 捕获异常信息
*/
private fun getApiException(e: Throwable): ApiException {
Log.e("httpException", e.localizedMessage)
return when (e) {
is UnknownHostException -> {
ApiException("网络异常", -100)
}
is JSONException -> {//|| e is JsonParseException
ApiException("数据异常", -100)
}
is SocketTimeoutException -> {
ApiException("连接超时", -100)
}
is ConnectException -> {
ApiException("连接错误", -100)
}
is HttpException -> {
ApiException("http code ${e.code()}", -100)
}
is ApiException -> {
e
}
/**
* 如果协程还在运行,个别机型退出当前界面时,viewModel会通过抛出CancellationException,
* 强行结束协程,与java中InterruptException类似,所以不必理会,只需将toast隐藏即可
*/
is CancellationException -> {
ApiException("", -10)
}
else -> {
ApiException("未知错误", -100)
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.integral
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.SimpleItemAnimator
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.clickNoRepeat
import com.zs.base_library.common.smartDismiss
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.view.LoadingTip
import kotlinx.android.synthetic.main.fragment_integral.*
/**
* des 积分
* @date 2020/7/14
* @author zs
*/
class IntegralFragment : BaseVmFragment(){
/**
* 文章适配器
*/
private lateinit var adapter: IntegralAdapter
/**
* 空白页,网络出错等默认显示
*/
private val loadingTip by lazy { LoadingTip(mActivity) }
private lateinit var integralVM: IntegralVM
override fun initViewModel() {
integralVM = getFragmentViewModel(IntegralVM::class.java)
}
override fun observe() {
integralVM.integralLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
adapter.submitList(it)
})
integralVM.emptyLiveDate.observe(this, Observer {
loadingTip.showEmpty()
})
integralVM.errorLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
if (it.errorCode == -100) {
//显示网络错误
loadingTip.showInternetError()
loadingTip.setReloadListener {
integralVM.getIntegral(true)
}
}
})
}
override fun init(savedInstanceState: Bundle?) {
initView()
loadData()
}
override fun initView() {
//关闭更新动画
(rvIntegral.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
adapter = IntegralAdapter(mActivity).apply {
rvIntegral.adapter = this
}
//刷新
smartRefresh.setOnRefreshListener {
integralVM.getIntegral(true)
}
//加载更多
smartRefresh.setOnLoadMoreListener {
integralVM.getIntegral(false)
}
ivBack.clickNoRepeat {
nav().navigateUp()
}
}
override fun loadData() {
smartRefresh.autoRefresh()
}
override fun getLayoutId() = R.layout.fragment_integral
override fun getDataBindingConfig(): DataBindingConfig? {
return null
}
}<file_sep>package com.zs.zs_jetpack.ui
import android.os.Bundle
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.initFragment
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.PlayViewModel
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.play.PlayerManager
import com.zs.zs_jetpack.ui.main.home.HomeFragment
import com.zs.zs_jetpack.ui.main.mine.MineFragment
import com.zs.zs_jetpack.ui.main.tab.TabFragment
import com.zs.zs_jetpack.ui.main.square.SquareFragment
import kotlinx.android.synthetic.main.fragment_main.*
/**
* des 主页面
* @author zs
* @date 2020-05-14
*/
class MainFragment : BaseVmFragment() {
private val fragmentList = arrayListOf<Fragment>()
/**
* 首页
*/
private val homeFragment by lazy { HomeFragment() }
/**
* 项目
*/
private val projectFragment by lazy {
TabFragment().apply {
arguments = Bundle().apply {
putInt("type",Constants.PROJECT_TYPE)
}
}
}
/**
* 广场
*/
private val squareFragment by lazy { SquareFragment() }
/**
* 公众号
*/
private val publicNumberFragment by lazy {
TabFragment().apply {
arguments = Bundle().apply {
putInt("type",Constants.ACCOUNT_TYPE)
}
}
}
/**
* 我的
*/
private val mineFragment by lazy { MineFragment() }
private var playViewModel: PlayViewModel? = null
init {
fragmentList.apply {
add(homeFragment)
add(projectFragment)
add(squareFragment)
add(publicNumberFragment)
add(mineFragment)
}
}
override fun initViewModel() {
playViewModel = getActivityViewModel(PlayViewModel::class.java)
}
override fun init(savedInstanceState: Bundle?) {
//初始化viewpager2
vpHome.initFragment(this, fragmentList).run {
//全部缓存,避免切换回重新加载
offscreenPageLimit = fragmentList.size
}
//取消viewPager2滑动
vpHome.isUserInputEnabled = false
vpHome.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
btnNav.menu.getItem(position).isChecked = true
}
})
//初始化底部导航栏
btnNav.run {
setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.menu_home -> vpHome.setCurrentItem(0, false)
R.id.menu_project -> vpHome.setCurrentItem(1, false)
R.id.menu_square -> vpHome.setCurrentItem(2, false)
R.id.menu_official_account -> vpHome.setCurrentItem(3, false)
R.id.menu_mine -> vpHome.setCurrentItem(4, false)
}
// 这里注意返回true,否则点击失效
true
}
}
val rv = vpHome[0] as RecyclerView
rv.isNestedScrollingEnabled = false
}
override fun onClick() {
floatLayout.playClick {
PlayerManager.instance.controlPlay()
}
floatLayout.rootClick {
nav().navigate(R.id.action_main_fragment_to_play_fragment)
}
}
override fun getLayoutId() = R.layout.fragment_main
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_main, playViewModel)
.addBindingParam(BR.vm, playViewModel)
}
}
<file_sep>package com.zs.zs_jetpack.ui.main.mine
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.base_library.utils.PrefUtils
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
/**
* des 我的
* @date 2020/7/10
* @author zs
*/
class MineRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
fun getInternal(internalLiveData: MutableLiveData<IntegralBean>) {
launch(
block = {
RetrofitManager.getApiService(ApiService::class.java)
.getIntegral()
.data()
},
success = {
PrefUtils.setObject(Constants.INTEGRAL_INFO, it)
internalLiveData.postValue(it)
}
)
}
suspend fun getInternal(): Flow<IntegralBean> {
return flow {
emit(
RetrofitManager.getApiService(ApiService::class.java)
.getIntegral()
.data()
)
}.flowOn(Dispatchers.IO)
}
}<file_sep>package com.zs.zs_jetpack.ui.integral
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.common.isListEmpty
import com.zs.base_library.common.toast
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des 收藏的文章
* @date 2020/7/8
* @author zs
*/
class IntegralRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
private var page = 1
/**
* 获取积分
*/
fun getIntegral(
isRefresh: Boolean
, integralLiveData: MutableLiveData<MutableList<IntegralListBean>>
, emptyLiveData: MutableLiveData<Any>
) {
launch(
block = {
if (isRefresh) {
page = 1
} else {
page++
}
RetrofitManager.getApiService(ApiService::class.java)
.getIntegralRecord(page)
.data()
},
success = {
//处理刷新/分页数据
integralLiveData.value.apply {
//第一次加载 或 刷新 给 articleLiveData 赋予一个空集合
val currentList = if (isRefresh || this == null) {
mutableListOf()
} else {
this
}
it.datas?.let { it1 -> currentList.addAll(IntegralListBean.trans(it1)) }
integralLiveData.postValue(currentList)
}
if (isListEmpty(it.datas)) {
//第一页并且数据为空
if (page == 1) {
emptyLiveData.postValue(Any())
} else {
toast("没有数据啦~")
}
}
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.main.mine
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.base.LazyVmFragment
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.toast
import com.zs.base_library.utils.PrefUtils
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.constants.UrlConstants
import com.zs.zs_jetpack.event.LoginEvent
import com.zs.zs_jetpack.event.LogoutEvent
import com.zs.zs_jetpack.utils.CacheUtil
import kotlinx.android.synthetic.main.fragment_mine.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.system.measureTimeMillis
/**
* des 我的
* @author zs
* @date 2020-05-14
*/
class MineFragment : LazyVmFragment() {
var job: Job? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
EventBus.getDefault().register(this)
return super.onCreateView(inflater, container, savedInstanceState)
}
/**
* 显示消息
*/
private fun showMessage(message: String) {
tvText.text = message
}
private suspend fun getMessageFromNetwork(text: String, delayTime: Int): String {
Log.e("coroutines", "=======执行getMessageFromNetWork=======" + delayTime)
var name = ""
// suspend里面调用的方法,也是被编译器用suspend关键字修饰的
withContext(Dispatchers.IO) {
for (i in 1..delayTime) {
// 这里模拟一个耗时操作
Thread.sleep(500)
Log.e("coroutines","${delayTime}-----------------------${i}")
}
}
name = text
return name
}
private suspend fun intValue1():Int {
delay(1000)
return 1
}
private suspend fun intValue2():Int {
delay(2000)
return 2
}
/**
* 用户积分信息
*/
private var integralBean: IntegralBean? = null
private var mineVM: MineVM? = null
override fun initViewModel() {
mineVM = getFragmentViewModel(MineVM::class.java)
val elapsedTime = measureTimeMillis {
// val value1 = intValue1()
// val value2 = intValue2()
// println("the result is ${value1 + value2}")
}
// job = GlobalScope.launch(Dispatchers.Main) {
// // 执行这一句之后,launch之后就只能执行一次
//// job?.cancel()
// // 下面方法都是顺序执行的
// var name = getMessageFromNetwork("Name1", 100)
// showMessage(name)
// Log.e("coroutines", "=======Name1=======" + name)
// var name1 = getMessageFromNetwork("Name2", 10000)
// showMessage(name1)
// Log.e("coroutines", "=======Name2=======" + name1)
// var name2 = getMessageFromNetwork("Name3", 10)
// showMessage(name2)
// Log.e("coroutines", "=======name2=======" + name2)
// }
}
override fun observe() {
mineVM?.internalLiveData?.observe(this, Observer {
integralBean = it
setIntegral()
})
}
private fun setIntegral() {
//通过dataBinDing与View绑定
mineVM?.username?.set(integralBean?.username)
mineVM?.id?.set("${integralBean?.userId}")
mineVM?.rank?.set("${integralBean?.rank}")
mineVM?.internal?.set("${integralBean?.coinCount}")
}
override fun lazyInit() {
//先判断数据是否为空,然后再强转,否则会出异常
PrefUtils.getObject(Constants.INTEGRAL_INFO)?.let {
//先从本地获取积分,获取不到再通过网络获取
integralBean = it as IntegralBean?
}
if (integralBean == null) {
if (CacheUtil.isLogin()) {
mineVM?.getFlowInternal()
}
} else {
setIntegral()
}
}
override fun getLayoutId() = R.layout.fragment_mine
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_mine, mineVM)
.addBindingParam(BR.vm, mineVM)
}
override fun onClick() {
setNoRepeatClick(
ivHead,
tvName,
tvId,
llHistory,
llRanking,
clIntegral,
clCollect,
clArticle,
clWebsite,
clSet,
clV2ex
) {
when (it.id) {
//头像
R.id.ivHead -> toast("我只是一只睡着的小老鼠...")
//用户名
R.id.tvName -> {
if (!CacheUtil.isLogin()) {
nav().navigate(R.id.action_main_fragment_to_login_fragment)
}
}
//历史
R.id.llHistory -> nav().navigate(R.id.action_main_fragment_to_history_fragment)
//排名
R.id.llRanking -> {
if (CacheUtil.isLogin()) {
nav().navigate(R.id.action_main_fragment_to_rank_fragment, Bundle().apply {
integralBean?.apply {
putInt(Constants.MY_INTEGRAL, coinCount)
putInt(Constants.MY_RANK, rank)
putString(Constants.MY_NAME, username)
}
})
} else {
toast("请先登录")
}
}
//积分
R.id.clIntegral -> {
if (CacheUtil.isLogin()) {
nav().navigate(R.id.action_main_fragment_to_integral_fragment)
} else {
toast("请先登录")
}
}
//我的收藏
R.id.clCollect -> {
if (CacheUtil.isLogin()) {
nav().navigate(R.id.action_main_fragment_to_collect_fragment)
} else {
toast("请先登录")
}
}
//我的文章
R.id.clArticle -> {
if (CacheUtil.isLogin()) {
nav().navigate(R.id.action_main_fragment_to_my_article_fragment)
} else {
toast("请先登录")
}
}
//官网
R.id.clWebsite -> {
nav().navigate(R.id.action_main_fragment_to_web_fragment, Bundle().apply {
putString(Constants.WEB_URL, UrlConstants.WEBSITE)
putString(Constants.WEB_TITLE, Constants.APP_NAME)
})
}
R.id.clSet -> {
nav().navigate(R.id.action_main_fragment_to_set_fragment)
}
R.id.clV2ex -> {
nav().navigate(R.id.action_main_fragment_to_v2ex_fragment)
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
EventBus.getDefault().unregister(this)
}
/**
* 登陆消息,收到消息请求个人信息接口
*/
@Subscribe(threadMode = ThreadMode.MAIN)
fun loginEvent(loginEvent: LoginEvent) {
mineVM?.getFlowInternal()
}
/**
* 退出消息
*/
@Subscribe(threadMode = ThreadMode.MAIN)
fun logoutEvent(loginEvent: LogoutEvent) {
mineVM?.username?.set("请先登录")
mineVM?.id?.set("---")
mineVM?.rank?.set("0")
mineVM?.internal?.set("0")
}
override fun onDestroy() {
super.onDestroy()
// 取消协程
job?.cancel()
}
}
<file_sep>package com.zs.zs_jetpack.ui.v2ex
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.constants.ApiConstants
import com.zs.zs_jetpack.http.RetrofitManager
import com.zs.zs_jetpack.http.V2exApiService
import kotlinx.coroutines.CoroutineScope
/**
* @author Zty
* @date 2020-11-12
*/
class V2exRepo(coroutineScope:CoroutineScope,errorLiveData: MutableLiveData<ApiException>) : BaseRepository(coroutineScope,errorLiveData){
fun getLateTopic(v2exItemData:MutableLiveData<MutableList<V2exBeanItem>>) {
launch(
block = {
RetrofitManager.getApiService(V2exApiService::class.java,ApiConstants.V2EX_URL).getV2exTopicList()
},
success = {
//处理刷新
v2exItemData.value.apply {
v2exItemData.postValue(it)
}
}
)
}
}<file_sep>package com.zs.zs_jetpack.ui.my
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.smartDismiss
import com.zs.base_library.common.toast
import com.zs.zs_jetpack.R
import com.zs.zs_jetpack.common.OnChildItemClickListener
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.utils.CacheUtil
import com.zs.zs_jetpack.view.LoadingTip
import kotlinx.android.synthetic.main.fragment_my_article.*
/**
* des 我的文章
* @author zs
* @data 2020/7/12
*/
class MyArticleFragment : BaseVmFragment(), OnChildItemClickListener {
private val adapter by lazy { MyArticleAdapter() }
private lateinit var myVM: MyArticleVM
private val loadingView by lazy { LoadingTip(mActivity) }
override fun initViewModel() {
myVM = getFragmentViewModel(MyArticleVM::class.java)
}
override fun init(savedInstanceState: Bundle?) {
initView()
loadData()
}
override fun initView() {
adapter.apply {
setOnChildItemClickListener(this@MyArticleFragment)
emptyView = loadingView
rvMyArticleList.adapter = this
}
smartRefresh.setOnRefreshListener {
myVM.getMyArticle(true)
}
smartRefresh.setOnLoadMoreListener {
myVM.getMyArticle(false)
}
}
override fun onClick() {
setNoRepeatClick(ivBack, ivAdd) {
when (it.id) {
R.id.ivBack -> nav().navigateUp()
R.id.ivAdd -> {
if (CacheUtil.isLogin()) {
nav().navigate(R.id.action_my_article_fragment_to_publish_fragment)
} else {
toast("请先登录~")
}
}
}
}
}
override fun observe() {
myVM.myLiveDate.observe(this, Observer {
smartDismiss(smartRefresh)
adapter.setNewData(it)
})
myVM.deleteLiveData.observe(this, Observer {
adapter.deleteById(it)
})
myVM.emptyLiveDate.observe(this, Observer {
loadingView.showEmpty()
})
myVM.errorLiveData.observe(this, Observer {
smartDismiss(smartRefresh)
})
}
override fun loadData() {
smartRefresh.autoRefresh()
}
override fun getLayoutId() = R.layout.fragment_my_article
override fun getDataBindingConfig(): DataBindingConfig? {
return null
}
override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
this.adapter.data.apply {
when(view.id){
R.id.rlContent->{
nav().navigate(R.id.action_my_article_fragment_to_web_fragment,Bundle().apply {
putString(Constants.WEB_URL,get(position).link)
putString(Constants.WEB_TITLE,get(position).title)
})
}
R.id.tvDelete->{
if (position<size){
myVM.delete(get(position).id)
}
}
}
}
}
}<file_sep>package com.zs.zs_jetpack.ui.search
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.zs.base_library.base.BaseViewModel
import com.zs.base_library.common.toast
import com.zs.zs_jetpack.bean.ArticleBean
import com.zs.zs_jetpack.bean.ArticleListBean
import org.w3c.dom.Text
/**
* @date 2020/7/8
* @author zs
*/
class SearchVM : BaseViewModel() {
private val repo by lazy { SearchRepo(viewModelScope, errorLiveData) }
/**
* 关键字,与搜索框保持一致
*/
val keyWord = ObservableField<String>().apply {
set("")
}
/**
* 搜索到的文章
*/
val articleLiveData = MutableLiveData<MutableList<ArticleListBean>>()
/**
* 是否为刷新或者首次加载
*/
fun search(isRefresh: Boolean) {
if (TextUtils.isEmpty(keyWord.get())) {
toast("请输入关键字")
return
}
repo.search(
isRefresh, keyWord.get()!!
, articleLiveData
, emptyLiveDate
)
}
/**
* 收藏
*/
fun collect(id:Int){
repo.collect(id,articleLiveData)
}
/**
* 取消收藏
*/
fun unCollect(id:Int){
repo.unCollect(id,articleLiveData)
}
}<file_sep>package com.zs.zs_jetpack.ui.history
import androidx.fragment.app.Fragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.base.LazyVmFragment
import com.zs.zs_jetpack.R
/**
* A simple [Fragment] subclass.
*/
class HistoryFragment : LazyVmFragment() {
override fun lazyInit() {
}
override fun getLayoutId() = R.layout.fragment_history
override fun getDataBindingConfig(): DataBindingConfig? {
return null
}
}
<file_sep>package com.zs.zs_jetpack.ui.main.tab
import androidx.lifecycle.MutableLiveData
import com.zs.base_library.base.BaseRepository
import com.zs.base_library.http.ApiException
import com.zs.zs_jetpack.constants.Constants
import com.zs.zs_jetpack.http.ApiService
import com.zs.zs_jetpack.http.RetrofitManager
import kotlinx.coroutines.CoroutineScope
/**
* des tab
* @date 2020/7/7
* @author zs
*/
class TabRepo(coroutineScope: CoroutineScope, errorLiveData: MutableLiveData<ApiException>) :
BaseRepository(coroutineScope, errorLiveData) {
fun getTab(type: Int, tabLiveData: MutableLiveData<MutableList<TabBean>>) {
launch(
block = {
if (type == Constants.PROJECT_TYPE) {
RetrofitManager.getApiService(ApiService::class.java)
.getProjectTabList()
.data()
} else {
RetrofitManager.getApiService(ApiService::class.java)
.getAccountTabList()
.data()
}
},
success = {
tabLiveData.postValue(it)
})
}
}
<file_sep>package com.zs.zs_jetpack.ui.v2ex
import android.os.Bundle
import androidx.lifecycle.Observer
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.clickNoRepeat
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.common.smartDismiss
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import kotlinx.android.synthetic.main.fragment_integral.*
import kotlinx.android.synthetic.main.fragment_v2ex.*
import kotlinx.android.synthetic.main.fragment_v2ex.ivBack
/**
* V2exFragment
*/
class V2exFragment : BaseVmFragment() {
private lateinit var v2exVm: V2exVM
private val adapter by lazy {
V2exAdapter(mActivity)
}
override fun initViewModel() {
v2exVm = getFragmentViewModel(V2exVM::class.java)
}
/**
* 初始化入口
*/
override fun init(savedInstanceState: Bundle?) {
v2exVm.getTopList()
v2exVm.mV2exLiveData.observe(viewLifecycleOwner, Observer {
smartDismiss(smartRefreshLayout)
adapter.submitList(it)
})
adapter.apply {
v2ExRecyclerView.adapter = this
setOnItemClickListener { i, view ->
nav().navigate(
R.id.action_v2ex_fragment_to_web_fragment,
this@V2exFragment.adapter.getBundle(i)
)
}
}
smartRefreshLayout.setOnRefreshListener {
v2exVm.getTopList()
}
smartRefreshLayout.setOnLoadMoreListener {
smartDismiss(smartRefreshLayout)
}
ivBack.clickNoRepeat {
nav().navigateUp()
}
}
override fun loadData() {
smartRefreshLayout.autoRefresh()
}
/**
* 获取layout布局
*/
override fun getLayoutId() = R.layout.fragment_v2ex
/**
* 获取dataBinding配置项
*/
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_v2ex, v2exVm).addBindingParam(BR.vm, v2exVm)
}
override fun onClick() {
setNoRepeatClick(btnLogin) {
v2exVm.getTopList()
}
}
}<file_sep>package com.zs.zs_jetpack.ui.web
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Html
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebResourceRequest
import android.webkit.WebViewClient
import androidx.activity.OnBackPressedCallback
import com.zs.base_library.base.BaseVmFragment
import com.zs.base_library.base.DataBindingConfig
import com.zs.base_library.common.setNoRepeatClick
import com.zs.base_library.utils.Param
import com.zs.zs_jetpack.BR
import com.zs.zs_jetpack.R
import kotlinx.android.synthetic.main.fragment_web.*
/**
* des 展示h5
* @author zs
* @date 2020-07-06修改
*/
class WebFragment : BaseVmFragment() {
/**
* 通过注解接收参数
* url
*/
@Param
private var loadUrl: String? = null
/**
* 文章标题
*/
@Param
private var title: String? = null
/**
* 文章id
*/
@Param
private var id: Int? = -1
/**
* 作者
*/
@Param
private var author: String? = null
private var webVM: WebVM? = null
override fun initViewModel() {
webVM = getActivityViewModel(WebVM::class.java)
}
override fun init(savedInstanceState: Bundle?) {
initView()
}
override fun initView() {
tvTitle.text = Html.fromHtml(title)
setNoRepeatClick(ivBack) {
when (it.id) {
R.id.ivBack -> nav().navigateUp()
}
}
initWebView()
}
@SuppressLint("SetJavaScriptEnabled")
private fun initWebView() {
val webSettings: WebSettings = webView.settings
webSettings.javaScriptEnabled = true
//自适应屏幕
webView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
webView.settings.loadWithOverviewMode = true
//如果不设置WebViewClient,请求会跳转系统浏览器
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//返回false,意味着请求过程里,不管有多少次的跳转请求(即新的请求地址)
//均交给webView自己处理,这也是此方法的默认处理
return false
}
override fun shouldOverrideUrlLoading(
view: WebView,
request: WebResourceRequest
): Boolean {
//返回false,意味着请求过程里,不管有多少次的跳转请求(即新的请求地址)
//均交给webView自己处理,这也是此方法的默认处理
return false
}
}
webView?.loadUrl(loadUrl)
//设置最大进度
webVM?.maxProgress?.set(100)
//webView加载成功回调
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
super.onProgressChanged(view, newProgress)
//进度小于100,显示进度条
if (newProgress<100){
webVM?.isVisible?.set(true)
}
//等于100隐藏
else if (newProgress==100){
webVM?.isVisible?.set(false)
}
//改变进度
webVM?.progress?.set(newProgress)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//自定义返回
val callback: OnBackPressedCallback =
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (webView.canGoBack()) {
//返回上个页面
webView.goBack()
} else {
//退出H5界面
nav().navigateUp()
}
}
}
requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}
override fun getLayoutId() = R.layout.fragment_web
override fun getDataBindingConfig(): DataBindingConfig? {
return DataBindingConfig(R.layout.fragment_web, webVM)
.addBindingParam(BR.vm, webVM)
}
}
<file_sep>package com.zs.zs_jetpack.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
/**
* 携程demo
*/
class CoroutinesTest {
}
fun main() {
GlobalScope.launch {
print("线程名: " + Thread.currentThread().name)
}
} | 4c4f299febad5c3d2daa20c65c17266f98b42ab2 | [
"Markdown",
"Kotlin",
"Gradle"
] | 59 | Kotlin | 815034762/KotlinMvvmJetPack | 4bbc28d9a6d403d08da4cd90b347f061d7e8fe7b | b30d4413707e8969a549bcfc9529f9b66bbd8d6b |
refs/heads/master | <file_sep>---
title: "ST663 - Semester 1 - Assignment 4"
author: "<NAME> (18145426)"
date: "24 November 2018"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
library(tidyverse)
```
# Question 1
We have data on ages in years from a random sample of 170 British husbands and their wives.
```{r q1_data, include=TRUE}
d <- read.table("Couples_Ages.txt", header=T)
str(d)
head(d)
sum(is.na(d)) # Check for the presence of NA values in the data
```
**Note that this dataset contains no NA values.**
a) Make a scatterplot of these data with Y=men and X=women. Superimpose the linear regresssion line.
```{r q1_a, include=TRUE}
ggplot (d, aes(x=WifesAge, y=HusbandsAge)) +
geom_point() +
geom_smooth(method="lm",se=F)
```
Describe the pattern in the data.
**At first glance, the data broadly appears to fit a linear model having a positive slope, and with no obvious outliers.**
b) Calculate the correlation coefficient.
$$r=\frac{\Sigma(x_i - \bar x)(y_i-\bar y)}{(n-1)s_xs_y}$$
```{r q1_b, include=TRUE}
r<-sum((d$WifesAge-mean(d$WifesAge))*(d$HusbandsAge-mean(d$HusbandsAge)))/((nrow(d)-1)*sd(d$WifesAge)*sd(d$HusbandsAge));r
cor(x=d$WifesAge,y=d$HusbandsAge)
```
Briefy describe what this coefficient reveals about the relationship between the ages of partners.
**Because the value of r above (0.9385598) is greater than 0.9, linear association is very strong and positive for this dataset.**
c) Fit the linear model relating the ages of men (Y) to those of women (X).
```{r q1_c, include=TRUE}
f<-lm(HusbandsAge~WifesAge, data=d);f
```
What is the intercept?
```{r q1_c_inter, include=TRUE}
bhat0<-round(as.numeric(f$`coefficients`[1]),4);
paste("Intercept =",bhat0)
```
The slope?
```{r q1_c_slope, include=TRUE}
bhat1<-round(as.numeric(f$`coefficients`[2]),4);
paste("Slope =",bhat1)
```
Interpret.
**The above figures mean that, for this model, for two couples, where one wife is a year older than the other, almost the same age gap (0.9667) will apply to their respective husbands.**
d) Deirdre is 60 years of age. Use the regression equation to predict the age of her husband.
$$\hat y=\hat\beta_0+\hat\beta_1x$$
```{r q1_d, include=TRUE}
x<-60
yhat<-bhat0+(bhat1*x);yhat
paste("Prediction =",round(yhat,1))
```
Calculate a 95% prediction interval and interpret.
# Question 2
There is some evidence that drinking a moderate amount of wine helps prevent heart attacks.
The data in wine.csv (on Moodle) gives yearly wine consumption (litres of alcohol from drinking wine, per person) and yearly deaths from heart disease (deaths per 100,000 people) in 19 developed nations.
```{r q2_data, include=TRUE}
wine <- read.csv("wine.csv", stringsAsFactors=F)
str(wine)
head(wine)
sum(is.na(wine)) # Check for the presence of NA values in the data
```
**Note that this dataset contains no NA values.**
a) Plot the data with yearly deaths on the y-axis. Superimpose the regression line.
```{r q2_a, include=TRUE}
f<-lm(Deaths~Wine,data=wine);f
summary(f)
plot(wine$Wine,wine$Deaths,pch=16)
abline(f,col="blue")
ggplot(aes(Wine,Deaths),data=wine) +
geom_point() +
geom_smooth(method="lm",se=F)
```
Describe the pattern in the data.
**At first glance, apart from a single outlier, this dataset appears to conform to a broadly linear model of negative slope. The main body of the dataset appears to fan out (slightly) to the left.**
b) Use the least squares regression line to estimate the effect of a 1 litre increase in wine consumption on the death rate.
```{r q2_b, include=TRUE}
bhat0<-as.numeric(f$coefficients[1]);bhat0
bhat1<-as.numeric(f$coefficients[2]);bhat1
```
**The second figure above (i.e. the slope value) indicates that a 1-litre increase in wine consumption would result in a reduction of approximately 22 in the number of deaths.**
c) Compute a 95% confidence interval for this effect.
$$SSE = \Sigma_{i=1}^n(\hat y_i-y_i)^2$$
$$s=\sqrt{SSE/(n-2)}$$
$$S_{xx}=\Sigma{(x_i-\bar x)^2}$$
$$SE=s/\sqrt{Sxx}$$
$$MoE = t_{\alpha/2}(n-2)*SE$$
```{r q2_c, include=TRUE}
c<-0.95 # Level of Confidence
alpha<-1-c # Alpha
alpha2<-alpha/2 # Half Alpha
n<-nrow(wine) # Sample size
df<-n-2 # Degrees of freedom
sse<-sum(f$residuals^2);sse # Sum of Squares for Errs (Residuals)
s<-sqrt(sse/(n-2));s # Standard Deviation (Errs/Residuals)
ssx<-sum((wine$Wine-mean(wine$Wine))^2);ssx # Sum of squared deviations of
# x from mean
se.bhat1<-s/sqrt(ssx);se.bhat1 # Standard error for slope
t<-abs(qt(alpha2,df=df));t # t-value for 95% level of confidence
moe<-t*se.bhat1;moe # Margin of error
paste(c," CI for Slope = (",round(bhat1-moe,4),",",round(bhat1+moe,4),")",sep="")
confint(f) # Compare above CI with confint o/put
```
Give your conclusions.
**We can be 95% confident that the slope of the regression line for poulation as a whole lies somewhere in the range from -33.52 to -10.52, approximately.**
d) Ireland is one of the countries in the data. What is the fitted value for Ireland?
```{r q2_d_fit, include=TRUE}
paste("Fitted Value for Ireland = ",round(f$fitted.values[which(wine$Country=="Ireland")],2))
```
What is the residual for Ireland?
```{r q2_d_res, include=TRUE}
paste("Residual for Ireland = ",round(f$residuals[which(wine$Country=="Ireland")],2))
```
e) Predict the yearly deaths from heart disease for a country whose yearly wine consumption is 4.5.
$$\hat y_0=\hat\beta_0+\hat\beta_1x_0$$
```{r q2_e_pred, include=TRUE}
x0<-4.5 # Consumption
yhat0<-bhat0+(bhat1*x0);yhat0 # Prediction
paste("Prediction =",round(yhat0))
```
Calculate a 95% prediction interval
$$\hat y_0=\hat\beta_0+\hat\beta_1x_0$$
$$SE_{pred}(\hat y_0)=s\sqrt{1+\frac{1}{n}+\frac{(x_0-\bar x)^2}{Sxx}}$$
where
$$S_{xx}=\Sigma{(x_i-\bar x)^2}$$
```{r q2_e_pi, include=TRUE}
se<-s*sqrt(1 + (1/n) + (((x0-mean(wine$Wine))^2)/ssx))
moe<-t*se;moe
paste(c," PI for yhat0=", round(yhat0), " where x0=", x0, ": (",round(yhat0-moe,4),",",round(yhat0+moe,4),")",sep="")
predict(f,data.frame(Wine=4.5),interval="prediction")
```
and interpret.
**We are 95% confident that an annual consumption of 4.5 litres of wine per per person in the country in question would result in a death rate in the 22.76-276.34 range per 100,000 people in that country's population.**
# Question 3
For the trees data:
a) Plot Volume versus Girth and superimpose the regression line.
```{r q3_a, include=TRUE}
str(trees)
head(trees)
sum(is.na(trees)) # Check for the presence of NA values in the data
ggplot(data=trees,aes(x=Girth,y=Volume)) +
geom_point() +
geom_smooth(method="lm",se=F)
```
**Note that this dataset does not contain NA values.**
Does the relationship look linear?
**At first glance, the data broadly appears to fit a linear model having a positive slope, and with no obvious outliers.**
b) Now make the plot again and this time superimpose the regression line and a smooth.
```{r q3_b, include=TRUE}
ggplot(data=trees,aes(x=Girth,y=Volume)) +
geom_point() +
geom_smooth(method="lm",se=F) +
geom_smooth(se=F)
```
Does the relationship look linear?
**The presence of the smooth now indicates the presence of some curvature.**
c) Fit the regression plot relating Volume to Girth.
```{r q3_c, include=TRUE}
f<-lm(Volume~Girth,data=trees);f
summary(f)
```
Construct the residuals versus fitted plot and the Normal plot of residuals.
```{r q3_c_plot, include=TRUE}
par(mfrow=c(1,2))
plot(f,which=1:2)
```
In light of these plots, assess the model assumptions.
**The above plots indicate that a significant amount of curvature exists in the data and that the residuals do not appear to follow a Normal distribution.**
d) Construct the plot of part (b),
i) taking a log transformation of y
```{r q3_d_i, include=TRUE}
volume.log<-log(trees$Volume)
ggplot(data=trees,aes(x=Girth,y=volume.log)) +
geom_point() +
geom_smooth(method="lm",se=F) +
geom_smooth(se=F)
```
ii) taking a log transformattion of x and
```{r q3_d_ii, include=TRUE}
girth.log<-log(trees$Girth)
ggplot(data=trees,aes(x=girth.log,y=Volume)) +
geom_point() +
geom_smooth(method="lm",se=F) +
geom_smooth(se=F)
```
iii) taking a log transformation of x and y.
```{r q3_d_iii, include=TRUE}
ggplot(data=trees,aes(x=girth.log,y=volume.log)) +
geom_point() +
geom_smooth(method="lm",se=F) +
geom_smooth(se=F)
```
In each case superimpose a straight line fit and a smooth.
Which plot looks the most linear?
**Plot iii) above appears to be the most linear one.**
e) Fit the linear model corresponding to your favourite plot of part (d). Construct the residuals versus fitted plot and the Normal plot of residuals.
```{r q3_e, include=TRUE}
f<-lm(volume.log~girth.log);f
summary(f)
par(mfrow=c(1,2))
plot(f,which=1:2)
```
In light of these plots, assess the model assumptions.
f) Use the fit of part (e) to predict and obtain a prediction interval for the Volume of a tree whose Girth is 12.
(Note if your fit uses log(y) you will need to calculate exp(p), if p is your prediction).
```{r q3_f, include=TRUE}
log12<-log(12)
p<-predict(f,data.frame(girth.log=log12),interval="prediction");p
p.exp<-exp(p);p.exp
```
Interpret your result.
**We are 95% confident that a tree with a girth measurement of 12 would result in a volume measurement in the 22.49-28.58 range.**
<file_sep>/**
* This program uses the round method of the Math class to round a randomly-generated number (of the double type, in the range 0 -100, by the Math.random method) to two decimal places
*
* @author <NAME>
* @author 18145426
* @version 17/09/2018
*/
public class RoundTest
{
public static void main(String args[])
{
double num = (double) Math.round((Math.random() * 100) *100) / 100; // Generate the random number in the range 0 - 100
System.out.println("num = " + num); // Display the result of the ternary operation above
}
}<file_sep>/**
* This program calculates and displays the result of raising a number (parameter 1) to a power (parameter 1) power, and the first 10 positive integers to the power 1, 2 and 3 using a recursive method
*
* @author <NAME>
* @author 18145426
* @version 20/09/2018
*/
import java.util.Arrays;
public class BubbleSortTest
{
public static void main(String args[])
{
int [] bubbles = new int[20]; // Create the array for sorting
for(int i = 0; i < bubbles.length; i++) // Load the array with random numbers in the range 0 to 100
{
bubbles[i] = (int) (Math.random() * 100);
}
displayArray(bubbles, "bubbles", "BEFORE bubble sort: ");
bubbleSort(bubbles);
displayArray(bubbles, "bubbles", " AFTER bubble sort: ");
}
public static void displayArray(int [] myArray, String name, String loc)
{
System.out.println(loc + name + " = " + Arrays.toString(myArray));
}
/**
* This method uses recursion to raise a specified integer number to the specified (integer) power> the result is returned as an integer number
*
* @param x is the integer number
* @param y is the integr power value
*/
public static void bubbleSort(int [] myArray) // Calculate x to the power of y
{
int temp = 0;
int swapCount = 0;
for(int i = 1; i < myArray.length; i++)
{
if(myArray[i] < myArray[i-1])
{
temp = myArray[i-1];
myArray[i-1] = myArray[i];
myArray[i] = temp;
swapCount++;
}
}
if (swapCount > 0) // This is the base case
bubbleSort(myArray); // This is the recursive operation
}
}<file_sep>---
title: "ST663 - Semester 1 - Assignment 5 - Solutions"
author: "<NAME> (18145426)"
date: "11 December 2018"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
suppressMessages(library(tidyverse))
```
# Question 1
Consider a multiple regression model which predicts the calories in breakfast cereals from sodium, potassium and sugar content in grams.
Examine the regression results given below.
```{r q1_setup, include=TRUE}
library(knitr)
df<-data.frame(x=c("(Intercept)","sodium","potass","sugars"),
matrix(c(83.0469,0.0572,-0.0193,2.3876,
5.1984,0.0215,0.0251,0.4066,
15.98,2.67,-0.77,5.87,
0.0000,0.0094,0.4441,0.0000),nrow = 4))
names(df)<-c("","Estimate","Std. Error","t value","Pr(>|t|")
kable(df)
df<-data.frame(c("Residual standard error: 15.6 on 73 degrees of freedom",
"Multiple R-squared: 0.3844, Adjusted R-squared: 0.3591",
"F-statistic: 15.2 on 3 and 73 DF, p-value: 8.868e-08"))
names(df)<-""
kable(df)
```
One of the interpretations below is correct. Which is it?
Explain what is wrong with the others.
a) Each extra gram of sugar increases calories by 2.39.
**This is not correct because it would only be valid if the values of the the other predictor (independent) variables (i.e. sodium and potassium) were fixed.**
b) Every extra gram of sodium is associated with a 0.0572 increase in average calories, for cereals with a given potassium and sugar content.
**This is the correct interpretation of the coefficient (slope) value for a predictor (independent) variable in multiple linear regression. **
c) Every extra calorie means the potassium content drops by 0.0193g.
**This is not correct because it is treating calories as a predictor (independent) variable when, for this regression, it is the response (dependent) variable.**
d) The model does not fit because R2 is only 38.4%.
**The R2 value provides some indication on the linear 'strength' of the model (indicating some degree of weakness in this case) but it does not, in itself, invalidate the model.**
**It merely indicates that 38.4% of the variation in the value of the response variable (Calories) is explainable by the model in question.**
<p style="page-break-before: always">
# Question 2
2. The FDA recorded data on tar, nicotine, weight and carbon monoxide for 25 cigarette brands. The data is in file Cigarette.csv.
```{r q2_data, echo=TRUE}
d<-read.csv("Cigarette.csv")
str(d)
```
a) Read in the data. Use pairs to make a plot of the 4 variables.
```{r q2_a, echo=TRUE}
pairs(d[,2:5])
```
Comment on the correlation between the variables.
**Visually, in the plots above, there appears be a linear relationship (correlation) between tar and nicotene, tar and carbon monoxide, and nicotene and carbon monoxide, and, possibly, between weight and carbon monoxide.**
Which of the three predictors has the hightest correlation with carbon.monoxide?
```{r q2_a_cor, echo=TRUE}
cor(d[,2:5])
```
**As shown in the carbon.monoxide column above, tar and nicotine have the highest (strongest) positive correlations (in decending order). **
The lowest?
**That column also shows that Weight has the lowest (weakest) correlation.**
Are there any outliers evident?
**In the pairs plot above, there is evidence that there is at least one outlier for all 3 predictors (tar, nicotine and weight).**
**The following boxplots support those observations.**
```{r q2_a_box, echo=TRUE}
par(mfrow=c(1,4))
boxplot(d$tar,xlab="Tar")
boxplot(d$nicotine,xlab="Nicotine")
boxplot(d$weight,xlab="Weight")
boxplot(d$carbon.monoxide,xlab="Carbon Monoxide")
```
b) Fit the regression model relating carbon.monoxide to tar, nicotine and weight.
```{r q2_b, echo=TRUE}
f<-lm(data=d,carbon.monoxide~tar+nicotine+weight)
summary(f)
```
Write down the regression equation relating carbon monoxide to tar, nicotine and weight.
$$y_{carbon.monoxide}=3.20+0.96*tar-2.63*nicotine-0.13*weight$$
c) Interpret $\beta_1$.
**A single unit increase in the Tar value will result in an increase of 0.96 in Carbon Monoxide value, where the Nicotine and Weight values are fixed.**
Find a 95% confidence interval for $\beta_1$.
```{r q2_c, echo=TRUE}
ci<-confint(f,"tar");ci
```
Interpret this interval carefully in words.
**A single unit increase in the Tar value will result in a change in the range of 0.46 and 1.47 in the Carbon Monoxide value (with 95% confidence), assuming that both the Nicotine and Weight values are fixed.**
d) Interpret $\beta_2$.
**A single unit increase in the Nicotine value will result in a decrease of 2.63 in the Carbon Monoxide value, where the Tar and Weight values are fixed.**
Test H0 : $\beta_2=0$ versus Ha : $\beta_2 \neq 0$.
```{r q2_d, echo=TRUE}
summary(f)
```
**As the p-value for Nicotine is approximately 0.51 and, therefore, greater than 0.05, we cannot reject the Null hyppthesis and must conclude (with 95% confidence) that Nicotine does not signicantly influence the Carbon Monoxide value.**
e) Interpret $\beta_3$.
**A single unit increase in the Weight value will result in a decrease of 0.13 in the Carbon Moonoxide value, where the Tar and Nicotine values are fixed.**.
Test H0 : $\beta_3=0$ versus Ha : $\beta_3 \neq 0$.
**As the p-value for Weight is 0.97 and, therefore, is greater than 0.05, we cannot reject the Null hyppthesis and must conclude (with 95% confidence) that Weight does not significantly influence the Carbon Monoxide value.**
f) Which of the three predictors is most important in explaining the response?
**Because its p-value of approximately 0.0007 is (much) lower than 0.05, Tar is the most important predictor.**
g) What is the estimate of $\sigma$ in the fit?
**As per the summary of the results of the lm function above, 1.446 (Residual standard error) is the estimate of sigma for this model.**
What is R2?
**As per the summary of the results of the lm function above, 0.9186 (Multiple R-Squared) is the R2 estimate for this model.**
h) Use the model to estimate the mean carbon.monoxide for brands with tar=10, nicotine=1 and weight = .9.
```{r q2_h_mean, echo=TRUE}
predict(f,data.frame(tar=10,nicotine=1,weight=0.9))
```
**The result of the predict function above indicates that the mean Carbon Monoxide value for such brands would be 10.08, approximately.**
Find the associated confidence interval.
```{r q2_h_conf, echo=TRUE}
predict(f,data.frame(tar=10,nicotine=1,weight=0.9),interval="confidence")
```
Interpret this interval carefully in words.
**The latest results of the predict function indicate (with a 95% level of confidence) that the mean Carbon Monoxide reading for brands with the specified Tar, Nicotine and Weight values, would be in the 7.79 to 12.36 range, approximately.**
i) Use the model to predict the carbon.monoxide for a brand with tar=10, nicotine=1 and weight = .9.
Find the associated prediction interval.
```{r q2_i, echo=TRUE}
predict(f,data.frame(tar=10,nicotine=1,weight=0.9),interval="prediction")
```
Interpret this interval carefully in words.
**The latest results of the predict function indicate (with a 95% level of confidence) that the Carbon Monoxide reading for brands with the specified Tar, Nicotine and Weight values, would be in the 6.3 to 13.85 range, approximately.**
j) Fit the reduced model with tar as the single predictor.
```{r q2_j_a, echo=TRUE}
f_tar<-lm(carbon.monoxide ~ tar, data=d)
summary(f_tar)
```
Use anova to compare this reduced model with the model fit in part (c).
```{r q1_j_b, echo=TRUE}
anova(f_tar,f)
```
State the hypothesis being tested and give your conclusions carefully.
<b>
$H_0 : \beta_{nicotine}=\beta_{weight}=0$
$H_A$ : At least one of $\beta_{nicotine}$, $\beta_{weight} \neq 0$
</b>
**As the p-value of 0.7937 achieved above is greater than 0.05, we cannot reject the Null hypothesis above, and conclude (with a 95% level of confidence) that we can omit the Nicotine and Weight predictors from the model.**
<p style="page-break-before: always">
# Question 3
The file Real estate.csv has data on recent home sales in the home towns of students in a large U.S. Statistics class. In this question, you will look at how Price (in dollars) relates to living area (square feet) and number of bedrooms. Later you will also look at the location (urban, suburban or rural).
Read in the data with
```{r q3_data, echo=TRUE}
house <- read.csv("Real_estate.csv")
house1 <- house[150:250,c(1:3, 8)]
house1$location.type <- factor(house1$location.type)
str(house1)
head(house1)
```
As the dataset is large, use the specified subset only, ie the dataset house1.
a) Use pairs to make a plot of the 3 variables Price, Living.area and bedrooms.
```{r q3_a_pairs, echo=TRUE}
pairs(house1[,1:3])
```
Comment on the correlation between the variables.
```{r q3_a_cor, echo=TRUE}
cor(house1[,1:3])
```
**The results of the cor function above indicate that Living Area has a weakly positive correlation with Price, while Bedrooms has a negligible (positive) correlation with Price.**
Which of the predictors has the highest correlation with Price?
**Living Area has the higher (weakly positive) correlation with Price.**
The lowest?
**Bedrooms has the lower (negligibly positive) correlation with Price.**
Are there any outliers evident?
**The following boxplots reveal that the Bedrooms predictor has 3 data points that are in the outlier category.
```{r q3_a_out, echo=TRUE}
par(mfrow=c(1,2))
boxplot(x=house1$Living.area,y=house1$Price,xlab="Living Area")
boxplot(x=house1$bedrooms,y=house1$Price,xlab="Bedrooms")
```
b) Fit the regression model relating Price to Living.area and bedrooms. Call this fit f1.
```{r q3_b, echo=TRUE}
f1<-lm(Price ~ Living.area + bedrooms, data=house1)
summary(f1)
```
Write down the regression equation.
$$y_{Price}=393569.62+175.46*{Living.area}-89690.08*{bedrooms}$$
c) Interpret $\beta_1$.
**A single unit increase in Living Area value will result in a 175.46 increase in the Price value, assuming that the Bedrooms value is fixed.**
Find a 95% confidence interval for $\beta_1$.
```{r q3_c, echo=TRUE}
confint(f1,"Living.area")
```
Interpret this interval carefully in words.
**A single unit increase in the Living Area value will result in a change in the Price value in the range of 85.13 to 265.793 (with 95% confidence), assuming that Bedroom value is fixed.**
d) Interpret $\beta_2$. Find a 95% confidence interval for $\beta_2$.
```{r q3_d, echo=TRUE}
confint(f1,"bedrooms")
```
Interpret this interval carefully in words.
**A single unit increase in the Bedrooms value will result in a decrease in the Price value in the range of 6712 to 172,668 (with 95% confidence), assuming that Living Area value is fixed.**
**Comment: The Bedrooms variable does not appear to be a good predictor because of its extremely wide CI and because it indicates the Price decrease as the number of Bedrooms increase.**
e) What is the estimate of $\sigma$ in the fit?
**The sigma estimate is 282,200 (the Residual Standard Error figure in the summary of the results of the lm function call for this fit above).**
What is $R^2$?
**0.1365 is the R2value for this model (the Multiple R-Squared value in the summary of the results of the lm function call for this fit above).**
f) Use your fit to predict the Price of a house with Living.area=2800 and bedrooms=3.
```{r q3_f_pred, echo=TRUE}
predict(f1,data.frame(Living.area=2800,bedrooms=3))
```
**As shown above, the current model predicts a Price value of 615,778 for the specified house type.**
Find the associated prediction interval.
```{r q3_f_pi, echo=TRUE}
predict(f1,data.frame(Living.area=2800,bedrooms=3),interval="prediction")
```
Interpret this interval carefully in words.
**The latest results of the predict function indicate (with a 95% level of confidence) that the Pricevalue for the specified type of house would be in the 46,865 to 1,1184,701 range, approximately.**
**Refer to my previous comment in relation to relying on Bedrooms as a predictor in this model.**
(g) Assess the model assumptions. (See the code at the end of question 4).
```{r q3_g, echo=TRUE}
suppressMessages(library(car))
residualPlots(f1, tests=F)
plot(f1,which=2)
```
**The above plots clearly indicate that two of the main assumptions of linear regression (i.e. that the residuals are normally distributed and with constant variance) are not satisfied by this model. Living Area appears to do better on the constant variance front.**
<p style="page-break-before: always">
# Question 4
For the house1 data of the previous question we will look at how the Price varies with location.type.
```{r q4_fit, echo=TRUE}
levels(house1$location.type)
levels(house1$location.type)<-c("Rural","Suburban","Urban")
levels(house1$location.type)
f2<-lm(Price ~ location.type, data=house1)
summary(f2)
```
a) Draw boxplots for the Price for each group.
```{r q4_a_box, echo=TRUE}
levels(house1$location.type)<-c("Rural","Suburban","Urban")
ggplot(data=house1,aes(x=location.type,y=Price)) + geom_boxplot()
```
Comment on the differences between the groups.
<b>
1. It is suprising that house prices in Urban areas have a significantly tighter spread and lower price range than those in both Rural and Suburban areas.
2. It is also surprising that Suburban and Rural areas have roughly the same median price and that Suburban prices have a greater spread than those in Rural areas.
3. The relative lack of outliers is also remarkable.
4. The previous comments indicate the need to review the spread of data across the location type for the selected sample of 101 houses (see below).
<\b>
```{r q4_a_group, echo=TRUE}
group_by(house1,location.type) %>%
summarise(n())
```
**The above breakdown of data points by Location Type may well explain the comments in relation to the features of the boxplots above. In particular, the relatively size of the sample of Urban prices and, to a leser extent, of the Rural prices may be skewing the overall results.**
Does it look like the variability is roughly constant across the 3 groups?
**The following scatter plots show a lack of constant variance accross all 3 house locations - although the paucity of Urban data points doesn't lend itself to pattern recognition.**
```{r q4_a_point, echo=TRUE}
ggplot(house1,aes(Living.area,Price),color=location.type) + geom_point() + geom_smooth(method=lm,se=F) +facet_wrap(~location.type)
```
b) Fit a model relating Price to location.type. Call your fit f2. Use the anova function on the fit.
```{r q4_b, echo=TRUE}
f2<-lm(Price ~ location.type, data=house1)
summary(f2)
anova(f2)
```
What conclusions can you draw from this about location.type?
**As the Anova results give a p-value (0.01541) for Location Type that is less than 0.05, we can conclude that Location Type is significant when explaining variation in Price.**
c) What is the estimate of $\sigma$ in the fit?
**291000 is the sigma (Residual standard error) for this model.**
What is $R^2$?
**0.08163 is the R2 (Multiple R-squared) value for this model.**
Compare these values to those of fit f1.
**The sigma value for f2 is greater than that of f1 and the R2 value for f2 is less than than for f1.**
**This (esp. the R2 value) indicate that f1 does a better job of explaining variation in price - although neither of them are impressive.**
d) Fit the model f3 <- lm(Price ~ Living.area+bedrooms+location.type, data=house1)
Use anova to compare f1 and f3.
```{r q4_d, echo=TRUE}
f3 <- lm(Price ~ Living.area+bedrooms+location.type, data=house1)
summary(f3)
anova(f1,f3)
```
What do the results of the anova tell you?
**As the p-value (0.008034) for the extended model is less than 0.05, we can conclude that the addition of Location Type to the f1 model can a significant contribution to explaining variation in Price.**
e) Assess the model assumptions for the fit f3 based on the plots produced by the given code.
```{r q4_e, echo=TRUE}
library(car)
residualPlots(f3, tests=F)
plot(f3,which=2)
```<file_sep>---
title: "ST464 - Assignment 2 - Solutions"
author: "<NAME> (18145426)"
date: "9 March 2019"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
suppressPackageStartupMessages(library(tidyverse))
```
## Question 1
For the data matrix below
$$\mathbf{X} = \left[\begin{array}
{rrr}
4 & 2 \\
1 & 0 \\
-1 & -1 \\
-3 & 5 \\
1 & -1
\end{array}\right]
$$
```{r q1_data, include=TRUE}
x<-c(4,1,-1,-3,1,2,0,-1,5,-1)
X<-matrix(x,nrow=5)
X
```
For a) to c) do all the calculations by hand and check your answers in R.
a) Calculate the sample variance-covariance matrix.
```{r q1a, include=TRUE}
S<-cov(X)
S
```
b) Calculate the correlation matrix.
```{r q1b, include=TRUE}
R<-cor(X)
R
```
c) Standardize the variables to have mean 0 and standard deviation 1.
```{r q1c, include=TRUE}
X_std<-scale(X)
X_std
round(mean(X_std))
round(sd(X_std))
```
d) In R find the eigenvectors of the correlation matrix of x.
```{r q1d, include=TRUE}
eigen<-eigen(R)
eigen$vectors
```
e) Using prcomp() function, find the loadings for the principal components of x.
```{r q1e, include=TRUE}
p<-prcomp(X)
p$rotation
```
\newpage
<P style="page-break-before: always">
## Question 2
Body fat data. The data consists of observations taken on a sample of 88 males. In this question you will look at PCA of the variables variables were measured:
Neck circumference (cm) Abdomen circumference (cm)
Knee circumference (cm) Ankle circumference (cm)
```{r q2_data, include=TRUE}
bfat <- read.table("data/bodyfat.txt", header=T)
bfat <- bfat[,c("neck","abdomen", "knee", "ankle")]
str(bfat)
```
a) Use pairs to construct a scatterplot matrix.
```{r q2a, include=TRUE}
pairs(bfat)
```
**The scatter plot matrix above indicates the existance of linear-type relationships for all of the variable pairings.**
Are there any outliers?
**Yes, there are two particularly obvious outliers in the ankle variable.**
If so, which cases are they?
**Let's do some boxplotting and analyse the output to answer this question accurately.**
```{r q2a_out, include=TRUE}
boxplot(bfat) # Display a boxplot for the dataset
# Construct an outliers data frame containing variable name, value and observation number.
outliers<-function(data){
box<-boxplot(data) # Boxplot the data and store its results
var<-rep("",length(box$out)) # Name of variable containing the outlier
val<-box$out # Outlier value
obs<-rep(0,length(box$out)) # Observation (row/case) number
for(i in c(1:length(box$out))){ # Parse the outlier details provided by boxplot
var[i]<-box$names[box$group[i]]
obs[i]<-which(data[,box$group[i]] == box$out[i])
}
out<-data.frame(var, val, obs) # Create the data frame
out<-arrange(out, var) # Sort the data frame by variable name
return(out) # Return the contents of the data frame
}
outliers(bfat) # Display the outlier details.
```
**Note how box plotting has identified 3 more outliers in the other variables too.**
(b) Carry out a principal components analysis of the data.
```{r q2b_prcomp, include=TRUE}
p<-prcomp(bfat, scale=T)
psum<-summary(p)
psum
```
**Note that, even though the measurement units are the same for all variables (cms), I have elected to standardise (scale) them during prcomp because of the relative magnitude difference between the abdominal measurements and the other measurement types.**
What percentage of the variability in the dataset is accounted for by the first component?
```{r q2b_prop1, include=TRUE}
round(psum$importance[3,1]*100,1)
```
What percentage of the variability in the dataset is accounted for by the first two components?
```{r q2b_cumprop2, include=TRUE}
round(psum$importance[3,2]*100,1)
```
Examine the scree diagram and comment. (You will find the code for the screeplot in h1code.R).
```{r q2b_scree, include=TRUE}
scree<-function(p){
if(class(p)=="princomp"){
var<-summary(p)$sdev^2
var_prop<-var/sum(var)
} else {
var_prop<-summary(p)$importance[2,]
}
len<-length(var_prop)
plot(var_prop, type="b", pch=16,
xlim=c(1,len),
xlab="Principal Component Number",
ylab="Variance Proportion", main="Scree Plot",
xaxt="n")
axis(1,at=c(1:len))
}
scree(p)
```
**The scree plot above also clearly shows that over 66% of the variance in the data is explained by PC1, while just over 85% is explained by PC1 and PC2 combined.**
Make a biplot to assist your interpretations.
```{r q2c_biplot, include=TRUE}
biplot(p, scale=0, cex=c(.5,.5), cex.axis=.5)
```
**The biplot above indicates, through the proximity of the red vectors, that there is a high degree of colinearity between 3 of the 4 measurement types - i.e. between the abdomen, knee and neck.**
(c) What does the first component measure?
```{r q2c_pc1, include=TRUE}
p$rotation[, 1]
```
**PC1 appears to measure the overall 'size' of the sampled males, giving (almost) equal weigthing to the knee, abdomen and neck measurements - and slighlty less to the ankle measurement - thereby, slightly downplaying the influence of the smallest measurement type (ankle), the one with the lower colinearity.**
the second component?
```{r q2c_pc2, include=TRUE}
p$rotation[, 2]
```
**PC2 appears to be focusing on the first three measurment types only, while seeking to downplay/eliminate/ignore the ankle measurement using a negative loading. Of the first three measurement types, the most emphasis appears to be placed on the larger measurment types with particular focus on the abdominal measurement and, to a lesser extent, on the neck measurement. Therefore, PC2 looks like it could be useful as an (surrogate) indicator of weight or BMI (body mass index). **
Are there any outliers?
**Of the 5 outlier observations previously identified using boxplotting (i.e. 31, 34, 40, 43 and 84), 3 of them (i.e. 31, 40 and 84) are also immediately apparent in the biplot above. Interestingly, the biplot also appears to identify that case 35 as an outlier, which boxplotting did not.**
What can you say about the outliers from the plot?
**As can be seen from the previous boxplot above, those 3 outliers are the most extreme of the 5 identified there, with the 2 most extreme being ankle measurements and the third being an abdominal measurement. The other 2 of the 5 (for knee and neck, respectively) are shown to be marginal ones by that boxplot. Therefore, the most prominent outliers are still being identified by the biplot of the PC1 & PC2 data. As boxplot implements the formal definition of an outlier (1.5 x IQR), I will discount case 35 on the biplot as a real outlier.**
(d) Omiting any outliers identified, repeat parts (b) and (c).
**Eliminating the 3 observations (i.e. 31, 40 and 84) containing the most prominent outliers...**
```{r q2d_data, include=TRUE}
bfat2<-bfat[c(-31,-40,-84),] # Eliminate the observations with outliers
```
**Boxplotting the reduced dataset and analysing its details...**
```{r q2d_box, include=TRUE}
boxplot(bfat2) # Display a boxplot of the new dataset
outliers(bfat2) # Display the remaining (marginal) outlier details.
```
**Note that only the 2 marginal outliers remain above.**
Carry out a principal components analysis of the data.
```{r q2d_prcomp, include=TRUE}
p2<-prcomp(bfat2, scale=T)
psum2<-summary(p2)
```
What percentage of the variability in the dataset is accounted for by the first component?
```{r q2d_prop1, include=TRUE}
round(psum2$importance[3,1]*100,1)
```
**Removing the 3 outlier cases has caused this percentage to be increased from 66.3 to 73.1.**
What percentage of the variability in the dataset is accounted for by the first two components?
```{r q2d_cumprop2, include=TRUE}
round(psum2$importance[3,2]*100,1)
```
**This percentage has increased from 85.3 to 87.3.**
Examine the scree diagram and comment.
```{r q2d_scree, include=TRUE}
scree(p2)
```
**Comparing the above scree plot with the previous one shows that PC1 now explains a higher proportion of the overall variance compared to PC2. In fact, by comparing the percentage variances figures underlying those 2 scree plots, we can see that PC1 gained about 7% while the PC1-PC2 combined percentage increased by 2%. This means that PC1 acquired 5% of its additional variance explanation from PC2.**
Make a biplot to assist your interpretations.
```{r q2d_biplot, include=TRUE}
biplot(p2, scale=0, cex=c(.5,.5), cex.axis=.5)
```
**The biplot above indicates, through the proximity of the red vectors, that there is still a reasonable level of collinearity between the abdominal and neck measurements, with decreasing levels between those for neck and knee, and between those for knee and ankle.**
(c) What does the first component measure?
```{r q2d_pc1, include=TRUE}
p2$rotation[, 1]
```
**PC1 still appears to measure the overall 'size' of the sampled males, now giving (roughly) equal loadings to neck and abdomen measurements, with those for knee and ankle only slightly above and below them, respectively.**
the second component?
```{r q2d_pc2, include=TRUE}
p2$rotation[, 2]
```
**PC2 now appears to be even more focused on the measurements that would be indication of weight/BMI by now discounting knee measurement as well as ankle measurement using negative loadings.**
Are there any outliers?
**There are now no obvious outliers, although the biplot still appears to identify that case 35 (and 74, perhaps) as a possible outlier, which boxplotting did not.**
What can you say about the outliers from the plot?
**As those possible outliers were not identified by boxplotting, they can be discounted.**
## Question 3
A 1902 study obtained measurements on seven physical characteristics for each of 3000 criminals. The seven variables measured were (1) head length (2) head breadth (3) face breadth (4) left finger length (5) left forearm length (6) left foot length (7) height.
$$\mathbf{R} = \left[\begin{array}
{rrr}
1.000 \\
0.402 & 1.000 \\
0.396 & 0.618 & 1.000 \\
0.301 & 0.150 & 0.321 & 1.000 \\
0.305 & 0.135 & 0.289 & 0.846 & 1.000 \\
0.339 & 0.206 & 0.363 & 0.759 & 0.797 & 1.000 \\
0.340 & 0.183 & 0.345 & 0.661 & 0.800 & 0.736 & 1.000
\end{array}\right]
$$
# read in the correlation data as a vector
```{r q3_data, include=TRUE}
crimcorr <- matrix(c(
1.000, 0.402, 0.396, 0.301, 0.305, 0.339, 0.340,
0.402, 1.000, 0.618, 0.150, 0.135, 0.206, 0.183,
0.396, 0.618, 1.000, 0.321, 0.289, 0.363, 0.345,
0.301, 0.150, 0.321, 1.000, 0.846, 0.759, 0.661,
0.305, 0.135, 0.289, 0.846, 1.000, 0.797, 0.800,
0.339, 0.206, 0.363, 0.759, 0.797, 1.000, 0.736,
0.340, 0.183, 0.345, 0.661, 0.800, 0.736, 1.000), nrow = 7, byrow = TRUE)
colnames(crimcorr)<- c("Head-L","Head-B","Face-B","L-Fing","L-Fore","L-Foot",
"Height")
```
Using the correlation matrix given above,find the principal components of the data
**Firstly, we will perform PCA the hard using the eigen vectors (loadings) & values (variations)**
```{r q3_prcomp1, include=TRUE}
e<-eigen(crimcorr) # Get eigen values and vectors (Primary Components)
e_sdev<-sqrt(e$values) # Calculate the standard deviations for the PCs
names(e_sdev)<-paste("PC", as.character(c(1:nrow(e$vectors))), sep="")
"Standard Deviations:"
e_sdev
# Name the Primary Components and their Loadings
colnames(e$vectors)<-paste("PC", as.character(c(1:nrow(e$vectors))), sep="")
rownames(e$vectors)<-colnames(crimcorr)
"Loadings:"
e$vectors
e_varp<-e$values/sum(e$values) # Calculate the variation proportions
names(e_varp)<-paste("PC", as.character(c(1:nrow(e$vectors))), sep="")
"Variation Percentages:"
e_varp
e_varc<-cumsum(e_varp) # Calculate the cumulative variation proportions
names(e_varc)<-paste("PC", as.character(c(1:nrow(e$vectors))), sep="")
"Cumulative Variation Percentages:"
e_varc
```
**Secondly, we will perform PCA the easy way using the princomp function**
```{r q3_prcomp2, include=TRUE}
p<-princomp(covmat=crimcorr)
p$sdev
p$loadings
psum<-summary(p)
psum
```
and interpret the results.
**From the results above, we can see that PC1 explains about 54% of the variability in the correlation matrix, while PC1 & PC2 explain almost 76% between them, and PC1 , PC2 & PC3 together explain 85% of the variability.**
```{r q3_rot, include=TRUE}
p$loadings
```
**The loadings for PC1 above gives focuses on the final 4 (non-head) measurements, while PC2 places emphasis on the head measurements and downplays the other measurements (using negative loadings). PC3 completely elimates the non-head measurements (using zero loadings), while placing particular emphasis on the head length measurement (using a relatively large positive loading).**
What percentage of the variability in the dataset is accounted for by the first component?
```{r q3_PC1, include=TRUE}
round(e_varc[1]*100, 1)
```
What percentage of the variability in the dataset is accounted for by the first two components?
```{r q3_PC2, include=TRUE}
round(e_varc[2]*100, 1)
```
Examine the scree diagram and comment.
```{r q3_scree, include=TRUE}
scree(p)
```
**The scree plot confirms the answers to the previous parts of this question - i.e. that PC1 explains just over 54% of the variance in the dataset's correlation matrix and PC1 and PC2 combined explain almost 76% (54+22) of the variance in it. PC1, PC2 & PC3 combined explain about 85% (54+22+9) of the variance, while adding PC4 brings the total explanation up to 90% (54+2+9+5).**
## Question 4
For each of the following situations, answer, if possible:
i) Is it a classification or regression problem?
ii) Are we most intererested in inference or prediction?
iii) Provide n and p. For each predictor described state whether it is categorical or quantitative.
iv) Indicate whether we would expect the performance of a flexible learning method to be better or worse than an inflexible method.
a) We have a set of data on 500 worldwide tech firms. For each firm, information on
profit, CEO salary, number of employees, average employee salary, and home country
is recorded. We are interested in the relationship between CEO salary and other
measurements.
<b>
i) This is a regression problem.
ii) We are more interested in inference.
iii) n=500; p=4 (which does not include the response variable of the CEO salary). The first 4 features are quantitative while the 5th is categorical.
iv) An inflexible method is more likely to be more suitable here.
</b>
b) A company wishes to launch a new product. They want to know in advance whether
it will be a success or failure. They collect data on 20 similar products, and record whether they succeeded or not, price charged, marketing budget, and 10 other variables.
<b>
i) This is a regression problem.
ii) We are more interested in prediction (of success or failure).
iii) n=20; p=12 (which does not include the response variable of the success-failure indicator). The first 2 features are quantative and the other 10 could be of either or both types.
iv) A flexible method is more likely to give better results here (provided that care is taken to avoid overfitting).
</b>
c) A dataset was collected to relate the birthweight of babies to the days of gestation and gender.
<b>
i) This is a regression problem.
ii) It is not clear as to whether this is an inference or prediction problem. If the ojective of the exercise is to be able to predict the birthweight response based on the other two features (predictors), it is a prediction problem. On the other hand, if the objective is to understand how changes in the values of those predictors influence the value of the response, the problem is one of inference.
iii) n is not specified. p=2 (which does not include the birthweight response variable). The first feature is quantative and the second one is categorical.
iv) If this is an inference problem, an inflexible (parametric) method would be better. Otherwise, a flexible method could be used instead (or as well). However, with only 2 predictors (of which one of them is categorical and binary) the level of flexibility of the method is probably not of major concern here.
</b>
d) Observations were collected on 56 attributes from 32 lung cancer patients belonging to one of 3 classes.
<b>
i) It is not clear as to whether this is a classification problem or a regression problem. If the classification of the patients is known and recorded it is a predictiregression problem. Otherwise, it is a classification problem.
ii) We are more interested in prediction (most likely).
iii) n=32, p=56 (which does not include the class response if it is recorded). The types of the 56 features is not given; they could be either all categorical (probably unlikely), all quantative or some combination of both types.
iv) A flexible method is more likely to give better results here (provided that care is taken to avoid overfitting).
</b>
\newpage
<P style="page-break-before: always">
## Question 5
In this exercise you will conduct an experiment to compare the fits on a linear and
exible model fit. You will use the Auto data from the package ISLR and explore the relationship between the response mpg with weight and horsepower.
a)
```{r q5a_data, include=TRUE}
# install.packages("ISLR") #home computer, first time only
library(ISLR)
Auto <-Auto[complete.cases(Auto[,c(1,4,5)]),] # to remove NAs
```
Plot the response (miles per gallon) vs weight and horsepower.
```{r q5a_plot, include=TRUE}
pairs(Auto[c(1,5,4)])
```
What do they tell you about the relationship between mpg and the predictors?
**There is (roughly) negative linear (although some curvature is evident at the higher values of mpg) between the mpg response variable and both of those predictors - i.e. as the predictor values increase, the value of the response decreases.**
b) Make a 3d plot of weight, horsepower and mpg (see commands below).
```{r q5b_plot, include=TRUE}
# install.packages("plot3D") #home computer, first time only nstall package
library(plot3D)
scatter3D(Auto$weight,Auto$horsepower,Auto$mpg)
library(plot3Drgl)
scatter3Drgl(Auto$weight,Auto$horsepower,Auto$mpg)
```
What do they tell you about the relationship between mpg and the predictors?
**As to be expected, there is a negative relationship between mpg (response) and both weight and horsdepower (predictors) - i.e. mpg decreases when either or both of those 2 predictors increase. As observed previously, those relationships are not perfectly linear as the plots show curvature in the data.**
c) Next, divide the data into a training set and a test set as follows:
```{r q5c_train, include=TRUE}
set.seed(123)
train <- sample(nrow(Auto), round(.8*nrow(Auto)))
AutoTrain <- Auto[train,]
AutoTest <- Auto[-train,]
```
Fit a linear regression model to mpg versus weight and horsepower on AutoTrain. Call
the fit f1.
```{r q5c_lm, include=TRUE}
f1<-lm(mpg ~ weight + horsepower, data=AutoTrain)
summary(f1)
```
Examine summary(f1) and comment on the significance of the predictors.
**In the Estimate column, the Intercept value tells us that the plot hits the Z-plane when the mpg value is 46.16 (its maximum value) and, as noted previously in relation to the 3D plots, the slope of its relationship between both horsepower and weight are both negative.**
**In the Pr(>|t|) column, all scores are tiny which tells us that all 3 coefficients are highly significant. In particular, for the 2 predictors (horsepower and mpg), this means that we can reject the null Hypothesis ($H_0$) - i.e. that their slope is zero - and, therefore, that their is a strong indication of linearity in their relationships with the response variable (mpg).**
d) Plot the fitted surface and the data. (See lecture notes for code).
```{r q5d_plot, include=TRUE}
wt <- seq(min(AutoTrain$weight), max(AutoTrain$weight), length.out = 100)
hp <- seq(min(AutoTrain$horsepower), max(AutoTrain$horsepower), length.out = 100)
pred <- predict(f1, expand.grid(weight=wt, horsepower=hp))
pred <- matrix(pred,100,100)
scatter3D(AutoTrain$weight, AutoTrain$horsepower, AutoTrain$mpg, pch = 18,
surf = list(x = wt, y = hp, z = pred))
scatter3Drgl(AutoTrain$weight, AutoTrain$horsepower, AutoTrain$mpg, pch = 18)
rgl.surface(wt, hp, pred, coords=c(1,3,2), alpha.col=0.2)
```
Does the linear surface look like a good fit?
**It is not easy to judge the goodness of fit from the static scatter3D plot above but it doesn't look particularly good. However, the rotatable scatter3Drgl plot clearly shows that the fit is poor.**
e) Use loess to fit a surface to the same data. Call the fit f2. Plot the fitted surface and the data.
```{r q5e_loess, include=TRUE}
f2 <- loess(mpg ~ weight + horsepower, data=AutoTrain)
wt <- seq(min(AutoTrain$weight), max(AutoTrain$weight), length.out = 100)
hp <- seq(min(AutoTrain$horsepower), max(AutoTrain$horsepower), length.out = 100)
pred <- predict(f2, expand.grid(weight=wt, horsepower=hp))
pred <- matrix(pred,100,100)
scatter3D(AutoTrain$weight, AutoTrain$horsepower, AutoTrain$mpg, pch = 18,
surf = list(x = wt, y = hp, z = pred))
scatter3Drgl(AutoTrain$weight, AutoTrain$horsepower, AutoTrain$mpg, pch = 18)
rgl.surface(wt, hp, pred, coords=c(1,3,2), alpha.col=0.2)
```
Does the loess surface look like a good fit?
**Again, it is not easy to judge the goodness of fit from the static scatter3D plot above but it does appear to be better than that of the linear fit used previously. However, the rotatable scatter3Drgl plot clearly shows that fit is much better than the previous than the linear one.**
f) Calculate the MSE for both fits on the training data. (See lecture notes for code.)
```{r q5f_mse, include=TRUE}
mean((f1$residuals)^2)
mse_f1<-mean((f1$fitted.values - AutoTrain$mpg)^2)
mse_f1
mean((f2$residuals)^2)
mse_f2<-mean((f2$fitted - AutoTrain$mpg)^2)
mse_f2
```
What do these tell you?
**The loess fit is confirmed as a better one because of the lower value of its MSE compared to the linear equivalent.**
g) Calculate the MSE for both fits on the test data.
```{r q5g_mse, include=TRUE}
AutoTestHat1<-predict(f1, AutoTest)
mse_f1<-mean((AutoTestHat1 - AutoTest$mpg)^2)
mse_f1
AutoTestHat2<-predict(f2, AutoTest)
mse_f2<-mean((AutoTestHat2 - AutoTest$mpg)^2)
mse_f2
```
What do these numbers tell you?
**This time, the linear fit achieved a lower MSE value than the loess equivalent. This may be an indication that the loess fit is overfitted. This calls into question the previously declared preference for the loess fit and it means that further evaluation of those 2 fits is required using additonal test datasets, assuming that they can be acquired.**
**Interestingly, the MSE values achieved for the test dataset are lower than those observed for the training set when higher values would have been expected - which is a further indication of possible overfitting in the case of the loess fit.**<file_sep>/**
* This program calculates and displays the result of raising a number (parameter 1) to a power (parameter 1) power, and the first 10 positive integers to the power 1, 2 and 3 using a recursive method
*
* @author <NAME>
* @author 18145426
* @version 22/09/2018
*/
import java.util.Arrays;
public class BubbleSortTest2
{
public static void main(String args[])
{
int [] bubbles = new int[20]; // Create the array for sorting
for(int i = 0; i < bubbles.length; i++) // Load the array with random numbers in the range 0 to 100
{
bubbles[i] = (int) (Math.random() * 100); // Generate and store a random integer number
}
// For testing pusposes, comment out the preceding array declaration and loading (with random numbers) and uncomment one of the 2 next statements (to replace it).
//DEBUG int [] bubbles = {24, 4, 13, 15, 73, 42, 22, 25, 7, 10, 9, 76, 52, 47}; // Load the array with a constant set of values
//DEBUG int [] bubbles = {24, 4, 13, 15, 52, 42, 22, 25, 7, 10, 9, 47, 73, 76}; // Load the array with a constant set of values
int [] counts = {0, 0, (bubbles.length - 1)}; // Counts array ([0] = Call Count; [1] = Loop Count; [2] = Upper limit element index for sort pass)
displayArray(bubbles, "bubbles", "BEFORE bubble sort: "); // Display the contents of the array before the bubble sort
counts = bubbleSort(bubbles, counts); // Perform the bubble sort
displayArray(bubbles, "bubbles", " AFTER bubble sort: "); // Display the contents of the array after the bubble sort
System.out.println("\nCall Count = " + counts[0] + "; Loop Count = " + counts[1]); // Display the call and loop counts for the current sort
}
public static void displayArray(int [] myArray, String name, String loc) // Display the contents of the specified 1D integer array
{
if(loc.startsWith(" AFTER")) System.out.print("\n"); // Display a blank line before the ' AFTER' contents.
System.out.println(loc + name + " = " + Arrays.toString(myArray)); // Display the contents of the array
if(loc.startsWith("BEFORE")) System.out.print("\n"); // Display a blank line after the "BEFORE" contents
}
/**
* This method uses recursion to perform a bubble sort on the specified (1D, integer) array
*
* @param x is the reference to the (1D, integer) array
* @param y is the array of counts (call and loop) whose updated values are to be returned to method call location
*/
public static int [] bubbleSort(int [] myArray, int [] myCounts) // Perform a bubble sort (recursively)
{
int temp = 0; // Declare a temporary variable for use during array element swap
int swapCount = 0; // Declare a counter for array element swapping
getLoopLimit(myArray, myCounts); // Get the upper limit (phyical element number) for array element swapping
//DEBUG System.out.println("Call Count = " + myCounts[0] + "; Loop Count = " + myCounts[1] + "; Limit = " + myCounts[2]);
int limit = myCounts[2]; // Set the upper limit
if(limit == 0) // This a base case (recursion completed)
return myCounts;
for(int i = 1; i <= limit; i++) // Loop to the array as far as the upper-limit element
{
if(myArray[i] < myArray[i-1]) // If the current element value is less that the previous one, swap their values
{
temp = myArray[i-1]; // Perform the value swap
myArray[i-1] = myArray[i];
myArray[i] = temp;
swapCount++; // Increment the swapp count
}
myCounts[1]++; // Increment the loop count
//DEBUG displayArray(myArray, "myArray", "DURING bubble sort: ");
}
myCounts[0]++; // Increment the (bubbleSort method) call count
if (swapCount > 0) // The opposite of this condition is another base case
myCounts = bubbleSort(myArray, myCounts); // This is the recursive operation
return myCounts; // Return (and preserve) the key count values
}
public static void getLoopLimit(int [] myArray, int [] myCounts) // Set the upper limit for array element swapping
{
for(int i = myCounts[2]; i > 0; i--) // Loop back through the array from the previous limit until the new limit is found
{
if(isLastMax(myArray, i, 0)) // If the current value is greater than its predecessors...
myCounts[2] = i - 1; // ...move the limit element for sorting back one position
else // Otherwise...
break; //...use the current element number as the limit
}
}
public static boolean isLastMax(int [] myArray, int last, int first) // Check if the current (last) element in the array is lesd than all
{ // all of its predecessors as far as the specified (first) element
for(int i = last; i > first; i--)
{
if(myArray[last] < myArray[i - 1]) // If a predecessor with a smaller value is found, return the false value
return false;
}
return true; // Otherwise (no smaller predecessor value found), return the true value
}
}<file_sep>/*
Author: <NAME> (18145426)
Date: 12/09/2018
Description: Display the product of two integer numbers passed in from the command line
*/
public class MethodTest
{
public static void main(String args[])
{
int num1 = Integer.parseInt(args[0]); // Declare and accept 2 integer numbers from the command line
int num2 = Integer.parseInt(args[1]);
System.out.println(num1 + " multiplied by " + num2 + " is " + mulTwoNumbers(num1, num2));
}
public static int mulTwoNumbers(int x, int y)
{
return (x * y);
}
}<file_sep>---
title: "ST464 - Assignment 1 - Solutions"
author: "<NAME> (18145426)"
date: "27 February 2019"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
suppressPackageStartupMessages(library(tidyverse))
```
## Question 3
The file eupop.txt contains the population and percentage distribution by age for EU countries in 1999. The age categories are 0-14 years, 15-44 years, 45-64 years and 65 years and over.
```{r q3_eupop, include=TRUE}
eupop <- read.table("eupop.txt", header=T, row.names=1)
eupop <- eupop[,-5]
```
a) Construct the euclidean distance matrix of the percentage variables.
```{r q3a_dist, include=TRUE}
d<-dist(eupop,method='euclidian')
head(d)
```
Use it to cluster the countries, using average linkage.
```{r q3a_hclust, include=TRUE}
h<-hclust(d,method='average')
h
```
Draw the dendrogram and interpret.
```{r q3a_dend, include=TRUE}
dg<-plot(as.dendrogram(h))
dg
```
<b>
Looking at the above dendrogram from right to left, and in keeping with Tobler's 1st Law of geography, there seems to be a general grouping of countries geographically with some exceptions (in brackets):
1. Southern (plus Germany, except Portugal);
2. Nordic;
3. Benelux (except Belgium);
4. Austria & Portugal (randomly);
5. Northwest (plus Belgium, except Ireland);
6. Ireland.
Combining the above clusters a bit more we get:
1. Southern (plus Germany, except Portugal);
2. Northern & Central (plus Portugal, except Germany and Ireland);
3. Ireland.
</b>
Are there any outlier countries?
**Ireland is a clear outlier, being the only country in a grouping (cluster) of its own.**
**Taking a closer look at the underlying data below, we can see that, for instance, Ireland is the only country to have a population percentage of greater than 20 in the 0-14 age group and less than 12 in the 65+ group....**
```{r q3a_outlier, include=TRUE}
rbind(eupop["Ireland",],head(eupop))
subset(eupop,p014>20)
subset(eupop,p65.<12)
```
(b) Examine the 3-cluster solution.
```{r q3b_cutree1, include=TRUE}
suppressPackageStartupMessages(library(dendextend))
col<-cutree(h, 3, order_clusters_as_data=F)
plot(color_branches(h, col=col+1))
```
Which countries belong to each of the three clusters?
```{r q3b_cutree2, include=TRUE}
col
```
Summarise the partitions with sumPartition (in h1code.R)
```{r q3b_sumpar1, include=FALSE}
sumPartition <- function(dat,z){
k <-length(unique(z))
nobs <- tapply(1:nrow(dat),z,length)
withinSS <- tapply(1:nrow(dat),z,function(i){
if (length(i)==1) 0
else {x<- dat[i,]
xm <- scale(x, scale=F)
sum(xm^2)
}
})
aveD <- tapply(1:nrow(dat),z,function(i){
if (length(i)==1) 0
else {x<- dat[i,]
xm <- scale(x, scale=F)
xm <- apply(xm, 1, function(y) sqrt(sum(y^2)))
mean(xm)
}
})
maxD <- tapply(1:nrow(dat),z,function(i){
if (length(i)==1) 0
else {x<- dat[i,]
xm <- scale(x, scale=F)
xm <- apply(xm, 1, function(y) sqrt(sum(y^2)))
max(xm)
}
})
part<- data.frame("N.obs"=nobs, "Within clus SS" = withinSS, "Ave dist Centroid" = aveD,
"Max dist centroid" =maxD)
rownames(part)<- paste("Cluster", 1:k)
cCen <- cbind(simplify2array(tapply(1:nrow(dat),z,function(i){
x<- dat[i,]
if (length(i)==1) x
else {
colMeans(x)
}
})), colMeans(dat))
colnames(cCen)<- c(paste("Cluster", 1:k), "Grand centrd")
cCenD <- as.matrix(dist(t(cCen[, -ncol(cCen)])))
cat("Final Partition\n")
cat("\n")
cat(paste("Number of clusters ", k))
cat("\n")
cat("\n")
print(part, quote=F)
cat("\n")
cat("\n")
cat("Cluster centroids\n")
cat("\n")
print(cCen,quote=F)
cat("\n")
cat("\n")
cat("Distances between Cluster centroids\n")
cat("\n")
print(cCenD,quote=F)
}
```
```{r q3b_sumpar2, include=TRUE}
sumPartition(eupop, col)
```
Interpret your findings.
<b>
The first section (of 3) of the report above shows us that the data points in Cluster 2 are about two times more closely spaced than those in Cluster 3 (as per the ratio of their average and maximum distances from their respective centroids). As Cluster 1 contains only 1 data point which, therefore, is its centroid, whose its distance from itself is zero.
The third (and final) section tells us that Cluster 2 is (almost) equidistant from both Cluster 1 and Cluster 3, while Cluster 1 and Cluster 3 are in relatively closer proximity to each other.
</b>
c) Use the kmeans algorithm to find another 3-cluster grouping of countries.
```{r q3c_kmeans, include=TRUE}
km<-kmeans(eupop, 3, nstart=100)
str(km)
```
Which countries belong to each of the three clusters?
```{r q3c_clustsum, include=TRUE}
sort(km$cluster)
```
d) Construct a stars plot which shows the data and clustering obtained from kmeans.
```{r q3d_stars, include=TRUE}
stars(eupop, col.stars=km$cluster+1)
```
Optional:
Can you think of a better way of showing the clusters?
```{r q3b_opt1, include=TRUE}
country<-rownames(as.matrix(km$cluster))
cluster<-km$cluster
df<-data.frame(country,cluster,eupop)
head(df)
ggplot(data=df, aes(x=cluster, fill=country)) +
geom_bar()
```
Can you think of a way to present the data and the clustering results of both methods on the same graphical display?
```{r q3b_opt2, include=TRUE}
dat<-gather(df, key=age_grp, value=pct_pop, p014, p1544, p4564, p65.,
factor_key=T)
ggplot(dat, aes(x=country, y=pct_pop,
fill=age_grp)) +
geom_bar(stat="identity") +
xlab("Country")+ylab("Population %") +
scale_fill_discrete(name = "Age Group",
labels=c("0-14", "15-44", "45-64", "65+")) +
facet_wrap(~cluster, scales="free") +
ggtitle("Population Percentages by Country & Cluster Number") +
coord_flip()
```
**This does the required job for the results of the kmeans method. The results of the hclust method could be combined with them, having manipulated (stacked) them in a similar way - plus adding 3 to their cluster numbers. The titles of the facet panels would then also need to be manipulated (using facet_wrap's labeller parameter) to display suitable text - e.g 'Cluster 1 (kmeans)' for the first, 'Cluster 1 (hclust)' for the fourth, etc. nrow and column parameter settings could be used to display both sets of facet panels on separate rows, if required.**
## Question 4
Music data from class.
```{r q4_data, include=TRUE}
music<-read.csv("music.csv")
str(music)
```
a) Run the k-means algorithm over the range k = 1,....,15 clusters and record the total within cluster sum of squares (TWSS). Let nstart = 25.
```{r q4a_kmeans, include=TRUE}
music.feat<-music[, 4:8]
music.feat<-scale(music.feat)
glimpse(music.feat)
twss<-rep(0, 15)
kval<-c(1:15)
for(k in c(1:15)){
km<-kmeans(music.feat, k, nstart=25)
kval[k]<-k
twss[k]<-km$tot.withinss
}
df<-data.frame(kval, twss)
head(df)
```
Plot k versus TWSS....
```{r q4a_plot, include=TRUE}
plot(x=df$kval, y=df$twss, xlab="k", ylab="TWSS")
```
**Please note that I've chosen to plot TWSS versus k (instead of k versus TWSS), as TWSS is the response variable.**
....and choose the best fitting number of clusters.
**From the plot above, it looks like a k value of 6 would be a reasonable choice - on the basis that at that point, just over 1/3 of the way through the k-value range achieved just over a 2/3 reduction (305->94) in the TWSS value.**
What do you observe?
**As expected the value of TWSS reduces (non-linearly - almost quadratically, in this case) as that of k increases.**
**In this case, as the resultant curve is a relatively gradual, the position of an elbow isn't that clear-cut (unlike a similiar graph that we've seen in class).**
b) Make a table of artist vs cluster solution from k = 5.
```{r q4b_table, include=TRUE}
km<-kmeans(music.feat, 5, nstart=25)
str(km)
tab<-cbind(km$cluster,as.character(music$Artist))
head(tab)
table(tab[,2], tab[, 1], useNA="ifany")
```
## Question 5
Protein data. We want to study the similarities and differences in the protein composition of the diets of different countries.
**Read in the data and extract the feature variables and scale them.**
```{r q5_data, include=TRUE}
# Read in the Protein data
protein<-read.csv("protein.csv")
str(protein)
# Extract only the feature variables
prot.feat<-protein[,-1]
# Standardise to feature values to values in the range 0 to 10
scale_0_10 <- function(x){((x-min(x))/(max(x)-min(x)))*10}
prot.feat<-apply(prot.feat,2,scale_0_10)
```
Using any methods that you choose from this course or otherwise, write a brief summary.
**Let's use kmeans clustering to identify groups of similar diets and compare them to identify the difference between them.**
**The first step is to find the optimum number of clusters (k) to use.**
```{r q5_find_k, include=TRUE}
# Find the optimum value of k to use
# Create the data frame for plotting
kval<-rep(0, 20)
twss<-rep(0, 20)
df<-data.frame(kval, twss)
# Populate the data frame
for(k in c(1:20)){
km<-kmeans(prot.feat, k, nstart=100)
df$kval[k]<-k
df$twss[k]<-km$tot.withinss
}
head(df)
# Plot twss versus k
plot(df$kval, df$twss, xlab="k", ylab="TWSS")
```
**Looking at the plot above, 4 looks like a reasonable choice of k, where TWSS is reduced by 60% after only 25% of values of k assessed.**
**With only 25 observations in the Protein dataset, it won't make sense to have a large number of clusters anyway.**
**Now to create those 4 clusters....**
```{r q5_kmeans_4, include=TRUE}
# Create the kmeans cluster data
km<-kmeans(prot.feat, 4, nstart=100)
prot<-data.frame(km$cluster, protein$Country, prot.feat, stringsAsFactors=T)
colnames(prot)[1:2]<-c("Cluster", "Country")
sort(km$cluster)
```
<b>
In the table above, we can see that the countries fall into the following geographical/cultural (and political and economical) groupings:
1. Nordic (x 4, EU/EEA-Capitalist-Tier 1);
2. Mediterranean (x 4, EU/EEA-Capitalist-Tier 2);
3. Slavic (x 6, Soviet Bloc-Communist-Tier 3);
4. Other (x 11, Various).
- Please note that these groupings are not necessarily listed in order of cluster number order (as that can vary from one execution to the next).
As USSR, West Germany, East Germany and Yugoslavia are included in the 25 countries in the dataset, in all probability it dates from either before, or shortly after, the fall of the Soviet Union.
Note that the wealth tiering (from wealthiest to poorest) is a crude, anectotal indicator of my own creation.
Of course, at first glance, at least, this clustering seems to make sense because the diet of a particular country will depend on its geopgraphic location (e.g. more fish consumed if it has a coastline).
Geoography will also tend to influence the cultural, political and economic links between nations. There is also a link between political system (capitalism/democracy versus communism/dictatorship) and economic success.
This, in turn, will also influence the diet of a countries inhabitants, in that more of the expensive forms of protein (e.g. red meat) will tend to be consumed in the wealthier countries.
Let's see if increasing the number of clusters by 1 (k = 5) will split the 4th cluster above in some meaningful way.....
</b>
```{r q5_kmeans_5, include=TRUE}
# Create the kmeans cluster data
km<-kmeans(prot.feat, 5, nstart=100)
# Combine the cluster numner and country with the protein feature data
prot<-data.frame(km$cluster, protein$Country, prot.feat, stringsAsFactors=T)
colnames(prot)[1:2]<-c("Cluster", "Country")
# Sort the countries by cluster
sort(km$cluster)
```
<b>
In the table above, we can now see an improved grouping of the countries into the following clusters:
1. Nordic (x 4, EU/EEA-Capitalist-Tier 1);
2. Western (x 8, Eu/EEA-Capitalise-Tier 1);
3. Slavic (x 5, Soviet Bloc-Communist-Tier 3);
4. Balkan (x4, Soviet Bloc-Communist-Tier 4);
5. Mediterranean (x 4, EU/EEA-Capitalist-Tier 2).
Please note that:
- These groupings are not necessarily listed in order of cluster number order (as that can vary from one execution to the next).
- The cultural labels Slavic and Balkan are used in a very loose way, in that, for instance, Hungarians are not Slavs and Bulgaria is not in the Balkan Peninsula (although it does include the Balkan mountains).
Now, let's use the Protein data to compare the dietary profiles of those 5 clusters......
</b>
```{r q5_plots, include=TRUE, results='asis'}
# Stack the features
dat<-gather(prot, key=Type, value=Units, RedMeat, WhiteMeat, Eggs, Milk,
Fish, Cereals, Starch, Nuts, Fr.Veg, factor_key=T)
# Create a list for the plots
plist <- list()
# Generate, store and print the relevant plot for each cluster
for(i in c(1:5)){
# Throw a page to ensure thata maximum of 2 plots appear on each page
if(i != 1 & i %% 2 == 1){
cat("\n\n\\newpage\n")
}
dat_clust<-filter(dat, Cluster==i)
plist[[length(plist) + 1]]<-ggplot(dat_clust,
aes(x=Country ,y=Units,
fill=Type)) +
geom_bar(stat="identity") +
xlab("Country")+ylab("Protein Units") +
ggtitle(paste("Cluster", dat_clust$Cluster,
": Protein Consumption Profile by Country")) +
theme(axis.text.x = element_text(angle = 30, vjust = 1, hjust=1))
plot<-plist[[i]]
print(plot)
}
```
<b>
The insights gleaned from the protein consumption profile graphs above can be summarised as follows:
1. As is to be expected, the protein consumption profiles of countries in the same cluster are similar (with a small number of notable variations - see below).
2. EU/EEA countries in the Western and Mediterranean clusters - and Denmark in the Nordic cluster - have the highest overall protein consumptions - at 40-45 (standardised) units each on average.
3. The Balkan cluster of communist countries have the lowest overall protein consumptions - at less than 30 units each on average - where Albania (probably the poorest country of the 25) is a prominent low-side outlier with less than 20 units.
4. However, Albania doesn't appear to show any consumption of white meat, eggs, fish and starch, so this may be indicative of missing data and requires further examination.
5. In the same cluster, Yugoslavia doesn't appear to show any consumption of red meat, which also requires further investigation for the same reason.
6. In the Mediterranean cluster, Portugal shows no evidence of milk consumption, which also requires further investigation.
7. In the Slavic cluster, East Germany doesn't appear to register any consumption of nuts, which also needs to be investigated.
8. In the Nordic cluster, Finland appears to show no consumption of fruit and vegetables, which also warrants attention.
9. As was expected, on average, the countries in the 3 EU/EEA clusters get a higher proportion of their protein consumption from the higher-value food types, such as red and white meat and fish, than the less affluent communist countries in the other 2 clusters.
10. In the Western cluster, at over 50 units, France shows the highest consumption of protein of any of the 25 countries and, therefore, is a (slight) outlier at the high end.
11. In the same cluster, being neighbouring islands, and having a common language, a shared history and a similar culture, the protein consumption profile of Ireland and Britain (UK) is very similar with practically the same total unit consumption.
12. Countries in the Mediterranean and Nordic clusters exhibit higher than average fish consumption - due to their extensive coastlines, maritime traditions and large fishing fleets, presumably.
13. Countries in the Mediterranean cluster show a higher than average consumption of fruit and vegetables - due to their favourable climatic conditions, presumably.
14. Countries in the Nordic countries reveal a lower than average consumption of fruit and vegetables - due to their less favourable climatic conditions, presumably.
15. Countries in the Slavic (communist) cluster, on average, have an overall protein consumption that is only slightly below that of their counterparts in the Western cluster - with Poland having an overall protein consumption that reaches the Western average.
16. In the Nordic cluster, 3 of the 4 countries have an overall protein consumption that is below the average (with about 36 units each) for other EU/EEA countries. Denmark is the exception here (with about 43 units).
</b><file_sep>---
title: 'GY638 - Housing Data Project'
author: "<NAME> (18145426)"
date: "17 May 2019"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
# install.packages("sqldf") # Install needed packages
# install.packages("mlbench") # (One time only)
# install.packages("doParallel")
# install.packages("randomForest")
# install.packages("caret")
suppressPackageStartupMessages(library(tidyverse)) # For deplyr functions etc.
suppressPackageStartupMessages(library(sqldf)) # For sqldf() etc.
suppressPackageStartupMessages(library(sp)) # For SpatialDataFrame() etc.
suppressPackageStartupMessages(library(rgdal)) # For readOGR() etc.
suppressPackageStartupMessages(library(rgeos)) # For mapping etc.
suppressPackageStartupMessages(library(classInt)) # For ClassIntervals()
suppressPackageStartupMessages(library(RColorBrewer)) # For Palette() etc.
suppressPackageStartupMessages(library(GISTools)) # For auto.shading() etc.
suppressPackageStartupMessages(library(wrapr)) # For match_order() etc.
suppressPackageStartupMessages(library(gclus)) # For cpairs() etc.
suppressPackageStartupMessages(library(mlbench)) # For Random Forest functions etc.
suppressPackageStartupMessages(library(randomForest)) # For Random Forest functions etc
suppressPackageStartupMessages(library(caret)) # For RFE functions etc.
suppressPackageStartupMessages(library(parallel)) # For parallelising RFE
suppressPackageStartupMessages(library(doParallel)) # For parallelising RFE
```
# London House Price Estimation Application (Proof of Concept)
## Executive Summary
### Objectives
Outlier Analytics Ltd. (OAL) has been engaged by our client, Charlton Estates Ltd. (CEL), to conduct a proof of concept (PoC) exercise whose aim is to demonstrate the feasibility of eventually building an application capable of accurately estimating the selling/purchase price of a residential property in any of the London Boroughs.
<P style="page-break-before: always">
### Background
CEL is a large estate agency that specialises in the valuation and sale of residential property exclusively within the London Boroughs. It operates a branch network of 32 offices across this territory and employs a total workforce of 295 people. With the advent of Brexit, CEL has been losing some of its most experienced agents, who are almost exclusively EU nationals returning to their home countries, and believes that this trend is only going to increase as the exit date approaches. It is also aware that many of its competitors are experiencing the same difficulties. Therefore, CEL predicts that replacing them is going to be extremely difficult (if not impossible) to do at an affordable cost in London's post-Brexit labour marketplace.
This has led CEL to the conclusion that it will need to use technology to enable its less experienced local staff - both current and future - to effectively perform the type of type of work that its lost staff used to do. In particular, it needs to provide them with a tool that can accurately estimate the value (i.e. selling/purchase price) of any residential property within its target market given its key attributes - its location and floor area, in particular.
To this end, CEL has provided OAL with a Microsoft Excel spreadsheet that contains the details of 12,536 residential properties that it has sold during the past 12 months. This data includes the selling/purchase price, location and floor area information as well as other details which CEL believes could be helpful during the valuation process. Because this data is commercially sensitive, the provision of this data is subject to a CEL non-disclosure agreement which has been duly signed by OAL.
### Business Requirements
As CEL has yet to be convinced as to the ability of modern Machine Learning techniques to deliver the type of capability referred to above,it is only prepared to fund the development of a proof-of-concept prototype (PoC) at this stage for which it has provided OAL with the following requirements (both functional and non-functional):
1. Given the location and size of a residential property in any of the London Boroughs, the PoC should be able to estimate its selling/purchase price (expressed as a price range with a £50,000 interval) with a 70%+ accuracy rate.
Also note that, although the following are not requirements for this PoC exercise, they will be **for any future production application**:
a) The price range interval must be configurable.
b) The sizes of properties in the dataset provided by CEL are in square meters but it must be configurable to use square feet instead depending on its user's preference.
c) The approximate location of the properties in that dataset are in Easting and Northing coordinate format but it must be capable of using GPS coordinates.
d) It must also be configurable to make use of additional house price data as they become available.
2. The PoC should provide some level of confidence that such an estimate could be produced with sub-second response time.
3. The PoC code must be capable of running on a Windows 10 workstation or laptop.
- Note that any eventual application must also be capable of running on other platforms - especially on mobile devices, such as smart phones and tablets on the then current Microsoft, Apple and Google operating system versions. <br><br>
4. As CEL outsources the vast bulk of its IT services, it is open to the use of any coding language for developing the PoC.
- However, it does wish to be consulted during the choice of such technologies for any resultant production application. <br><br>
5. While CEL is open to the use of any Machine Learning technique which achieves the required level of accuracy (see above), it has a preference for one that is based on linear regression.
- Therefore, this exercise will include an evaluation of the suitability of using such a method. <br><br>
6. At this stage, CEL is more interested in seeing evidence of the level of accuracy that the PoC can achieve rather than in what the user interface of any eventual production application might look like.
- Therefore, provision of a prototype user interface is outside the scope of this exercise. <br><br>
7. Because of the current challenging Brexit timelines, this PoC exercise must be completed no later than Friday, 17th May 2019.
8. Due to its limitiations in terms of timelines and budget, CEL authorises OAL to reuse code, where possible, and to maximise the use of automation during the development of the PoC (e.g. during training and testing of its resultant Machine Learning algoithm).
### Approach
OAL used the following approach to complete this PoC:
1. Select the coding language and Integrated Development Environment (IDE).
2. Load the dataset provided by CEL into the selected IDE.
3. Analyse the dataset provided by CEL under the following headings:
a) Missing data;
b) Anomalous data;
c) Presence of outliers;
d) Presence of collinearity. <br><br>
4. Address any limitations in the dataset identified during the previous step.
5. Assess the suitability of using a linear regression-based Machine Learning method.
6. Choose an alternative Machine Learning method (if found necessary during the previous step).
7. Select the fields (variables) that would optimise the predictive power of the chosen ML method (using a suitable automated stepwise selection approach with 5-fold cross validation).
8. Split the dataset into training and test datasets (using an 80:20 random split).
9. Train the selected Machine Learning algorithm using the data for the selected variables in the training dataset (also with 5-fold cross validation automation).
10. Test the selected Machine Learning algorithm using the data for the selected variables in the test dataset.
11. Document the test results (in terms of both performance and accuracy).
### Findings
The following points summarise the results of this PoC exercise:
1. R was selected as the coding language and RStudio as Integrated Development Environment (IDE).
2. The dataset provided by CEL was successfully loaded into the selected IDE.
3. During the data analysis phase:
a) Some of the property-related attributes were provided in the form of sets of two or more dummy variables which were consolidated into a series of single categorical variables with CEL's agreement.
b) 10 records pertained to locations outside of the London Boroughs (spatial outliers) and were deleted from the dataset with CEL's agreement.
c) The level of quality of the socio-economic data in the dataset was found to be very poor/suspect (both in terms of its consistency at the level of the dataset's areal units and due to presence of invalid values and the prevalence of zero values which was adjudged to be indicative of missing data). Therefore, that data was deleted from the dataset with CEL's agreement.
d) Although the presence of outlier data was detected in the remaining data, it was considered not to be appropriate to delete the (potentially many) impacted records. Instead, selecting an outlier-insensitive (robust) Machine Learning algorithm was crucial.
e) A significant level of multicollinearity (at the global level) was detected in the remaining data. This provided further impetus to select a Machine Learning method which would also be insensitive to it.
f) An additional variable (field/column) was added to the loaded dataset which specified the price range interval into which the selling/purchase price of each property fell.
g) One other variable was added to the loaded dataset which identified the London Borough in which each property is located (based on the values of its Easting & Northing cordinates).
4. In the light of findings 3d and 3e above a Machine Learning method based on Ordinary Least Squares (OLS) muliple linear regression was deemed not to be viable.
5. Due to finding 4 above, the size of the CEL dataset and its future growth potential (see requirement 1d above), and CEL's sub-second response time requirement (2), the use of a Geographically Weighted Regression-based method was also ruled out.
6. Because of the previous 2 findings, a Machine Learning method based on the K Nearest Neighbours (KNN) algorithm was chosen for this PoC (in consultation with CEL).
7. An automated stepwise variable selection process (based on the Random Forest algorthm) discovered that 11 of the 12 predictor variables could make a contribution toward optimising the predictive power of the selected Machine Learning method.
8. The dataset provided by CEL was successfully split into training and test datasets (using an 80:20 random split).
9. The selected Machine Learning algorithm KNN) was successfully trained using the data for the selected variables in the training dataset (with 5-fold cross validation automation).
10. The automated testing of the selected Machine Learning algorithm (KNN) using the data for the selected variables in the test dataset was completed successfully.
11. The results of that test prove that:
a. An accuracy rate of around 70% is achievable.
b. Sub-second response time is attainable.
Please refer to the Conclusions section at the end of this document for further details and to the intervening sections for information on how the various stages of this project were executed and what their results were.
### Next Steps
Finally, we in OAL would like to thank CEL for the opportunity to develop this prototype and trust that it proves that the underlying technology has the potential to satisfy all of CEL's business requirments as set out that the beginning of this document. We look forward to discussing the next steps toward those ends with you in the near future.
### Acknowledgments
<NAME>, the senior OAL staff member who developed this PoC, wishes to acknowledge the following:
1. The help and support of the following OAL colleagues in terms of peer reviewing the overall approach and much of its code and for supplying some of the code needed for generating maps of the London Boroughs:
- <NAME>;
- <NAME>.
2. The reuse of some techniques and code from a similar type of engagement undertaken by OAL on behalf of another client, Brunson Electoral Research (BER), which was permitted under the terms of the contract under which that engagement was performed.
3. CEL's techical department provided R code for combining a set of dummy variables into a single factor and for producing a scatter plot that illustrates the link between purchase price and floor area.
<P style="page-break-before: always">
## Proof of Concept Details
The following subsections of this document show how each of the stages of this PoC (as outlined in the Approach section above) were executed and what their results were.
### Data Loading & Wrangling
CEL's dataset was loaded and its structure reviewed as follows:
```{r load, include=TRUE}
data1<-read.csv("DataScienceProj.csv")
str(data1)
```
We can see from the structure of the data above that there are several groupings of dummy variables (starting with BldIntWr and ending with NewPropD) that we can consolidate to reduce the dataset's dimensionality - for the data analysis phase of this engagement at least.
**Note that we will need to reinstate those dummy variables if the use of a linear regression-based Machine Learning method proves to be suitable.**
This is because that type of ML method can only handle categorical variables if they are binary variables (aka dichotomous variables). That is, they can only take one of two possible values (e.g. Male or Female; On or Off, Up or Down; 0 or 1).**
#### Dummy Variables Replacement
The following code replaces each of the 4 non-binary sets of dummy variables with a single (factor) variable.
```{r dummies, include=TRUE}
Dummy2Factor <- function(mat,lev1="Level1") {
mat <- as.matrix(mat)
factor((mat %*% (1:ncol(mat))) + 1,
labels = c(lev1, colnames(mat)))
}
Bld <- Dummy2Factor(data1[,5:9],"PreWW1") # Build (age)
Typ <- Dummy2Factor(data1[,10:12],"Others") # Type
Gar <- Dummy2Factor(data1[,13:14],"HardStnd") # Garage(s)?
Bed <- Dummy2Factor(data1[,18:21],"BedOne") # Bedrooms
data <- data.frame(data1[,c(1:4,15:17,22,23:31)],Bld,Typ,Gar,Bed)
# Check that the expected results have been achieved
str(data)
```
The results above show that the relevant dummy variables have been replaced successfully.
#### Price Range Variable Addition
In accordance with requirement 1, the following code assigns a (categorical) price range value to each observation (property) based on its purchase price.
```{r range, include=TRUE}
# This function provides the price range bracket for a give price
priceR<-function(x,k=50){ # Set the default interval (k) at £50k
if(k==0){ # Handle a zero price
r<-"NA"
} else{ # For non-zero price
y<-k*1000 # Interval assumed in multiples of 1000
r1<-((x%/%y)*y%/%1000) # Lower range value
r2<-r1+(y/1000) # Upper range value
r<-paste(r1,"-",r2,"k",sep="") # Construct the range description
}
return(r)
}
data$PriceR<-factor(priceR(data$Purprice)) # Add the price range variable as a factor
str(data) # Verify price range variable added
head(paste(data$X,": ",data$Purprice," (", # Verify range assigned correctly
data$PriceR,")",sep=""))
```
As shown above, the new price range variable (PriceR) has been added to the dataset correctly.
#### London Borough Identifier Addition
The following code adds the London Borough identifier to each observation based on its Easting-Northing coordinate values.
```{r boro, include=TRUE}
# Create spatial data frame using the Northing and Easting variables
lh<-SpatialPointsDataFrame(cbind(data[,2:3]),data)
# Import the LondonBoroughs shape file data
lb<-readOGR(dsn=".", "LondonBoroughs", stringsAsFactors=F)
class(lb)
str(lb@data)
Bname<-gsub(" London Boro","",lb$NAME) # Store the borough names
xy <- coordinates(lb) # Store the borough coordinates
proj4string(lh) <- CRS(proj4string(lb)) # Copy CRS
lhlb <- over(lh,lb) # spatial join: points first, then polygons
dim(lhlb)
head(lhlb) # data frame has lb attributes in lh order
str(lhlb)
# Append the London Borough Identifier to our original data frame
data$Boro<-gsub(" London Boro", "", x=lhlb$NAME) # Strip spurious naming text
data$Boro<-factor(data$Boro) # Convert to a factor
str(data) # Verify borough id appended
head(data$Boro) # Verify text stripped
```
Here is a map that provides an overview of CEL's territory, the London Boroughs, and the distribution of its sales across a 10-interval price range:
```{r boro_map, include=TRUE}
# Set the number of intervals
nClass = 10
# Choose the palette type, interval type (quantile) and use them to create the colour palette
Palette <- rev(brewer.pal(nClass,"Spectral"))
Classes <- classIntervals(data$Purprice,nClass,"quantile")
Colours <- findColours(Classes,Palette)
# Plot the sales locations and add the borough bounderies and legend
plot(data$Easting,data$Northing,pch=16,cex=0.25,col=Colours,asp=1)
plot(lb,add=TRUE)
legend("bottomright",
legend=names(attr(Colours,"table")),
fill=attr(Colours,"palette"),
cex=0.75,bty="n")
```
There appears to be a higher concentration of the less expensive (blue/green) properties in the eastern half of the city relative to the western half. The opposite is the case for the more expensive (red/orange) properties.
We will now locate (in terms of row numbers) any instances where the spatial join (overlay) failed (because the relevant Easting-Northing coordinates do not fall within a London Borough, presumably).
```{r boro_na, include=TRUE}
which(is.na(lhlb$NAME)==T)
```
The above results shows us that 10 such anomalies exist.
With CEL's agreement, we have elected to delete them from our dataset because they do not fall within its target geography - i.e. as defined by the London Borough boundaries.
```{r boro_del, include=TRUE}
# Delete rows with no Boro value
paste("Rows Before = ",
nrow(data),sep="") # Number of rows in dataset
paste("For Deletion = ",
nrow(filter(data, is.na(Boro))),sep="") # Number of rows with no Boro value
data<-filter(data, !is.na(Boro)) # Delete rows with no Boro value
paste("Rows After = ",
nrow(data),sep="") # Number of rows in dataset
```
#### Factor to Numeric Variable Conversion
To allow for the possibility of using an alternative to linear regression for house price prediction, we can increase the pool of potential predictors by converting our new categorical variables to (pseudo) continuous ones using their level numbers instead of their values.
We can do so because nearly all of them are ordered (ordinal) variables (i.e. their level values reflect some form of magnitude) or they are boolean (e.g. Ten, Cen, New). For instance, the age of the property is quantified by the levels of the Bld variable and, number of bedrooms is quantified by the levels of the Bed variable and even its price range is quantifed by the levels of the PriceR variable. However, as well as applying this type of conversion to the PriceR and Boro variables we will also retain them in factor format to preserve their level descriptions for possible use later.
```{r fact2lev, include=TRUE, warning=FALSE}
# Store the level values of the following factors:
PriceL<-levels(data$PriceR)
BoroL<-levels(data$Boro)
# Convert factors to integer variables
data$Bld<-as.integer(data$Bld)
data$Typ<-as.integer(data$Typ)
data$Gar<-as.integer(data$Gar)
data$Bed<-as.integer(data$Bed)
data$BoroNum<-as.integer(data$Boro)
data$Boro<-BoroL[data$Boro] # Add the Boro level information variable
data$PriceRNum<-as.integer(data$PriceR)
data$PriceRTxt<-PriceL[data$PriceRNum] # Add the Price Range level info variable
str(data) # Check the results
```
The results above show that the required variable conversions and additions have been completed successfully.
Note that by doing these conversions now, we can also include them in our outlier and correlation analysis studies later.
### Range of Values Review
The following subsections decribe how each of the variables in the original dataset provided by CEL were assessed for basic data quality in terms of their value ranges.
#### Unique Identifier
The uniqueness of the values of variable X, which seems to be the dataset's unique identifier, was checked as follows:
```{r dq_id, include=TRUE}
paste("X values are unique? =", # Check that this is the dataset's unique id
length(unique(data$X))==length(data$X))
```
The result of the code above indicates that the value of the X variable can be used to uniquely identify each observation in the dataset.
#### Northing and Easting
The spatial join that we have done previously implicitly ensures the validity of the easting-northing coordinate value pairs vis-a-vis their location within one of the London boroughs.
We will now take a look at the level of resolution of the Easting and Northing variables by looking at the level of uniqueness (in terms of coordinates) that they achieve across the dataset.
```{r dq_east_north_unique, include=TRUE}
# Calculate the percentage uniqueness
coords_uni<-length(unique(paste(data$Easting,",",data$Northing,sep="")))
coords_tot<-length(paste(data$Easting,",",data$Northing,sep=""))
paste("Unique Coordinates Percentage: ", round(coords_uni/coords_tot*100,2),
"% (", coords_uni, " of ", coords_tot, ")", sep="")
# Check if this has been caused by deliberate location obfuscation (by settiing the 2 rightmost digits of the Easting & Northing variables to zeros, apparently)
sum(data$Easting %% 100==0)
sum(data$Northing %% 100==0)
```
As can be seen from the calculations above, only about 75% of the properties have unique Easting-Northing coordinate pairs. As it appears that all Easting and Northing values are exactly divisible by 100 (for location obfuscation purposes, presumably), we cannot treat this lack of uniqueness as a potential data quality issue.
#### Purchase Price
The following code checks that the values of this variable fall within a reasonable range. For instance, observations with very low values (e.g. zero or close to it) would require further investigation.
```{r qa_price, include=TRUE}
summary(data$Purprice) # Check the minimum and maximum values versus their median
```
The above results show that, while no price is very close to zero the fact that the minimum is as low as £8,500 and the maximum is at £850,000, when compared with a median value of £70,000, indicates that there is a high degree of variability in this variable which will need to be investigated further during outlier analysis.
Here is a choropleth map of the London Boroughs showing the spatial distribution of average purchase price:
```{r qa_price_map, include=TRUE}
# Get the average purchase price by borough
SQL_avgp<-sqldf("select Boro, AVG(Purprice) as avgp
from data
group by boro;")
# Set up the map shading for 5 cuts
p<-match_order(SQL_avgp$Boro, Bname)
shades<-auto.shading(SQL_avgp[p,,drop=FALSE]$avgp,
cutter=quantileCuts,n=5,cols=brewer.pal(5, "Reds"))
# Render the choropleth map
choropleth(lb, SQL_avgp[p,, drop=FALSE]$avgp,
shading=shades)
# Add the borough names
text(xy[,1],xy[,2],Bname,col="black",cex=0.25)
# Add the legend for 5 cuts
choro.legend(558000, 175000,shades,title='Avg Price',cex=.6, bty="n",
fmt="%0.0f")
# Add a border
box()
```
This map clearly shows how the most expensive properties spread out north and south from the city centre as well as the Bromley borough in the southeast.
#### Floor Area
As per the purchase price, we need to take a high-level look at the range of values for this variable.
```{r qa_floor, include=TRUE}
summary(data$FlorArea) # Check the minimum and maximum values versus their median
```
The metadata for this dataset informs us that this variable is specified in units of square meters which means that above results tell us that it ranges from about $23m^2$ (c. 250 square feet) to $278m^2$ (c. 3,000 square feet) with a median value of $91m^2$ (c. 1,000 square feet). While the median value appears to be reasonable enough, the relatively low values at the lower and upper ends of the range demand further scrutiny during outlier analysis.
The following plot shows how, in general, purchase price rises in line with floor area:
```{r qa_floor_plot, include=TRUE}
plot(data[,c("FlorArea","Purprice")],pch=16,cex=0.5)
lines(lowess(data[,c("FlorArea","Purprice")]),col="red")
```
Here is a choropleth map of the London Boroughs showing the spatial distribution of average purchase price per square meter:
```{r qa_floor_map, include=TRUE}
# Get the average purchase price by borough
SQL_avgpm2<-sqldf("select Boro, AVG(Purprice/FlorArea) as avgpm2
from data
group by boro;")
# Set up the map shading for 5 cuts
p<-match_order(SQL_avgpm2$Boro, Bname)
shades<-auto.shading(SQL_avgpm2[p,,drop=FALSE]$avgpm2,
cutter=quantileCuts,n=5,cols=brewer.pal(5, "Reds"))
# Render the choropleth map
choropleth(lb, SQL_avgpm2[p,, drop=FALSE]$avgpm2,
shading=shades)
# Add the borough names
text(xy[,1],xy[,2],Bname,col="black",cex=0.25)
# Add the legend for 5 cuts
choro.legend(558000, 175000,shades,title='Avg Price / m2',cex=.6, bty="n",
fmt="%0.0f")
# Add a border
box()
```
This map shows a slightly different picture of the location of the most expensive properties per square meter with a clear east-west divide.
#### Dummy Variables
With the removal of the most of groupings of dummy variables, data analysis on them is no longer required or possible.
#### Socio-Economic Indicator Variables
The metadata for this dataset shows that there are number of variables that provide various socio-economic indicators which can be used to assess the level of deprivation (or otherwise) that prevails at the location of each property and which, in turn, could influence the house prices in that locality. The variables in question are (mostly) expressed as proportions/percentanges of the local population, the validity of whose values are checked in the following subsections.
##### Consistency Analysis
We will firstly take a look at these variables to ensure that they take the same values at the same location (at coordinate level). Even though, as we have seen earlier, those coordinates have been modified to obfuscate actual location, properties with the same obfuscated coordinates should be in close proximity to each other in actuality. Therefore, we would expect to see those properties (or a sizeable proportion of them, at least) to have the same values for all of the socio-economic variables.
For starters, let's check that there are properties with the same (obfuscated) coordinate pairs:
```{r qa_socio_con_1, include=TRUE}
sqldf("select easting, northing, count(*) as count
from data
group by easting, northing
having count(*) > 1
order by 3 desc
limit 10;")
```
As it happens, the results above can show that there are 2,186 easting-northing coordinate pairs at which more than one property is located. The results of that query have been limited to show the top 10 in the table above. It tells us, for instance, that there are 17 properties with the easting-northing coordinate values (520600, 188700).
Now let's use that query to look at the values of the socio-economic variables for a sample of 20 properties which have those same (sample) coordinate value pairs.
```{r qa_socio_con_2, include=TRUE}
sqldf("select d.easting, d.northing, d.nocarhh, d.carspp, d.profpct, d.unskpct,
d.retipct, d.saleunem, d.unemploy, d.popndnsy
from data d
inner join (
select easting, northing, count(*) as count
from data
group by easting, northing
having count(*) > 1
order by 1, 2
limit 10
) X on X.easting = d.easting and X.northing = d.northing
order by 1, 2
limit 20;")
```
We can see from even a 20-instance subset of the results of the query above that properties in the same locality (i.e. with the same (obfuscated) coordinates) have wildly differing values for their socio-economic variables.
As an aside, we can also see that individual properties have the same value (down to 4 decimal places) for more than one variable. For instance, one of the properties at (504400, 191100) has the value 7.6923 for both the percentage of professional and unskilled workers (how likely is that?), and one of the properties at (505000, 188200) has the value 55.5556 for the both the percentage of professional workers and retirees (even if we ignore the fact that their sum is greater than 100, how likely is that?).
These observations (sic) provide us with an initial impression that leads us to the conclusion that the socio-economic data subset is meaningless and, therefore, should not be used by this proof-of-concept exercise. However, we will refrain from removing them until our data quality review of them has been completed at least.
##### Value Range Analysis
Let's take a high-level look at the range of that these variables exhibit:
```{r qa_socio_values, include=TRUE}
apply(data[,10:17], 2, summary)
```
From the results above, we have identified the following potential issues that will required further investigation:
1. The minumum value of all of them is zero which may be indicative of missing values (for instance, a population density of zero does not make sense in a populous city like London).
2. The median value of the UnskPct variable is zero which may be flagging to us that there are a lot of missing values for it.
3. The maximum values of both the RetiPct and Unemploy variables indicate the presence of invalid (percentage) values.
#### Missing Values Analysis
```{r qa_socio_miss, include=TRUE}
miss<-function(x){sum(x==0)} # Function to count zero value
table(apply(data[,10:17],1,miss)) # Count zero values for all variables
table(apply(data[,10:11],1,miss)) # Count zero values for car-related vars
table(apply(data[,12:14],1,miss)) # Count zero values for job-related vars
sum(data[,13]==0) # Count zero values for Unsk$Pct var
table(apply(data[,15:16],1,miss)) # Count zero values for unemployment vars
sum(data[,17]==0) # Count zero values for PopnDnsy var
```
The main points arising from the results above are as follows:
1. Only 1784 of the remaining 12,526 observations have no zeros in any of these variables.
2. One observation has all zeros for these variables.
3. Most observations (12,487) have non-zero values for both private transport-related variables (i.e. NoCarHh and CarspP).
4. Only 1,803 of the observations have non-zero values for all of occupation-related variables (i.e. ProfPct, UnskPct and RetiPct),
5. As expected, the value of the UnskPct variable is zero for a large number (8,129) of the observations.
6. Most observations (12,350) have non-zero values for both unemployment-related variables (i.e. Saleunem and Unemploy, assuming that the former is unemployment-related).
7. 134 observations have zero values for the population density (PopnDnsy) variable.
Now let's take a look at the minimum values of these variables if we discount their zero values:
```{r qa_socio_min, include=TRUE}
min_nonzero<-function(x){ # Function to get min of non-zero values
min(subset(x,x!=0))
}
apply(data[10:17],2,min_nonzero)
```
The above results lead us to the following conclusion:
- They all look like reasonable percentage values except that the non-zero minimum value of the Unemploy variable appears to be implausibly low (but we will be taking a closer look at that variable later).
#### Invalid Data Analysis
As noted previously, the RetiPct and Unemploy appear to have invalid percentage values so the first step is to quantify the scale of the problem as follows:
```{r qa_socio_bad, include=TRUE}
# Display counts of the invalid values (we are treating 100 as potentially invalid)
sqldf("select count(*) as Bad_RetiPct from data where RetiPct>=100;")
sqldf("select count(*) as Bad_Unemploy from data where Unemploy>=100;")
# Display counts of sample instances of the invalid values
sqldf("select RetiPct, count(*) as count from data where RetiPct>=100 group by RetiPct order by 2 desc limit 10;")
sqldf("select Unemploy, count(*) as count from data where Unemploy>=100 group by Unemploy order by 2 desc limit 10;")
# Display the minimum values
summary(data[,c(14,16)])
```
We can see from the results above that around 10% of the values of both variables are invalid.
One possible explanation for those invalid values is that they might have been erroneously multiplied by 100. Dividing them all by 100 would give reasonable maximum values (while dividing by 10 would still give them very big but valid values). However, this would make their mimimum values implausibly low. Therefore, we have concluded that the values of this variable have been corrupted in some way and that they should be removed from the dataset.
However, as all of our analysis of the socio-economic data subset to this point has done nothing to assuage our initial concerns as to its overall level of validity (as expressed in the Consistency Analysis section above), we have decided to remove all of the variables from the dataset (with CEL's agreement) on the grounds that they are likely to have a deleterious effect on the results of any house price predictions that relied upon them.
```{r qa_socio_drop, include=TRUE}
data<-data[,-c(10:17)] # Drop the Soci-Economic variables
str(data)
```
The results above confirm the the socio-economic variables have been successfully removed from the dataset.
### Outlier Analysis
Outlier analysis is not appropriate for the first 3 columns because the first one is just a unique identifier and the other two are coordinates which have already been implicitly checked for (spatial) outliers by the previous map plotting exercise.
Because we have not yet performed any variable (or model) selection, we will have to take a univariate approach to outlier detection (as opposed to a multivariate one).
As we now have numeric representations of all of the potential predictors, they are in scope for this exercise.
The objective of this exercise is not to definitively identify all genuine outliers based on the weight of evidence provided by a number of detection methods. It is rather to get a high-level impression (at the global level) of the preponderance (or otherwise) of outlier values in the univariate context.
To do this, we will write a function to count the outliers per variable using the same definition of an outlier (by <NAME>) that is used in box plots as follows:
```{r out_box, include=TRUE, fig.show="hide"}
# This function uses the same definition of an outlier (by <NAME>) that is used in box plots
out.count<-function(x){
min<-summary(x)[2]*1.5 # 1.5 times the 1st quantile
max<-summary(x)[5]*1.5 # 1.5 times the 3rd quantile
return(sum(x<min | x>max)) # Return the count
}
apply(data[,4:13],2,out.count)
```
While the outlier counts for the erstwhile dummy variables (especially the binary ones) may not have much significance, there is a clear indication of the presence of outliers in what is effectively the dataset's response variable (Purprice) and in what turns out to be its main predictor variable (FlorArea).
Of course, the existence of outliers is a fact of life in all areas of human endeavour and buying and selling property is no exception. For instance, it is not unheard of for the buyer of a property to get a bargain (despite the vendor's or agent's best efforts). Similarly, it is not uncommon for a vendor to achieve an exceptionlly high price for his property (e.g. in the event of a 'bidding war'). As this is a phenomenon of the marketplace, we cannot simply choose to delete observations containing outliers and, therefore, we need to use a Machine Learning method that is insensitive to their presence (i.e. a robust method).
## Correlation Analysis
The objective of this exercise is to get an overview of the presence (or otherwise) and the strength of collinearity in our dataset *at the global level only*.
```{r coll_glo, include=TRUE}
data.cor<-cor(data[,c(2:3,5:13,16)])
data.cor %>%
dmat.color()->cols
cpairs(data[,c(2:3,5:13,16)],panel.colors=cols,pch=".",gap=.5)
```
The cpairs variant of the standard scatter plot matrix (pair) provides a kind of heat map of the level of correlation exists between all variable pairings in the data set. It does this by cutting the correlation values of the variable pairings into 3 equal intervals (breaks): red for noteworthy positive correlation, cream for noteworthy negative correlation and blue for weak or no correlation.
As can be seen from its output above, there is evidence of quite a bit of multicollinearity in the dataset under review, which also applies to its spatial (Easting-Northing coordinate) variables.
The following code will display the value intervals for the cream, blue and red colour codes above:
```{r coll_cut, include=TRUE}
cormat<-cor(data[,c(2:3,5:13,16)]) # Create the correlation matrix
n<-nrow(cormat) # Get number of rows
for(i in c(1:n)){ # 'Blank' the redundant cells
for(j in c(i:n)){
cormat[i,j]<-NA
}
}
cut<-cut_number(cormat,3) # Cut cormat into 3 ranges
levels(cut) # Display the intervals/breaks
```
The intervals above indicate that, where strong correlation exists, it is positive (with a Pearson r value of up to 0.803).
We will now take a closer look at the noteworthy correlations (both positive and negative) by producing a correlation matrix with a view to quantifying it in descending order of importance (as measured by their Pearson r values).
```{r coll_cor, include=TRUE}
cormat<-cor(data[,c(2:3,5:13,16)]) # Create the correlation matrix
n<-nrow(cormat) # Get number of rows
for(i in c(1:n)){ # 'Blank' the redundant cells
for(j in c(i:n)){
cormat[i,j]<-NA
}
}
cut<-cut_number(cormat,3) # Cut cormat into 3 ranges
corind<-which(as.numeric(cut) %in% c(1,3)) # Find cells with highest cor value
corrow<-corind %% n # Convert cell index to row no.
corcol<-corind %/% n + 1 # Convert cell index to col. no.
fix<-which(corrow==0) # corrow/corcol elements to fix
corrow[fix]<-n # Fix corrow
corcol[fix]<-corcol[fix]-1 # Fix corcol
rowname<-attr(cormat,"dimnames")[[1]][corrow] # Convert row number to name
colname<-attr(cormat,"dimnames")[[2]][corcol] # Convert column number to name
val<-cormat[corind] # Get r value
cordf<-data.frame(rowname,colname,val) # Create correlation data frame
head(arrange(cordf,desc(abs(val))),10) # Display correlation data frame
# (largest absolute r values first)
```
The table above shows (for the top ten pairings only) that there is a significant amount of strong multicollinearity involving what would appear be important potential predictors (e.g. floor area, number of bedrooms, property type and type of tenure).
### Machine Learning Algorithm Selection
The results of the study documented in the Outlier Analysis and Collinearity Analysis sections above lead us to seek a Machine Learning method other than one based on Linear Regression (which are sensitive to both types of data).
Therefore, we will now proceed to use K Nearest Neighbours (KNN) because it is more robust on both fronts. However, there are 2 key problems to solve for this method to be successful:
1. Selection of the correct predictors.
2. Choosing the optimum number of nearest neighbours (k) to use.
Fortunately, the caret package in R provides us with the following functionality to solve both of those problems:
1. Recursive Feature Selection (RFE) which also comes with inbuilt cross validation for problem 1.
2. A model training function (called train) which also comes with inbuilt cross validation for problem 2.
That functionality will be implemented in the following sections of document.
Of course one of the other advantages of using KNN in place of linear regression is that it can be used for classification as well as regression. This means that we can use it to directly predict a price range instead of predicting an exact price and then deriving its price range interval. A potential disadvantage of KNN is that how it arrived at its predictions is not interpretable - but, as this is not a requirement for this project, that does not pose a problem for us.
### Training-Test Set Split
The following code splits (based on a 80:20 ratio) the complete dataset into a training set and a test set.
```{r split, include=TRUE}
set.seed(123) # Set the seed value for repeatability
s<-sample(seq(to=nrow(data)), nrow(data)*0.8) # Get a random sample of 80% of obs.
train<-droplevels(data[s,]) # Create the training set using sample
test<-droplevels(data[-s,]) # Create the test set from the rest
train$PriceR<-factor(priceR(train$Purprice)) # Regenerate the Price Range factors
test$PriceR<-factor(priceR(test$Purprice)) # after the split
dim(train) # Verify the training set size
dim(test) # Verify the test set size
```
The row counts of the training and test sets above indicate that the split has been performed as expected.
### Predictor Selection using Recursive Feature Elimination (with Random Forest)
Even though we are not now going to use linear regression for modelling (prediction) purposes, before we proceed with using RFE, let's fit a linear regression model for all predictors and look at the p-values for the predictors in the resultant fit which it considers to be the most significant variables statistically.
```{r select_lm, include=TRUE}
# Fit a model with all (12) predictors
f.lm <- lm(PriceRNum ~ .,data = data[,c(2:3,5:13,16:17)])
summary(f.lm)
```
The results above indicate that almost all of the predictors have some degree of significant linear relationship with selling/purchase price (range). Surprisingly, of those that don't, two of them are location-related - i.e. the Northing coordinate and the Boro (number).
The following code now sets up RFE to perform its work across a number of cores in parallel (as it is very heavy on resources) and configures it to use Random Forest with 5-fold cross validation for all potential predictors in the training set.
**Note that RFE inexplicably fails when the response variable is a factor, so we had to use its numeric equivalent (PriceRNum) instead as a work-around.**
```{r rfe_select, include=TRUE}
# This function builds a formula (f) involving the named predictors (x) and the specified response variable name (y)
form<-function(x,y){ # Initialise the formula using the response variable name
f<-paste(y,"~",x[1],sep="") # and that of the name of the first predictor
for(i in 2:length(x)){ # Use a loop to append the remaining predictor names
f<-paste(f,"+",x[i],sep="")
}
return(as.formula(f)) # Create (classify) the formula and return it
}
#####################
subsetSizes <- c(1:12) # Specify the number of predictors
# Set the seed value to predictably set the sample seed values for the cluster helpers
set.seed(123)
# Set a separate seed value for each of the 5 folds in a list
seeds <- vector(mode = "list", length = 6)
for(i in 1:5) seeds[[i]] <- sample.int(1000, length(subsetSizes) + 1)
seeds[[6]] <- sample.int(1000, 1)
# Set the debug file name (so that we can monitor the progress of this long-running process)
sys_date<-Sys.Date()
outfile<-paste("debug-rfe-",as.character(sys_date),".txt",sep="")
# Create (register) a parallel processing cluster to use all available cores except 1 (for the operating system)
cl <- makeCluster(detectCores() - 1, type='PSOCK', outfile=outfile)
registerDoParallel(cl)
# Define the control using a random forest selection function with 5-fold CV
control <- rfeControl(functions=rfFuncs, # Random Forest
method="cv", # with cross validation
seeds=seeds, # using the seed values generated above
verbose=TRUE, # with logging to the debug file set on
number=5) # for this number of folds
#### Note that we have to use the numeric form (PriceRNum) of the predictor instead of its factor version (PriceR) which would have been referable (even after trying to build and rebuild the factor in different ways). This is because we get the following error message when we try to use PriceR in the formula: "Can't have empty classes in y". RFE or RF appears to be indicating that there are some levels with no value. But the results of the following command contradicts that:
table(train$PriceR)
# Create the formula for all predictor variables
f<-form(names(train[,c(2:3,5:13,16)]), "PriceRNum")
# Invoke RFE (as configured by its control variable above) to produce a model that selects what Random Forest considers to be the optimal set of predictors
rf_model <- rfe(form=f, data=train,
sizes=subsetSizes,rfeControl=control)
# Deregister the cluster
stopCluster(cl)
# Summarize the results
print(rf_model)
# List the chosen features
predictors(rf_model)
# Plot the results
plot(rf_model, type=c("g", "o"))
```
The results above show us that Random Forest is telling us that 11 of the 12 predictors can contribute to towards prediction accuracy based on their RMSE values. Therefore, we will only them when building (training) our KNN model in the following section of this document.
Coincidentally (or otherwise), NewPropD is the only predictor it didn't recommend and that was also the least significant variable (i.e. the one with the highest p-value) as per our earlier linear regression model fitting.
Interestingly, its graph also show that add the location-based predictors (Easting, Northing and Boro), which it ranks in positions 6, 7 and 8, make a relatively modest contribution to the predictive power of the model.
These results are broadly in agreement with those achieved by fitting a multiple linear regression model for all of our predictors.
Note that we also tried using just the first 7 predictors (not documented here) because the RMSE value for them is very close to the lowest one achieved overall but that resulted in a slightly worse success rate.
### Machine Learning Algorithm (KNN) Training
The following code uses the train function in the caret package to automate the testing of our KNN algorithm. It uses a configurable cross validation process to automate the selection of the number of nearest neighbours (k) to create the best predictive model for the specified set of predictor variables (the 11 predictors recommended by RFE/RF above).
```{r knn_train, include=TRUE}
# Create the formula for the KNN model using all of the predictors recommended by RFE (i.e. all of them except New). But this time we can use the factorised Price Range as the response variable without a problem.
f<-form(names(train[,c(2:3,5:7,9:13,16)]), "PriceR")
#
knn_fit<-train(f,data=train, #
trControl=trainControl(method="cv", # Configure cross validation
number=5, allowParallel = FALSE),
preProcess = c("center","scale"), # Standardise the predictor values
method="knn") # Use the KNN algorithm
# Display the details of the resultant model
knn_fit
# Visualise how the value of k was selected
plot(knn_fit)
# Test the model on the training set
pred_train<-predict(knn_fit)
# Calculate the success rate
rate_train<-round(sum(pred_train==train$PriceR)/length(train$PriceR),2)
# Display the success rate
paste("Training Accuracy:", rate_train)
```
The results above that our KNN model was created successfully for which the optimum value of k=9 was selected.
Although its success rate when used with the training set is not brilliant, it does satisfy the relevant requirement as set out at the beginning of this document.
Let's hope that this models predictive power is sufficient to achieve a similar rate on the test set.......
### Machine Learning Algorithm (KNN) Testing
We will now use the KNN model created during the model training phase above to perform prediction on the test set and calculate the success rate achieved using data that was previously 'unseen' by the model.
```{r knn_test, include=TRUE}
# Perform a prediction on the test set
pred_test <- predict(knn_fit, newdata = test)
# Calculate the success rate
rate_test<-round(sum(as.character(pred_test)==as.character(test$PriceR))/
length(test$PriceR),2)
# Display the accuracy rate
paste("Test Accuracy:", rate_test)
```
The results above indicate that our new selling/purchase price (range) prediction model achieved an accuracy rate of 69% on the test set.
### Conclusions
While the average of the success rates achieved by this model only barely achieves the 70% rate set out at the beginning of this document, OAL is very confident that, with more time, it can be tuned to attain even greater levels of accuracy and performance and to do so for even narrower price intervals.
This can be approached on a number of fronts including:
1. Reviewing the predictor selection.
2. Exploring the myriad of tuning parameters that both RFE/RF and KNN offer
- but which, unfortunately, we have been unable to do within the tight timescales that govern this project.
3. Trying Random Forest for prediction as well as variable selection.
On the plus side, the model produced predictions for the both the training and test sets (with c. 10,000 and 2,500 records, respectively) within a few seconds in total so satisfying CEL's sub-second response time requirement for individual predictions will not be a problem.
Furthermore, should this initiative proceed to the development phase, this R prototype will very likely be replaced by a production version that will most likely be developed in Python (subject to CEL's agreement). In that case, Python offers even better performance and configurability - e.g. Manhattan (City Block) distance calculation which might prove to be more effective than that Euclidian distance, the only option currently offered by the KNN inplementation in R's caret library.<file_sep>---
title: "ST464 - Assignment 3 - Solutions - Version 2"
author: "<NAME> (18145426)"
date: "29 March 2019"
output: html_document
---
```{r setup, include=TRUE}
getwd()
suppressPackageStartupMessages(library(tidyverse)) # Needed for deplyr funcs.
suppressPackageStartupMessages(library(MASS)) # Needed for lda, qda &
# stepAIC and Pima data
suppressPackageStartupMessages(library(ISLR)) # Needed for Auto data
suppressPackageStartupMessages(library(class)) # Needed for knn()
suppressPackageStartupMessages(library(leaps)) # Needed for regsubsets()
```
## Question 1
The Titanic dataset records for each person on the ship the passenger class, age (child or adult), and sex, and whether they survived or not.
In this assignment you will use logistic regression on a training set (ttrain) to develop a classification rule, and then this rule will be applied to the test set (ttest).
```{r q1_data, include=TRUE}
ttrain <- read.csv("ttrain.csv", header=T, row.names=1)
ttest <- read.csv("ttest.csv", header=T, row.names=1)
```
a) Use logistic regression to build a model relating Survived to Class Age and Sex for the training data ttrain.
```{r q1_a, include=TRUE}
str(ttrain)
f<-glm(Survived ~ Class + Age + Sex, data=ttrain, family="binomial")
summary(f)
```
b) From the fitted model, calculate a vector prob of survival probabilities and a vector pred of predicted classes, for the training data.
```{r q1_b1, include=TRUE}
prob<-predict(f, type="response") # Probabilities vector
head(prob)
pred<-factor(ifelse(prob < 0.5, "No", "Yes")) # Predicted classes vector
head(pred)
confmat<-table(ttrain$Survived, pred) # Construct the confusion matrix
confmat
```
What proportion of survivors are missclassified?
```{r q1_b2, include=TRUE}
paste(round(confmat["Yes","No"]/rowSums(confmat)["Yes"]*100, 2),"%",sep="")
```
What proportion of those who died are missclassified?
```{r q1_b3, include=TRUE}
paste(round(confmat["No","Yes"]/rowSums(confmat)["No"]*100, 2),"%",sep="")
```
What proportion of the predicted survivors actually survived?
```{r q1_b4, include=TRUE}
paste(round(confmat["Yes","Yes"]/colSums(confmat)["Yes"]*100, 2),"%",sep="")
```
What is the overall error rate for the training data?
```{r q1_b5, include=TRUE}
paste(round((confmat["No","Yes"]+confmat["Yes","No"])/sum(confmat)*100, 2),"%",sep="")
```
c) From the fitted model, calculate a vector prob of survival probabilities and a vector pred of predicted classes, for the test data.
```{r q1_c1, include=TRUE}
str(ttest)
prob<-predict(f, ttest, type="response") # Probabilities vector
head(prob)
pred<-factor(ifelse(prob < 0.5, "No", "Yes")) # Predicted classes vector
head(pred)
confmat<-table(ttest$Survived, pred) # Construct the confusion matrix
confmat
```
What proportion of survivors are misclassified?
```{r q1_c2, include=TRUE}
paste(round((confmat["Yes","No"]/rowSums(confmat)["Yes"])*100,2),"%",sep="")
```
What proportion of those who died are misclassified?
```{r q1_c3, include=TRUE}
paste(round((confmat["No","Yes"]/rowSums(confmat)["No"])*100,2),"%",sep="")
```
What proportion of the predicted survivors actually survived?
```{r q1_c4, include=TRUE}
paste(round(((confmat["Yes","Yes"])/colSums(confmat)["Yes"])*100,2),"%",sep="")
```
What is the overall error rate for the test data?
```{r q1_c5, include=TRUE}
paste(round(((confmat["No","Yes"]+confmat["Yes","No"])/sum(confmat))*100,2),"%",sep="")
```
\newpage
<P style="page-break-before: always">
# *** Not for Marking ***
## Question 2
Suppose we wish to predict whether a given stock will issue a dividend this year (yes or no) based on X, last year's percentage profit.
We examine a large number of companies and discover that the mean value of X for companies that issued a dividend was 10, while the mean for those that didn't was 0.
<b>
$$\mu_{Y=Yes}=10$$
$$\mu_{Y=No}=0$$
</b>
In addition, the variance of X for these two sets of companies was 36.
<b>
$$\sigma^2=36$$
$$\sigma=6$$
</b>
Finally, 80% of companies issued dividends.
<b>
$$P(Y=1)=0.8$$
$$P(Y=0)=0.2$$
</b>
Assuming that X follows a normal distribution, predict the probability that a company will issue a dividend this year given that its percentage profit was X = 4 last year.
<b>
$$P(Y=1|X=4)$$
</b>
```{r q2_1, include=TRUE}
# Let's simulate some data based on the information provided above
# Simulating data for 8000 companies (80%) for which a dividend is issued...
set.seed(123)
x<-round(rnorm(8000,mean=10,sd=6),2)
y<-rep(1,length(x))
data_yes<-data.frame(pct=x, div=y)
# Simulating data for 2000 companies (20%) for which a dividend is not issued...
x<-round(rnorm(2000,mean=0,sd=6),2)
y<-rep(0,length(x))
data_no<-data.frame(pct=x, div=y)
# Combining both of those simulated datasets.....
data<-rbind(data_yes, data_no)
str(data)
head(data)
# Fitting a model to the combined dataset.....
f<-glm(div ~ pct, data=data, family="binomial")
summary(f)
# Predicting if dividend will be issued where a company has a 4% profit margin
prob<-round(predict(f, data.frame(pct=4), type="response"), 2)
paste("Predicted Probability =",prob)
```
\newpage
<P style="page-break-before: always">
## Question 3
In the Auto data, create a new variable that contains the value 1 for cars with above the median mpg, and 0 for other cars. Name this variable mpg01. Split the data into a test and training sets of size containing 50% and 50% of observations each.
```{r q3_data, include=TRUE}
m <- median(Auto$mpg)
Auto$mpg01 <- factor(ifelse(Auto$mpg < m, 0, 1))
set.seed(1)
s <- sample(nrow(Auto), round(.5*nrow(Auto)))
Atrain <- Auto[s,]
Atest <- Auto[-s,]
str(Atrain)
str(Atest)
```
a) Plot the variables weight and acceleration using colour to show the two levels of mpg01 for the training set.
```{r q3_a, include=TRUE}
ggplot(data=Atrain, aes(x=weight, y=acceleration, colour=mpg01)) +
geom_point(stat="identity")
```
**This plot indicates that there is a (negative) linear relationship between weight and acceleration.**
b) Perform a linear discriminant analysis to predict mpg01, using variables weight and acceleration, on the training set.
```{r q3_b_lda, include=TRUE}
f<-lda(mpg01 ~ weight + acceleration, data=Atrain) # Fit the model
f
pred<-predict(f)$class # Get predicted classes
confmat<-table(Atrain$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall training error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2),"%",sep="")
```
Use a plot to show the discriminant boundaries.
```{r q3_b_plot, include=TRUE}
# Create a grid representing a range of values for both predictors
grid<-expand.grid(weight=seq(min(Atrain$weight), max(Atrain$weight), length=100),
acceleration=seq(min(Atrain$acceleration),
max(Atrain$acceleration),
length=100))
# Use the model to get class predictions for the grid (for 100x100 weight-acceleration value combinations) and append results as new column in grid df
grid$pred<-predict(f, grid)$class
str(grid) # Check the grid data frame
# Draw t1he required plot using the data in the grid data frame
ggplot(data=grid, aes(x=weight, y=acceleration, colour=pred)) +
geom_point(size=0.5)
```
What is the test error of the model obtained?
```{r q3_b_err, include=TRUE}
pred<-predict(f, Atest)$class # Get predicted classes for test
confmat<-table(Atest$mpg01, pred) # Construct the confusion matrix
confmat
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2),"%",sep="")
```
c) Repeat (b) using quadratic discriminant analysis.
```{r q3_c_qda, include=TRUE}
f<-qda(mpg01 ~ weight + acceleration, data=Atrain) # Fit the model
f
pred<-predict(f)$class # Get predicted classes
confmat<-table(Atrain$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall training error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2),"%",sep="")
```
Use a plot to show the discriminant boundaries.
```{r q3_c_plot, include=TRUE}
# Create a grid representing a range of values for both predictors
grid<-expand.grid(weight=seq(min(Atrain$weight), max(Atrain$weight), length=100),
acceleration=seq(min(Atrain$acceleration),
max(Atrain$acceleration),
length=100))
# Use the model to get class predictions for the grid (for 100x100 weight-acceleration value combinations) and append results as new column in grid df
grid$pred<-predict(f, grid)$class
str(grid) # Check the grid data frame
# Draw t1he required plot using the data in the grid data frame
ggplot(data=grid, aes(x=weight, y=acceleration, colour=pred)) +
geom_point(size=0.5)
```
What is the test error of the model obtained?
```{r q3_c_err, include=TRUE}
pred<-predict(f, Atest)$class # Get predicted classes for test
confmat<-table(Atest$mpg01, pred) # Construct the confusion matrix
confmat
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2),"%",sep="")
```
Which is better, LDA or QDA?
**In this case, QDA performed better than LDA because it achieved the lower error rate on the test set (and on the training set too).**
**Coincidentally, QDA achieved the same error rate on the test set as LDA achieved on the training set.**
d) Perform a linear discriminant analysis to predict mpg01, using variables displacement, horsepower, weight and acceleration on the training set.
```{r q3_d_lda, include=TRUE}
f<-lda(mpg01 ~ displacement + horsepower + weight + acceleration, data=Atrain)
f # The fitted model
pred<-predict(f)$class # Get the predicted classes
confmat<-table(Atrain$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall training error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2), "%", sep="")
```
What is the test error of the model obtained?
```{r q3_d_err, include=TRUE}
pred<-predict(f, Atest)$class # Get the predicted classes
confmat<-table(Atest$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall test error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2), "%", sep="")
```
e) Repeat (d) using quadratic discriminant analysis.
```{r q3_e_qda, include=TRUE}
f<-qda(mpg01 ~ displacement + horsepower + weight + acceleration, data=Atrain)
f # The fitted model
pred<-predict(f)$class # Get the predicted classes
confmat<-table(Atrain$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall training error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2), "%", sep="")
```
What is the test error of the model obtained?
```{r q3_e_err, include=TRUE}
pred<-predict(f, Atest)$class # Get the predicted classes
confmat<-table(Atest$mpg01, pred) # Construct the confusion matrix
confmat
# Calculate the overall test error rate
paste(round((confmat["0","1"]+confmat["1","0"])/sum(confmat)*100, 2), "%", sep="")
```
Which is better, LDA or QDA?
**In this case, LDA performed better than QDA because it achieved the lower error rate on the test set.**
**In fact, the test error rate by QDA in this instance is the same as the one it achieved in (d) which had fewer predictors (although the confusion matrix shows that the errors are distributed slightly differently).**
f) Perform KNN with response of mpg01, and the four predictors displacement, horsepower, weight and acceleration.
Remember to scale the predictors. Use k = 5 and k = 30.
```{r q3_f_knn, include=TRUE}
set.seed(123) # Setting seed value to ensure that knn gives consistent results
# Scale the predictors for both the training and test sets
xdata<-scale(Atrain[,3:6])
means<-attr(xdata,"scaled:center")
sds<-attr(xdata,"scaled:scale")
xdataTest<-scale(Atest[,3:6], center=means, scale=sds)
# Create function to perform KNN
my_knn<-function(train, test, resp, k){
pred<-knn(train, test, cl=resp, k=k)
confmat<-table(resp, pred)
return(confmat)
}
# Create a function to extract the various error rates from the specified confusion matrix
my_err<-function(confmat, pos_first=F){
err<-(confmat[1,2]+confmat[2,1])/sum(confmat) # Overall error rate
if(pos_first){ # 1st row is the positive one
tpr<-confmat[1,1]/sum(confmat[1,]) # True positive rate
fpr<-confmat[2,1]/sum(confmat[2,]) # False positive rate
fnr<-confmat[1,2]/sum(confmat[1,]) # False negative rate
tnr<-confmat[2,2]/sum(confmat[2,]) # True negative rate
} else{
tpr<-confmat[2,2]/sum(confmat[2,]) # True positive rate
fpr<-confmat[1,2]/sum(confmat[1,]) # False? positive rate
fnr<-confmat[2,1]/sum(confmat[2,]) # False negative rate
tnr<-confmat[1,1]/sum(confmat[1,]) # True negative rate
}
return(data.frame(ERR=err,FPR=fpr,TPR=tpr,FNR=fnr,TNR=tnr)) # Return error rates
}
# For k = 5
k<-5
# Perform KNN on the training set
confmat<-my_knn(xdata, xdata, Atrain$mpg01, k)
confmat
paste("k = ", k, ": ", "Training Error Rate = ",
round(my_err(confmat)["ERR"]*100,2),"%",sep="")
# Perform KNN on the test set
confmat<-my_knn(xdata, xdataTest, Atrain$mpg01, k)
confmat
paste("k = ", k, ": ", "Test Error Rate = ",
round(my_err(confmat)["ERR"]*100,2),"%",sep="")
# For k = 30
k<-30
# Perform KNN on the training set
confmat<-my_knn(xdata, xdata, Atrain$mpg01, k)
confmat
paste("k = ", k, ": ", "Training Error Rate = ",
round(my_err(confmat)["ERR"]*100,2),"%",sep="")
# Perform KNN on the test set
confmat<-my_knn(xdata, xdataTest, Atrain$mpg01, k)
confmat
paste("k = ", k, ": ", "Test Error Rate = ",
round(my_err(confmat)["ERR"]*100,2),"%",sep="")
```
Which value of k gives the best result on the test set?
**k=5 gives a better result for the test set because it achieved the lower overall error rate (and for the training set too).**
\newpage
<P style="page-break-before: always">
# *** Not for Marking ***
## Question 4
4. A classifier gives the following result. In the table below, Group gives the true class, and Prob gives the estimated probability of Group A (positive) using the classifier.
```{r q4_data, include=TRUE}
Group<-c(rep("A",6), rep("B",4))
Prob<-c(0.486,0.560,0.701,0.936,0.441,0.593,0.623,0.436,0.415,0.041)
Group_Other<-c(rep("B",6), rep("A",4))
data<-data.frame(Group, Prob, Group_Other)
data
```
(You can do this question in R or by hand)
a) What are the predicted classes? Use a threshold of 0.5.
```{r q4_a, include=TRUE}
pred<-data$Group # Assume the classifier is perfect
misses<-which(data$Prob < 0.5) # Identify the classifier misses
pred[misses]<-data$Group_Other[misses] # Select the other group
pred
```
b) What is the error rate?
```{r q4_b_err, include=TRUE}
confmat<-table(data$Group, pred) # Create the confusion matrix
confmat # Display the confusion matrix
paste("Error Rate = ",round(my_err(confmat,T)["ERR"]*100,2),"%",sep="")
```
What is the false positive rate?
```{r q4_b_fpr, include=TRUE}
paste("False Positive Rate = ",round(my_err(confmat,T)["FPR"]*100,2),"%",sep="")
```
The true positive rate?
```{r q4_b_tpr, include=TRUE}
paste("True Positive Rate = ",round(my_err(confmat, T)["TPR"]*100,2),"%",sep="")
```
c) Now let the threshold take values 0, .2, .4,.6,.8,1. For each threshold calculate the false positive rate, and the true positive rate. (If doing this in R use more thresholds.)
```{r q4_c, include=TRUE}
# Create a function to calculate all error rates for the specified threshold level
t_err<-function(data, t){
pred<-data$Group # Assume the classifier is perfect
misses<-which(data$Prob < t) # Identify the classifier misses
pred[misses]<-data$Group_Other[misses] # Select the other group
confmat<-table(data$Group, pred) # Create the confusion matrix
return(data.frame(Threshold=t, my_err(confmat, T)))
}
t<-seq(0, 1, 0.05) # Generate a sequence of threshold values
df<-t_err(data, t[1]) # Initialise the error rate details data frame
for(i in 2:length(t)){ # Loop for all threshold values
df<-rbind(df, # Retrieve and append the other error details
t_err(data, t[i]))
}
df # Display the error rate details
```
d) Plot the true positive rate versus the false positive rate. This is the ROC curve.
```{r q4_d, include=TRUE}
plot(df$FPR, df$TPR, col="black", type="l", ylim=c(0,1),
xlab="False positive rate", ylab="True positive rate")
abline(0,1,col="grey80")
```
e) (Optional, if doing in R) Another classifier just assigns class probabilities randomly, ie the estimated probabilities are:
```{r q4_e_data, include=TRUE}
Group<-c(rep("A",6), rep("B",4))
Prob<-c(0.206,0.177,0.687,0.384,0.770,0.498,0.718,0.992,0.380,0.777)
Group_Other<-c(rep("B",6), rep("A",4))
data_e<-data.frame(Group, Prob, Group_Other)
data_e
```
Plot the ROC curve for this classifier.
```{r q4_e, include=TRUE}
t<-seq(0, 1, 0.05) # Generate a sequence of threshold values
df<-t_err(data_e, t[1]) # Initialise the error rate details data frame
for(i in 2:length(t)){ # Loop for all other threshold values
df<-rbind(df, # Retrieve and append the other error details
t_err(data_e, t[i]))
}
df # Display the error rate details
plot(df$FPR, df$TPR, col="black", type="l", ylim=c(0,1),
xlab="False positive rate", ylab="True positive rate")
abline(0,1,col="grey80")
```
\newpage
<P style="page-break-before: always">
## Question 5
Dataset on diabetes in Pima Indian Women in library(MASS). For a description of the data see ?Pima.tr.
```{r q5_data, include=TRUE}
str(Pima.tr)
str(Pima.te)
```
Use any supervised classification technique to predict diabetes from the 7 available features.
Train your algorithms on Pima.tr
**Will use logistic regression to build the prediction model.**
**Using the stepwise logistic regression (step function) to recommend the 'optimal' predictor selection.....**
```{r q5_select, include=TRUE}
# Fit a model with all (7) predictors
f <- glm(type ~ ., family = binomial, data = Pima.tr)
summary(f)
# Perform stepwise model fitting (direction=backward by default)
steps<-step(f, trace=F)
# Summarise the predictors that are recommended to be dropped
steps$anova
# Doublechecking using the stepAIC function in the MASS library....
stepAICs<-stepAIC(f, trace=F)
# Summarise the predictors that are recommended to be dropped
stepAICs$anova
```
**Both the step and stepAIC functions recommend omission of the skin and bp predictors - which reduces the AIC value from 194.39 to 190.47 (because omitting other predictors failed to reduce the AIC value any further).**
**As it happens, those are also the two variables with the highest p-values in the summary(f) output above.**
```{r q5_train, include=TRUE}
# Create function to create the confusion matrix for the specified fit
my_confmat<-function(f, data, resp){
prob<-predict(f, data, type="response") # Get the predicted probs.
pred<-factor(ifelse(prob < 0.5, "No", "Yes")) # Translate probs. to preds.
confmat<-table(resp, pred) # Create the confusion matrix
return(confmat) # Return the confusion matrix
}
f<-glm(type ~ npreg + glu + bmi + ped + age, family=binomial, data=Pima.tr)
confmat<-my_confmat(f, Pima.tr, Pima.tr$type)
confmat
paste("Error Rate = ",round(my_err(confmat)["ERR"]*100,2),"%",sep="")
```
and present the overall error rate for the test data Pima.te.
```{r q5_test, include=TRUE}
confmat<-my_confmat(f, Pima.te, Pima.te$type)
confmat
paste("Error Rate = ",round(my_err(confmat)["ERR"]*100,2),"%",sep="")
```
## Question 6
Generate some fake data using the following code:
```{r q6_data, include=TRUE}
set.seed(1)
x <- rnorm(100)
y <- 1 + .2*x+3*x^2+.6*x^3 + rnorm(100)
d <- data.frame(x=x,y=y)
str(d)
```
a) Use best subset selection to choose the best model containing predictors X, $X^2$,. . .$X^{10}$.
```{r q6_a, include=TRUE}
for(i in 2:10){
d<-cbind(d, d$x^i)
colnames(d)[i+1]<-paste("x",i,sep="")
}
str(d)
allfits<-regsubsets(y ~ ., data=d)
allfits_s<-summary(allfits)
```
Which terms are included in the best 3 variable model?
```{r q6_a1, include=TRUE}
terms<-attr(which(summary(allfits)$which[3,]),"names")
terms[2:length(terms)]
```
b) Make a plot of $C_p$ versus number of predictors for the models in allfits.
```{r q6_b, include=TRUE}
cp<-allfits_s$cp # Extract the Cp values for all stepwise models
np<-rowSums(allfits_s$which)-1 # Extract the number of predictors for each too
# Draw the required plot
plot(np, cp, pch=16, xlab="Number of predictors")
lines(np, cp)
```
Which model has the lowest $C_p$?
```{r q6_b1, include=TRUE}
min_cp<-which(cp==min(cp))
min_cp
```
What are its predictors?
```{r q6_b2, include=TRUE}
names(which(allfits_s$which[min_cp,]))[-1]
```
c) Reconstruct allfits with option method = "forward".
```{r q6_c, include=TRUE}
allfits<-regsubsets(y ~ ., data=d, method="forward")
allfits_s<-summary(allfits)
cp<-allfits_s$cp # Extract the Cp values for all stepwise models
np<-rowSums(allfits_s$which)-1 # Extract the number of predictors for each too
```
Which model has the lowest $C_p$?
```{r q6_c1, include=TRUE}
min_cp<-which(allfits_s$cp==min(cp))
min_cp
```
What are its predictors?
```{r q6_c2, include=TRUE}
names(which(allfits_s$which[min_cp,]))[-1]
```
d) Reconstruct allfits with option method = "backward".
```{r q6_d, include=TRUE}
allfits<-regsubsets(y ~ ., data=d, method="backward")
allfits_s<-summary(allfits)
cp<-allfits_s$cp # Extract the Cp values for all stepwise models
np<-rowSums(allfits_s$which)-1 # Extract the number of predictors for each too
```
Which model has the lowest $C_p$?
```{r q6_d1, include=TRUE}
min_cp<-which(allfits_s$cp==min(cp))
min_cp
```
What are its predictors?
```{r q6_d2, include=TRUE}
names(which(allfits_s$which[min_cp,]))[-1]
```<file_sep>---
title: "ST464 - Assignment 4 - Solutions"
author: "<NAME> (18145426)"
date: "30 April 2019"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
suppressPackageStartupMessages(library(tidyverse)) # Needed for dplyr functions etc.
suppressPackageStartupMessages(library(MASS)) # Needed for Boston data etc.
suppressPackageStartupMessages(library(splines)) # Needed for bs() etc.
suppressPackageStartupMessages(library(gam)) # Needed for gam() etc.
suppressPackageStartupMessages(library(tree)) # Needed for tree() etc.
suppressPackageStartupMessages(library(glmnet)) # Needed for glmnet() etc.
```
## Question 1
For the Boston data available in package MASS we wish to relate dis (weighted mean
of distances to five Boston employment centres) to nox (nitrogen oxides concentration in parts per 10 million).
```{r q1_data, include=TRUE}
data("Boston")
str(Boston)
```
a) Fit a cubic polynomial to the data.
```{r q1a_fit, include=TRUE}
f.q1a<-lm(dis ~ nox + I(nox^2) + I(nox^3), data=Boston)
```
Plot the data and the fit.
```{r q1a_plot, include=TRUE}
ggplot(data=Boston, aes(x=nox, y=dis)) + geom_point() +
geom_line(aes(y=fitted(f.q1a)), color="red")
```
Comment on the fit.
**The fit appears to be pretty good except for the highest values of dis, where it bypasses those data points.**
Calculate the MSE.
```{r q1a_mse, include=TRUE}
mse.q1a<-mean(f.q1a$residuals^2)
mse.q1a
```
b) Repeat (a), this time using a 10th degree polynomial.
```{r q1b, include=TRUE}
f.q1b<-lm(dis~nox+I(nox^2)+I(nox^3)+I(nox^4)+I(nox^5)+I(nox^6)+I(nox^7)+
I(nox^8)+I(nox^9)+I(nox^10), data=Boston)
ggplot(data=Boston, aes(x=nox, y=dis)) + geom_point() +
geom_line(aes(y=fitted(f.q1a)), colour="red") +
geom_line(aes(y=fitted(f.q1b)), colour="blue")
mse.q1b<-mean(f.q1b$residuals^2)
mse.q1b
```
Compare the fits and the MSE.
**The new (blue) fit appears to be better than the previous cubic (red) one except for the highest values of dis, where it curves sharply away from those data points. The lower MSE value for the blue fit seems to confirm this.**
Use anova to compare the two fits and comment on your findings.
```{r q1c_anova, include=TRUE}
anova(f.q1a,f.q1b)
```
**The results above indicate that the additional terms ($nox^4$ to $nox^{10}$) make a statistically signifcant difference to the model fit and, therefore, should be retained at least (if not added to).**
c) Describe how you might use cross-validation to select the optimal degree (say between 1 and 10).
**It should be possible to create a function to build and fit the required polynomial expression based on a passed parameter which specifies the required order number (integer) and variables. Then invoke it iteratively, passing order values in the required range, to store the resultant MSE value of each fit in an array. The number of the array element with the lowest (minimum) MSE value would then give the optimal order (degree) number. We could then use Anova to compare the fit at that optimal degree with that achieved for one of our earlier attempts at assessing goodness of fit at a lower degree to confirm the goodness of optimal fit statistically.**
d) Carry out the cross-validation procedure.
```{r q1d_cv, include=TRUE}
# This function builds the regression formula for the required polynomial expression.
cv.formula<-function(x, y, o=2){
p<-paste(y," ~ ",x,sep="")
if(o > 1){
for(i in c(2:o)){
p<-paste(p," + I(",x,"^",i,")",sep="")
}
}
return(p)
}
# This function performs the regression for the required polynomial expression
cv.fit<-function(x, y, o=2){
f<-lm(formula=cv.formula(x,y,o), data=Boston)
return(f)
}
# This function performs the regression for the required polynomial expression and calculates its MSE
cv.mse<-function(x, y, o=2){
mse<-mean(residuals(cv.fit(x,y,o))^2)
return(mse)
}
# This loop iteratively performs regression for the polynomial expressions with the specified range of degrees (1 to 100 in this case)
for(i in c(1:100)){
ifelse(i==1,mse<-cv.mse("nox","dis",i),
mse<-c(mse,cv.mse("nox","dis",i)))
}
head(mse)
```
**Note that when iterating 10 times, the 10th order polynomial had the lowest MSE value. Therefore, I decided to try iterating 100 times to see where the ultimate lowest MSE might be found (see the result below).**
What is the optimal degree?
```{r q1d_opt, include=TRUE}
min(which(mse==min(mse)))
```
**Now let's use Anova to see if the fit for this degree is statistically better than that for a degree that we looked at earlier (the 10th degree was the best fit we found prior to this cross validation exercise).**
```{r q1d_anova, include=TRUE}
anova(cv.fit("nox","dis",10),cv.fit("nox","dis",54))
```
**The Anova results above appear to confirm that the fit using optimal degree value (54) is statisitically better than the best fit achieved previously (using a 10th degree polynomial expression). **
e) Use bs() to fit a regression spline with 4 degrees of freedom.
```{r q1e_bs, include=TRUE}
f.q1e<-lm(dis~bs(nox,4),data=Boston)
```
What are the knots used?
```{r q1e_knots, include=TRUE}
attr(bs(Boston$nox, df=4), "knots")
```
Plot the data and the fit.
```{r q1e_plot, include=TRUE}
ggplot(data=Boston, aes(x=nox, y=dis)) + geom_point() +
geom_line(aes(y=fitted(f.q1e)), colour="red")
```
Comment on the fit.
**The fit is pretty good except for the highest values of dis, where it bypasses those data points.**
Calculate the MSE.
```{r q1e_mse, include=TRUE}
mean(f.q1e$residuals^2)
```
f) Fit a curve using a smoothing spline with the automatically chosen amount of smoothing.
```{r q1f_fit, include=TRUE}
f.q1f<-smooth.spline(Boston$nox,Boston$dis, cv=T)
f.q1f
```
Display the fit.
```{r q1f_plot, include=TRUE}
ggplot(data=Boston, aes(x=nox, y=dis)) + geom_point() +
geom_line(aes(y=fitted(f.q1f), colour="red"))
```
Does the automatic fit give a good result?
**This apears to be a pretty good fit except for the highest values of dis, where it bypasses those data points.**
g) Now use smoothing spline with a larger value of spar.
```{r q1g_fit, include=TRUE}
f.q1g<-smooth.spline(Boston$nox,Boston$dis,spar=1)
```
Overlay both smoothing spline fits on the plot.
```{r q1g_plot, include=TRUE}
ggplot(data=Boston,aes(x=nox,y=dis)) + geom_point() +
geom_line(aes(y=fitted(f.q1f)), colour="red") +
geom_line(aes(y=fitted(f.q1g)), colour="blue")
```
Which looks better?
**The (blue) fit with the higher spar value appears to be slightly better than the previous (red) one (especially at the highest values of dis).**
## Question 2
Using the Boston data, with dis as the response and predictors medv, age and nox.
a) Split the data into training 60% and test 40%.
```{r q2a_train, include=TRUE}
set.seed(123)
s<-sample(seq(1, nrow(Boston)),0.6*nrow(Boston))
Boston.train<-Boston[s,]
Boston.test<-Boston[-s,]
nrow(Boston.train)
nrow(Boston.test)
```
Using the training data, fit a generalised additive model (GAM). Use ns with 4 degrees of freedom for each predictor.
```{r q2a_fit, include=TRUE}
f.q2a<-lm(dis ~ ns(medv,4) + ns(age,4) + ns(nox,4), data=Boston.train)
```
b) Use plot.gam to display the results.
```{r q2b_plot, include=TRUE}
par(mfrow=c(1,3))
plot.Gam(f.q2a)
```
Does it appear if a linear term is appropriate for any of the predictors?
**No. None of the above plots indicate linearity for their respective model.**
c) Simplify the model fit in part (a). Refit the model.
```{r q2c_fit, include=TRUE}
f.q2c<-lm(dis ~ ns(nox,4), data=Boston.train)
```
Use anova to compare the two fits
```{r q2c_anova, include=TRUE}
anova(f.q2c, f.q2a)
```
and comment on your results.
**The very low p-value in the Anova results above indicates that the unsimplified model (2) is a significantly (statistically speaking) better fit than the simplified model (1) with the medv and age predictors removed.**
## Question 4
a) For the training data in question 2, fit a tree model. Use dis as response, and predictors medv, age and nox.
```{r q4a_fit_train, include=TRUE}
f.q4a<-tree(dis ~ medv + age + nox, data=Boston.train)
summary(f.q4a)
```
Draw the tree.
```{r q4a_plot, include=TRUE}
plot(f.q4a)
text(f.q4a)
```
Calculate the training and test MSE.
```{r q4a_fit_test, include=TRUE}
mse.train<-mean((predict(f.q4a) - Boston.train$dis)^2)
paste("Training MSE =", round(mse.train,5))
mse.test<-mean((predict(f.q4a, newdata=Boston.test) - Boston.test$dis)^2)
paste(" Test MSE =", round(mse.test, 5))
```
b) Use cv.tree to select a pruned tree.
```{r q4b_cvtree, include=TRUE}
set.seed(123)
cvtree <- cv.tree(f.q4a)
plot(cvtree$size,cvtree$dev,type="b")
```
If pruning is required, fit and draw the pruned tree.
```{r q4b_prune, include=TRUE}
f.q4b<-prune.tree(f.q4a,best=4)
summary(f.q4b)
```
Calculate the training and test MSE.
```{r q4b_mse, include=TRUE}
mse.train.pruned<-mean((predict(f.q4b) - Boston.train$dis)^2)
paste("Training MSE =", round(mse.train.pruned,5))
mse.test.pruned<-mean((predict(f.q4b, newdata=Boston.test) - Boston.test$dis)^2)
paste(" Test MSE =", round(mse.test.pruned, 5))
```
Compare the results to those in (a).
**The training MSE value of the unpruned tree is less than that of the pruned tree which indicates that it makes a better fit for the training dataset. However, the pruned tree achieved a lower test MSE value than the unpruned tree did. This an indicator that the unpruned model may be overfitted vis a vis the training dataset.**
c) Which fit is better, the (optionally pruned) tree or the GAM?
```{r q2c_train, include=TRUE}
mse.gam.train<-mean((predict(f.q2a)-Boston.train$dis)^2)
paste("Training MSE (GAM) =", round(mse.gam.train,5))
```
**The GAM delivers a better (lower) MSE (0.7906) on the training dataset than that achieved by the pruned tree model (0.82112).**
Compare their performance on the test data.
```{r q2c_test, include=TRUE}
mse.gam.test<-mean((predict(f.q2a, newdata=Boston.test)-Boston.test$dis)^2)
paste(" Test MSE (GAM) =", round(mse.gam.test,5))
```
**The GAM delivers a worse (higher) MSE (1.29454) on the test dataset than that achieved by the pruned tree model (1.26445).**
## Question 5
For the data generated in question 6, Assignment 3:
```{r q5_data, include=TRUE}
set.seed(1)
x <- rnorm(100)
y <- 1 + .2*x+3*x^2+.6*x^3 + rnorm(100)
d <- data.frame(x=x,y=y)
```
a) Fit a regression model containing predictors $X$, $X^2$, . . .$X^{10}$.
```{r q5a_fit, include=TRUE}
formula<-cv.formula("x","y",10)
formula
f.q5a<-lm(formula,data=d)
summary(f.q5a)
```
Based on the output in summary() which terms are needed in the model?
**The above output indicates that none of the terms are significant.**
b) Fit a ridge regression model using the glmnet function over a grid of values for $\lambda$ ranging from 0.001 to 50.
```{r q5b_ridge, include=TRUE}
grid<-seq(0.001,50,length=100)
x<-model.matrix(as.formula(formula),data=d)
y<-d$y
f.q5b<-glmnet(x,y,alpha=0,lambda=grid)
summary(f.q5b)
```
Plot coefficients vs penalty using the default plot method.
```{r q5b_plot, include=TRUE}
plot(f.q5b)
```
Use the inbuilt function cv.glmnet to choose the tuning parameter $\lambda$.
```{r q5b_cv, include=TRUE}
set.seed(123)
cv<-cv.glmnet(x,y,alpha=0)
lambda.q5b<-cv$lambda.min
lambda.q5b
```
How do the coefficients at the optimal value of $\lambda$ compare to the linear regression ones in (a)?
```{r q5b_coef, include=TRUE}
coefficients<-data.frame(lm=f.q5a$coefficients,ridge=coef(cv)[-2])
coefficients
```
**As shown in the table above, the ridge regression cofficients (for the most part) follow a decreasing pattern culminating in their only negative value, while the values for the linear regression coefficients are more randomly distributed in terms of both value and sign.**
c) Repeat (b) for lasso regression instead of ridge.
Fit a Lasso regression model using the glmnet function over a grid of values for $\lambda$ ranging from 0.001 to 50.
```{r q5c_lasso, include=TRUE}
grid<-seq(0.001,50,length=100)
x<-model.matrix(as.formula(formula),data=d)
y<-d$y
f.q5c<-glmnet(x,y,alpha=1,lambda=grid)
summary(f.q5c)
```
Plot coefficients vs penalty using the default plot method.
```{r q5c_plot, include=TRUE}
plot(f.q5c)
```
Use the inbuilt function cv.glmnet to choose the tuning parameter $\lambda$.
```{r q5c_cv, include=TRUE}
set.seed(123)
cv<-cv.glmnet(x,y,alpha=1)
lambda.q5c<-cv$lambda.min
lambda.q5c
```
How do the coefficients at the optimal value of $\lambda$ compare to the linear regression ones in (a)?
```{r q5c_coef, include=TRUE}
coefficients<-data.frame(lm=f.q5a$coefficients,lasso=coef(cv)[-2])
coefficients
```
**As shown in the table above, apart from 4 zero values, the lasso regression coefficient values are all positive, unlike their linear regression equivalents.**
d) Plot the data y vs x and superimpose the fitted models from linear regression, ridge and lasso with optimal values of lambda as chosen by cross-validation.
```{r q5d_plot, include=TRUE}
ridge.pred<-predict(f.q5b, s=lambda.q5b,
newx=model.matrix(as.formula(formula), data=d))
lasso.pred<-predict(f.q5c, s=lambda.q5c,
newx=model.matrix(as.formula(formula), data=d))
ggplot(aes(x=x,y=y), data=d) +
geom_point() +
geom_line(aes(y=fitted(f.q5a)),colour="blue") +
geom_line(aes(y=ridge.pred),colour="red") +
geom_line(aes(y=lasso.pred),colour="green")
```
**It is remarkable, for this dataset at least, how similar the fits produced by linear, ridge and lasso regression have achieved are once the optimal value of lambda was used for the latter two methods.**<file_sep>public class ArgsTest
{
public static void main(String args[])
{
String arg1 = args[0]; // Declare and accept the first (string) argument/parameter from the command line
int arg2 = Integer.parseInt(args[1]); // Do the same for the second (integer) argument
double arg3 = Double.parseDouble(args[2]); // Do the same for the third (double) argument
System.out.println("arg1 = " + arg1 + "; arg2 = " + arg2 + "; arg3 = " + arg3);
}
}<file_sep>/**
* This program uses the Ternary operator to set the value of a variable (y) depending on whether the value of another variable (x) is greater than 0 or not
*
* @author <NAME>
* @author 18145426
* @version 17/09/2018
*/
public class TernaryTest
{
public static void main(String args[])
{
int x = -10; // Declare and initialise the local variables
int y = 0;
y = (x > 0) ? 1 : -1; // This is the test ternary operation
System.out.println("y = " + y); // Display the result of the ternary operation above
}
}<file_sep>---
title: 'NCG603 - Modelling Voter Turnout Assignment'
author: "<NAME> (18145426)"
date: "8 May 2019"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd() # Display the current working directory
suppressPackageStartupMessages(library(tidyverse)) # Needed for dplyr functions etc.
suppressPackageStartupMessages(library(GWmodel)) # Needed for GWR functions
suppressPackageStartupMessages(library(car)) # Needed for Boxplot()
suppressPackageStartupMessages(library(classInt)) # Needed for ClassIntervals()
suppressPackageStartupMessages(library(RColorBrewer)) # Needed for Palette() etc.
suppressPackageStartupMessages(library(spdep)) # Needed for moran() etc.
suppressPackageStartupMessages(library(gclus)) # Needed for cpairs() etc.
suppressPackageStartupMessages(library(sqldf)) # Needed for sqldf() etc.
suppressPackageStartupMessages(library(OutlierDetection)) # Needed for OutlierDetection() etc.
suppressPackageStartupMessages(library(leaps)) # Needed for regsubsets()
suppressPackageStartupMessages(library(MASS)) # Needed for stepAIC()
suppressPackageStartupMessages(library(gridExtra)) # Needed for gridArrange()
data(DubVoter) # Get the relevant spatial dataframe
str(Dub.voter@data) # Display the structure of the dataframe's data slot
```
<P style="page-break-before: always">
# Introduction
## Objective
The aim of this assignment is to predict the variation in voter turnout across the 322 electoral districts (ED) in Dublin for the General Election of 2002.
## Context
To enable us to do this we have a spatial polygons dataframe for those areal units which, in its data slot, contains a row for each ED with a value in each of their 12 columns (variables). Refer to the results of the most recent command above for the structure of that dataset.
Those 12 variables can be broken down into the following categories:
- The first variable contains a unique identifier for each row/ED;
- the next 2 contain the coordinates (of their centroids, presumably);
- the next 5 contain socio-economic (percentage) metrics that are considered to be important predictors of voter participation (e.g. percentage unemployed and percentage of low educational attainment);
- the next 3 socio-economic variables contain the percentage value of the ED's population in each of 3 key voting-eligible age groups;
- and the final (response) variable provides the actual percentage of the electorate that turned out to vote in each ED for the election in question.
## Approach
As the last variable referred to above contains the values that we are required to predict, we will be using a suitable, supervised machine learning technique to do so.
Before selecting that technique, we will do due diligence on the dataset itself by assessing its level of data quality (e.g. in terms of valid value ranges, completeness etc.), and by looking for the presence of outliers and collinearity and the extent of same.
# Data Quality Analysis
In this section, we will look at the dataset, variable by variable, and assess the level of data quality as well as its spatial distribution in each case.
## DED_ID (Unique Identifier)
Here, we will assess whether or not this variable provides a unique identifier for each row in the dataset (and for which spatial distibution is not relevant).
```{r qa_ded_id_uniq, include=TRUE}
paste("DED_ID values are unique? =", # Check for uniqueness
length(Dub.voter$DED_ID)==length(unique(Dub.voter$DED_ID)))
```
<P style="page-break-before: always">
## X and Y (Coordinates)
We will now attempt to draw a map showing the distribution of the response variable (GenEl2004) to ensure that the dataset refers to EDs in the Dublin area only.
```{r qa_xy_map, include=TRUE}
quickMap3 <- function(SPDF,Var,nClass=9,dp=0,plotVar=FALSE){
Classes <- classIntervals(Var,nClass,method="quantile",dataPrecision=dp)
Palette <- brewer.pal(nClass,"Reds")
Colours <- findColours(Classes,Palette)
plot(SPDF,col=Colours)
legend("bottomright",
legend=names(attr(Colours,"table")),
fill=attr(Colours,"palette"),
cex=0.75,bty="n")
box()
if(plotVar) {
xy <- coordinates(SPDF)
text(xy[,1],xy[,2],round(Var,dp),col="blue",cex=0.5)
}
}
quickMap3(Dub.voter,Dub.voter$GenEl2004)
```
The above map confirms that we are dealing with EDs in the Dublin area only - i.e. no ED is an 'outlier' in that sense (as specified by its coordinates).
We will now attempt to compare the values of the X and Y variables with those that were used to draw the map above:
```{r qa_xy_coords, include=TRUE}
coords<-data.frame(coordinates(Dub.voter),X2=Dub.voter$X,Y2=Dub.voter$Y)
names(coords)<-c("x_poly","y_poly","x_data","y_data")
head(coords)
```
We can see from the sample values above that both sets of coordinates do not quite match up. Having consulted with the data owner, <NAME>, we will now get both sets of coordinates in synch using the following code:
```{r qa_xy_sync, include=TRUE}
coords.new<-data.frame(X=coords$x_poly,Y=coords$y_poly)
head(Dub.voter@data)[1:3]
Dub.voter@data %>%
mutate(X=coords.new$X, Y=coords.new$Y) ->
Dub.voter@data
head(Dub.voter@data)[1:3]
```
We can see from the final results above that the values of the X and Y coordinates in Dub.voter@data slot have been updated to the their equivalents from the Dub.voter@polygons slot.
<P style="page-break-before: always">
## DiffAdd (Percentage who changed address within the past year)
Now let's take a look at the range of values for this variable.
```{r qa_diff, include=TRUE}
summary(Dub.voter$DiffAdd)
spplot(Dub.voter,"DiffAdd")
```
The above results indicate a reasonable spread of valid percentage values for this variable. The map shows that there are population mobility hotspots in the city centre EDs, in the Dun Laoghaire area and the outer, northwestern suburbs.
<P style="page-break-before: always">
## LARent (Percentage of local authority renters)
Now let's take a look at the range of values for this variable.
```{r qa_larent, include=TRUE}
summary(Dub.voter$LARent)
which(Dub.voter$LARent==100)
spplot(Dub.voter,"LARent")
```
The above results indicate a wide spread of valid percentage values for this variable. Later in this document we will take a closer look at the observations with the minimum (0) and maximum (100) values to assess the possibility of missing or outlier values.
The map shows that those high-end outlier EDs in relation to public housing are primarily located primarily around the city centre and in the midwestern suburbs.
<P style="page-break-before: always">
## SC1 (Percentage of Social Class 1 people)
Now let's take a look at the range of values for this variable.
```{r qa_sc1, include=TRUE}
summary(Dub.voter$SC1)
spplot(Dub.voter,"SC1")
```
The above results indicate a reasonable spread of valid percentage values for this variable. The maps shows that the affluence hotspots are located around Dublin Bay (with the exception of the central port areas) and in certain midwestern EDs.
<P style="page-break-before: always">
## Unempl (Percentage of unemployed people)
Now let's take a look at the range of values for this variable.
```{r qa_unempl, include=TRUE}
summary(Dub.voter$Unempl)
spplot(Dub.voter,"Unempl")
```
The above results indicate a reasonable spread of valid percentage values for this variable. The map shows that the unemployment blackspots are sprinkled around some north-central and midwestern EDs.
<P style="page-break-before: always">
## LowEduc (Percentage who changed address within the past year)
Now let's take a look at the range of values for this variable.
```{r qa_loweduc, include=TRUE}
summary(Dub.voter$LowEduc)
spplot(Dub.voter,"LowEduc")
```
The above results indicate a reasonable spread of valid percentage values for this variable. However, later in this document we will take a closer look at occurences of the minimum value (0) to assess the possibility of them being missing values. Th map shows only 2 main educational attainment hotpots in the outer northeastern and southwestern suburbs, respectively.
<P style="page-break-before: always">
## Age18_24 (Percentage in the 18-24 Age Group)
Now let's take a look at the range of values for this variable.
```{r qa_age18_24, include=TRUE}
summary(Dub.voter$Age18_24)
spplot(Dub.voter,"Age18_24")
```
The above results indicate a reasonable spread of valid percentage values for this variable.The maps shows that some youthful hotspots are located in the city centre with a high-end on in the inner southern suburbes and in a small number of isolated outer suburbs.
<P style="page-break-before: always">
## Age25_44 (Percentage in the 25-44 Age Group)
Now let's take a look at the range of values for this variable.
```{r qa_age25_44, include=TRUE}
summary(Dub.voter$Age25_44)
spplot(Dub.voter,"Age25_44")
```
The above results indicate a reasonable spread of valid percentage values for this variable. The map shows that millennials are concentrated in the city centre and in a broad arc in the outer suburbs.
<P style="page-break-before: always">
## Age45_64 (Percentage in the 45-64 Age Group)
Now let's take a look at the range of values for this variable.
```{r qa_age45_64, include=TRUE}
summary(Dub.voter$Age45_64)
spplot(Dub.voter,"Age45_64")
```
The above results indicate a reasonable spread of valid percentage values for this variable. The map shows that the older generation are distributed across the EDs with some hotspots in the well-to-do suburbs at the north and south ends of Dublin Bay and its hinterland as well as some southwestern EDs.
<P style="page-break-before: always">
## GenEl2004 (Percentage Turnout)
Now let's take a look at the range of values for this variable.
```{r qa_genel2004, include=TRUE}
summary(Dub.voter$GenEl2004)
spplot(Dub.voter,"GenEl2004")
```
The above results indicate a reasonable spread of valid percentage values for this variable. This map shows a similar pattern to the previous one (re the older population) especially in the affluent suburbs at the southern and northern ends of Dulin Bay and its hinterland.
<P style="page-break-before: always">
# Missing Data Analysis
We will now look at the presence of missing date (NA) or potentially missing values (0) in this dataset.
```{r miss, include=TRUE}
miss_na<-function(x){sum(is.na(x))} # Function to count NA values
miss_0<-function(x){sum(x==0)} # Function to count zero values
apply(Dub.voter@data,2,miss_na) # Count zero NA for all variables
apply(Dub.voter@data,2,miss_0) # Count zero values for all variables
```
The results above show that NA values are not present for any variable, that the LARent variable has 12 occurences of the zero value, and the LowEduc variable has 24 occurrences of the zero value.
As the the proportion of zero values in both cases is relatively low, and because it is not unreasonable for the more prosperous EDs to have zero values for these 2 variables, we can conclude that those zero values do not represent missing values.
<P style="page-break-before: always">
# Outlier Analysis
Outlier analysis is not appropriate for the first 3 columns because the first one is just a unique identifier and the other two are coordinates which have already been implicitly checked for outliers by the previous map plotting exercise.
As we have not yet performed any variable (or model) selection, we will have to take a univariate approach to outlier detection (as opposed to a bivariate or multivariate one).
We will now perform univariate outlier detection using the following functions:
1. Boxplot() in the car library;
2. UnivariateOutlierDetection() in the OutlierDetection library.
In the case of the latter function, we will apply all of its available merthods (distance-, density- and depth-based) to identify the observations that are considered to be outliers by all of them.
Finally, we will merge the results of both functions to find the observations which are common to both of them and then take a closer look at all of them, based on the weight of evidence provided by the use of multiple methods performed by both functions.
## Using Boxplot()
We will now display the observation (row) numbers where an outlier was detected for each variable:
```{r out_box, include=TRUE, fig.show="hide"}
# Get the observation numbers where an outlier was detected for each variable
out.box.list<-apply(Dub.voter@data[,4:12],2,Boxplot,id=list(cex=0.5))
str(out.box.list)
```
And the total number of outlier observations (overall and for unique observations):
```{r out_box_tot, include=TRUE}
# Get the total number of outlier observations
out.box<-unlist(out.box.list)
paste("Total (Overall) =",length(out.box))
paste("Total (Unique) =",length(unique(out.box)))
```
The results above show us that:
- A total of 57 outlier values are present across the entire dataset
- in 44 of the 322 observations.
- At least 1 outlier value was detected for all of those variables.
- The maximum number of outliers per variable is 10.
- The minimum number of outliers per variable is 2.
<P style="page-break-before: always">
## Using UnivariateOutlierDetection()
We will now use this function to apply all of its methods to find all of outliers for each of the same variables as previously. Those methods are as follows:
- Robust Kernal-based Outlier Factor(RKOF) algorithm
- depthTools package
- Generalised Dispersion (using LOO dispersion matrix)
- Mahalanobis Distance (an observation and )based on the Chi square cutoff)
- k Nearest Neighbours Distance
- kth Nearest Neighbour Distance
Only the numbers of observations that are identified as outliers by all of those methods is returned to provide the required weight of evidence.
```{r out_uod, include=TRUE, fig.show="hide"}
# This function runs all methods of UnivariateOutlierDetection() for the specified variable (x)
UOD<-function(x){
obs<-try(UnivariateOutlierDetection(x,dist=T,depth=T,dens=T)$`Location of Outlier`)
if (class(obs)=='try-error') { # If no outliers found for a variable
return(as.integer(NA)) # return NA
} else { # Otherwise
return(obs) # return their observation numbers
}
}
out.uod.list<-apply(Dub.voter@data[,4:12],2,UOD) # Invoke the function
str(out.uod.list) # Display a summary of its results
```
And the total number of outlier observations (overall and for unique observations):
```{r out_uod_tot, include=TRUE}
# Get the total number of outlier observations
out.uod<-unlist(out.uod.list)
paste("Total (Overall) =",length(out.uod))
paste("Total (Unique) =",length(unique(out.uod)))
```
The results above show us that, when all methods of UnivariateOutlierDetection() were applied:
- A total of 24 outlier values are present across the entire dataset
- in 22 of the 322 observations.
- No outliers were detected for 2 variables.
- The maximum number of outliers per variable is 8.
- The minimum number of outliers per variable is 1.
We will now find the observation numbers that are common to both lists of outliers (as provided Boxplot() and UnivariateOutlierDetection(), respectively):
```{r out_comp_ind, include=TRUE}
# This function matches the contents of two lists (l1 and l2) and returns the indexes of matching values for each element in the form of another list (l)
match.list<-function(l1,l2){
l<-vector("list",length(l1)) # Initialise the output list
names(l)<-names(l1) # and name its elements (based on l1)
for(i in c(1:length(l))){ # Construct the output list
v<-intersect(unlist(l1[i]),unlist(l2[i])) # Find the matching elements of l1 & l2
if(length(v)==0){v<-as.integer(NA)} # If no matching element, use NA
l[[i]]<-v # Load the current list element
}
return(l) # Return the output list
}
out.both.list<-match.list(out.box.list,out.uod.list)# Invoke the function
str(out.both.list) # Display a summary of its results
```
And the total number of outlier observations (overall and for unique observations):
```{r out_both_tot, include=TRUE}
# Get the total number of outlier observations
out.both<-unlist(out.both.list)
paste("Total (Overall) =",sum(!is.na(out.both)))
paste("Total (Unique) =",sum(!is.na(unique(out.both))))
```
The results above show us that both functions have identified a total of 13 distinct outliers in common across the 322 observations. Let's take a look at their values now:
```{r out_comp_val, include=TRUE}
# This function uses a list of index values (list) to provide the values of the corresponding cells of the specified data frame (df)
match.list.val<-function(list,df){
l<-vector("list",length(list)) # Initialise the output list
names(l)<-names(list) # and name its elements based on list
for(i in c(1:length(list))){ # Construct the output list (l)
v<-unlist(list[i]) # Unlist the current index list element
l[[i]]<-df[,i][v] # Load the output list
}
return(l) # Return the output list
}
out.both.list.val<-match.list.val(out.both.list,# Invoke the function
Dub.voter@data[,4:12])
str(out.both.list.val) # Display a summary of its results
```
As of the values of the 13 (common) outliers appear to be unreasonable and they are rellatively small in number no further action is considered necessary.
<P style="page-break-before: always">
# Collinearity Analysis
## Global Collinearity
Firstly, let's see if we can detect any evidence of collinearity at the global level:
```{r coll_glo, include=TRUE}
data.cor<-cor(Dub.voter@data[,2:12])
data.cor %>%
dmat.color()->cols
cpairs(Dub.voter@data[,2:12],panel.colors=cols,pch=".",gap=.5)
```
The cpairs variant of the standard scatter plot matris (pair) provides a kind of heat map of the level of correlation exists between all variable pairings in the data set. It does this by cutting the correlation values of the variable pairings into 3 equal intervals (breaks): red for noteworthy positive correlation, cream for noteworthy negative correlation and blue for weak or no correlation.
As can be seen from its output above, there is evidence of quite a bit of multicollinearity in the dataset under review, which also applies to its spatial (x-Y coordinate) variables.
The following code will display the value intervals for the cream, blue and red colour codes above:
```{r coll_cut, include=TRUE}
cormat<-cor(Dub.voter@data[,2:12]) # Create the correlation matrix
n<-nrow(cormat) # Get number of rows
for(i in c(1:n)){ # 'Blank' the redundant cells
for(j in c(i:n)){
cormat[i,j]<-NA
}
}
cut<-cut_number(cormat,3) # Cut cormat into 3 ranges
levels(cut) # Display the intervals/breaks
```
The above results tell us that the cream (noteworthy negative) interval covers Pearson r correlation values in the range -0.1 and below, the red (noteworthy positive) interval covers values in the range 0.1 and above, while the blue (weak or none) covers the range from 0.1 to -0.1.
As we will be looking at local collinearity in the next section of the document, for now we will focus solely on the non-spatial variables.
We will now take a closer look at the noteworthy correlations (both positive and negative) by producing a correlation matrix with a view to quantifying it in descending order of importance (as measured by the Pearson r values).
```{r coll_cor, include=TRUE}
cormat<-cor(Dub.voter@data[,4:12]) # Create the correlation matrix
n<-nrow(cormat) # Get number of rows
for(i in c(1:n)){ # 'Blank' the redundant cells
for(j in c(i:n)){
cormat[i,j]<-NA
}
}
cut<-cut_number(cormat,3) # Cut cormat into 3 ranges
corind<-which(as.numeric(cut) %in% c(1,3)) # Find cells with highest cor value
corrow<-corind %% n # Convert cell index to row no.
corcol<-corind %/% n + 1 # Convert cell index to col. no.
fix<-which(corrow==0) # corrow/corcol elements to fix
corrow[fix]<-n # Fix corrow
corcol[fix]<-corcol[fix]-1 # Fix corcol
rowname<-attr(cormat,"dimnames")[[1]][corrow] # Convert row number to name
colname<-attr(cormat,"dimnames")[[2]][corcol] # Convert column number to name
val<-cormat[corind] # Get r value
cordf<-data.frame(rowname,colname,val) # Create correlation data frame
arrange(cordf,desc(abs(val))) # Display correlation data frame
# (largest absolute r values first)
```
Now let's evaluate the top 10 (in terms of strength of correlation) for plausibility:
1. People in the 25-44 age group in an ED are the most mobile in terms of changing address (plausible).
2. EDs with the more people in the 45-64 age group have less in the 25-44 age bracket (plausible).
3. EDs with a high proportion of unemployed people have a lower turnout rate (plausible).
4. EDs with a high proportion of local authority renters have a lower turnout rate (plausible).
5. EDs with a high proportion of unemployed people also have a high level of local authority renters (plausible).
6. EDs with a high proportion of unemployed people have a lower proportion of well-off (SC1) people (plausible).
7. EDs with a high proportion of people in the 45-64 age group have a lower proportion of people who have changed their address within the past 12 months (plausible).
8. EDs with a high proportion of people in the 45-64 age group have a high turnout rate (plausible).
9. EDs with a high proportion of people in the 45-64 age group have low proportions of local authority renters (not so obvious).
10. EDs with a high proportion of people in the 25-44 age group have a low turnout rate (plausible).
<P style="page-break-before: always">
## Local Collinearity
We will now perform a Moran's I test to see if the probability of local collinearity being present in the data is statistically significant for the variables of interest.
```{r coll_loc, include=TRUE}
nbl<-poly2nb(Dub.voter) # Create a neighbours list for the SPDF
print(nbl)
wts<-nb2listw(nbl) # Create a weights matrix for the neighbours list
print(wts)
mt<-apply(Dub.voter@data[,4:12], # Perform the moran test for the required vars.
2,moran.test,wts)
v<-vector("double",length(mt)) # Initialise the output vector
names(v)<-names(Dub.voter@data[,4:12]) # and name its elements based on vector
for(i in c(1:length(mt))){ # Load the ouput vector
v[i]<-mt[[i]][2]
}
str(v) # Display a summary of the results
v[which(v>0.05)] # Any high p-values?
```
The p-values resulting from the above test indicate that only one variable (LowEduc) has a p-value greater than 0.05 and, therefore, we cannot reject the null hypothesis for it (i.e. zero spatial autocorrelation present).
Corollarily, the null hypothesis can be rejected for the other variables which indicates that spatial autocorrelation is present for them.
<P style="page-break-before: always">
# Variable (Feature) Selection
Before we can begin modelling, we must first identify the set of predictors that are most likely to predict the response variable most accurately. In so doing, we must ensure that the model is not overfitted because its predictive power for other similar datasets (e.g. the same type voter data in other areas for the same election or in the same area for other elections) could be impaired.
For linear regression two of the most commonly used measures for assessing a model's goodness of fit are Mallow's $C_p$ and the Akaike Information Criterion (AIC) which a designed to avoid overfitting.
Stepwise linear regression is the process of systemmatically evaluating models with different combinations of predictors by calculating the relevant goodness of fit metric for each one and choosing the combination the results in the lowest value.These techniques can typically be configured to run in a forward (starting with one predictor and systematically add others) or a backward direction (starting with all predictors and systematically remove predictors) or in both firections (sometimes referred to as an exhaustive approach).
R provides a number of different functions for performing stepwise regression of which we will now use the following ones (in both directions):
- regsubsets() in the leaps package (which uses $C_p$ as its metric);
- steps() in the base stats package (which uses AIC as its metric);
- stepAIC() in the MASS package (which also uses AIC as its metric).
We will also use Geographically Weighted Principle Component Analysis (PCA) to sanity-check the outcome of the stepwise regression approach.
## Using lm() and p-Values
But before we perform stepwise regression, let's fit a linear regression model for all predictors and look at the p-values for the predictors in the resultant fit which it considers to be the most significant variables statistically.
```{r select_lm, include=TRUE}
# Fit a model with all (9) predictors
f.lm <- lm(GenEl2004 ~ .,data = Dub.voter@data[,4:12])
summary(f.lm)
```
The results above indicate the following predictors are significant in descending order of probability: Unempl, LARent, Age25_44 and Age18_24. Interestingly, their coefficient estimate values are all negative which indicates that the higher their percentage values are in a particular ED the lower the turnout is likely to be there. Intuitively, this seems to make sense because turnout in deprived areas (where Unempl and LARent values can be relatively high) is expected to be lower and turnout is known to be higher among senior citizens relative to the younger age groups (as measured by the Age25_44 and Age45_64 predictors).
Let's go ahead and perform the types of stepwise regression referred to above to see how the combination of those 4 predictors compares with many other predictor combinations.
## Using regsubsets() and $C_p$ Values
Firstly, we run the stepwise regression function and store its key results:
```{r select_regs, include=TRUE}
f.regs<-regsubsets(GenEl2004 ~ .,# Run the stepwise regression function
data=Dub.voter@data[,4:12])
f.regs.sum<-summary(f.regs) # Store the results
cp<-f.regs.sum$cp # Extract the Cp values for all stepwise models
np<-rowSums(f.regs.sum$which)-1 # Extract the number of predictors for each too
```
We now plot the $C_p$ value achieved versus the number of predictors for the favoured predictor combination for each number of predictors.
```{r select_regs_plot, include=TRUE}
# Plot the cp value against the number of predictors
plot(np, cp, pch=16, xlab="Number of predictors")
lines(np, cp)
```
The above plot indicates that best 4-predictor combination achieved the lowest $C_p$ value.
Finally, let's get the names of the predictors in that combination and display them:
```{r select_regs_vars, include=TRUE}
# Extract the recommended variable names
terms<-attr(which(f.regs.sum$which[4,]),"names")
terms[2:length(terms)]
```
The results above agree with those achieved during the preliminary study using lm() and p-values.
So let's see what lm()'s p-values look like now if we fit a model with only those 4 predictors:
```{r select_lm_4, include=TRUE}
# Fit a model with all (9) predictors
f.lm.4 <- lm(GenEl2004 ~ LARent + Unempl + Age18_24 + Age25_44,
data = Dub.voter@data[,4:12])
summary(f.lm.4)
```
The p-values in the results above show (not unexpectedly) that the statistical significance of those 4 predictors has increased, especially for Age18_24, although their relative significance has changed slightly in terms of descending order of p-values: Unempl, Age25-44, LARent and Age18_24 (LARrent has swapped position with Age25_44). All of their coefficient estimates remain in negative territory.
<P style="page-break-before: always">
## Using Step() and AIC Values
Now let's run this stepwise regression function, which uses AIC instead of $C_p$ as its goodness of fit measurement and the all-predictor regression model as its starting point, and display its results:
```{r select_step, include=TRUE}
# Perform stepwise model fitting (direction=backward by default)
f.step<-step(f.lm, direction="both", trace=F)
# Summarise the predictors that are recommended to be dropped
f.step$anova
```
The results above recommend dropping the following predictors: LowEduc, DiffAdd, Age45_64 and SC1, leaving us with LARent, Unempl, Age18_24 and Age25_44 as the recommended predictors yet again.
## Using StepAIC() aand AIC Values
Now let's try anotherAIC-based stepwise regression function to double-check the previous results.
```{r select, include=TRUE}
# Doublechecking using the stepAIC function in the MASS library....
f.step.AIC<-stepAIC(f.lm, direction="both", trace=F)
# Summarise the predictors that are recommended to be dropped
f.step.AIC$anova
```
The results above also recommend dropping the following predictors: LowEduc, DiffAdd, Age45_64 and SC1, leaving us with LARent, Unempl, Age18_24 and Age25_44 as the recommended predictors yet again.
<P style="page-break-before: always">
## Using gwpca() and Loading Values
We will firstly use the bw.gwpca() for establish the optimum bandwidth value (k) and then run the gwpca() itself to perform the PCA, after which we will display its results.
```{r gwrpca, include=TRUE}
bw.choice<-bw.gwpca(Dub.voter,vars=names(Dub.voter)[4:11],k=2)
pca.gw.auto<-gwpca(Dub.voter,vars=names(Dub.voter)[4:11],bw=bw.choice,k=2,scores=T)
pca.gw.auto
```
The results above consider the first two components to be the most important because they collectively explain almost 62% of the global variance in the voter data and about 90% of the local variance (on average). The loadings for the first component put its focus on the young (Age18_24 and Age25_44), mobile (DiffAdd) and less well off (LARent and Unempl) while down-weighting the well off (SC1) and older people (Age45_64).
Age18_24 and Age25_44 are the only predictors with a positive weight for both components so that seems to support its inclusion in the predictor set recommended by our stepwise regression exercises above. Age45_64 is the only predictor that has negative weightings for both components so that appears to support its elimination by stepwise regression. DiffAdd has sizable positive weightings for both components but the fact that it has the highest correlation (0.70) of any variable (with Age25_44) could explain why it was eliminated when Age24_45 was included. It is unclear what justification has to offer for the selection of the Unempl and LARent apart from the fact that LARent has the second highest positive weighting for the first component and, after DiffAdd has been discounted, Unempl has the third highest.
On balance, we will go with the recommended predictor set of LARent, Unempl, Age18_24 and Age25_44.
# Model Evaluation
As a prelude to performing a proper cross-valisation test of the recommended model (which is outside the scope of this document), we will perform a graphical comparison of its predicted (fitted) values with their actual equivalents (using the same scale) as follows:
```{r model, include=TRUE}
Dub.voter@data$Fitted<-fitted(f.lm.4)
p1<-spplot(Dub.voter,"GenEl2004",main="Turnout: Actual Values",
at=seq(25,75,5))
p2<-spplot(Dub.voter,"Fitted",main="Turnout: Fitted Values",
at=seq(25,75,5))
grid.arrange(p1,p2,nrow=1,ncol=2)
```
The maps above show that our oLS-based linear regression model has not done a particularly good job at predicting, so it certainly cannot be accused of overfitting. Whle it does appear to have done a fair job in some EDs in the north and southwest of the county, the relative lack of blue areas in the fitted map suggests that it has particular difficulty with predicting where very low turnout rates will occur. For instance, it completely missed that dark blue (very low) outlier in an ED just north of the city centre in the actual turnout map. It also missed that yellow (very high) outlier in an ED in the southeast corner of the county, so it seems to have problems at that end too.
Let's now do a very high-level comparison of the numbers undelying both of the graphs above:
```{r model_sum, include=TRUE}
summary(Dub.voter$GenEl2004)
summary(Dub.voter$Fitted)
```
Even though the median and mean values for both the actual and fitted turnout value sets are exactly the same (to all intents and purposes), as expect, the results above confirm that the model is overestimating at the low end and underestimating at the top end.
Here are some approaches that could be taken toward creating an improved model (which are outside the scope of this document):
1. Take another look at the classification of outliers and at what might be done to lessen any influence that they might be having on the model;
2. Try using Geographically Weighted Regression (the robust version to cope with outliers) instead of Multiple Linear Regression (for both predictor selection and model fitting);
3. Try a different (e.g. non-linear) predictor selection method like Random Forest;
4. Try a modelling technique that does not rely on linearity such as K Nearest Neighbours (KNN).<file_sep>---
title: "ST663 - Semester 1 - Assignment 3 - Solutions"
author: "<NAME> (18145426)"
date: "12 November 2018"
output: html_document
---
```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)
getwd()
```
# Question 1
The data in file census1.csv is obtained from www.censusatschool.ie. It contains observations
from the Phase 14 census at school Ireland project. The data contains a sample of 97 students.
The variables are Height FootR (right foot size) FootL (left foot size) in cm and Gender. Read the data into R and form a female only subset using the code below.
```{r q1_data, include=TRUE}
census <- read.csv("census1.csv")
censusF <- subset(census, Gender=="F")
str(censusF)
head(censusF)
```
a) Construct a graph comparing FootR and FootL for females.
```{r q1_a, include=TRUE}
boxplot(censusF$FootL,censusF$FootR,col=c(2:3),
names=c("Left Foot (F)","Right Foot (F)"),
ylab="Size (cm)")
```
Also use a suitable hypothesis test.
State the appropriate null and alternative hypotheses.
<b>
Answer:
$$H_0 : \mu_l-\mu_r=0$$
$$H_A : \mu_l-\mu_r\neq0$$
</b>
Perform the test......
```{r q1_a_hypo, include=TRUE}
tails<-2 # Two-tailed test
n<-length(censusF[,1]);n # Sample size
df<-n-1;df # Degrees of Freedom
diff<-censusF$FootL-censusF$FootR # Compute difference
xbar_diff<-mean(diff);xbar_diff # Sample mean of diffs
s_diff<-sd(diff);s_diff # Sample Std Dev of diffs
c<-0.95 # Level of Conf. (assumed)
alpha<-1-c;alpha # Level of Significance
se_diff<-s_diff/sqrt(n);se_diff # Standard Error of diffs
z<-(xbar_diff - 0)/se_diff;z # z-value
pval<-tails*pnorm(-abs(z));pval # p-value
# Use t.test to sanity-check the calculated p-value
t.test(diff,df=df,alternative="two.sided")
```
....and give your conclusions.
**Answer: As the p-value (both manual & t.test) is greater than alpha (for a Level of Confidence assumed to be 0.95), we cannot reject $H_0$ and, therefore, we conclude (with the stated Level of Confidence) that, on average, there is no difference between left and right foot size in the general female population.**
Check the normality of the relevant data using a QQ plot.
```{r q1_a_qqplot, include=TRUE}
par(mfrow=c(1,3))
qqnorm(censusF$FootL,xlab="Left Foot (F)") # QQPlot for Left
qqline(censusF$FootL,col=2)
qqnorm(censusF$FootR,xlab="Right Foot (F)") # QQPlot for Right
qqline(censusF$FootR,col=3)
qqnorm(diff,xlab="Difference") # QQPlot for Diffs
qqline(diff,col=4)
```
Interpret your results.
**Answer: None of the above plots exhibit any approximation to a normal distribution, all having significant tails on both the left and right. In particular, the difference data shows a stepped, linear distribution with significant clustering of data points at the zero (especially), -1 and +1 (cm) plateaux.**
b) Construct a graph comparing FootR for males and females.
```{r q1_b_boxplot, include=TRUE}
x<-subset(census, Gender=="F")$FootR # Extract the Female data
y<-subset(census, Gender=="M")$FootR # Extract the Male data
x<-na.omit(x) # Drop any NaNs
y<-na.omit(y)
head(x) # Take a peek at the data
head(y)
boxplot(x,y,col=c("red","blue"), # Draw the box plots
names=c("Right Foot (Female)","Right Foot (Male)"),
ylab="Size (cm)")
```
Also use a suitable confidence interval.
```{r q1_b_ci, include=TRUE}
mx<-mean(x);mx # Mean (Female)
sx<-sd(x);sx # Standard Dev. (Female)
my<-mean(y);my # Mean (Male)
sy<-sd(y);sy # Standard Dev. (Male)
n<-length(x);n # Sample size (Female)
m<-length(y);m # Sample size (Male)
s<-sqrt(((n-1)*sx^2 + (m-1)*sy^2)/(n+m-2));s # Sample Std. Dev
se<-s*sqrt(1/n+1/m);se # Standard Error of diffs
t<-qt(.975,df=n+m-2);t # t-value
e<-t*se;e # Margin of error
cil<-mx - my - e;cil # Confidence Interval(low)
ciu<-mx - my + e;ciu # Confidence Interval(high)
t.test(x,y)
```
Interpret your interval.
**Answer: We are 95% confident that the average difference in the size of the right foot between males and females in the general population falls within the range of 2.28 to 6.62 cm (in favour of the males).**
Check the normality of the relevant data using a QQ plot.
```{r q1_b_qqplot, include=TRUE}
par(mfrow=c(1,2))
qqnorm(x,xlab="Right Foot (F)") # QQPlot for women
qqline(x,col="red")
qqnorm(y,xlab="Right Foot (M)") # QQPlot for men
qqline(y,col="blue")
```
Interpret your findings.
**Answer: Neither the female or male sample data sets follow a normal distribution, having significant tails to the right and left.**
# Question 2
Of a random sample of 750 local residents, 400 were strongly opposed to the location of a hospital in the area. Does the sample provide sufficient evidence to conclude that a majority of residents oppose the new hospital?
a) What is the null hypothesis? What is the alternative hypothesis?
**Answer:**
$$H_0: p_{opposed} <= 0.50$$
$$H_A: p_{opposed} > 0.50$$
b) Perform the hypothesis test.
```{r q2_b, include=TRUE}
p<-0.50 # Population proportion (as per H0)
n<-750 # Sample size
m<-400 # Sample 'successes'
phat<-m/n;phat # Sample proportion
c<-0.95 # Level of Confidence (assumed)
alpha<-1-c;alpha # Level of Significance
tails<-1; # This is a single (right)-tailed test
if(n*phat > 10 & n*(1-phat) > 10){
print("The Normal distribution approximation condition is satisfied.")
} else {
print("The Normal distribution approximation condition is not satisfied.")
}
se<-sqrt((p*(1-p))/n);se # Standard error
z<-(phat-p)/se;z # Test Statistic (z-value)
pvalue<-tails*pnorm(-abs(z));pvalue # p-value
## Let's check the calculated value of the p-value using prop.test (without correction)
prop.test(x=m,n=n,p=p,alternative="greater",conf.level=c,correct=F)
```
Find the p-value.
**Answer: 0.03394 is the calculated p-value.**
State your conclusions.
**Answer: As the p-value is less that alpha (0.05), we can reject the Null Hypothesis ($H_0$) and conclude that the majority of residents are opposed to the proposed location of the hospital (at the 95% Level of Confidence).**
# Question 3
Suppose you have been hired to estimate the percentage of adults who are illiterate. You take a random sample of 600 adults, and find (using a standard literacy test) that 65 of them are illiterate.
a) Compute a 95% confidence interval for the percentage of the population who are illiterate.
```{r q3_a, include=TRUE}
n<-600 # Sample size
m<-65 # Sample 'successes'
phat<-m/n;phat # Sample proportion
c<-0.95 # Level of Confidence (assumed)
alpha<-1-c;alpha # Level of Significance
# Check for Normal approximation
if(n*phat>10 & n*(1-phat) > 10){
print("Normal distribution approximation condition is satisfied")} else{
print("Normal distribution approximation condition is NOT satisfied")
}
sep<-sqrt((phat*(1-phat))/n); sep # Standard Error
z<-round(abs(qnorm((alpha/2))),2);z # z-value
e<-z*sep;e # Margin of error
cil<-phat-e;cil # Lower CI value
ciu<-phat+e;ciu # Upper CI value
## Let's check the calculated values of the Confidence Interval using prop.test (without correction)
prop.test(x=m,n=n,conf.level=c,correct=F)
```
**Answer: (Calculated) 95% CI = (0.083, 0.133), when rounded to 3 decimal places**
Interpret your results.
**Answer: We can be 95% confident that the population illiteracy rate lies somewhere in the 8.3% to 13.3% range.**
b) How many people would need to be surveyed if the percentage of the population who are illiterate is required to be estimated within + or - 1% with 95% confidence?
$$se_p=\sqrt{\hat{p}(1-\hat{p})/n}$$
$$se_p^2=\hat{p}(1-\hat{p})/n$$
$$n=\hat{p}(1-\hat{p})/se_p^2$$
$$e=z*se_p$$
$$se_p=e/z$$
$$n=\hat{p}(1-\hat{p})/(e/z)^2$$
**Answer: In this case, we must find the value of n where the Margin of Error (e)=0.01 - i.e. n = 3711 (as shown below)**
```{r q3_b, include=TRUE}
n<-round((phat*(1-phat))/(0.01/z)^2);n
```
# Question 4
In 1889, Geissler collected data on 6,115 families of size 12. For each family the number of females was recorded.
```{r q4_data, include=TRUE}
female <- 0:12
nfamilies <- c(7,45,181,478,829,1112,1343,1033,670,286,104,24,3)
d <- data.frame(female=female, nfamilies=nfamilies)
d
```
Are the data consistent with the assumption of a binomial distribution?
Answer this with a chi-squared test.
Note: you will need to adjust the degrees of freedom, similar to the soccer data. You may need to pool the last two categories.
```{r q4_probs, include=TRUE}
dc<-d # Copy the data
po<-dc$nfamilies/sum(dc$nfamilies) # Calculate data probabilities
sum(po) # Check observed probabilities
dcp<-cbind(dc,po) # Append the observed probs.
prob<-sum(dcp$female*dcp$nfamilies)/(12*sum(dcp$nfamilies));prob # Female probability
pt<-dbinom(x=c(0:max(dcp$female)), # Generate the theoretical probs.
size=length(dcp$female)-1, # (as per Binomial distribution)
prob=prob)
sum(pt) # Check the theoretical probs.
dcp<-cbind(dcp,pt) # Append the theoretical probs.
dcp # Display the data with po and pt
plot(dcp$female-.1, dcp$po, lwd=4, # Plot to compare po and pt
type="h",col="blue",
xlab="Females", ylab="Probabilities")
lines(dcp$female+.1, dcp$pt, lwd=4,
type="h",col="red")
```
**The above plot shows a reasonable match between the observed and theoretical (Binomial) probabilities**
**Let's perform the following hypothesis test:**
$H_0$: $P_{observed}$ = $P_{theoretical}$
$H_A$: $P_{observed}$ <> $P_{theoretical}$
```{r q4_hypo_test, include=TRUE}
pop<-sum(po[1:2]) # Pool the first 2 and last 2
pop<-c(pop,po[3:11]) # elements of po to avoid
pop[11]<-1-sum(pop) # warning in chisq.test call
ptp<-sum(pt[1:2]) # Pool the first 2 and last 2
ptp<-c(ptp,pt[3:11]) # elements of pt to avoid
ptp[11]<-1-sum(ptp) # warning in chisq.test call
pop<-pop*sum(d$nfamilies) # Scale pop back up (values too # small for chisq.test)
ctest<-chisq.test(pop,p=ptp);ctest # Perform the Chi Squared test
pval<-1-pchisq(ctest$statistic, 9);pval
```
**Answer: As the p-value achieved above is less than that of alpha (assumed to be 0.05, in this case), we must reject $H_0$ and conclude that the sample data is not sufficiently close (for a 95% Level of Confidence) to a Binomial distribution.**
# Question 5
Market researchers know that background music can influence the mood and purchasing behaviour of customers.
One study in a supermarket in Northern Ireland compared three treatments: no music, French accordion music and Italian string music. Under each condition, the researchers recorded the number of bottles of French, Italian and other wine purchased.
```{r q5_data, include=TRUE}
d<-matrix(c(30,39,30,11,1,19,43,35,35),nrow=3)
rownames(d)<-c("French wine","Italian wine","Other wine")
colnames(d)<-c("None","French music","Italian music")
d
```
a) Is there a relationship between the type of wine purchased and the type of music that is playing?
**Answer:**
$H_0$ : There is no relationship between the type of wine purchased and the type of music that is playing.
$H_A$ : There is a relationship between the type of wine purchased and the type of music that is playing.
```{r q5_a, include=TRUE}
tab<-d
chisq.test(tab)
```
**As the p-value achieved above is less than alpha (assumed to be 0.05, in this case), we reject $H_0$ and conclude that there is a relationship between the type of wine purchased and the type of music that is playing.**
b) If the store manager wishes to improve the proportion of French wine sold, what music should she play?
Answer using a suitable barchart.
```{r q5_b, include=TRUE}
tab1 <- prop.table(tab,1)
barplot(t(tab1), legend=T, col=2:4)
```
**Answer: The bar plots above indicate that, proportionately more bottles of French wine was sold while Italian music was playing than for any of the other two wine categories.Therefore, playing more Italian music (perversely) could help to sell more French wine.**
c) Write a short summary of your conclusions.
**Answer: In addition to the previous conclusion, the following points are worthy of note:**
1. For this piece of analysis, we are assuming that, in a given period, the playing of music or not will not increase the average number of customers and that the same average number of bottles will be sold in total.
2. As the playing of French music appears to suppress the sales of Italian wine, it might also be argued that playing more French music could benefit the sales of the other wine categories (including French wine).
3. As the playing of no music appears to have more positive impact on the sales of Italian wine relative to the other 2 wine categories, playing less music might help to sell proportionally more Italian wine.
4. The sales of wine in the 'Other' category appears to be relatively less influenced by whether or not music is played, so modifying the choice of music should have relatively less impact on the proportion of sales made in that category.<file_sep>public class StringTest
{
public static void main(String args[])
{
String str = args[0]; // Declare and accept the(string) argument/parameter from the command line
System.out.println("This is the passed string: " + "\"" + str + "\"");
System.out.println("The length of that string is " + str.length());
System.out.println("This is the string's 3rd character: " + str.substring(2, 3));
}
} | 2d8e9f1c376cf2eeb834352f5456a371411e0d25 | [
"Java",
"RMarkdown"
] | 16 | RMarkdown | oriogain/Higher-Diploma-in-Data-Analytics | 12b766bfb6e5139f608b62aaff97f31880079191 | 3e114a938d67240636b7a4865d212437f4416a23 |
refs/heads/main | <repo_name>pkuyyj/PointCNN_Submit<file_sep>/sample_probability.py
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
def sample_x_distance(current_x_1, current_l_1, block_size, max_point_num):
file_size = int(current_x_1.shape[0])
print(current_x_1[0][0])
print(current_l_1[0][0])
num_size = int(current_x_1.shape[1])
return_data = []
return_label = []
for i in range(file_size):
print("This is",i)
return_data_1 = []
return_label_1 = []
max_x, max_y, max_z = np.amax(current_x_1[i], axis=0)
min_x, min_y, min_z = np.amin(current_x_1[i], axis=0)
size_x = block_size
delta_x = (max_x - min_x) / size_x
delta_y = (max_y - min_y) / size_x
h = list()
print("dealing p")
for p in range(num_size):
hx = np.floor((current_x_1[i][p][0] - min_x) / size_x)
hy = np.floor((current_x_1[i][p][1] - min_y) / size_x)
hz = np.floor((current_x_1[i][p][2] - min_z) / size_x)
h.append(hx + hy * delta_x + hz * delta_x * delta_y)
h = np.array(h)
h_indices = np.argsort(h)
h_sorted = h[h_indices]
count = 0
cnt = 0
print("appending q")
for q in range(len(h_sorted) - 1):
if h_sorted[q] == h_sorted[q + 1]:
continue
else:
point_idx = h_indices[count: q + 1]
print(np.mean(current_x_1[i][point_idx], axis=0))
print(current_l_1[i][point_idx[0]])
total_x = len(point_idx)
print(total_x)
max_label = 0
max_num = 0
for m in range(total_x):
cnt_1 = 0
for m_1 in range(total_x):
if current_l_1[i][point_idx[m]] == current_l_1[i][point_idx[m_1]]:
cnt_1 = cnt_1 + 1
if cnt_1 >= max_num:
max_num = cnt_1
max_label = current_l_1[i][point_idx[m]]
print(np.mean(current_x_1[i][point_idx], axis=0))
return_data_1.append(np.mean(current_x_1[i][point_idx], axis=0))
return_label_1.append(max_label)
count = q
cnt = cnt + 1
if cnt == max_point_num:
break
while cnt < max_point_num:
cnt = cnt + 1
t = np.array([(max_x + min_x)//2, (max_y + min_y)//2, (max_z + min_z)//2])
return_data_1.append(t)
return_label_1.append(0)
return_data.append(return_data_1)
return_label.append(return_label_1)
return_data = np.array(return_data)
return_label = np.array(return_label)
print("successful_generate")
np.save(file="sample_try_data_probability_0.npy", arr=return_data)
np.save(file="sample_try_label_probability_0.npy", arr=return_label)
print("successful_save")
<file_sep>/README.md
# PointCNN_PekingUniversity
### 算法设计与分析 项目源代码
小组成员:俞跃江 刘文睿 李畅
#### 程序说明
修改后的主程序为`train_shuffle.py`,需要用到`SemanticPOSS`数据集,在`train_shuffle.py`的`datapath`中需要修改路径为本地数据集路径
`model.py`为模型文件
生成的`log`文件夹为参数及log文件,其中`log_train.txt`为详细训练正确率记录
#### 代码运行
见`PointCNN Tensorflow安装及运行.md`
<file_sep>/PointCNN Tensorflow安装及运行.md
## PointCNN Tensorflow安装及运行
### 安装环境
系统:CentOS7 Linux
Conda版本:miniconda3
### 具体安装顺序
#### 1. 新建python3.6环境
按照Tensorflow的版本要求,需要python版本3.5-3.6,CUDA 9.0,cuDNN 7.0
```bash
conda create -n tf python=3.6
conda activate tf
```
#### 2.1 CPU版本:安装Cuda Toolkit、cuDNN、tensorflow、h5py
```bash
conda install cudnn=7.0 h5py tensorflow=1.6
```
以下用`tf_cpu`代指此环境
#### 2.2 GPU版本:
##### 2.2.1 配置CUDA环境
为了使用GPU版本的tf 1.6,需要CUDA 9.0;一般电脑和服务器都是CUDA 10以上,所以需要重装,集群上在`/opt/cuda-9.0`下,故需要在`.bashrc`中导入环境变量
```bash
export PATH=/opt/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/opt/cuda-9.0/lib64/${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
```
##### 2.2.2 安装依赖库
```bash
conda install cudnn=7.0 h5py tensorflow_gpu=1.6
```
以下用`tf_gpu`代指此环境
### 运行
#### 1.原始PointCNN.Pytorch
数据集:原始数据集
在`PointCNN.Pytorch\sem_seg`下执行
##### CPU版本:
```bash
conda activate tf_cpu
python train.py --batch_size 12 --max_epoch 50
```
##### GPU版本:
```bash
conda activate tf_gpu
CUDA_VISIBLE_DEVICES=1,2 python train.py --batch_size 24 --max_epoch 50 --gpu 0
```
注:由于GPU较快,可以适当增加batch size; CUDA_VISIBLE_DEVICES按照当时空闲GPU序号填写
此处的train.py为原始文件,需要修改`dataset`的路径并提前准备好ModelNet40和indoor_h5数据集.
运行日志保存在`log`文件夹下,具体训练日志可以通过以下方式查看
```bash
cd log
vi log_train.txt
```
#### 2.应用在SemanticPOSS上的PointCNN.Pytorch
##### CPU版本:
在`PointCNN_semantic_segmantation`下执行
```bash
conda activate tf_cpu
python train.py --batch_size 12
```
##### GPU版本:
由于POSS数据集较大,无法全部放入内存,故需要进行降采样。具体步骤如下:
```bash
cd ~/PointCNN_downs
conda activate tf_gpu
CUDA_VISIBLE_DEVICES=1,2 python train.py --batch_size 12 --max_epoch 100 --gpu 0 --learning_rate 0.001
```
实际上,只会用到一个GPU.
<file_sep>/evaluate.py
import argparse
import os
import sys
import numpy as np
import tensorflow as tf
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
import provider
from model import *
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]')
parser.add_argument('--batch_size', type=int, default=1, help='Batch Size during training [default: 1]')
parser.add_argument('--num_point', type=int, default=8196, help='Point number [default: 65536]')
parser.add_argument('--model_path', required=True, help='model checkpoint file path')
parser.add_argument('--dump_dir', required=True, help='dump folder path')
parser.add_argument('--output_filelist', required=True, help='TXT filename, filelist, each line is an output for a image')
FLAGS = parser.parse_args()
BATCH_SIZE = FLAGS.batch_size
NUM_POINT = FLAGS.num_point
MODEL_PATH = FLAGS.model_path
GPU_INDEX = FLAGS.gpu
DUMP_DIR = FLAGS.dump_dir
if not os.path.exists(DUMP_DIR): os.mkdir(DUMP_DIR)
LOG_FOUT = open(os.path.join(DUMP_DIR, 'log_evaluate.txt'), 'w')
LOG_FOUT.write(str(FLAGS)+'\n')
NUM_CLASSES = 17
# 将分类序号对应到原始数据的标记序号
# 实际只有17个类
CLASS_MAP = {0: 0, 1: 0, 2: 0, 3: 0,
4: 1,
5: 2,
6: 3,
7: 4,
8: 5,
9: 6,
10: 7,
11: 8,
12: 9,
13: 10,
14: 11,
15: 12,
16: 13,
17: 14, 18: 0, 19: 0, 20: 0,
21: 15,
22: 16}
class_map = lambda t: CLASS_MAP[t]
np_class_map = np.vectorize(class_map)
#需要设置
DATA_PATH = 'SemanticPOSS_dataset\dataset'
#默认用05序列做预测
#提取要预测的文件的序列号 如000001
RANK_LIST = [line.rstrip()[:-4] for line in open(DATA_PATH+'/sequence/05/velodyne/all_file_greater_65536.txt')]
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
def evaluate():
is_training = False
with tf.device('/gpu:'+str(GPU_INDEX)):
pointclouds_pl, labels_pl = placeholder_inputs(BATCH_SIZE, NUM_POINT)
is_training_pl = tf.placeholder(tf.bool, shape=())
# simple model
pred = get_model(pointclouds_pl, is_training_pl)
loss = get_loss(pred, labels_pl)
pred_softmax = tf.nn.softmax(pred)
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Create a session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
config.log_device_placement = True
sess = tf.Session(config=config)
# Restore variables from disk.
saver.restore(sess, MODEL_PATH)
log_string("Model restored.")
ops = {'pointclouds_pl': pointclouds_pl,
'labels_pl': labels_pl,
'is_training_pl': is_training_pl,
'pred': pred,
'pred_softmax': pred_softmax,
'loss': loss}
total_correct = 0
total_seen = 0
#输出文件
fout_out_filelist = open(FLAGS.output_filelist,'w')
for line in RANK_LIST:
out_data_label_filename = line+'_pred.txt'
out_data_label_filename = os.path.join(DUMP_DIR,out_data_label_filename)
out_true_label_filename = line + '_true.txt'
out_true_label_filename = os.path.join(DUMP_DIR, out_true_label_filename)
print(line, out_data_label_filename)
a, b = eval_one_epoch(sess, ops, line, out_data_label_filename, out_true_label_filename)
total_correct += a
total_seen += b
#输出结果
fout_out_filelist.write(out_data_label_filename+'\n')
fout_out_filelist.close()
log_string('all room eval accuracy: %f'% (total_correct / float(total_seen)))
#每轮检测只投入一帧(one image)
def eval_one_epoch(sess, ops, rank, out_data_label_filename, out_true_label_filename):
is_training = False
total_seen_class = [0 for _ in range(NUM_CLASSES)]
total_correct_class = [0 for _ in range(NUM_CLASSES)]
#打开要输出到的文件
fout_data_label = open(out_data_label_filename, 'w')
fout_true_label = open(out_true_label_filename, 'w')
#读入点的信息 这里维数先用二维的 可能有Bug
current_data, current_label = provider.load_one_image(DATA_PATH,rank)
#current_data = current_data.reshape((1,NUM_POINT,3))
#current_label = current_label.reshape((1,NUM_POINT))
feed_dict = {ops['pointclouds_pl']: current_data,
ops['labels_pl']: current_label,
ops['is_training_pl']: is_training}
loss_val, pred_val = sess.run([ops['loss'], ops['pred_softmax']],
feed_dict=feed_dict)
# If true, do not count the clutter class
pred_label = np.argmax(pred_val, 1) # N
# 为了这个map搞出来的结果
pred_label = np_class_map(pred_label)
for i in range(len(pred_label)):
fout_data_label.write("%f %f %f %f %d\n" % (current_data[i][0],current_data[i][1],current_data[i][2],pred_val[i,pred_label[i]],pred_label[i]))
fout_true_label.write("%d\n"%(current_label[i]))
currect = np.sum(pred_label == current_label)
seen = NUM_POINT
loss = loss_val
for i in range(NUM_POINT):
l = current_label[i]
total_seen_class[l] += 1
total_correct_class += 1 if pred_label[i] == l else 0
log_string('eval loss: %f' % (loss))
log_string('eval accuracy: %f'% (currect/seen))
fout_data_label.close()
fout_true_label.close()<file_sep>/sample_x.py
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
def sample_x_distance(current_x_1, current_l_1, block_size, max_point_num):
file_size = int(current_x_1.shape[0])
num_size = int(current_x_1.shape[1])
return_data = []
return_label = []
print(file_size)
for i in range(file_size):
print("This is",i)
return_data_1 = []
return_label_1 = []
max_x, max_y, max_z = np.amax(current_x_1[i], axis=0)
min_x, min_y, min_z = np.amin(current_x_1[i], axis=0)
size_x = block_size
delta_x = (max_x - min_x) / size_x
delta_y = (max_y - min_y) / size_x
h = list()
for p in range(num_size):
hx = np.floor((current_x_1[i][p][0] - min_x) / size_x)
hy = np.floor((current_x_1[i][p][1] - min_y) / size_x)
hz = np.floor((current_x_1[i][p][2] - min_z) / size_x)
h.append(hx + hy * delta_x + hz * delta_x * delta_y)
h = np.array(h)
h_indices = np.argsort(h)
h_sorted = h[h_indices]
count = 0
cnt = 0
for q in range(len(h_sorted) - 1):
if h_sorted[q] == h_sorted[q + 1]:
continue
else:
point_idx = h_indices[count: q + 1]
return_data_1.append(np.mean(current_x_1[i][point_idx], axis=0))
return_label_1.append(current_l_1[i][point_idx[0]])
count = q
cnt = cnt + 1
if cnt == max_point_num:
break
while cnt < max_point_num:
cnt = cnt + 1
t = np.array([(max_x + min_x)//2, (max_y + min_y)//2, (max_z + min_z)//2])
return_data_1.append(t)
return_label_1.append(0)
return_data.append(return_data_1)
return_label.append(return_label_1)
break
return_data = np.array(return_data)
return_label = np.array(return_label)
print(return_data.shape[0])
print("successful_generate")
np.save(file="sample_train_data_total_1.npy", arr=return_data)
np.save(file="sample_train_label_total_1.npy", arr=return_label)
print("successful_save")
| 627fbadcab0143f537ffa688f6c55436d90f885f | [
"Markdown",
"Python"
] | 5 | Python | pkuyyj/PointCNN_Submit | 32ae4d8a9dad26c5e930fd14794b32b5e6588cf4 | e16361165a068aa6137e6a433528610f98b5462b |
refs/heads/master | <file_sep>from binary_search_tree import BinarySearchTree
import time
import sys
start_time = time.time()
f = open('names_1.txt', 'r') # O(c)
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r') # O(c)
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = []
# for name_1 in names_1: #O(n)
# for name_2 in names_2: #O(n)
# if name_1 == name_2:
# duplicates.append(name_1) #O(c)
listed = BinarySearchTree(names_1[0])
for name_1 in names_1: #0(n)
listed.insert(name_1)
for name_2 in names_2: #0(n)
if listed.contains(name_2):
duplicates.append(name_2)
end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")
# runtime ----> 0(n) + 0(n) ------> 0(2n) ----> 0(n)
<file_sep>class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.current = 0
self.storage = [None]*capacity
def append(self, item):
# check if the capacity is full
# if the capacity is not full add to tail
# if the capacity is full remove from head
# then add to head.
if self.current == self.capacity:
self.current = 0
self.storage[self.current] = item
self.current +=1
def get(self):
return list(filter(None ,self.storage))
| ecdd23a4065bfd4afc8a511d8c55df270b215161 | [
"Python"
] | 2 | Python | basilcea/Sprint-Challenge--Data-Structures-Python | c0d7b79c89978bbd8e19480a0584f865f3c2c01f | 58e9fe2339799f40fc865349be4fd8d349df0bbb |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PacMan
{
public enum EntityState
{
Scatter,
Chase,
Frightened,
Eaten,
GhostPoints200,
GhostPoints400,
GhostPoints800,
GhostPoints1600
}
public class Entity
{
public int X;
public int Y;
public Direction currentDirection = Direction.RIGHT;
public Direction selectedDirection = Direction.RIGHT;
public bool IsAtIntersection = false;
public int currentSpriteNumber = 0;
public bool IsPlayerEntity = false;
public bool Visible = true;
public float Speed = 5;
public int DotCounter = 0;
public EntityState State = EntityState.Scatter;
//Bad
public Direction prevDirection = Direction.RIGHT;
private int startX;
private int startY;
private Direction startDirection = Direction.RIGHT;
public string Name;
public Entity(string name, int StartingX, int StartingY, Direction StartDirection)
{
Name = name;
startX = StartingX;
startY = StartingY;
X = StartingX;
Y = StartingY;
startDirection = StartDirection;
currentDirection = startDirection;
selectedDirection = startDirection;
}
public void ResetToStartingPosition()
{
X = startX;
Y = startY;
currentDirection = startDirection;
selectedDirection = startDirection;
}
public void ReverseDirection()
{
if (this.currentDirection == Direction.UP) this.currentDirection = Direction.DOWN;
else if (this.currentDirection == Direction.DOWN) this.currentDirection = Direction.UP;
else if (this.currentDirection == Direction.RIGHT) this.currentDirection = Direction.LEFT;
else if (this.currentDirection == Direction.LEFT) this.currentDirection = Direction.RIGHT;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Audio;
using SFML.Graphics;
using SFML.Window;
using System.Diagnostics;
namespace PacMan
{
public class MainScene : Scene
{
object[] powerSprites = new object[3];
int powerSpriteId = 0;
int entityStateCounter = 0;
int ghostEatCounter = 0;
bool reset = true;
bool gotExtraLife = false;
bool playerPause = false;
Sprite spDot;
Sprite spPower;
Sprite spReady;
Sprite spGhostPoints;
Sprite spLivesRemaining;
List<Entity> entities = new List<Entity>();
Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
static Random rnd = new Random();
System.Timers.Timer stateTimer = new System.Timers.Timer();
System.Timers.Timer frightenedTimer = new System.Timers.Timer();
const int TILEHEIGHT = 20;
const int TILEWIDTH = 20;
const int SCREENOFFSET = 10;
Text txtScore;
int score = 0;
int playerLives = 3;
Sound startSound, chompSound, energizerSound, sirenSound, playerDeathSound, eatGhostSound, extraPacSound;
Map map = new Map();
// Override Methods for the Scene
public MainScene(GameObject gameObject) : base(gameObject)
{
}
public override void Initialize()
{
// Set up score text
txtScore = new Text("Score: 0", ResourceManager.Instance.GetFont("arial"));
txtScore.Position = new Vector2f(0, 0);
txtScore.CharacterSize = 20;
// Set up player sprite
Texture texture = new Texture(@"resources\pacman-sprites.png");
Sprite sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("pacman", 26, 14, Direction.LEFT, true, texture, sp);
// And lives remaining...
spLivesRemaining = new Sprite(texture);
spLivesRemaining.TextureRect = new IntRect(2 * 40 + 160, 0, 40, 40);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-red.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("red", 14, 13, Direction.RIGHT, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-blue.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("blue", 17, 12, Direction.UP, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-pink.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("pink", 17, 14, Direction.UP, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-orange.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("orange", 17, 15, Direction.UP, false, texture, sp);
// Set up ready sprite
texture = new Texture(@"resources\ready.png");
spReady = new Sprite(texture);
spReady.Position = new Vector2f(240, 410);
frightenedTimer.Elapsed += frightenedTimer_Elapsed;
texture = new Texture(@"resources\dot.png");
spDot = new Sprite(texture);
texture = new Texture(@"resources\energizer.png");
spPower = new Sprite(texture);
spPower.TextureRect = new IntRect(0, 0, 20, 20);
startSound = ResourceManager.Instance.GetSound("begin");
chompSound = ResourceManager.Instance.GetSound("eatdot");
energizerSound = ResourceManager.Instance.GetSound("eatenergizer");
sirenSound = ResourceManager.Instance.GetSound("siren");
playerDeathSound = ResourceManager.Instance.GetSound("pacdie");
eatGhostSound = ResourceManager.Instance.GetSound("eatghost");
extraPacSound = ResourceManager.Instance.GetSound("extrapac");
base.Initialize();
}
public override void Reset()
{
map = new Map();
playerLives = 3;
score = 0;
stateTimer.Enabled = false;
frightenedTimer.Enabled = false;
gotExtraLife = false;
playerPause = false;
reset = true;
entityStateCounter = 0;
foreach (Entity e in entities)
{
e.ResetToStartingPosition();
this.UpdateSpritePosition(e);
e.Visible = false;
if (e.Name == "blue") e.DotCounter = 30;
if (e.Name == "orange") e.DotCounter = 60;
}
startSound.Play();
this.Pause(5000);
}
public override void HandleInput(KeyEventArgs e)
{
Entity player = entities.Find(x => x.Name == "pacman");
if (e.Code == Keyboard.Key.Left)
player.selectedDirection = Direction.LEFT;
if (e.Code == Keyboard.Key.Right)
player.selectedDirection = Direction.RIGHT;
if (e.Code == Keyboard.Key.Up)
player.selectedDirection = Direction.UP;
if (e.Code == Keyboard.Key.Down)
player.selectedDirection = Direction.DOWN;
if (e.Code == Keyboard.Key.P)
playerPause = (playerPause ? false : true);
if (e.Code == Keyboard.Key.Escape)
SceneManager.Instance.GotoScene("start");
}
public override void Update()
{
if (!playerPause)
{
if (playerLives == 0)
SceneManager.Instance.GotoScene("start");
else
{
UpdateScore();
foreach (Entity e in entities)
{
MoveEntity(e);
if (e.IsAtIntersection)
UpdateDirection(e);
AnimateEntity(e);
CollisionCheck(e);
}
AnimatePowerPellets();
CheckForEndOfLevel();
if (!reset && sirenSound.Status != SoundStatus.Playing)
sirenSound.Play();
}
}
}
public override void Draw()
{
DrawMap();
txtScore.Draw(_gameObject.Window, RenderStates.Default);
// Draw each entity
foreach(Entity e in entities)
if (e.Visible)
sprites[e.Name].Draw(_gameObject.Window, RenderStates.Default);
// Draw lives remaining
int lifePosition = 10;
for (int x = playerLives-1; x > 0; x--)
{
spLivesRemaining.Position = new Vector2f(lifePosition, 700);
lifePosition += 50;
spLivesRemaining.Draw(_gameObject.Window, RenderStates.Default);
}
}
public override void AfterPause()
{
foreach (Entity e in entities)
{
// We added a pause whenever a ghost is eaten so that
// the points could be displayed. Its a crude solution, but works
// Anyway, after the pause ends, if any ghost is in a points state,
// change them to an eaten state
// Ghosts and Pacman are temporarily hidden when the points are displayed also
if (!e.Visible)
e.Visible = true;
if (e.State == EntityState.GhostPoints200 ||
e.State == EntityState.GhostPoints400 ||
e.State == EntityState.GhostPoints800 ||
e.State == EntityState.GhostPoints1600)
e.State = EntityState.Eaten;
}
reset = false;
}
public override void OnPause()
{
if (reset)
{
// A pause is called so that the READY! message is displayed when a player starts
spReady.Draw(_gameObject.Window, RenderStates.Default);
}
// A pause is called when PacMan eats a ghost, so that the points are displayed
foreach (Entity e in entities)
{
if (e.State == EntityState.GhostPoints200)
{
spGhostPoints = new Sprite();
spGhostPoints.Texture = ResourceManager.Instance.GetTexture("ghostpoints");
spGhostPoints.TextureRect = new IntRect(0, 0, 80, 20);
spGhostPoints.Position = sprites[e.Name].Position;
spGhostPoints.Draw(_gameObject.Window, RenderStates.Default);
}
if (e.State == EntityState.GhostPoints400)
{
spGhostPoints = new Sprite();
spGhostPoints.Texture = ResourceManager.Instance.GetTexture("ghostpoints");
spGhostPoints.TextureRect = new IntRect(81, 0, 80, 20);
spGhostPoints.Position = sprites[e.Name].Position;
spGhostPoints.Draw(_gameObject.Window, RenderStates.Default);
}
if (e.State == EntityState.GhostPoints800)
{
spGhostPoints = new Sprite();
spGhostPoints.Texture = ResourceManager.Instance.GetTexture("ghostpoints");
spGhostPoints.TextureRect = new IntRect(161, 0, 80, 20);
spGhostPoints.Position = sprites[e.Name].Position;
spGhostPoints.Draw(_gameObject.Window, RenderStates.Default);
}
if (e.State == EntityState.GhostPoints1600)
{
spGhostPoints = new Sprite();
spGhostPoints.Texture = ResourceManager.Instance.GetTexture("ghostpoints");
spGhostPoints.TextureRect = new IntRect(241, 0, 80, 20);
spGhostPoints.Position = sprites[e.Name].Position;
spGhostPoints.Draw(_gameObject.Window, RenderStates.Default);
}
}
}
// Private Methods
private void RegisterEntity(string id, int startX, int startY, Direction startDirection, bool IsPlayerEntity, Texture texture, Sprite sprite)
{
Entity e = new Entity(id, startX, startY, startDirection);
e.IsPlayerEntity = IsPlayerEntity;
if (e.Name == "red" || e.Name == "pink") e.DotCounter = 0;
if (e.Name == "blue") e.DotCounter = 30;
if (e.Name == "orange") e.DotCounter = 60;
entities.Add(e);
sprites.Add(e.Name, sprite);
UpdateSpritePosition(e);
}
private void MoveEntity(Entity e)
{
int angle = 0;
if (e.currentDirection == Direction.RIGHT) angle = 0;
if (e.currentDirection == Direction.DOWN) angle = 90;
if (e.currentDirection == Direction.LEFT) angle = 180;
if (e.currentDirection == Direction.UP) angle = 270;
var scalex = Math.Round(Math.Cos(angle * (Math.PI / 180.0)));
var scaley = Math.Round(Math.Sin(angle * (Math.PI / 180.0)));
var velocityx = (float)(e.Speed * scalex);
var velocityy = (float)(e.Speed * scaley);
// Update the characters sprite position
Sprite sp = sprites[e.Name];
Vector2f v = new Vector2f(sp.Position.X + velocityx, sp.Position.Y + velocityy);
sp.Position = v;
// Get the center screen position of the character
var eCenterX = sp.Position.X + sp.TextureRect.Width / 2;
var eCenterY = sp.Position.Y + sp.TextureRect.Height / 2;
// Determine which tile the center of the character is in
var tileY = Math.Floor((eCenterY-SCREENOFFSET) / TILEHEIGHT);
var tileX = Math.Floor((eCenterX-SCREENOFFSET) / TILEWIDTH);
// Determine the center screen position of the tile
var tileXpos = TILEWIDTH * Math.Floor(tileX+1);
var tileYpos = TILEHEIGHT * Math.Floor(tileY+1);
// Update the entity's tile number
e.X = (int)tileY;
e.Y = (int)tileX;
// This flag determines if we can actually change directions now
if (eCenterX == tileXpos && eCenterY == tileYpos)
e.IsAtIntersection = true;
else
e.IsAtIntersection = false;
}
private void UpdateDirection(Entity e)
{
List<Direction> possibleDirections = map.PossibleEntityDirections(e);
// Perform AI if Ghost
if (!e.IsPlayerEntity)
e.selectedDirection = EntityAI(e, possibleDirections);
if (possibleDirections.Contains(e.selectedDirection))
{
e.prevDirection = e.currentDirection;
e.currentDirection = e.selectedDirection;
if (e.State == EntityState.Frightened)
e.Speed = 2.5F; // 1, 2, 2.5, 4, 5 (evenly divisible by tile size - 20)
else
e.Speed = 5;
}
if (!possibleDirections.Contains(e.currentDirection))
e.Speed = 0;
// Check for tunnels
if (map.GetTileType(e.X, e.Y + 1) == Map.TileType.RIGHTTUNNEL && e.currentDirection == Direction.RIGHT)
{
e.Y = 2;
UpdateSpritePosition(e);
}
if (map.GetTileType(e.X, e.Y - 1) == Map.TileType.LEFTTUNNEL && e.currentDirection == Direction.LEFT)
{
e.Y = 26;
UpdateSpritePosition(e);
}
}
private void CheckForEndOfLevel()
{
if (map.GetDotCount() == 0)
{
map.Reset();
foreach (Entity z in entities)
{
z.ResetToStartingPosition();
UpdateSpritePosition(z);
}
System.Threading.Thread.Sleep(2000);
}
}
private void CollisionCheck(Entity e)
{
if (e.IsPlayerEntity)
{
// If we have eaten a dot, add to the score and play the chomp sound
if (map.GetTileType(e.X, e.Y) == Map.TileType.DOT)
{
score = score + 10;
map.ClearTile(e.X, e.Y);
if (chompSound.Status != SoundStatus.Playing)
chompSound.Play();
Entity eBlue = entities.Find(x => x.Name == "blue");
Entity eOrange = entities.Find(x => x.Name == "orange");
// Dot counters are used to determine when some ghosts can leave the pen
if (eBlue.DotCounter > 0)
{
eBlue.DotCounter--;
}
else if (eBlue.DotCounter == 0 && eOrange.DotCounter > 0)
{
eOrange.DotCounter--;
}
}
if (map.GetTileType(e.X, e.Y) == Map.TileType.POWERPELLET)
{
score = score + 50;
map.ClearTile(e.X, e.Y);
foreach (Entity entity in entities)
if (!entity.IsPlayerEntity && entity.State != EntityState.Eaten)
{
entity.State = EntityState.Frightened;
entity.ReverseDirection();
}
stateTimer.Enabled = false;
frightenedTimer.Interval = 5000;
frightenedTimer.Start();
// This flag tells us how many ghosts have been eaten during this
// instance of the power pellet / energizer
// Used to determine score
ghostEatCounter = 0;
}
}
if (!e.IsPlayerEntity)
{
Entity player = entities.Find(x => x.Name == "pacman");
if (player.X == e.X && player.Y == e.Y)
{
switch (e.State)
{
case EntityState.Frightened:
{
stateTimer.Enabled = false;
switch (ghostEatCounter)
{
case 0:
e.State = EntityState.GhostPoints200;
score += 200;
break;
case 1:
e.State = EntityState.GhostPoints400;
score += 400;
break;
case 2:
e.State = EntityState.GhostPoints800;
score += 800;
break;
case 3:
e.State = EntityState.GhostPoints1600;
score += 1600;
break;
}
ghostEatCounter++;
if (ghostEatCounter > 3) ghostEatCounter = 3;
e.Visible = false;
player.Visible = false;
eatGhostSound.Play();
this.Pause(500);
break;
}
case EntityState.Chase:
case EntityState.Scatter:
{
playerDeathSound.Play();
while (playerDeathSound.Status == SoundStatus.Playing) { }
foreach (Entity z in entities)
{
z.ResetToStartingPosition();
UpdateSpritePosition(z);
}
playerLives--;
reset = true;
this.Pause(3000);
break;
}
default:
break;
}
}
}
}
private int GetManhattanDistance(int x1, int y1, int x2, int y2)
{
int d = Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
return d;
}
private void UpdateSpritePosition(Entity e)
{
Sprite sp = sprites[e.Name];
sp.Position = new Vector2f(TILEWIDTH * e.Y, TILEHEIGHT * e.X);
}
private Direction EntityAI(Entity e, List<Direction> possibleDirections)
{
// Simple AI. Much more needs to be done here. Each ghost has a different
// method of finding PacMan. This code basically just does a simple pathfind
Direction d = Direction.RIGHT;
Entity player = entities.Find(x => x.Name == "pacman");
// Avoids ghost constantly reversing directions
if (e.currentDirection == Direction.UP && possibleDirections.Contains(Direction.DOWN) && possibleDirections.Contains(Direction.UP))
possibleDirections.Remove(Direction.DOWN);
if (e.currentDirection == Direction.DOWN && possibleDirections.Contains(Direction.DOWN) && possibleDirections.Contains(Direction.UP))
possibleDirections.Remove(Direction.UP);
if (e.currentDirection == Direction.RIGHT && possibleDirections.Contains(Direction.RIGHT) && possibleDirections.Contains(Direction.LEFT))
possibleDirections.Remove(Direction.LEFT);
if (e.currentDirection == Direction.LEFT && possibleDirections.Contains(Direction.RIGHT) && possibleDirections.Contains(Direction.LEFT))
possibleDirections.Remove(Direction.RIGHT);
// Dont let ghosts go down into the ghost house if not eaten
if (e.State != EntityState.Eaten && map.IsEntityIsAboveGate(e))
possibleDirections.Remove(Direction.DOWN);
int shortestDistance = 1000;
int targetX = 0;
int targetY = 0;
// If ghosts are in the ghost house, special logic applies. We need them to exit
if (map.GetTileType(e.X, e.Y) == Map.TileType.GHOSTONLY)
{
targetX = 14;
targetY = 14;
if (e.State == EntityState.Eaten)
e.State = EntityState.Chase;
}
else
{
bool retreatMode = (e.State == EntityState.Scatter || e.State == EntityState.Frightened);
if (retreatMode && e.Name == "red")
{
targetX = 0;
targetY = 26;
}
if (retreatMode && e.Name == "blue")
{
targetX = 33;
targetY = 27;
}
if (retreatMode && e.Name == "green")
{
targetX = 33;
targetY = 0;
}
if (retreatMode && e.Name == "pink")
{
targetX = 0;
targetY = 2;
}
if (e.State == EntityState.Eaten)
{
targetX = 14;
targetY = 14;
}
else if (e.State == EntityState.Chase)
{
targetX = player.X;
targetY = player.Y;
}
}
if (possibleDirections.Contains(Direction.UP) && e.prevDirection != Direction.DOWN)
{
int z = GetManhattanDistance(targetX, targetY, e.X - 1, e.Y);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.UP;
}
}
if (possibleDirections.Contains(Direction.DOWN) && e.prevDirection != Direction.UP)
{
int z = GetManhattanDistance(targetX, targetY, e.X + 1, e.Y);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.DOWN;
}
}
if (possibleDirections.Contains(Direction.LEFT) && e.prevDirection != Direction.RIGHT)
{
int z = GetManhattanDistance(targetX, targetY, e.X, e.Y - 1);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.LEFT;
}
}
if (possibleDirections.Contains(Direction.RIGHT) && e.prevDirection != Direction.LEFT)
{
int z = GetManhattanDistance(targetX, targetY, e.X, e.Y + 1);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.RIGHT;
}
}
return d;
}
private void UpdateScore()
{
Entity player = entities.Find(x => x.Name == "pacman");
string text = "Score: " + score.ToString("000") + " "; // +" - X: " + player.X.ToString("0#") + " Y: " + player.Y.ToString("0#");
txtScore.DisplayedString = text;
if (!gotExtraLife && score > 9999)
{
gotExtraLife = true;
playerLives++;
extraPacSound.Play();
}
}
private void AnimateEntity(Entity e)
{
// Selects the sprite for the entity depending on the state
Sprite sp = sprites[e.Name];
if (e.IsPlayerEntity)
{
switch (e.currentDirection)
{
case Direction.RIGHT:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.LEFT:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 160, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.UP:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 320, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.DOWN:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 480, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
}
}
else
{
if (e.State == EntityState.Frightened)
{
if (energizerSound.Status != SoundStatus.Playing)
energizerSound.Play();
sp.TextureRect = new IntRect(320, 0, 40, 40);
}
else
{
e.currentSpriteNumber = (e.State == EntityState.Eaten ? 4 : 0);
switch (e.currentDirection)
{
case Direction.RIGHT:
e.currentSpriteNumber += 0;
break;
case Direction.LEFT:
e.currentSpriteNumber += 1;
break;
case Direction.UP:
e.currentSpriteNumber += 2;
break;
case Direction.DOWN:
e.currentSpriteNumber += 3;
break;
}
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40, 0, 40, 40);
}
}
}
private void AnimatePowerPellets()
{
spPower.TextureRect = new IntRect(powerSpriteId * 21, 0, 20, 20);
powerSpriteId++;
if (powerSpriteId == 4) powerSpriteId = 0;
}
private void DrawMap()
{
// Draw the dots
for (int x = 0; x < 33; x++)
{
for (int y = 0; y < 28; y++)
{
if (map.GetTileType(x, y) == Map.TileType.DOT)
{
spDot.Position = new Vector2f((TILEHEIGHT * y) + SCREENOFFSET, (TILEWIDTH * x) + SCREENOFFSET);
spDot.Draw(_gameObject.Window, RenderStates.Default);
}
if (map.GetTileType(x, y) == Map.TileType.POWERPELLET)
{
spPower.Position = new Vector2f((TILEHEIGHT * y) + SCREENOFFSET, (TILEWIDTH * x) + SCREENOFFSET);
spPower.Draw(_gameObject.Window, RenderStates.Default);
}
}
}
}
// Timers
void frightenedTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
frightenedTimer.Enabled = false;
foreach (Entity entity in entities)
if (!entity.IsPlayerEntity && entity.State == EntityState.Frightened)
entity.State = EntityState.Chase;
stateTimer.Enabled = true;
}
void stateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs el)
{
EntityState newState = EntityState.Scatter;
entityStateCounter++;
// Switch states for ghosts
if (entityStateCounter == 1)
{
newState = EntityState.Chase;
stateTimer.Interval = 20000;
stateTimer.Enabled = true;
}
if (entityStateCounter == 2)
{
newState = EntityState.Scatter;
stateTimer.Interval = 7000;
stateTimer.Enabled = true;
}
if (entityStateCounter == 3)
{
newState = EntityState.Chase;
stateTimer.Interval = 20000;
stateTimer.Enabled = true;
}
if (entityStateCounter == 4)
{
newState = EntityState.Scatter;
stateTimer.Interval = 5000;
stateTimer.Enabled = true;
}
if (entityStateCounter > 4)
{
newState = EntityState.Chase;
stateTimer.Enabled = false;
stateTimer.Enabled = true;
}
foreach (Entity e in entities)
{
e.State = newState;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PacMan
{
public class Map
{
public enum TileType
{
WALL,
DOT,
EMPTY,
POWERPELLET,
GHOSTONLY,
LEFTTUNNEL,
RIGHTTUNNEL,
GATE
}
private int[,] map = new int[34, 28] {
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
{ 0,3,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,3,0 },
{ 0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0 },
{ 0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0 },
{ 0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0 },
{ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 },
{ 0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0 },
{ 0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0 },
{ 0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0 },
{ 0,0,0,0,0,0,1,0,0,0,0,0,2,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,0,0,0,2,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,2,2,2,2,2,2,2,2,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,0,7,7,0,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,4,4,4,4,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,5,2,2,2,2,1,2,2,2,0,0,4,4,4,4,0,0,2,2,2,1,2,2,2,2,6,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,2,2,2,2,2,2,2,2,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0 },
{ 0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0 },
{ 0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0 },
{ 0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0 },
{ 0,3,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,3,0 },
{ 0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0 },
{ 0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0 },
{ 0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0 },
{ 0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0 },
{ 0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0 },
{ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 },
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 },
};
private int[,] orgMap;
public Map()
{
orgMap = (int[,])map.Clone();
}
public void ClearTile(int x, int y)
{
map[x, y] = 2;
}
public TileType GetTileType(int x, int y)
{
switch(map[x,y])
{
case 0: return TileType.WALL;
case 1: return TileType.DOT;
case 2: return TileType.EMPTY;
case 3: return TileType.POWERPELLET;
case 4: return TileType.GHOSTONLY;
case 5: return TileType.LEFTTUNNEL;
case 6: return TileType.RIGHTTUNNEL;
case 7: return TileType.GATE;
default:
return TileType.WALL;
}
}
public List<Direction> PossibleEntityDirections(Entity e)
{
List<Direction> possibleDirections = new List<Direction>();
if (!e.IsPlayerEntity)
{
if (GetTileType(e.X, e.Y + 1) != TileType.WALL) possibleDirections.Add(Direction.RIGHT);
if (GetTileType(e.X, e.Y - 1) != TileType.WALL) possibleDirections.Add(Direction.LEFT);
if (GetTileType(e.X + 1, e.Y) != TileType.WALL) possibleDirections.Add(Direction.DOWN);
if (GetTileType(e.X - 1, e.Y) != TileType.WALL)
{
bool addUp = false;
if(GetTileType(e.X - 1, e.Y) == TileType.GATE && e.DotCounter == 0)
addUp = true;
else if (GetTileType(e.X - 1, e.Y) != TileType.GATE)
{
// Ghosts may not move up at these locations
if ((e.X == 14 || e.X == 26) && (e.Y == 12 || e.Y == 15) && e.State != EntityState.Frightened)
addUp = false;
else
addUp = true;
}
if(addUp) possibleDirections.Add(Direction.UP);
}
}
else
{
if (GetTileType(e.X, e.Y + 1) != TileType.WALL && GetTileType(e.X, e.Y + 1) != TileType.GHOSTONLY && GetTileType(e.X, e.Y + 1) != TileType.GATE) possibleDirections.Add(Direction.RIGHT);
if (GetTileType(e.X, e.Y - 1) != TileType.WALL && GetTileType(e.X, e.Y - 1) != TileType.GHOSTONLY && GetTileType(e.X, e.Y - 1) != TileType.GATE) possibleDirections.Add(Direction.LEFT);
if (GetTileType(e.X - 1, e.Y) != TileType.WALL && GetTileType(e.X - 1, e.Y) != TileType.GHOSTONLY && GetTileType(e.X - 1, e.Y) != TileType.GATE) possibleDirections.Add(Direction.UP);
if (GetTileType(e.X + 1, e.Y) != TileType.WALL && GetTileType(e.X + 1, e.Y) != TileType.GHOSTONLY && GetTileType(e.X + 1, e.Y) != TileType.GATE) possibleDirections.Add(Direction.DOWN);
}
return possibleDirections;
}
public int GetDotCount()
{
int counter=0;
for (int x = 0; x < 34; x++)
for (int y = 0; y < 28; y++)
if (map[x, y] == 1 || map[x, y] == 3)
counter++;
return counter;
}
public void Reset()
{
map = (int[,])orgMap.Clone();
}
public bool IsEntityIsAboveGate(Entity e)
{
if (e.X == 14 && (e.Y == 13 || e.Y == 14))
return true;
else
return false;
}
public void GetTileAtLocation(int screenX, int screenY, out int tileX, out int tileY)
{
tileX = Math.Abs(screenY / 20);
tileY = Math.Abs(screenX / 20);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;
using SFML.Window;
namespace PacMan
{
public class StartScene :Scene
{
public StartScene(GameObject gameObject) : base(gameObject)
{
}
public override void HandleInput(KeyEventArgs e)
{
if (e.Code == Keyboard.Key.Space)
{
SceneManager.Instance.StartScene("main");
}
if (e.Code == Keyboard.Key.Escape)
this._gameObject.Window.Close();
base.HandleInput(e);
}
}
}
<file_sep>using System;
namespace hello_world
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
Person person = new Person ("Minh");
person.PrintMyName ();
person.DivideMyAge (0);
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name)
{
this.Name = name;
}
public void PrintMyName()
{
Console.WriteLine ("My name is: " + this.Name);
}
public void DivideMyAge(int number)
{
try {
this.Age = this.Age / number;
Console.WriteLine("My age is : " + this.Age);
}
catch (Exception ex) {
Console.Write ("Error:" + ex.Message);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;
using SFML.Audio;
namespace PacMan
{
public class ResourceManager
{
private static ResourceManager instance = null;
Dictionary<string, Texture> _textures = new Dictionary<string, Texture>();
Dictionary<string, AnimatedTexture> _animTextures = new Dictionary<string, AnimatedTexture>();
Dictionary<string, Sound> _sounds = new Dictionary<string, Sound>();
Dictionary<string, Font> _fonts = new Dictionary<string, Font>();
public static ResourceManager Instance
{
get
{
if (instance == null)
{
instance = new ResourceManager();
}
return instance;
}
}
public void LoadTextureFromFile(string name, string path)
{
Texture texture = new Texture(path);
_textures.Add(name, texture);
}
public Texture GetTexture(string name)
{
return _textures[name];
}
public void LoadAnimatedTextureFromFile(string name, string path, int columns, int rows)
{
AnimatedTexture animTexture = new AnimatedTexture();
animTexture.texture = new Texture(path);
animTexture.columns = columns;
animTexture.rows = rows;
_animTextures.Add(name, animTexture);
}
public AnimatedTexture GetAnimatedTexture(string name)
{
return _animTextures[name];
}
public AnimatedSprite GetAnimatedSprite(string upTexture, string downTexture, string rightTexture, string leftTexture)
{
AnimatedTexture up = _animTextures[upTexture];
AnimatedTexture down = _animTextures[downTexture];
AnimatedTexture right = _animTextures[rightTexture];
AnimatedTexture left = _animTextures[leftTexture];
return new AnimatedSprite(up, down, right, left);
}
public bool LoadSoundFromFile(string name, string path)
{
SoundBuffer _soundBuffer = new SoundBuffer(path);
Sound s = new Sound(_soundBuffer);
_sounds.Add(name, s);
return true;
}
public bool LoadFontFromFile(string name, string path)
{
Font font = new Font(path);
_fonts.Add(name, font);
return true;
}
public Sound GetSound(string name)
{
return _sounds[name];
}
public Font GetFont(string name)
{
return _fonts[name];
}
}
}
<file_sep>using SFML;
using SFML.Audio;
using SFML.Graphics;
using SFML.Window;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
///
/// Pacman clone
/// Written By <NAME>
/// September 2014
///
/// Demonstration of a game written in C# and SFML
///
namespace PacMan
{
public enum Direction
{
UP,
DOWN,
RIGHT,
LEFT
}
internal sealed class PacGame
{
RenderWindow _window;
object[] powerSprites = new object[3];
int powerSpriteId = 0;
int entityStateCounter = 0;
Sprite spBack;
Sprite spDot;
Sprite spPower;
Sprite spStart;
List<Entity> entities = new List<Entity>();
Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
static Random rnd = new Random();
System.Timers.Timer stateTimer = new System.Timers.Timer();
System.Timers.Timer frightenedTimer = new System.Timers.Timer();
const int TILEHEIGHT = 20;
const int TILEWIDTH = 20;
const int SCREENOFFSET = 10;
Font arial = new Font(@"resources\arial.ttf");
Text txtScore;
int score = 0;
int playerLives = 3;
SoundBuffer startBuffer, chompBuffer, energizerBuffer, sirenBuffer, playerDeathBuffer;
Sound startSound, chompSound, energizerSound, sirenSound, playerDeathSound;
Map map = new Map();
public PacGame()
{
Initialize();
LoadResources();
}
public void Initialize()
{
// Initialize values
_window = new RenderWindow(new VideoMode(1024u, 768u), "PacMan");
_window.SetVisible(true);
_window.SetVerticalSyncEnabled(true);
// Set up event handlers
_window.Closed += new EventHandler(OnClosed);
_window.KeyPressed += _window_KeyPressed;
// Set up score text
txtScore = new Text("Score: 0", arial);
txtScore.Position = new Vector2f(0, 0);
txtScore.CharacterSize = 20;
// Set up player sprite
Texture texture = new Texture(@"resources\pacman-sprites.png");
Sprite sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("pacman", 26, 14, Direction.LEFT, true, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-red.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("red", 14, 13, Direction.RIGHT, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-blue.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("blue", 17, 12, Direction.UP, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-pink.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("pink", 17, 14, Direction.UP, false, texture, sp);
// Set up a ghost
texture = new Texture(@"resources\ghost-sprites-orange.png");
sp = new Sprite(texture, new IntRect(0, 0, 40, 40));
RegisterEntity("green", 17, 15, Direction.UP, false, texture, sp);
frightenedTimer.Elapsed += frightenedTimer_Elapsed;
}
private void LoadResources()
{
// Set up start screen graphics
Texture txStart = new Texture(@"resources\logo.png");
spStart = new Sprite(txStart);
// Main game screen background
Texture txBack = new Texture(@"resources\back.png");
spBack = new Sprite(txBack);
Texture txDot = new Texture(@"resources\dot.png");
spDot = new Sprite(txDot);
powerSprites[0] = new Texture(@"resources\power-1.png");
powerSprites[1] = new Texture(@"resources\power-2.png");
powerSprites[2] = new Texture(@"resources\power-3.png");
spPower = new Sprite((Texture)powerSprites[powerSpriteId]);
startBuffer = new SFML.Audio.SoundBuffer(@"resources\pacman_beginning.wav");
startSound = new SFML.Audio.Sound(startBuffer);
chompBuffer = new SFML.Audio.SoundBuffer(@"resources\dot.wav");
chompSound = new SFML.Audio.Sound(chompBuffer);
energizerBuffer = new SFML.Audio.SoundBuffer(@"resources\energizer.wav");
energizerSound = new SFML.Audio.Sound(energizerBuffer);
sirenBuffer = new SFML.Audio.SoundBuffer(@"resources\siren.wav");
sirenSound = new SFML.Audio.Sound(sirenBuffer);
playerDeathBuffer = new SFML.Audio.SoundBuffer(@"resources\pacman_death.wav");
playerDeathSound = new SFML.Audio.Sound(playerDeathBuffer);
}
private void RegisterEntity(string id, int startX, int startY, Direction startDirection, bool IsPlayerEntity, Texture texture, Sprite sprite)
{
Entity e = new Entity(id, startX, startY, startDirection);
e.IsPlayerEntity = IsPlayerEntity;
entities.Add(e);
sprites.Add(e.Name, sprite);
UpdateSpritePosition(e);
}
public void Run()
{
// Main game loop routine
stateTimer.Interval = 7000;
stateTimer.Elapsed += stateTimer_Elapsed;
stateTimer.Enabled = true;
Stopwatch timer = Stopwatch.StartNew();
TimeSpan dt = TimeSpan.FromSeconds(3);
TimeSpan elapsedTime = TimeSpan.Zero;
timer.Restart();
elapsedTime = timer.Elapsed;
while (_window.IsOpen())
{
startSound.Play();
while (playerLives > 0)
{
if (elapsedTime >= dt)
{
if (sirenSound.Status != SoundStatus.Playing && startSound.Status != SoundStatus.Playing)
sirenSound.Play();
DrawMap();
UpdateScore();
foreach (Entity e in entities)
{
MoveEntity(e);
AnimateEntity(e);
CheckEntityForCollision(e);
}
foreach (KeyValuePair<string, Sprite> entry in sprites)
entry.Value.Draw(_window, RenderStates.Default);
AnimatePowerPellets();
CheckForEndOfLevel();
_window.Display();
while (startSound.Status == SFML.Audio.SoundStatus.Playing) { };
timer.Restart();
elapsedTime = timer.Elapsed;
}
else
{
_window.DispatchEvents();
elapsedTime += TimeSpan.FromSeconds(1.0 / 1000.0); // dt;
}
}
break;
}
}
private void MoveEntity(Entity e)
{
List<Direction> possibleDirections = map.PossibleEntityDirections(e);
// Perform AI if Ghost
if (!e.IsPlayerEntity && e.IsAtIntersection)
e.selectedDirection = EntityAI(e, possibleDirections);
if (e.IsAtIntersection && possibleDirections.Contains(e.selectedDirection))
{
e.prevDirection = e.currentDirection;
e.currentDirection = e.selectedDirection;
}
if (possibleDirections.Contains(e.currentDirection))
UpdateEntityCoords(e);
// Check for tunnels
if (map.GetTileType(e.X, e.Y + 1) == Map.TileType.RIGHTTUNNEL && e.currentDirection == Direction.RIGHT)
{
e.Y = 2;
UpdateSpritePosition(e);
}
if (map.GetTileType(e.X, e.Y - 1) == Map.TileType.LEFTTUNNEL && e.currentDirection == Direction.LEFT)
{
e.Y = 26;
UpdateSpritePosition(e);
}
}
private void CheckForEndOfLevel()
{
// Check for end
// TODO: Add an actual end / restart
if (map.GetDotCount() == 0)
{
map.Reset();
foreach (Entity z in entities)
{
z.ResetToStartingPosition();
UpdateSpritePosition(z);
}
System.Threading.Thread.Sleep(2000);
}
}
private void CheckEntityForCollision(Entity e)
{
// Check for collisions
if (!e.IsPlayerEntity)
{
Entity player = entities.Find(x => x.Name == "pacman");
if (player.X == e.X && player.Y == e.Y)
{
switch (e.State)
{
case EntityState.Frightened:
{
e.State = EntityState.Eaten;
stateTimer.Enabled = false;
break;
}
case EntityState.Chase:
case EntityState.Scatter:
{
playerDeathSound.Play();
while (playerDeathSound.Status == SoundStatus.Playing) { }
foreach (Entity z in entities)
{
z.ResetToStartingPosition();
//z.State = EntityState.Scatter;
UpdateSpritePosition(z);
}
playerLives--;
System.Threading.Thread.Sleep(2000);
break;
}
default:
break;
}
}
}
}
private int GetManhattanDistance(int x1, int y1, int x2, int y2)
{
int d = Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
return d;
}
private void UpdateSpritePosition(Entity e)
{
Sprite sp = sprites[e.Name];
sp.Position = new Vector2f(20 * e.Y, 20 * e.X);
}
private Direction EntityAI(Entity e, List<Direction> possibleDirections)
{
Direction d = Direction.RIGHT;
Entity player = entities.Find(x => x.Name == "pacman");
// Avoids ghost constantly reversing directions
if (e.currentDirection == Direction.UP && possibleDirections.Contains(Direction.DOWN) && possibleDirections.Contains(Direction.UP))
possibleDirections.Remove(Direction.DOWN);
if (e.currentDirection == Direction.DOWN && possibleDirections.Contains(Direction.DOWN) && possibleDirections.Contains(Direction.UP))
possibleDirections.Remove(Direction.UP);
if (e.currentDirection == Direction.RIGHT && possibleDirections.Contains(Direction.RIGHT) && possibleDirections.Contains(Direction.LEFT))
possibleDirections.Remove(Direction.LEFT);
if (e.currentDirection == Direction.LEFT && possibleDirections.Contains(Direction.RIGHT) && possibleDirections.Contains(Direction.LEFT))
possibleDirections.Remove(Direction.RIGHT);
// Dont let ghosts go down into the ghost house if not eaten
if (e.State != EntityState.Eaten && map.IsEntityIsAboveGate(e))
possibleDirections.Remove(Direction.DOWN);
int shortestDistance = 1000;
int targetX = 0;
int targetY = 0;
// If ghosts are in the ghost house, special logic applies. We need them to exit
if (map.GetTileType(e.X, e.Y) == Map.TileType.GHOSTONLY)
{
targetX = 14;
targetY = 14;
if (e.State == EntityState.Eaten)
e.State = EntityState.Chase;
}
else
{
bool retreatMode = (e.State == EntityState.Scatter || e.State == EntityState.Frightened);
if (retreatMode && e.Name == "red")
{
targetX = 0;
targetY = 26;
}
if (retreatMode && e.Name == "blue")
{
targetX = 33;
targetY = 27;
}
if (retreatMode && e.Name == "green")
{
targetX = 33;
targetY = 0;
}
if (retreatMode && e.Name == "pink")
{
targetX = 0;
targetY = 2;
}
if (e.State == EntityState.Eaten)
{
targetX = 14;
targetY = 14;
}
else if (e.State == EntityState.Chase)
{
targetX = player.X;
targetY = player.Y;
}
}
if (possibleDirections.Contains(Direction.UP) && e.prevDirection != Direction.DOWN)
{
int z = GetManhattanDistance(targetX, targetY, e.X - 1, e.Y);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.UP;
}
}
if (possibleDirections.Contains(Direction.DOWN) && e.prevDirection != Direction.UP)
{
int z = GetManhattanDistance(targetX, targetY, e.X + 1, e.Y);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.DOWN;
}
}
if (possibleDirections.Contains(Direction.LEFT) && e.prevDirection != Direction.RIGHT)
{
int z = GetManhattanDistance(targetX, targetY, e.X, e.Y - 1);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.LEFT;
}
}
if (possibleDirections.Contains(Direction.RIGHT) && e.prevDirection != Direction.LEFT)
{
int z = GetManhattanDistance(targetX, targetY, e.X, e.Y + 1);
if (z < shortestDistance)
{
shortestDistance = z;
d = Direction.RIGHT;
}
}
return d;
}
private void UpdateScore()
{
Entity player = entities.Find(x => x.Name == "pacman");
string text = "Score: " + score.ToString("000") + " "; // +" - X: " + player.X.ToString("0#") + " Y: " + player.Y.ToString("0#");
txtScore.DisplayedString = text;
txtScore.Draw(_window, RenderStates.Default);
}
private void AnimateEntity(Entity e)
{
// Locate the sprite
Sprite sp = sprites[e.Name];
if (e.IsPlayerEntity)
{
switch (e.currentDirection)
{
case Direction.RIGHT:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.LEFT:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 160, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.UP:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 320, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
case Direction.DOWN:
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40 + 480, 0, 40, 40);
e.currentSpriteNumber++;
if (e.currentSpriteNumber == 4) e.currentSpriteNumber = 0;
break;
}
}
else
{
if (e.State != EntityState.Frightened)
{
if (e.State == EntityState.Eaten)
e.currentSpriteNumber = 4;
else
e.currentSpriteNumber = 0;
switch (e.currentDirection)
{
case Direction.RIGHT:
e.currentSpriteNumber += 0;
break;
case Direction.LEFT:
e.currentSpriteNumber += 1;
break;
case Direction.UP:
e.currentSpriteNumber += 2;
break;
case Direction.DOWN:
e.currentSpriteNumber += 3;
break;
}
sp.TextureRect = new IntRect(e.currentSpriteNumber * 40, 0, 40, 40);
}
else
{
if (energizerSound.Status != SoundStatus.Playing)
energizerSound.Play();
sp.TextureRect = new IntRect(320, 0, 40, 40);
}
}
}
private void AnimatePowerPellets()
{
spPower.Texture = (Texture)powerSprites[powerSpriteId];
powerSpriteId++;
if (powerSpriteId == 3) powerSpriteId = 0;
}
void UpdateEntityCoords(Entity e)
{
int mx = 0;
int my = 0;
int speed = 5;
//if (e.State == EntityState.Frightened)
// speed = 1;
// Pixels to move the character
if (e.currentDirection == Direction.RIGHT) mx = +speed;
if (e.currentDirection == Direction.LEFT) mx = -speed;
if (e.currentDirection == Direction.UP) my = -speed;
if (e.currentDirection == Direction.DOWN) my = +speed;
// Locate the sprite
Sprite sp = sprites[e.Name];
Vector2f v = new Vector2f(sp.Position.X, sp.Position.Y);
v.X += mx;
v.Y += my;
// Update its position
sp.Position = v;
// if the character has moved directly into a tile
// (Movement happens anyway in order to have a smooth transition from one tile to another)
if (Math.Round(sp.Position.Y / TILEWIDTH) == (sp.Position.Y / TILEWIDTH) &&
Math.Round(sp.Position.X / TILEHEIGHT) == (sp.Position.X / TILEHEIGHT))
{
// Update the player's tile number
e.X = (int)(sp.Position.Y / TILEWIDTH);
e.Y = (int)(sp.Position.X / TILEHEIGHT);
if (e.IsPlayerEntity)
{
// If we have eaten a dot, add to the score and play the chomp sound
if (map.GetTileType(e.X, e.Y) == Map.TileType.DOT)
{
score = score + 10;
if (chompSound.Status != SoundStatus.Playing)
chompSound.Play();
}
if (map.GetTileType(e.X, e.Y) == Map.TileType.POWERPELLET)
{
score = score + 50;
foreach (Entity entity in entities)
if (!entity.IsPlayerEntity)
entity.State = EntityState.Frightened;
stateTimer.Enabled = false;
frightenedTimer.Interval = 5000;
frightenedTimer.Start();
}
// Set the space we are on to empty (eaten)
if (map.GetTileType(e.X, e.Y) == Map.TileType.DOT || map.GetTileType(e.X, e.Y) == Map.TileType.POWERPELLET)
map.ClearTile(e.X, e.Y);
}
// We can safely process directional changes now
e.IsAtIntersection = true;
}
else
e.IsAtIntersection = false;
}
void frightenedTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
stateTimer.Enabled = true;
foreach (Entity entity in entities)
if (!entity.IsPlayerEntity && entity.State != EntityState.Eaten)
entity.State = EntityState.Chase;
stateTimer.Enabled = true;
frightenedTimer.Enabled = false;
}
void stateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs el)
{
EntityState newState = EntityState.Scatter;
entityStateCounter++;
// Switch states for ghosts
if (entityStateCounter == 1)
{
newState = EntityState.Chase;
stateTimer.Interval = 20000;
//stateTimer.Enabled = true;
}
if (entityStateCounter == 2)
{
newState = EntityState.Scatter;
stateTimer.Interval = 7000;
//stateTimer.Enabled = true;
}
if (entityStateCounter == 3)
{
newState = EntityState.Chase;
stateTimer.Interval = 20000;
//stateTimer.Enabled = true;
}
if (entityStateCounter == 4)
{
newState = EntityState.Scatter;
stateTimer.Interval = 5000;
//stateTimer.Enabled = true;
}
if (entityStateCounter > 4)
{
newState = EntityState.Chase;
stateTimer.Enabled = false;
//stateTimer.Enabled = true;
}
foreach (Entity e in entities)
{
e.State = newState;
}
}
void _window_KeyPressed(object sender, KeyEventArgs e)
{
Entity player = entities.Find(x => x.Name == "pacman");
if (e.Code == Keyboard.Key.Left)
player.selectedDirection = Direction.LEFT;
if (e.Code == Keyboard.Key.Right)
player.selectedDirection = Direction.RIGHT;
if (e.Code == Keyboard.Key.Up)
player.selectedDirection = Direction.UP;
if (e.Code == Keyboard.Key.Down)
player.selectedDirection = Direction.DOWN;
}
void OnClosed(object sender, EventArgs e)
{
_window.Close();
}
void DrawMap()
{
_window.Clear(Color.Black);
// Draw the background
spBack.Position = new Vector2f(SCREENOFFSET, SCREENOFFSET);
spBack.Draw(_window, RenderStates.Default);
// Draw the dots
for (int x = 0; x < 33; x++)
{
for (int y = 0; y < 28; y++)
{
if (map.GetTileType(x, y) == Map.TileType.DOT)
{
spDot.Position = new Vector2f((TILEHEIGHT * y) + SCREENOFFSET, (TILEWIDTH * x) + SCREENOFFSET);
spDot.Draw(_window, RenderStates.Default);
}
if (map.GetTileType(x, y) == Map.TileType.POWERPELLET)
{
spPower.Position = new Vector2f((TILEHEIGHT * y) + SCREENOFFSET, (TILEWIDTH * x) + SCREENOFFSET);
spPower.Draw(_window, RenderStates.Default);
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Window;
using SFML.Graphics;
using SFML.Audio;
namespace PacMan
{
public class GameObject
{
private RenderWindow _window;
public RenderWindow Window { get { return this._window; } }
public GameObject()
{
// Initialize values
_window = new RenderWindow(new VideoMode(1024u, 768u), "PacMan");
_window.SetVisible(true);
_window.SetVerticalSyncEnabled(true);
// Set up event handlers
_window.Closed += _window_Closed;
_window.KeyPressed += _window_KeyPressed;
}
void _window_KeyPressed(object sender, KeyEventArgs e)
{
SceneManager.Instance.CurrentScene.HandleInput(e);
}
void _window_Closed(object sender, EventArgs e)
{
_window.Close();
}
private void Initialize()
{
ResourceManager.Instance.LoadTextureFromFile("start", @"resources\logo.png");
ResourceManager.Instance.LoadTextureFromFile("main", @"resources\back.png");
ResourceManager.Instance.LoadTextureFromFile("ghostpoints", @"resources\ghostpoints.png");
ResourceManager.Instance.LoadSoundFromFile("begin", @"resources\pacman_beginning.wav");
ResourceManager.Instance.LoadSoundFromFile("eatdot", @"resources\dot.wav");
ResourceManager.Instance.LoadSoundFromFile("eatenergizer", @"resources\energizer.wav");
ResourceManager.Instance.LoadSoundFromFile("siren", @"resources\siren.wav");
ResourceManager.Instance.LoadSoundFromFile("pacdie", @"resources\pacman_death.wav");
ResourceManager.Instance.LoadSoundFromFile("eatghost", @"resources\pacman_eatghost.wav");
ResourceManager.Instance.LoadSoundFromFile("extrapac", @"resources\pacman_extrapac.wav");
ResourceManager.Instance.LoadFontFromFile("arial", @"resources\arial.ttf");
}
public void Run()
{
this.Initialize();
// Build the startup menu scene
StartScene s = new StartScene(this);
s.Name = "start";
s.BackgroundTexture = ResourceManager.Instance.GetTexture("start");
SceneManager.Instance.AddScene(s);
// Build the main game scene
MainScene d = new MainScene(this);
d.Name = "main";
d.BackgroundTexture = ResourceManager.Instance.GetTexture("main");
SceneManager.Instance.AddScene(d);
// Start the game
SceneManager.Instance.GotoScene("start");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace falling_rocks
{
class MainClass
{
/**
* This is your MAIN PROGRAM
*/
static void Main(string[] args)
{
// The width of player field
int playFieldWidth = 20;
int livesCount = 5;
// Start score
int score = 0;
// Console size
Console.BufferHeight = Console.WindowHeight = 20;
Console.BufferWidth = Console.WindowWidth = 40;
// Define new dwarf
Dwarf userDwarf = new Dwarf();
userDwarf.x = 10;
userDwarf.y = Console.WindowHeight - 1;
// Default dwarf icon
userDwarf.c = "(0)";
userDwarf.color = ConsoleColor.Green;
Random randomGen = new Random();
List<Dwarf> objList = new List<Dwarf>();
while (true)
{
bool hit = false;
int variations = randomGen.Next(0, 100);
if (variations <= 10)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Cyan;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "^";
objList.Add(objectOne);
}else if (variations>10 && variations<=20)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Magenta;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "@";
objList.Add(objectOne);
}
else if (variations>20 && variations<=30)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Yellow;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "*";
objList.Add(objectOne);
}
else if (variations > 30 && variations <= 40)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.DarkYellow;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "&";
objList.Add(objectOne);
}
else if (variations > 40 && variations <= 50)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Gray;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "+";
objList.Add(objectOne);
}
else if (variations > 50 && variations <= 60)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Magenta;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "%";
objList.Add(objectOne);
}
else if (variations > 60 && variations <= 70)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Yellow;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "$";
objList.Add(objectOne);
}
else if (variations > 70 && variations <= 80)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.White;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "#";
objList.Add(objectOne);
}
else if (variations > 80 && variations <= 85)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.Blue;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = "!";
objList.Add(objectOne);
}
else if (variations > 85 && variations <= 90)
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.DarkMagenta;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = ".";
objList.Add(objectOne);
}
else
{
Dwarf objectOne = new Dwarf();
objectOne.color = ConsoleColor.DarkRed;
objectOne.x = randomGen.Next(0, playFieldWidth);
objectOne.y = 0;
objectOne.c = ",";
objList.Add(objectOne);
}
if (Console.KeyAvailable)
{
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
ConsoleKeyInfo pressedKey = Console.ReadKey(true);
if (pressedKey.Key == ConsoleKey.LeftArrow)
{
if ((userDwarf.x - 1) >= 0)
{
userDwarf.x = userDwarf.x - 1;
}
}
else if (pressedKey.Key == ConsoleKey.RightArrow)
{
if ((userDwarf.x + 1) < playFieldWidth)
{
userDwarf.x = userDwarf.x + 1;
}
}
}
List<Dwarf> newList = new List<Dwarf>();
for (int i = 0; i < objList.Count; i++)
{
Dwarf oldDwarf = objList[i];
Dwarf objectOne = new Dwarf();
objectOne.x = oldDwarf.x;
objectOne.y = oldDwarf.y + 1;
objectOne.c = oldDwarf.c;
objectOne.color = oldDwarf.color;
if (objectOne.y == userDwarf.y && (objectOne.x == userDwarf.x || objectOne.x == (userDwarf.x + 1) || objectOne.x == (userDwarf.x + 2)))
{
livesCount--;
// As the dwarf hits a rock, the score is downgrade. You can change it!
score-=100;
hit = true;
if (livesCount <= 0)
{
PrintStatOnPosition(2, 10, "GAME OVER!", ConsoleColor.Red);
PrintStatOnPosition(2, 11, "Press ENTER to exit", ConsoleColor.Red);
Console.ReadLine();
Environment.Exit(0);
}
}
if (objectOne.y < Console.WindowHeight)
{
newList.Add(objectOne);
// The score is increased, you can change it!
score++;
}
}
objList = newList;
Console.Clear();
PrintOnPosition(userDwarf.x, userDwarf.y, userDwarf.c, userDwarf.color);
foreach (var dwarf in objList)
{
if (hit)
{
Console.Clear();
PrintOnPosition(userDwarf.x, userDwarf.y, "#", ConsoleColor.Red);
}
else
{
PrintOnPosition(dwarf.x, dwarf.y, dwarf.c, dwarf.color);
}
}
PrintStatOnPosition(25, 10, "Lives:" + livesCount, ConsoleColor.White);
PrintStatOnPosition(25, 9, "Score:" + score, ConsoleColor.Yellow);
Thread.Sleep(150);
}
}
static void PrintOnPosition( int x, int y, string c, ConsoleColor color = ConsoleColor.White)
{
Console.SetCursorPosition(x, y);
Console.ForegroundColor = color;
Console.Write(c);
}
static void PrintStatOnPosition(int x, int y, string c, ConsoleColor color = ConsoleColor.Gray)
{
Console.SetCursorPosition(x, y);
Console.ForegroundColor = color;
Console.Write(c);
}
}
struct Dwarf
{
public int x;
public int y;
public string c;
public ConsoleColor color;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;
using SFML.Window;
namespace PacMan
{
public class SceneManager
{
private static SceneManager instance = null;
Dictionary<string, Scene> _scenes = new Dictionary<string, Scene>();
public Scene CurrentScene = null;
public static SceneManager Instance
{
get
{
if (instance == null)
{
instance = new SceneManager();
}
return instance;
}
}
public void AddScene(Scene s)
{
_scenes.Add(s.Name, s);
s.Initialize();
}
public void StartScene(string name)
{
CurrentScene = _scenes[name];
CurrentScene.Reset();
CurrentScene.Run();
}
public void GotoScene(string name)
{
CurrentScene = _scenes[name];
CurrentScene.Run();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;
using SFML.Window;
using System.Diagnostics;
namespace PacMan
{
public class Scene
{
public string Name;
public Texture BackgroundTexture;
DateTime currentTime = System.DateTime.Now;
DateTime targetTime = System.DateTime.Now;
private bool pause = false;
private int pauseSeconds = 0;
protected GameObject _gameObject;
protected Sprite BackSprite;
public Scene(GameObject gameObject)
{
_gameObject = gameObject;
}
public virtual void Initialize()
{
// This method is called when the Scene object is created
if (this.BackgroundTexture == null)
BackSprite = new Sprite();
else
BackSprite = new Sprite(this.BackgroundTexture);
}
public virtual void Reset()
{
// This method is called when the Scene is reset
}
public void Run()
{
// This is the main loop for the scene
Stopwatch timer = Stopwatch.StartNew();
TimeSpan dt = TimeSpan.FromSeconds(3);
TimeSpan elapsedTime = TimeSpan.Zero;
timer.Restart();
elapsedTime = timer.Elapsed;
while (_gameObject.Window.IsOpen())
{
currentTime = System.DateTime.Now;
if (elapsedTime >= dt)
{
_gameObject.Window.Clear(Color.Black);
this.DrawBackground();
if (!pause)
{
this.Update();
}
else
{
if (currentTime > targetTime)
{
pause = false;
this.AfterPause();
}
else
this.OnPause();
}
this.Draw();
_gameObject.Window.Display();
this.AfterDraw();
timer.Restart();
elapsedTime = timer.Elapsed;
}
else
{
_gameObject.Window.DispatchEvents();
elapsedTime += TimeSpan.FromSeconds(1.0 / 1000.0); // dt;
}
}
}
public virtual void HandleInput(KeyEventArgs e)
{
// This is the input handler for the scene
}
public virtual void DrawBackground()
{
BackSprite.Draw(_gameObject.Window, RenderStates.Default);
}
public virtual void Update()
{
// This is the update method for the scene. It will call entity update methods
}
public virtual void Draw()
{
// This is the draw method for the scene. It will call entity draw methods
}
public virtual void AfterDraw()
{
// This method is called after the window drawing is complete
}
public void Pause(int milliseconds)
{
targetTime = currentTime.AddMilliseconds(milliseconds);
pause = true;
}
public virtual void OnPause()
{
// This method is called each frame during the pause
}
public virtual void AfterPause()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;
using SFML.Window;
namespace PacMan
{
public class AnimatedTexture
{
public Texture texture;
public int rows;
public int columns;
public int currentFrame = 0;
public int totalFrames
{
get { return rows * columns; }
}
}
public class AnimatedSprite : Sprite
{
private Dictionary<string, AnimatedTexture> textures = new Dictionary<string, AnimatedTexture>();
public Direction Facing = Direction.RIGHT;
public AnimatedSprite(AnimatedTexture upTexture, AnimatedTexture downTexture, AnimatedTexture rightTexture, AnimatedTexture leftTexture)
{
textures.Add("right", rightTexture);
textures.Add("left", leftTexture);
textures.Add("up", upTexture);
textures.Add("down", downTexture);
}
public void Update(Direction d)
{
AnimatedTexture t = textures["right"];
if (d == Direction.RIGHT) t = textures["right"];
if (d == Direction.LEFT) t = textures["left"];
if (d == Direction.UP) t = textures["up"];
if (d == Direction.DOWN) t = textures["down"];
t.currentFrame++;
if (t.currentFrame == t.totalFrames)
t.currentFrame = 0;
int width = (int)t.texture.Size.X / t.columns;
int height = (int)t.texture.Size.Y / t.rows;
int row = (int)((float)t.currentFrame / (float)t.columns);
int column = t.currentFrame % t.columns;
base.Texture = t.texture;
base.TextureRect = new IntRect(width * column, height * row, width, height);
}
}
}
<file_sep># FIT451SourceCode
The source code for FIT451 - .NET Technology 2015
| 2c69592776d606984c624662361069cdc8b6b974 | [
"Markdown",
"C#"
] | 13 | C# | minhprg/FIT451SourceCode | 910b4d43553d85a05f80d5de0e487efbafbd3643 | c53ee6cbe4a16090c804db35441ec5a95fd3297d |
refs/heads/master | <file_sep><?php
/**
* This file has all the auxilory functions regarding the display of content and its editing
*/
//function to validate internal links
function verify_internal_link($link) {
global $mysqli;
$title_query = $mysqli->query("SELECT page_title FROM page WHERE page_title='$link'");
if($title_query->num_rows == 0) return FALSE;
else return TRUE;
}
function text_to_link($text) {
preg_match_all("/\[\[[a-zA-Z *]*\]\]/", $text, $output_array);
foreach ($output_array[0] as &$value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = str_replace("*", "", $value_new);
if(verify_internal_link($value_new)) {
$value_link = preg_replace("/[ ]/", "_", $value_new);
$link = '<a href="articles/'.$value_link.'" class="internal true link">'.$value_new.'</a>';
$text = str_replace($value, $link, $text);
}
else {
$value_link = preg_replace("/[ ]/", "_", $value_new);
$link = '<a href="Javascript:void(0);" class="internal false link">'.$value_new.'</a>';
$text = str_replace($value, $link, $text);
}
}
return $text;
}
function text_to_external_link($text) {
preg_match_all("/--[a-zA-Z \/\+?&:\.\*0-9]*--/", $text, $output_array);
foreach ($output_array[0] as &$value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = str_replace("*", "", $value_new);
$link_parts = explode("++", $value_new);
$link = '<a target="_blank" href="'.$link_parts[0].'" class="external link">'.$link_parts[1].'</a>';
$text = str_replace($value, $link, $text);
}
return $text;
}
//function to convert <a href="Article_Name">Article Name</a> to [[Article Name]]
function link_to_text($text) {
preg_match_all("/\<a href=\"[a-zA-Z_\/]*\" class=\"[a-zA-Z-]*\">[a-zA-Z ]*<\/a>/", $text, $output_array);
foreach ($output_array[0] as &$value) {
preg_match("/>[a-zA-Z ]*</", $value, $output_value);
$len = strlen($output_value[0]);
$value_new = substr($output_value[0], 1, $len-2);
$value_new = '[['.$value_new.']]';
$text = str_replace($value, $value_new, $text);
}
return $text;
}
function external_link_to_text($text) {
return $text;
}
function text_searchable($text) {
preg_match_all("/\[\[[a-zA-Z \*]*\]\]/", $text, $output_array);
foreach ($output_array[0] as &$value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = str_replace("*", "", $value_new);
$value_new = "[[".$value_new."]]";
$text = str_replace($value, $value_new, $text);
}
preg_match_all("/--[a-zA-Z0-9&?\+\.:\/ \*]*--/", $text, $output_array_2);
foreach ($output_array_2[0] as $value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = str_replace("*", "", $value_new);;
$value_new = "--".$value_new."--";
$text = str_replace($value, $value_new, $text);
}
return $text;
}
function text_unsearchable($text) {
preg_match_all("/\[\[[a-zA-Z ]*\]\]/", $text, $output_array);
foreach ($output_array[0] as &$value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = chunk_split($value_new, 1, "*");
$value_new = "[[".$value_new."]]";
$text = str_replace($value, $value_new, $text);
}
preg_match_all("/--[a-zA-Z0-9&?\+\.:\/ ]*--/", $text, $output_array_2);
foreach ($output_array_2[0] as $value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
$value_new = chunk_split($value_new, 1, "*");
$value_new = "--".$value_new."--";
$text = str_replace($value, $value_new, $text);
}
return $text;
}
?><file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$error = "";
if(isset($_POST['uploadSubmit'])) {
$id = $_POST['primary_select'];
if(!empty($_FILES["imageFile"])) {
$pdf = $_FILES["imageFile"];
if($pdf["error"] !== UPLOAD_ERR_OK) {
$error = "An error occured during the file upload.";
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $pdf['tmp_name']);
if($mime == "image/jpeg") {
$name = $pdf['name'];
$article_query = $mysqli->query("SELECT * FROM primary_category WHERE cat_id = '$id'");
$article_result = $article_query->fetch_assoc();
$name = str_replace(" ", "_", $article_result['cat_name'].".jpg");
$success = move_uploaded_file($pdf["tmp_name"], UPLOAD_IMAGE_DIR.$name);
if(!$success) {
$error = "Unable to save the file. Please try again.";
}
else {
chmod(UPLOAD_IMAGE_DIR.$name, 0644);
header("Location: confirmcatmod.php?status=7");
}
}
else {
$error = "Incorrect format of the upload.";
}
}
else {
$error = "Please select a file to upload.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div class="container" style="padding-top:5rem">
<h3>Upload image</h3>
<!--Form for adding a new secondary category of articles-->
<form action="workspace/cat/uploadprimary.php" method="POST" name="uploadForm" id="uploadForm" enctype="multipart/form-data">
<div id="primary_cat">
Primary Category
<select id="primary_select" name="primary_select"> <!--Selection of primary category-->
<?php
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
echo '<option selected value="0">Select category</option>'; //Default option
$primary_category_count = $get_primary->num_rows; //Get number of primary categories
while($get_primary_list = $get_primary->fetch_assoc()) {
echo '<option value="'.$get_primary_list['cat_id'].'">'.$get_primary_list['cat_name'].'</option>';
}
?>
</select>
</div>
<input type="file" name="imageFile" id="imageFile"/>
<br/>
<input name="uploadSubmit" class="button-primary" type="submit" value="Submit">
<p style="color:red"><?php echo $error; ?></p>
</form>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#uploadForm').submit(function() {
var primCat = $('#primary_select').val();
if(primCat == 0) {
alert("Select Primary Category.");
return false;
}
});
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
<link rel="stylesheet" type="text/css" href="css/calendar.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php include("./includes/layout/navbar.php") ?>
<div id="content" class="container" style="padding-top:5em">
</div>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
//to populate the primary categories
$.ajax({
type: 'GET',
url: "api/calendar.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(data) {
var content = "";
var i;
for(i = 0; i < data.length; i++) {
content += "<h3>" + data[i].name + "</h3>";
var j;
content += '<table class="tg u-full-width heavyTable" style="undefined;table-layout: fixed; width: 100%;margin-bottom:3em">';
content += ' <colgroup>';
content += ' <col style="width: 15%">';
content += ' <col style="width: 20%">';
content += ' <col style="width: 10">';
content += ' <col style="width: 15%">';
content += ' <col style="width: 15%">';
content += ' <col style="width: 15%">';
content += ' <col style="width: 10%">';
content += ' </colgroup>';
content += ' <tr>';
content += ' <th class="tg-s6z2">Name of Crop</th>';
content += ' <th class="tg-s6z2">Time and Season</th>';
content += ' <th class="tg-s6z2">Seeds (g)</th>';
content += ' <th class="tg-s6z2">Gap between seeds (cm)</th>';
content += ' <th class="tg-s6z2">Depth (cm)</th>';
content += ' <th class="tg-s6z2">Sapling Density</th>';
content += ' <th class="tg-s6z2">Produce (kg)</th>';
content += ' </tr>';
for(j = 0; j < data[i]['rows'].length; j++) {
content += ' <tr>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][0] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][1] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][2] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][3] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][4] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][5] + '</td>';
content += ' <td class="tg-s6z2">' + data[i]['rows'][j][6] + '</td>';
content += ' </tr>';
}
content += ' </table>';
}
$('#content').html(content);
},
error: function(jqXHR, textStatus) {
alert("Please check your internet connection");
}
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("./functions.php");
require_once("../authenticate.php");
if(isset($_POST['update_changes'])) {
$article_id = $_POST['article_id'];
$article_content = text_unsearchable($_POST['content']);
$update_query = $mysqli->query("UPDATE `page` SET `page_content` = '$article_content' WHERE `page_id` = '$article_id'");
if($update_query) {
$get_name = $mysqli->query("SELECT page_title FROM page WHERE page_id = '$article_id'");
$get_name_text = $get_name->fetch_assoc();
header("Location:./article.php?success=1&page=".$get_name_text['page_title']);
}
}
if(isset($_POST['cancel_changes'])) {
header("Location:../worskpace.php");
}
if(isset($_POST['back_to_edit'])) {
$article_id = $_POST['article_id'];
header("Location: editor.php?article=".$article_id);
}
else {
$article_id = $_GET['article'];
$article_content_old = $_POST['preserve'];
$article_content = $_POST['content']; //this will hold the content to be sent to the database
$article_display = text_to_external_link(text_to_link($article_content)); //this will be the content that we will parse to display.
$flag = 1;
//Checking if the article has been modified by someone else since it has been taken up for editting
$check_change = $mysqli->query("SELECT page_content FROM page WHERE page_id = '$article_id'");
$check_change_result = $check_change->fetch_assoc();
if($check_change_result['page_content'] == $article_content_old) {
$flag = 1;
}
else {
$flag = 0;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Article Preview</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<body>
<!-- Navigation Bar -->
<?php include("../../includes/layout/navbar.php") ?>
<div class="container" style="padding-top:10em;padding-bottom:4rem;height:95%">
<form method="post" action="<?php echo $article_link?>preview.php" id="article_preview_form" name="article_preview_form">
<!-- This hidden text is where the content in the blob form will be stored for sending to the database.-->
<input type="hidden" id="article_id" name="article_id" value="<?php echo $article_id; ?>">
<input type="hidden" id="content" name="content" value="<?php echo str_replace('"', '"', $article_content);?>" />
<!-- update button -->
<?php
if($flag) {
echo '
<input name="update_changes" type="submit" value="Save All Changes" />
<input name="cancel_changes" type="submit" value="Discard Changes" />
';
}
else {
echo '
<p>The base article has been changed. Please go back and modify your edits accordingly</p>
<input name="update_changes" type="submit" value="Save All Changes" disabled/>
<input name="back_to_edit" type="submit" value="Back to editor" />
<input name="cancel_changes" type="submit" value="Discard Changes" />
';
}
?>
</form>
<?php
echo "Article ID : <b>".$article_id."</b> <br/>";
$article_details_query = $mysqli->query("SELECT page_title,user_real_name FROM page INNER JOIN user ON (page_creator=user_id) WHERE page_id='$article_id'");
$article_details = $article_details_query->fetch_assoc();
echo "Article Name : ".$article_details['page_title']."<br/>";
echo "Article Author : ".$article_details['user_real_name']."<br/><br/><br/>";
echo "<h4>Preview</h4>";
$article_sections = explode("||sec||",$article_display);
$sections_count = count($article_sections);
echo "<h5>Introduction</h5>";
echo "<p>".$article_sections[0]."</p>";
$i = 1;
while($i < $sections_count) {
$section_title = explode("||ttl||", $article_sections[$i]);
echo "<h5>".$section_title[0]."</h5>";
echo "<p>".$section_title[1]."</p>";
$i++;
}
?>
</div>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("../authenticate.php");
if(isset($_GET['id'])) {
$table = $_GET['id'];
$delete_table = $mysqli->query("DELETE FROM `calendar` WHERE `id` = '$table'");
if($delete_table) {
header("Location: ../calendar.php?deleterow=1");
}
else {
echo'Could not delete the table. Please try again';
}
}
else {
header("Location: ../calendar.php");
}
?>
<file_sep>var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
frmvalidator.addValidation("scaptcha","req","Please enter the code in the image above");
document.forms['contactus'].scaptcha.validator = new FG_CaptchaValidator(document.forms['contactus'].scaptcha, document.images['scaptcha_img']);
function SCaptcha_Validate() {
return document.forms['contactus'].scaptcha.validator.validate();
}
frmvalidator.setAddnlValidationFunction("SCaptcha_Validate");
function refresh_captcha_img() {
var img = document.images['scaptcha_img'];
img.src = img.src.substring(0,img.src.lastIndexOf("?")) + "?rand="+Math.random()*1000;
}<file_sep><?php
/**
* This page is included throughout the CMS as shorthand
* for establishing database connection and starting a session
*/
//Set up database connection
$mysqli = new mysqli($host,$database_user,$database_password,$database_name);
if ($mysqli->connect_errno)
die("Connect failed: ".$mysqli->connect_error);
// This function is used as a shorthand for closing the database and exiting
function _exit($s="") {
global $mysqli;
$mysqli->close();
exit($s);
}
?><file_sep><?php
require("./config.php");
require("./initialize_database.php");
$error = "";
if(isset($_POST['login'])){
if(isset($_POST['usernameLogin']) AND isset($_POST['passwordLogin']) AND $_POST['usernameLogin'] != "" AND $_POST['passwordLogin'] != "") {
$username = htmlspecialchars($_POST['usernameLogin']);
$password = htmlspecialchars($_POST['passwordLogin']);
$user_check = $mysqli->query("SELECT * FROM user WHERE user_name = '$username' AND user_password = <PASSWORD>' AND user_status = 1");
$user_result = $user_check->fetch_assoc();
if($user_check->num_rows == 1) {
session_start();
$_SESSION['user_id'] = $user_result['user_id'];
$_SESSION['login'] = substr(md5('appletree'), 0, 20);
$_SESSION['usertype'] = md5('editor');
header("Location: ./workspace.php");
}
else {
$error = "Invalid username or password";
}
}
else {
$error = "Please enter both fields";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" >
<meta charset="utf-8">
<title>Editor Login</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php include("../includes/layout/navbar.php") ?>
<div style="padding-top:5rem">
<div class="container">
<div class="row">
<form action="./workspace/login.php", method="POST" class="twelve columns" style="position:absolute;top:15em;left:20em;">
<div class="row">
<div class="four columns">
<input class="u-full-width" type="text" placeholder="username" id="usernameLogin" name="usernameLogin">
</div>
</div>
<div class="row">
<div class="four columns">
<input class="u-full-width" type="password" placeholder="<PASSWORD>" id="<PASSWORD>Login" name="passwordLogin">
</div>
</div>
<input class="button-primary" type="submit" value="Submit" name="login">
</form>
<h5><?php echo $error; ?></h5>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
require_once('../workspace/article/functions.php');
$result = $mysqli->query("SELECT * FROM calendar_tables");
$arr = array();
while($row = $result->fetch_assoc()) {
$table = array();
$table['name'] = $row['name'];
$id = $row['id'];
$row_content = array();
$row_query = $mysqli->query("SELECT * FROM calendar WHERE `table` = '$id'");
while($row_result = $row_query->fetch_assoc()) {
$row_item = array();
array_push($row_item, $row_result['column1']);
array_push($row_item, $row_result['column2']);
array_push($row_item, $row_result['column3']);
array_push($row_item, $row_result['column4']);
array_push($row_item, $row_result['column5']);
array_push($row_item, $row_result['column6']);
array_push($row_item, $row_result['column7']);
array_push($row_content, $row_item);
}
$table['rows'] = $row_content;
array_push($arr, $table);
}
$json=json_encode($arr);
print_r($json);
?><file_sep><?php
require("../config.php");
require("../initialize_database.php");
require_once("../authenticate.php");
if(isset($_GET['execute'])) {
if($_GET['execute'] == 'delete') {
$id = $_GET['id'];
$update_status = $mysqli->query("DELETE FROM user WHERE user_id='$id'");
}
if($_GET['execute'] == 'approve') {
$id = $_GET['id'];
$update_status = $mysqli->query("UPDATE user SET user_status = 1 WHERE user_id='$id'");
}
if($update_status) {
header("Location: ../workspace.php");
}
else {
echo "Please try again";
}
}
?><file_sep><?PHP
require_once("./includes/fgcontactform.php");
require_once("./includes/captcha-creator.php");
$formproc = new FGContactForm();
$captcha = new FGCaptchaCreator('scaptcha');
$formproc->EnableCaptcha($captcha);
//1. Add your email address here.
//You can add more than one receipients.
$formproc->AddRecipient('<EMAIL>'); //<<---Put your email address here
//2. For better security. Get a random tring from this link: http://tinyurl.com/randstr
// and put it here
$formproc->SetFormRandomKey('<KEY>');
if(isset($_POST['submitted'])) {
if($formproc->ProcessForm()) {
$formproc->RedirectToURL("index.php?email=1#contact");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar" style="position:absolute">
<div class="container">
<ul class="navbar-list">
<li class="navbar-item"><a class="navbar-link" href="http://www.niravu.com" target="_blank">NIRAVU</a></li>
</ul>
<ul class="navbar-list" style="float:right">
<li class="navbar-item"><a class="navbar-link" href="#contact">CONTACT US</a></li>
</ul>
</div>
</nav>
<div id="main-section" class="shadow">
<div class="main-header">Krishipurra</div>
</div>
<div id="intro-section" class="shadow">
<div class="container"><p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<div id="search-section">
<div id="morphsearch" class="morphsearch" style="margin-left: auto;margin-right: auto">
<form class="morphsearch-form" id="searchForm">
<input class="morphsearch-input" type="search" placeholder="Start typing..." id="searchInput"/>
<input class="morphsearch-submit" type="submit" id="searchSubmit" value="Search"/>
<div class="twelve columns">
<div class="button three columns advanced_trig" id="advanced_trigger">Advanced Options</div>
</div>
<div id="advanced" class="advanced">
<div id="primary_cat" class="three columns" style="margin-left:0;margin-top:10px"></div>
<div id="secondary_cat" class="three columns" style="margin-left:10px;margin-top:10px"></div>
</div>
</form>
<div class="morphsearch-content" style="height:50%;width:100%">
<div id="search_results" class="twelve columns" ></div>
</div>
<span class="morphsearch-close"></span>
</div>
<div class="overlay"></div>
</div>
<div id="primary-section" class="shadow">
<div class="container" style="overflow:auto">
<div class="grid">
<div id="primary"></div>
</div>
</div>
</div>
<div id="contact" class="" style="">
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' accept-charset='UTF-8' class="six columns">
<fieldset>
<?php if(isset($_GET['email'])) {
if($_GET['email'] == 1) {
echo '<h5>Email Sent Successfully. Thank you.</h5>';
}
} ?>
<h3 class="section-heading">Contact us</h3>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='<?php echo $formproc->GetFormIDInputName(); ?>' value='<?php echo $formproc->GetFormIDInputValue(); ?>'/>
<input type='text' class='spmhidip' name='<?php echo $formproc->GetSpamTrapInputName(); ?>' />
<div><span class='error'><?php echo $formproc->GetErrorMessage(); ?></span></div>
<div class='container'>
<input type='text' name='name' placeholder="Enter your name here" id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
</div>
<div class='container'>
<input type='text' name='email' placeholder="Enter your email address here" id='email' value='<?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='contactus_email_errorloc' class='error'></span>
</div>
<div class='container'>
<span id='contactus_message_errorloc' class='error'></span>
<textarea rows="10" cols="50" placeholder="Enter your message here" name='message' id='message'><?php echo $formproc->SafeDisplay('message') ?></textarea>
</div>
<div class='container'>
<div><img alt='Captcha image' src='show-captcha.php?rand=1' id='scaptcha_img' /></div>
<div class='short_explanation'>Can't read the image?
<a href='javascript: refresh_captcha_img();'>Click here to refresh</a></div>
<input type='text' placeholder="Enter the code shown above" name='scaptcha' id='scaptcha' maxlength="10" /><br/>
<span id='contactus_scaptcha_errorloc' class='error'></span>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>
</fieldset>
</form>
<div class="six columns" style="text-align:left" id="address">
<div class="ten columns">
<h3>Address</h3>
<p>Niravu vengeri E-19,</p>
<p>Vengeri (P.O.), Calicut-673010, </p>
<p>Kerala, India.</p>
<p>+91 9447 276177</p>
<p><EMAIL></p>
</div>
</div>
</div>
<div id="footer-section"></div>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/main.js"></script>
<script type="text/javascript" src="scripts/classie.js"></script>
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<script type='text/javascript' src='scripts/fg_captcha_validator.js'></script>
<script type='text/javascript' src="scripts/validate.js"></script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("../authenticate.php");
if(isset($_GET['table'])) {
$table = $_GET['table'];
$delete_table = $mysqli->query("DELETE FROM `calendar_tables` WHERE `id` = '$table'");
if($delete_table) {
header("Location: ../calendar.php?deletetable=1");
}
else {
echo'Could not delete the table. Please try again';
}
}
else {
header("Location: ../calendar.php");
}
?>
<file_sep>Krishipurra is an Agricultural Information System, brainchild of Niravu, an NGO based in Calicut.
<file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
$i = 0;
$arr = array(); //Variable to hold the json array
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
//$arr['primary_count'] = $get_primary->num_rows;
while($get_primary_list = $get_primary->fetch_assoc()) {
$primary_category_id = $get_primary_list['cat_id'];
$primary_category_name = $get_primary_list['cat_name'];
$options = array();
$get_secondary = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_category_id'");
//$secondary_category = array();
//$category['secondary_count'] = $get_secondary->num_rows;
while($get_secondary_list = $get_secondary->fetch_assoc()) {
$sub_item = array();
//array_push($sub_item, $get_secondary_list['sub_cat']);
//array_push($sub_item, $get_secondary_list['cat_name']);
$sub_item['id'] = $get_secondary_list['sub_cat'];
$sub_item['name'] = $get_secondary_list['cat_name'];
array_push($options, $sub_item);
}
//$category['options'] = $options;
array_push($arr, $options);
}
$json = json_encode($arr);
print_r($json);
?> <file_sep><?php
// this is where content is entered for the appropriate event using an HTML editor.
// content from the database will be filled in hidden text boxes and then populated to sections
require_once('../authenticate.php');
require_once('../config.php');
require_once("../initialize_database.php");
require_once("./functions.php");
$eventcode = "";
$eventcode = $_GET['article'];
// get the content from the database
$query="SELECT * FROM page WHERE page_id='$eventcode'";
$result=$mysqli->query($query);
$row=$result->fetch_assoc();
if($row) {
$creator = $row['page_creator'];
$page_name=$row['page_title'];
$content_to_preserve = $row['page_content'];
$content=text_searchable($row['page_content']);
$result->free();
}
$mysqli->close();
?>
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Article Editor</title>
<link rel="stylesheet" type="text/css" media="all" href="css/manager.css"/>
<link rel="stylesheet" type="text/css" media="all" href="css/normalize.css">
<link rel="stylesheet" type="text/css" media="all" href="css/skeleton.css">
<link rel="stylesheet" type="text/css" media="all" href="css/custom.css">
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/ajaxupload.js"></script>
<script type="text/javascript" src="scripts/kaja-input.js"></script>
<script type="text/javascript" src="scripts/editor.js"></script>
</head>
<body>
<!-- Navigation Bar -->
<?php include("../../includes/layout/navbar.php") ?>
<a name="#" ></a>
<div class="container" style="padding-top:10em;padding-bottom:4rem;height:95%">
Article ID: <b><?php echo $eventcode; ?></b>
<br/>
Article Title: <b><?php echo $page_name; ?></b>
<br/>
Article Creator: <b><?php echo $creator; ?></b>
<br/>
<form method="post" style="padding-top:1em;" action="<?php echo $article_link; ?>preview.php?article=<?php echo $eventcode;?>" id="event_form" name="event_form">
<input type="hidden" id="preserve" name="preserve" value="<?php echo str_replace('"', '"', $content_to_preserve);?>" />
<input type="hidden" id="desc" name="content" value="<?php echo str_replace('"', '"', $content);?>" />
<!-- update button -->
<input name="update" type="submit" value="Update" />
<input name="cancel_changes" type="submit" value="Discard Changes" />
</form>
<div class="row" style="padding-bottom:10em">
<div class="main">
<h5>Introduction</h5>
<textarea id="intro" name="intro"></textarea>
<!-- button for adding new sections -->
<a href="javascript:void(0)" id="new_sec" class="button">Add a Section</a>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
require_once('./workspace/config.php');
require_once("./workspace/initialize_database.php");
if(isset($_GET['category'])) {
$category = $_GET['category'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body style="background: linear-gradient(to bottom,#262b2e 0%,#1d2022 3000px);color:#fff">
<!-- Navigation Bar -->
<?php require("./includes/layout/navbar.php") ?>
<div class="container" style="padding-top:10em">
<div id="articles_list" style="height:auto">
<?php
$primary_query = $mysqli->query("SELECT * FROM primary_category WHERE cat_id = $category");
while($primary_query_list = $primary_query->fetch_assoc()) {
$primary_id = $primary_query_list['cat_id'];
$primary_name = $primary_query_list['cat_name'];
echo '<h1>'.$primary_name.'</h1>';
$secondary_query = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_id'");
while($secondary_query_list = $secondary_query->fetch_assoc()) {
$secondary_id = $secondary_query_list['sub_cat'];
echo '<div style="width:100%;position:relative;float:left;margin-bottom:1em"><h4>'.$secondary_query_list['cat_name'].'</h4><div class="grid2">';
//echo '<table class="" style="undefined;table-layout: fixed; width: 100%"> <colgroup> <col style="width: 100%"> </colgroup>';
$pages_list_query = $mysqli->query("SELECT * FROM page INNER JOIN user ON (page_creator=user_id) WHERE prim_cat = '$primary_id' AND sec_cat = '$secondary_id'");
while($pages_entry = $pages_list_query->fetch_assoc()) {
echo '
<figure class="effect-lily">';
if($pages_entry['thumbnail_status']) {
echo '<img src="images/thumbs/'.str_replace(" ", "_", $pages_entry['page_title']).'.jpg" alt="img12"/>';
}
echo '
<figcaption>
<div>
<h2>'.$pages_entry['page_title'].'</h2>
</div>
<a href="articles/'.str_replace(" ", "_", $pages_entry['page_title']).'">View more</a>
</figcaption>
</figure>
';
//echo ' <tr> <td class="tg-s6z2"><a href="articles/'.str_replace(" ", "_", $pages_entry['page_title']).'">'.$pages_entry['page_title'].'</a></td> </tr> ';
}
//echo " </table>";
echo '</div></div>';
}
}
?>
</div>
</div>
</body>
</html>
<file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
require_once('../workspace/functions.php');
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
$arr = array();
$arr['primary_category_count'] = $get_primary->num_rows; //number of primary categories
$arr['primary_category'] = array();
while($get_primary_list = $get_primary->fetch_assoc()) {
$primary_category_id = $get_primary_list['cat_id'];
$primary_category_name = $get_primary_list['cat_name'];
array_push($arr["primary_category"], $primary_category_name);
}
$json=json_encode($arr);
print_r($json);
?><file_sep><?php
require("./workspace/config.php");
require("./workspace/initialize_database.php");
$error = "";
if(isset($_POST['signup'])){
if(isset($_POST['nameLogin'])
AND isset($_POST['usernameLogin'])
AND isset($_POST['passwordLogin'])
AND isset($_POST['repasswordLogin'])
AND isset($_POST['emailLogin'])
AND $_POST['nameLogin'] != ""
AND $_POST['usernameLogin'] != ""
AND $_POST['passwordLogin'] != ""
AND $_POST['repasswordLogin'] != ""
AND $_POST['emailLogin'] != "") {
$name = htmlspecialchars($_POST['nameLogin']);
$username = htmlspecialchars($_POST['usernameLogin']);
$password = htmlspecialchars($_POST['passwordLogin']);
$repassword = htmlspecialchars($_POST['repasswordLogin']);
$email = htmlspecialchars($_POST['emailLogin']);
$user_check = $mysqli->query("INSERT INTO `user` (`user_id`, `user_name`, `user_real_name`, `user_password`, `user_creation_time`, `user_email`, `user_status`) VALUES (NULL, '$username', '$name', '$password', CURRENT_TIMESTAMP, '$email', '0');");
if($user_check) {
$error = "You have signed up successfully. Please wait while another editor approves you.";
}
else {
$error = "Signup failed. Please try again";
}
}
else {
$error = "Please enter all fields";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" >
<meta charset="utf-8">
<title>Signup</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php include("./includes/layout/navbar.php") ?>
<div class="container" style="padding-top:5rem">
<div class="row">
<form action="signup.php", method="POST" name="signUpForm" id="signUpForm">
<div class="row">
<div class="eight columns">
<input class="u-full-width" type="text" placeholder="Enter Name" id="nameLogin" name="nameLogin">
</div>
</div>
<div class="row">
<div class="four columns">
<input class="u-full-width" type="text" placeholder="username" id="usernameLogin" name="usernameLogin">
</div>
</div>
<div class="row">
<div class="four columns">
<input class="u-full-width" type="<PASSWORD>" placeholder="Enter password" id="passwordLogin" name="passwordLogin">
</div>
<div class="four columns">
<input class="u-full-width" type="<PASSWORD>" placeholder="<PASSWORD>" id="<PASSWORD>Login" name="repasswordLogin">
</div>
</div>
<div class="row">
<div class="eight columns">
<input class="u-full-width" type="text" placeholder="Enter email address" id="emailLogin" name="emailLogin">
</div>
</div>
<input class="button-primary" type="submit" value="Submit" name="signup">
</form>
<h5><?php echo $error; ?></h5>
</div>
</div>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$error = "";
if(isset($_POST['newArticleNameSubmit'])) {
$article_id = $_POST['articleID'];
$new_name = $_POST['newArticleName'];
$name_check = $mysqli->query("SELECT * FROM page WHERE page_title = '$new_name'");
if($name_check->num_rows == 0) {
$update_name = $mysqli->query("UPDATE page SET page_title = '$new_name' WHERE page_id = '$article_id'");
if($update_name) {
header("Location: confirm.php?status=1");
}
else {
$error = "Updating Article Name failed. Please try again.";
}
}
else {
$error = "New Article name already exists or Article name same as before.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h3>Rename Article</h3>
<!--Form for adding a new category of articles-->
<form action="workspace/article/rename.php?article=<?php echo $_GET['article']; ?>" method="POST" name="renameArticleForm" id="renameArticleForm">
<input type="hidden" value="<?php echo $_GET['article']; ?>" id="articleID" name="articleID"/>
<p>Article ID : <?php echo $_GET['article'];?></p>
<p>Current Name :
<?php
$id = $_GET['article'];
$article_query = $mysqli->query("SELECT page_title FROM page WHERE page_id = '$id'");
$article_result = $article_query->fetch_assoc();
echo $article_result['page_title'];
?>
</p>
<input name="newArticleName" id="newArticleName" type="text" placeholder="Enter new article name" />
<input name="newArticleNameSubmit" class="button-primary" type="submit" value="Submit">
<p><?php echo $error; ?></p>
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#renameArticleForm').submit(function() {
var newArticleName = $('#newArticleName').val();
if(newArticleName == "") {
alert("Enter the new name for the article");
return false;
}
});
</script>
</body>
</html>
<file_sep>// remove a section
function remove_sec() {
$(this).remove();
}
// move a section up
function move_sec_up() {
var next = $(this).next('.desc-sec');
var mover = $(this).prev('.desc-sec');
if (next.length == 0 || mover.offset().top + $(this).height() > $(document).scrollTop() + $(window).height() - 200) $('body,html').animate({
scrollTop: '+=' + $(this).height()
}, 400);
$(this).insertBefore(mover);
$(this).animate({
height: 'show',
opacity: 'show'
}, 400);
}
// move a section down
function move_sec_down() {
$(this).insertAfter($(this).next('.desc-sec'));
$(this).animate({
height: 'show',
opacity: 'show'
}, 400);
}
// get (parent) section in which the DOM object 'e' is in
function get_par_sec(e) {
return $(e).closest(".desc-sec");
}
// create and add a new section at the bottom (right before the element with id 'new_sec')
function new_desc_sec(title, content) {
var link = $("#new_sec");
var new_section = $("<div/>", {
class: "desc-sec"
});
var desc_head = $("<span/>", {
html: "Section Title: ",
class: "desc-head"
});
var sec_ttl = $("<input type='text' />").appendTo(desc_head); //$(..).attr({name: 'xyz'})
// dynamically creating buttons: Remove, Down, Up
$("<span/>", {
html: "Remove",
class: "desc-but"
}).click(function () {
get_par_sec(this).hide(400, remove_sec);
}).appendTo(desc_head);
$("<span/>", {
html: "Down",
class: "desc-but"
}).appendTo(desc_head).click(function () {
var par_sec = get_par_sec(this);
par_sec.next('.desc-sec').animate({
height: 'hide',
opacity: 'hide'
}, 400, move_sec_up);
});
$("<span/>", {
html: "Up",
class: "desc-but"
}).appendTo(desc_head).click(function () {
var par_sec = get_par_sec(this);
par_sec.prev('.desc-sec').animate({
height: 'hide',
opacity: 'hide'
}, 400, move_sec_down);
});
//dynamically creating textarea
var desc_src = document.createElement("textarea");
new_section.hide();
new_section.insertBefore(link);
desc_head.appendTo(new_section);
$(desc_src).appendTo(new_section);
//calling new kaja input to make a new section
new_kaja_input(desc_src);
// scrolling down to shift view to the newly added section
$('body,html').animate({
scrollTop: '+=' + new_section.height()
}, 400);
new_section.show(400);
if (title) {
sec_ttl.val(title);
if (content) {
desc_src.value = content;
update_preview(desc_src);
}
} else sec_ttl.focus();
}
$(document).ready(function () {
// creating the intro section which is the default section
new_kaja_input($("#intro"));
$("#new_sec").click(function () {
new_desc_sec();
});
$("#event_form").submit(function () {
var desc_hid = $("#desc").get(0);
desc_hid.value = $("#intro").val();
$(".desc-sec").each(function(index) {
$("#desc").get(0).value += "||sec||" + $(this).find("input").val() + "||ttl||" + $(this).find("textarea").val();
});
desc_hid.value = desc_hid.value.replace(/'/g, "'").replace(/\u2013/g, "–");
//var articleName = $("#articleName").html();
//articleName = articleName.replace(" ","_");
var desc = $("#desc").get(0).value;
/*var res = desc.match(/\[\[(.+?)\]\]/g);
for (var i = 0; i < res.length; i++) {
res[i] = res[i].substring(2,res[i].length-2);
link = res[i].replace(" ","_");
res[i] = '<a href="articles/'+link+'">'+res[i]+'</a>';
desc = desc.replace(/\[\[(.+?)\]\]/, res[i]);
}; */
$("#desc").get(0).value = desc;
//desc.value = desc.value.replace(/\[\[(.+?)\]\]/, '<a href="articles/$1">$1</a>');
return true;
});
// format: <title>||ttl||<body>||sec||<title>||ttl||<body>||sec||
// #desc contains complete event description, divided into sections using separator ||sec||
var desc = $("#desc").get(0).value;
/*res = desc.match(/<a href="articles\/(.+?)">(.+?)<\/a>/g);
if(res) {
for (var i = 0; i < res.length; i++) {
res[i] = res[i].replace(/<a href="articles\/(.+?)">(.+?)<\/a>/,'\[\[$2\]\]');
desc = desc.replace(/<a href="articles\/(.+?)">(.+?)<\/a>/,res[i]);
}
}*/
//desc = desc.replace(/<a href="articles\/(.+?)">(.+?)<\/a>/,'\[\[$2\]\]');
var descs = desc.split("||sec||");
if (descs.length > 0) {
update_preview($("#intro").val(descs[0]).get(0));
if (descs.length > 1) {
var sec_data, i;
for (i = 1; i<descs.length; i++) {
sec_data = descs[i].split("||ttl||"); // section: "<title>||ttl||<body>"
new_desc_sec(sec_data[0], sec_data[1]);
}
}
}
});
//-->
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});<file_sep><?php
require_once("./initialize_database.php");
require_once("./functions.php");
$article_name = str_replace("_", " ", $_GET['page']);
?>
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Article Preview</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<body>
<!-- Navigation Bar -->
<?php require("./includes/layout/navbar.php") ?>
<div class="container" style="padding-top:5rem;padding-bottom:4rem;height:95%">
<?php
$article_details_query = $mysqli->query("SELECT page_title,user_real_name,page_content FROM page INNER JOIN user ON (page_creator=user_id) WHERE page_title='$article_name'");
$article_details = $article_details_query->fetch_assoc();
echo "<h2>".$article_details['page_title']."</h2>";
$article_content = text_to_link($article_details['page_content']);
$article_sections = explode("||sec||",$article_content);
$sections_count = count($article_sections);
echo "<p>".$article_sections[0]."</p>";
$i = 1;
while($i < $sections_count) {
$section_title = explode("||ttl||", $article_sections[$i]);
echo "<h5>".$section_title[0]."</h5>";
echo "<p>".$section_title[1]."</p>";
$i++;
}
?>
</div>
<footer class="footer">
<div class="container">
Copyright. All rights reserved.
</div>
</footer>
</body>
</html>
<file_sep>/*!
* jQuery HTML Ajax Uploader 2.2
* <NAME>
* <EMAIL>
* copyright
*
*/
(function($)
{
//Test if support pure ajax upload and create browse file input
var axtest = document.createElement('input');
axtest.type = 'file';
var isAjaxUpload=('multiple' in axtest && typeof File != "undefined" && typeof (new XMLHttpRequest()).upload != "undefined" );
axtest = null;
//isAjaxUpload=false;
/**
* @settings object setting
* @filename
* @filesize size of file in html 5 browser
*/
function getURL(settings, fileName, size)
{
var getpath = (typeof(settings.remotePath)=='function')?settings.remotePath():settings.remotePath;
var params = [];
params.push('ax-file-path=' + encodeURIComponent(getpath));
params.push('ax-allow-ext=' + encodeURIComponent(settings.allowExt.join('|')));
params.push('ax-file-name=' + encodeURIComponent(fileName));
params.push('ax-thumbHeight=' + settings.thumbHeight);
params.push('ax-thumbWidth=' + settings.thumbWidth);
params.push('ax-thumbPostfix=' + encodeURIComponent(settings.thumbPostfix));
params.push('ax-thumbPath=' + encodeURIComponent(settings.thumbPath));
params.push('ax-thumbFormat=' + encodeURIComponent(settings.thumbFormat));
params.push('ax-maxFileSize=' + encodeURIComponent(settings.maxFileSize));
params.push('ax-fileSize=' + size);
var otherdata = (typeof(settings.data)=='function')?settings.data():settings.data;
if(typeof(otherdata)=='object')
{
for(var i in otherdata)
{
params.push(i + '=' + encodeURIComponent(otherdata[i]));
}
}
else if(typeof(otherdata)=='string' && otherdata!='')
{
params.push(otherdata);
}
var c = (settings.url.indexOf('?')==-1)?'?':'&';
return settings.url+c+params.join('&');
}
/*
* Upload ajax function supported by modern browsers Firefox 3.6+, Chrome, Safari
* IE 10 maybe will support this
*
*/
function uploadAjax(queued, settings)
{
var file = queued.file;
var startByte = queued.byte;
var name = queued.name;
var size = file.size;
var chunkSize = settings.chunkSize; //chunk size
var endByte = chunkSize + startByte;
var isLast = (size - endByte <= 0);
var chunk = file;
var xhr = new XMLHttpRequest();//prepare xhr for upload
var chunkNum = endByte / chunkSize;
queued.xhr = xhr;
if(startByte == 0) settings.SLOTS++;
if(chunkSize == 0)//no divide
{
chunk = file;
isLast = true;
}
else if(file.mozSlice) // moz slice
{
chunk = file.mozSlice(startByte, endByte);
}
else if(file.webkitSlice) //webkit slice
{
chunk = file.webkitSlice(startByte, endByte);
}
else if(file.slice) // w3c slice
{
chunk = file.slice(startByte, chunkSize);
}
else
{
chunk = file;
isLast = true;
}
//abort event, (nothing to do for the moment)
xhr.upload.addEventListener('abort', function(e){
settings.SLOTS--;
}, false);
//progress function, with ajax upload progress can be monitored
xhr.upload.addEventListener('progress', function(e)
{
if (e.lengthComputable)
{
var perc = Math.round((e.loaded + chunkNum * chunkSize - chunkSize) * 100 / size);
queued.progress(perc);
}
}, false);
xhr.upload.addEventListener('error', function(e){
queued.error(this.responseText, name);
}, false);
xhr.onreadystatechange=function()
{
if(this.readyState == 4 && this.status == 200)
{
try
{
var ret = JSON.parse(this.responseText);
if(startByte == 0)
queued.name = ret.name;
if(isLast)
{
settings.SLOTS--;
queued.end(ret.name, ret.size, ret.status, ret.info);
}
else if(ret.status == 'error')
{
throw ret.info;
}
else
{
queued.byte = endByte;
uploadAjax(queued, settings);
}
}
catch(err)
{
settings.SLOTS--;
queued.error('error', err);
}
}
};
var finalUrl=getURL(settings, name, size);
xhr.open('POST', finalUrl + '&ax-start-byte=' + startByte + '&isLast=' + isLast, settings.async);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//header
xhr.setRequestHeader('Content-Type', 'application/octet-stream');//generic stream header
//TODO set boundary for future version, for sending other data in post rather than only files
//TODO use sendasbinary or sendasbinarystring
xhr.send(chunk);
}
function generateBoundary() {
return "AJAX-----------------------" + (new Date).getTime();
}
//TODO add fine zoom on light box
function createPreview(prevC, fileObj, ext, settings)
{
if (fileObj.type.match(/image.*/) && (ext=='jpg' || ext=='gif' || ext=='png') && typeof (FileReader) !== "undefined")
{
var img = prevC.css('background','none').children('img:first');
var reader = new FileReader();
reader.onload =function(e) {
img.css('cursor','pointer').attr('src',e.target.result).click(function(){
var imgloader=new Image();
imgloader.onload = function()
{
var ratio = Math.min($(window).width() / this.width, ($(window).height()-100) / this.height);
var newWidth = (ratio<1)?this.width * ratio:this.width;
var newHeight = (ratio<1)?this.height * ratio:this.height;
$('#ax-box').html('<img width="'+newWidth+'" height="'+newHeight+'" src="'+e.target.result+'" /><a>Close</a><span>'+fileObj.name+'</span>')
.fadeIn(100)
.css({
'top': ($(window).scrollTop()-20+($(window).height()-newHeight)/2) + 'px',
'height':(newHeight+20)+'px',
'width':newWidth+'px',
'left':($(window).width()-newWidth)/2
});
$('#ax-box').find('a').css('cursor','pointer').click(function(e){
e.preventDefault();
$('#ax-box-shadow, #ax-box').fadeOut(100);
});
$('#ax-box-shadow').css('height',$(document).height()).fadeIn(100);
};
imgloader.src=e.target.result;
});
};
reader.readAsDataURL(fileObj);
}
else
{
prevC.children('img:first').remove();//FIXME
prevC.addClass('ax-filetype-'+ext);
}
}
function uploadAll(FILES)
{
setTimeout(function(){
var stop = true;
for(var i = 0;i < FILES.length;i++)
{
if(FILES[i].xhr === null && FILES[i].status != 'uploaded' && FILES[i].status != 'error')
{
stop = false;
FILES[i].sns();
}
}
if(!stop) uploadAll(FILES);
},300);
}
function sizeFormat(format, size)
{
switch(format)
{
case 'gb' : size = size / (1024*1024*1024);break;
case 'mb' : size = size / (1024*1024);break;
case 'kb' : size = size / (1024);break;
}
return (Math.round(size*100)/100)+' '+format;
}
function fileTemplate(list, fileobj, settings)
{
var fn = fileobj.name;
var size = sizeFormat(settings.showSize, fileobj.size);
var li = $('<li />').appendTo(list).attr('title',fn);
var prevC = $('<a class="ax-prev-container" />').appendTo(li);
var prevImg = $('<img class="ax-preview" src="" alt="Preview" />').appendTo(prevC);
var details = $('<div class="ax-details" />').appendTo(li);
var nameC = $('<div class="ax-file-name">'+fn+'</div>').appendTo(details);
//if edit file name allowed bind events TODO control conditions inside events?
if(settings.editFilename)
{
nameC.dblclick(function(e){
e.stopPropagation();
var fn_noext = fn.substr(0,fn.lastIndexOf("."));
$(this).html('<input type="text" value="'+fn_noext+'" />.'+fileobj.ext);
}).bind('blur',function(e){
e.stopPropagation();
var new_fn = $(this).children('input').val();
if(typeof(new_fn) != 'undefined')
{
var cleanString = new_fn.replace(/[|&;$%@"<>()+,]/g, '');//remove bad filename chars
var final_fn = cleanString+'.'+fileobj.ext;
$(this).html(final_fn);
fileobj.name = final_fn;
if(!isAjaxUpload && fileobj.xhr)//on form upload also rename input hidden input
{
fileobj.xhr.children('input[name="ax-file-name"]').val(final_fn);
}
}
});
}
var sizeC = $('<div class="ax-file-size">'+size+'</div>').appendTo(details);
var progres = $('<div class="ax-progress" />').appendTo(li);
var pBar = $('<div class="ax-progress-bar" />').appendTo(progres);
var pNum = $('<div class="ax-progress-info">0%</div>').appendTo(progres);
var toolbar = $('<div class="ax-toolbar" />').appendTo(li);
var upload = $('<a title="Start upload" class="ax-upload ax-button" />').click(function(){
if(settings.enable) fileobj.sns();
}).appendTo(toolbar).append('<span class="ax-upload-icon ax-icon"></span>');
var remove = $('<a title="Remove file" class="ax-remove ax-button" />').click(function(){
if(settings.enable) fileobj.remove();
}).appendTo(toolbar).append('<span class="ax-clear-icon ax-icon"></span>');
createPreview(prevC, fileobj.file, fileobj.ext, settings);
return {pBar:pBar, pNum:pNum, upload:upload, remove:remove, nameC:nameC, li:li, sizeC:sizeC};
}
//update the file list
function ajaxList(list, obj, settings)
{
var FILES = settings.FILES;
var tools = fileTemplate(list, obj, settings);
var upload = tools.upload;
var remove = tools.remove;
obj.tools=tools;
obj.end = function(name, size, status, info)
{
settings.UPLOADED++;
this.name = name;
this.status = status;
this.info = info;
this.xhr = null;
this.byte = 0;
this.tools.nameC.html(name);
this.tools.li.attr('title', name);
this.tools.pNum.html('100%');
this.tools.pBar.css('width','100%');
this.tools.upload.removeClass('ax-abort');
settings.success(name);
if(FILES.length == settings.UPLOADED)
{
var arrFiles = [];
settings.UPLOADED = 0;
for(var j = 0; j < FILES.length; j++) arrFiles.push(FILES[j].name);
settings.finish(arrFiles);
settings.internalFinish(arrFiles);
}
};
obj.progress = function(p)
{
this.tools.pNum.html(p+'%');
this.tools.pBar.css('width',p+'%');
};
obj.error = function(status, err)
{
this.xhr = null;
this.byte = 0;
this.status = status;
this.info = err;
this.tools.pNum.html(err);
this.tools.pBar.css('width','0%');
this.tools.upload.removeClass('ax-abort');
settings.error(err, this.name);
};
//startNstop
obj.sns = function(all)
{
if(this.xhr !== null)
{
this.xhr.abort();
this.xhr = null;
this.byte = 0;
this.tools.upload.removeClass('ax-abort');
}
else if(settings.SLOTS < settings.maxConnections)
{
this.tools.pNum.html('0%');
this.tools.pBar.css('width','0%');
this.tools.upload.addClass('ax-abort');
uploadAjax(this, settings);
}
};
obj.remove = function()
{
FILES.splice(this.pos, 1);
if(this.xhr) this.xhr.abort();
this.file = null;
this.xhr = null;
for(var j=0; j<FILES.length; j++) FILES[j].pos=j;
this.tools.li.remove();
};
}
function formList(list, obj, settings)
{
var FILES = settings.FILES;
var tools = fileTemplate(list, obj, settings);
var upload = tools.upload;
var remove = tools.remove;
var iframe = document.getElementById('ax-main-frame');
var url = getURL(settings,'',0);
var form = $('<form action="'+url+'" method="post" target="ax-main-frame" encType="multipart/form-data" />').hide().appendTo(tools.li);
form.append('<input type="hidden" value="'+encodeURIComponent(obj.name)+'" name="ax-file-name" />');//input for re-name of file
$(obj.file).appendTo(form);
obj.xhr = form;
obj.tools=tools;
obj.end = function(name, size, status, info)
{
settings.UPLOADED++;
this.name = name;
this.status = status;
this.info = info;
//this.xhr = null;
this.byte = 0;
this.size = size;
this.tools.nameC.html(name);
this.tools.sizeC.html(sizeFormat(settings.showSize, size));
this.tools.li.attr('title', name);
if(status == 'error')
{
this.tools.pNum.html(info);
this.tools.pBar.css('width','0%');
}
else
{
this.tools.pNum.html('100%');
this.tools.pBar.css('width','100%');
}
this.tools.upload.removeClass('ax-abort');
settings.success(name);
if(FILES.length == settings.UPLOADED)
{
var arrFiles = [];
settings.UPLOADED = 0;
for(var j = 0; j < FILES.length; j++) arrFiles.push(FILES[j].name);
settings.finish(arrFiles);
settings.internalFinish(arrFiles);
}
};
obj.progress = function(p)
{
this.tools.pNum.html(p+'%');
this.tools.pBar.css('width',p+'%');
};
obj.sns = function()
{
if(upload.hasClass('ax-abort'))
{
try{iframe.contentWindow.document.execCommand('Stop');}catch(ex){iframe.contentWindow.stop();}
upload.removeClass('ax-abort');
}
else
{
this.tools.pNum.html(0+'%');
this.tools.pBar.css('width',0+'%');
this.tools.upload.addClass('ax-abort');
uploadForm(this, false, FILES);
}
};
obj.remove = function()
{
FILES.splice(this.pos, 1);
try{iframe.contentWindow.document.execCommand('Stop');}catch(ex){iframe.contentWindow.stop();}
$(this.file).remove();
this.file = null;
for(var j=0; j<FILES.length; j++) FILES[j].pos=j;
this.tools.li.remove();
};
}
function uploadForm(obj, all, FILES)
{
if(FILES.length>0)
{
$('#ax-main-frame').unbind('load').bind('load',function(){
var frameDoc;
if ( this.contentDocument )
{ // FF
frameDoc = this.contentDocument;
}
else if ( this.contentWindow )
{ // IE
frameDoc = this.contentWindow.document;
}
var ret = $.parseJSON(frameDoc.body.innerHTML);
obj.progress(100);
obj.end(ret.name, ret.size, ret.status, ret.info);
if(all && FILES[obj.pos+1])
{
uploadForm(FILES[obj.pos+1], true, FILES);
}
});
obj.xhr.submit();
}
}
function addFiles(arr, fileList, settings)
{
var FILES = settings.FILES;
for (var i = 0; i < arr.length; i++)
{
var ext, name, size, pos = FILES.length;
if(isAjaxUpload)
{
name = arr[i].name;
size = arr[i].size;
}
else
{
name = arr[i].value.replace(/^.*\\/, '');
size = 0;
}
ext = name.split('.').pop().toLowerCase();
if (FILES.length == 1 && settings.maxFiles == 1) //+++Added+++
clearQueue(settings); //+++Added+++
if(FILES.length < settings.maxFiles && ($.inArray(ext, settings.allowExt)>=0 || settings.allowExt.length==0))
{
var obj={pos : pos,
byte : 0,
sns : function(){},
error : function(){},
end : function(){},
progress: function(){},
file : arr[i],
status : 'ok',
name : name,
size : size,
xhr : null,
info : '',
ext : ext};
FILES.push(obj);
if(isAjaxUpload)
ajaxList(fileList, obj, settings);
else
formList(fileList, obj, settings);
}
}
}
function startUpload(FILES)
{
(isAjaxUpload)? uploadAll(FILES) : uploadForm(FILES[0], true, FILES);
}
function clearQueue(settings)
{
if(!settings.enable) return;
while(settings.FILES.length>0) settings.FILES[0].remove();
}
var globalSettings =
{
remotePath : 'images/articles/', //remote upload path, can be set also in the php upload script
url: 'uploader.php', //php/asp/jsp upload script
data: '', //other user data to send in GET to the php script
async: true, //set asyncron upload or not
maxFiles: 9999, //max number of files can be selected
allowExt: [], //array of allowed upload extesion, can be set also in php script
showSize: 'Mb', //show size in Mb, Kb or bytes, or Gb
success: function(fileName){}, //function that triggers every time a file is uploaded
finish: function(arrFiles){}, //function that triggers when all files are uploaded
error: function(txt,fileName){}, //function that triggers if an error occuors during upload
enable: true, //start plugin enable or disabled
chunkSize: 1024*1024,//default 1Mb, //if supported send file to server by chunks, not at once
maxConnections: 3, //max parallel connection on multiupload recomended 3, firefox support 6, only for browsers that support file api
dropColor: 'red', //back color of drag & drop area, hex or rgb
dropArea: 'self', //set the id or element of area where to drop files. default self
autoStart: false, //if true upload will start immediately after drop of files or select of files
thumbHeight: 0, //max thumbnial height if set generate thumbnial of images on server side
thumbWidth: 0, //max thumbnial width if set generate thumbnial of images on server side
thumbPostfix: '_thumb', //set the post fix of generated thumbs, default filename_thumb.ext,
thumbPath: '', //set the path where thumbs should be saved, if empty path setted as remotePath
thumbFormat: '', //default same as image, set thumb output format, jpg, png, gif
maxFileSize: '1001M', //max file size of single file,
form: null, //integration with some form, set the form selector or object, and upload will start on form submit
editFilename: false, //if true allow edit file names before upload, by dblclick
sortable: false //set if need to sort file list, need jquery-ui
};
var methods =
{
init : function(options)
{
return this.each(function()
{
var $this = $(this);
if($this.hasClass('ax-uploader'))//for avoiding two times call errors
{
return;
}
$this.addClass('ax-uploader').data('author','http://www.albanx.com/');
var settings = $.extend({},globalSettings,options);
settings.FILES = []; //the queue
settings.UPLOADED = 0; //count uploaded files
settings.SLOTS = 0; //slot number
settings.internalFinish = function(){};
settings.source = this; //+++Added+++
//If used with form combination, the bind upload on form submit
var form = null;
if($(settings.form).length>0)
form = $(settings.form);
else if(settings.form=='parent')
form = $this.parents('form:first');
if(typeof(form) != 'undefined' && form!=null)
{
//on submit form, if there are files, first upload and the submit form
$(form).bind('submit.ax',function(){
if(settings.FILES.length>0)
{
startUpload(settings.FILES);
return false;
}
});
//this function is run after files are upload, adds hidden inputs with file uploaded paths, and submits the final form
settings.internalFinish = function(files){
if(form!=null)
{
var basepath = (typeof(settings.remotePath)=='function')?settings.remotePath():settings.remotePath;
for(var i=0;i<files.length;i++)
{
var filepath = basepath+files[i];
$(form).append('<input name="ax-uploaded-files[]" type="hidden" value="'+filepath+'" />');
}
$(form).unbind('submit.ax').submit();
}
};
}
//normalize strings
settings.showSize = settings.showSize.toLowerCase();
settings.allowExt = $.map(settings.allowExt, function(n, i){ return n.toLowerCase(); });
$this.data('settings', settings);
if($('#ax-box').length==0) $('<div id="ax-box"/>').appendTo('body');
if($('#ax-box-shadow').length==0) $('<div id="ax-box-shadow"/>').appendTo('body');
if($('#ax-main-frame').length==0) $('<iframe name="ax-main-frame" id="ax-main-frame" />').hide().appendTo('body');
//var mainForm = $('<form target="ax-main-frame" method="POST" action="" encType="multipart/form-data" />').appendTo($this);
var fieldSet = $('<fieldset />').append('<legend class="ax-legend">Select files</legend>').appendTo($this);
var browse_c = $('<a class="ax-browse-c ax-button" title="Add Files" />').appendTo(fieldSet);//Browse container
browse_c.append('<span class="ax-plus-icon ax-icon"></span> <span>Add Files</span>');
var browseFiles = $('<input type="file" class="ax-browse" name="ax-files[]" />').attr('multiple',isAjaxUpload).appendTo(browse_c);
var uploadFiles = $('<a class="ax-upload-all ax-button" title="Upload all files" />').appendTo(fieldSet);
uploadFiles.append('<span class="ax-upload-icon ax-icon"></span> <span>Start upload</span>');
var removeFiles = $('<a class="ax-clear ax-button" title="Clear all" />').appendTo(fieldSet);
removeFiles.append('<span class="ax-clear-icon ax-icon"></span> <span>Remove all</span>');
var fileList = $('<ul class="ax-file-list" />').appendTo(fieldSet);
var otherinfo = $('<span class="ax-net-info"></span>').appendTo($this);
//get selected files
browseFiles.bind('change',function(){
//disable option
if(!settings.enable) return;
if(isAjaxUpload)
{
addFiles(this.files, fileList, settings);
if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1);
refreshBrowse();//Chrome "bug??" fix reselecting the same file
}
else
{
addFiles([this], fileList, settings);
$(this).clone(true).val('').appendTo(browse_c);
$(this).hide();
}
if(settings.autoStart)
{
startUpload(settings.FILES);
}
});
function refreshBrowse(){
var newB=browseFiles.clone(true).appendTo(browse_c);
browseFiles.remove();
browseFiles=newB;
}
//upload files
uploadFiles.bind('click',function(){
if(!settings.enable) return;
startUpload(settings.FILES);
return false;
});
//remove all files from list
removeFiles.bind('click',function(){
clearQueue(settings);
return false;
});
if(isAjaxUpload)
{
var dropArea = (settings.dropArea=='self')? this: $(settings.dropArea).get(0);
//Add files by drag and drop
dropArea.addEventListener('dragenter',function(e){
e.stopPropagation();
e.preventDefault();
},false);
dropArea.addEventListener('dragover',function(e){
if(!settings.enable) return;
e.stopPropagation();
e.preventDefault();
$(this).css('background-color',settings.dropColor);
},false);
dropArea.addEventListener('dragleave',function(e){
e.stopPropagation();
e.preventDefault();
$(this).css('background-color','');
},false);
dropArea.addEventListener('drop',function(e)
{
if(!settings.enable) return;
e.stopPropagation();
e.preventDefault();
addFiles(e.dataTransfer.files, fileList, settings);
$(this).css('background-color','');
if(settings.autoStart)
{
startUpload(settings.FILES);
}
},false);
}
$this.bind('click.ax',function(e){
if(e.target.nodeName!='INPUT')
$('.ax-file-name').trigger('blur');
});
$(document).unbind('.ax').bind('keyup.ax',function(e){
if (e.keyCode == 27) {
$('#ax-box-shadow, #ax-box').fadeOut(100);
}
});
if(!settings.enable)
{
$this.ajaxupload('disable');
}
});
},
enable:function()
{
return this.each(function()
{
var $this = $(this);
var settings = $this.data('settings');
settings.enable = true;
$this.data('settings', settings);
$(this).removeClass('ax-disabled').find('input').attr('disabled',false);
});
},
disable:function()
{
return this.each(function()
{
var $this = $(this);
var settings = $this.data('settings');
settings.enable = false;
$this.data('settings', settings);
$(this).addClass('ax-disabled').find('input').attr('disabled',true);
});
},
start:function()
{
return this.each(function(){
var settings = $(this).data('settings');
startUpload(settings.FILES);
});
},
clear:function()
{
return this.each(function(){
var settings = $(this).data('settings');
clearQueue(settings);
});
},
destroy : function()
{
return this.each(function()
{
var $this=$(this); //+++Added+++
var settings = $this.data('settings');
clearQueue(settings);
$this.removeData('settings').html('');
$this.removeClass('ax-uploader'); //+++Added+++
});
},
option : function(option, value)
{
return this.each(function(){
var $this=$(this);
var settings = $this.data('settings');
if(value != null && value != undefined)
{
settings[option] = value;
$this.data('settings', settings);
if(!settings.enable)
{
$this.ajaxupload('disable');
}
else
{
$this.ajaxupload('enable');
}
}
else
{
return settings[option];
}
});
}
};
$.fn.ajaxupload = function(method, options)
{
if(methods[method])
{
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if(typeof method === 'object' || !method)
{
return methods.init.apply(this, arguments);
}
else
{
$.error('Method ' + method + ' does not exist on jQuery.ajaxupload');
}
};
})(jQuery);
<file_sep>// Ref: http://stackoverflow.com/questions/401593/understanding-what-goes-on-with-textarea-selection-with-javascript
var imagesSrc = "images/articles";
(function ($) {
$.fn.get_selection = function () {
var e = this.get(0);
if('selectionStart' in e) { //Mozilla and DOM 3.0
return { start: e.selectionStart,
end: e.selectionEnd,
length: e.selectionEnd - e.selectionStart,
text: e.value.substring(e.selectionStart, e.selectionEnd) };
}
else if(document.selection) { //IE
e.focus();
var r = document.selection.createRange();
var tr = e.createTextRange();
if (r == null || tr == null) return { start: e.value.length, end: e.value.length, length: 0, text: '' };
var tr2 = tr.duplicate();
tr2.moveToBookmark(r.getBookmark());
tr.setEndPoint('EndToStart',tr2);
var text_part = r.text.replace(/[\r\n]/g,'.'); //for some reason IE doesn't always count the \n and \r in length
var text_whole = e.value.replace(/[\r\n]/g,'.');
var the_start = text_whole.indexOf(text_part,tr.text.length);
return { start: the_start, end: the_start + text_part.length, length: text_part.length, text: r.text };
}
else //Browser not supported
return { start: e.value.length, end: e.value.length, length: 0, text: '' };
};
$.fn.set_selection = function (start_pos,end_pos) {
var e = this.get(0);
if('selectionStart' in e) { //Mozilla and DOM 3.0
e.focus();
e.selectionStart = start_pos;
e.selectionEnd = end_pos;
}
else if (document.selection) { //IE
e.focus();
var tr = e.createTextRange();
//Fix IE from counting the newline characters as two seperate characters
var stop_it = start_pos;
for (i=0; i < stop_it; i++) if( e.value[i].search(/[\r\n]/) != -1 ) start_pos = start_pos - .5;
stop_it = end_pos;
for (i=0; i < stop_it; i++) if( e.value[i].search(/[\r\n]/) != -1 ) end_pos = end_pos - .5;
tr.moveEnd('textedit',-1);
tr.moveStart('character',start_pos);
tr.moveEnd('character',end_pos - start_pos);
tr.select();
}
return this.get_selection();
};
}(jQuery));
/*
Before going further, you should be aware of the alternate approach called "editable iframe" [keywords: designMode, execCommand, WYSIWYG] [see also: http://www.quirksmode.org/dom/execCommand.html]
*/
// 'src' parameters of functions below denotes the DOM textarea element
function update_preview(src, str) {
if (typeof str == "string") {
$(src).nextAll(".view").html(str);
return;
}
// Filter out tags which are not allowed
src.value = src.value.replace("<internal>","[[Article Name");
src.value = src.value.replace("</internal>","]]");
src.value = src.value.replace("<external>","--http://www.example.com++Link title");
src.value = src.value.replace("</external>","--");
src.value = src.value.replace(/<(?!\/|([biusqp]|br ?\/?|sup|sub|ul|ol|li|table|tr|td|th( style=['"][^'"]+['"])?|a href=['"][^'"]+['"]|center|img [^>]+)>)/g, "<");
src.value = src.value.replace(/<\/(?!([biusqpa]|sup|sub|ul|ol|li|center|table|tr|td|th)>)/g, "</");
$(src).nextAll(".view").html(src.value);
}
function get_corrected_selection(src) {
// make the selection wrap around (or unwrap) partially selected html-tags at the ends
var sel = $(src).get_selection();
var invalidable1 = /^[^<]*>/.exec(sel.text), invalidable2 = /<[^>]*$/.exec(sel.text);
var new_start = sel.start+(invalidable1 == null ? 0 : invalidable1[0].length);
var new_end = sel.end-(invalidable2 == null ? 0 : invalidable2[0].length);
if (new_start != sel.start || new_end != sel.end) {
$(src).set_selection(new_start, new_end);
sel = $(src).get_selection();
}
return sel;
}
function valid_selection_ends(src, sel) {
// check if the selection ends cuts an html-tag
var invalidable1 = /<[^>]*$/.test(src.value.substring(sel.start-8, sel.start)),
invalidable2 = /^[^<]*>/.test(src.value.substring(sel.end, sel.end+8));
return !(invalidable1 || invalidable2);
}
function styler(src, tag) {
// handles buttons such as bold, italics, underline etc.
var tag_o = "<"+tag+">", tag_c = "</"+tag+">";
var sel = get_corrected_selection(src);
if (sel.length == 0)
if (!valid_selection_ends(src, sel))
return;
var start_pos = sel.start;
var end_pos;
var tag_o_i = sel.text.indexOf(tag_o), tag_c_i = sel.text.indexOf(tag_c), tag_c_li = sel.text.lastIndexOf(tag_c);
// each cases of selected contents is commented beside the if-conditions below
if (tag_o_i == 0 && tag_c_li > 0 && tag_c_li == sel.length-tag_c.length) { //<tag>...</tag>
end_pos = sel.end - tag_o.length - tag_c.length;
src.value = src.value.substring(0, sel.start) + sel.text.substring(tag_o.length, sel.length-tag_c.length) + src.value.substring(sel.end);
} else if (tag_o_i >= 0 && tag_c_i > tag_o_i && tag != "q") { //...<tag>...</tag>...
end_pos = sel.end;
src.value = src.value.substring(0, sel.start) + tag_o + sel.text.replace(tag_o, "").replace(tag_c, "") + tag_c + src.value.substring(sel.end);
} else if (tag_o_i >= 0 && tag_c_i >= 0 && tag_c_i < tag_o_i) { //...</tag>...<tag>...
end_pos = sel.end - tag_o.length - tag_c.length;
src.value = src.value.substring(0, sel.start) + sel.text.replace(tag_o, "").replace(tag_c, "") + src.value.substring(sel.end);
} else if (tag_o_i == 0 && tag_c_i < 0) { //<tag>...
end_pos = sel.end;
src.value = src.value.substring(0, sel.start) + sel.text.replace(tag_o, "") + tag_o + src.value.substring(sel.end);
} else if (tag_o_i > 0 && tag_c_i < 0) { //...<tag>...
end_pos = sel.end;
src.value = src.value.substring(0, sel.start) + tag_o + sel.text.replace(tag_o, "") + src.value.substring(sel.end);
} else if (tag_o_i < 0 && tag_c_i >= 0 && tag_c_i == sel.length-tag_c.length) { //...</tag>
end_pos = sel.end;
src.value = src.value.substring(0, sel.start) + tag_c + sel.text.replace(tag_c, "") + src.value.substring(sel.end);
} else if (tag_o_i < 0 && tag_c_i >= 0 && tag_c_i < sel.length-tag_c.length) { //...</tag>...
end_pos = sel.end;
src.value = src.value.substring(0, sel.start) + sel.text.replace(tag_c, "") + tag_c + src.value.substring(sel.end);
} else { //...
src.value = src.value.substring(0, sel.start) + tag_o + sel.text + tag_c + src.value.substring(sel.end);
if (sel.length == 0)
start_pos = end_pos = sel.start + tag_o.length;
else
end_pos = start_pos + tag_o.length + sel.length + tag_c.length;
}
$(src).set_selection(start_pos,end_pos);
update_preview(src);
}
function styler_click(e) {
styler($(e.target).closest(".kaja-input").children("textarea").get(0), e.data.tag);
}
function before_state1(state1_i, state2_i) {
return (state1_i >= 0 && ((state2_i >= 0 && state1_i < state2_i) || state2_i < 0));
}
function after_state1(state1_li, state2_li) {
return (state1_li >= 0 && ((state2_li >= 0 && state1_li > state2_li) || state2_li < 0));
}
function enter_pressed(src, shifted) {
// handles the enter-key press event, with the second parameter indicating whether shift was pressed
if (!shifted)
return true;
var sel = $(src).get_selection();
if (!valid_selection_ends(src, sel)) {
update_preview(src);
return false;
}
var cursor_pos, new_start, new_end, ex;
if (/^[^<]*<\/li>/.test(src.value.substring(sel.start))) {
src.value = src.value.substring(0, sel.start) + "</li>\n<li>" + src.value.substring(sel.start);
cursor_pos = sel.start+10;
} else if ( ex=/<\/li>\s*$/.exec(src.value.substring(0,sel.start)) ) {
src.value = src.value.substring(0, ex.index) + "</li>\n<li>" + src.value.substring(ex.index);
cursor_pos = ex.index+10;
} else {
var li_c_i = src.value.indexOf("</li>", sel.start), li_o_i = src.value.indexOf("<li>", sel.start), //>=0 implies >=sel.start
li_c_li = src.value.lastIndexOf("</li>", sel.start-1), li_o_li = src.value.lastIndexOf("<li>", sel.start-1),
ul_c_i = src.value.indexOf("</ul>", sel.start), ul_o_i = src.value.indexOf("<ul>", sel.start),
ul_c_li = src.value.lastIndexOf("</ul>", sel.start-1), ul_o_li = src.value.lastIndexOf("<ul>", sel.start-1),
ol_c_i = src.value.indexOf("</ol>", sel.start), ol_o_i = src.value.indexOf("<ol>", sel.start),
ol_c_li = src.value.lastIndexOf("</ol>", sel.start-1), ol_o_li = src.value.lastIndexOf("<ol>", sel.start-1);
var after_ul_o = after_state1(ul_o_li, ul_c_li), after_ol_o = after_state1(ol_o_li, ol_c_li),
before_ul_c = before_state1(ul_c_i, ul_o_i), before_ol_c = before_state1(ol_c_i, ol_o_i);
//alert("after_ol_o: " + after_ol_o + ", after_ul_o: " + after_ul_o + ", before_ol_c: " + before_ol_c + ", before_ul_c: " + before_ul_c);
var inside_ul = false, inside_ol = false, ignore = false;
if (after_ul_o && before_ul_c) {
if (!after_ol_o && !before_ol_c)
inside_ul = true;
else if (after_ol_o && before_ol_c) {
if (ul_o_li > ol_o_li && ul_c_i < ol_c_i)
inside_ul = true;
else if (ol_o_li > ul_o_li && ol_c_i < ul_c_i)
inside_ol = true;
else
ignore = true;
} else {
if (after_ol_o && ol_o_li > ul_o_li) {
//src.value = src.value.substring(0, ol_o_li+4) + "</ol>" + src.value.substring(ol_o_li+4);
new_start = ol_o_li;
new_end = new_start+4;
} else if (before_ol_c && ol_c_i < ul_c_i) {
new_start = ol_c_i;
new_end = new_start+5;
}
ignore = true;
}
} else if (after_ol_o && before_ol_c && !after_ul_o && !before_ul_c)
inside_ol = true;
else if (after_ul_o && ul_o_li > ol_o_li) {
//src.value = src.value.substring(0, ul_o_li+4) + "</ul>" + src.value.substring(ul_o_li+4);
new_start = ul_o_li;
new_end = new_start+4;
ignore = true;
} else if (before_ul_c && ul_c_i < ol_c_i) {
new_start = ul_c_i;
new_end = new_start+5;
ignore = true;
}
if (inside_ol || inside_ul) {
var par_o_li = (inside_ol ? ol_o_li : ul_o_li), par_c_i = (inside_ol ? ol_c_i : ul_c_i);
if (after_state1(li_o_li, li_c_li)) {
if (before_state1(li_c_i, li_o_i)) { //<li>..<x>..|..</x>..</li>
src.value = src.value.substring(0, li_c_i+5) + "\n<li></li>" + src.value.substring(li_c_i+5);
cursor_pos = li_c_i+10;
} else if (before_state1(li_o_i, li_c_i) && par_o_li > li_o_li) { //<li>...<xl>|<li>
src.value = src.value.substring(0, par_o_li+4) + "\n<li></li>\n" + src.value.substring(li_o_i);
cursor_pos = par_o_li+9;
} else {
new_end = new_start = li_o_li+4;
ignore = true;
}
} else if (before_state1(li_o_i, li_c_i)) { //<xl>|<li>
src.value = src.value.substring(0, par_o_li+4) + "\n<li></li>\n" + src.value.substring(li_o_i);
cursor_pos = par_o_li+9;
} else { //<xl>|</xl>
src.value = src.value.substring(0, par_o_li+4) + "\n<li></li>\n" + src.value.substring(par_c_i);
cursor_pos = par_o_li+9;
}
} else if (!ignore) {
src.value = src.value.substring(0, sel.start) + "<br/>\n" + src.value.substring(sel.end);
cursor_pos = sel.start+6;
}
}
if (ignore) {
if (!new_start)
new_end = new_start = sel.start;
} else
new_end = new_start = cursor_pos;
update_preview(src);
$(src).set_selection(new_start,new_end);
return false;
}
function get_line(str, index) {
var i = str.indexOf("\n", index), li = index > 0 ? str.lastIndexOf("\n", index-1) : -1;
if (i >= 0) {
if (li >= 0)
return {start: li+1, end: i, text: str.substring(li+1, i)};
else
return {start: 0, end: i, text: str.substring(0, i)};
} else if (li >= 0)
return {start: li+1, end: str.length, text: str.substring(li+1)};
else
return {start: 0, end: str.length, text: str};
}
function lister(src, tag) {
// handles bulleting and numbering buttons
var tag_o = "<"+tag+">", tag_c = "</"+tag+">", li_o = "\n<li>", li_c = "</li>\n";
var sel = get_corrected_selection(src);
var cursor_pos;
if (sel.length == 0) {
var curline = get_line(src.value, sel.start), i1, i2;
var li_o_i = curline.text.indexOf("<li>"), li_c_i = curline.text.indexOf("</li>");
if (li_o_i < li_c_i) { //li_c_i >= 0
var li_c_li = src.value.lastIndexOf("</li>", curline.start);
if (li_c_li > 0 && li_c_li > curline.start-8) {
i1 = i2 = curline.start;
i2 += li_c_i;
src.value = src.value.substring(0, li_c_li) + "\n" + tag_o + "\n" + src.value.substring(i1, i2) + li_c + tag_c + "\n" + src.value.substring(i2);
cursor_pos = li_c_li + 6 + li_c_i;
} else if (li_o_i < 0) {
i1 = i2 = curline.start;
i2 += li_c_i;
src.value = src.value.substring(0, i1) + tag_o + li_o + src.value.substring(i1, i2) + li_c + tag_c + "\n" + src.value.substring(i2);
cursor_pos = i2 + 9;
}
} else if (li_c_i < 0 && li_o_i < 0 && !(/<\/?[uo]l>/.test(curline.text))) {
i1 = curline.start; i2 = curline.end;
src.value = src.value.substring(0, i1) + tag_o + li_o + src.value.substring(i1, i2) + li_c + tag_c + src.value.substring(i2);
cursor_pos = i2 + 9;
}
} else if (/^\s*<li>/.test(sel.text) && /<\/li>\s*$/.test(sel.text.substring(sel.text.lastIndexOf("\n")))) {
var li_c_li = src.value.substring(sel.start-10, sel.start).lastIndexOf("</li>");
if (li_c_li >= 0) {
li_c_li += sel.start-10;
src.value = src.value.substring(0, li_c_li) + "\n" + tag_o + "\n" + sel.text.substring(sel.text.indexOf("<li>"), sel.text.lastIndexOf("</li>")+5) + "\n" + tag_c + "\n</li>" + src.value.substring(sel.end);
cursor_pos = li_c_li+5;
}
} else if (/<\/?(ol|ul|li)>/.test(sel.text) == false) {
src.value = src.value.substring(0, sel.start) + tag_o + li_o + sel.text.replace(/\n/g, "</li>\n<li>") + li_c + tag_c + src.value.substring(sel.end);
cursor_pos = sel.start+4;
} //TODO else if's: switch ol-ul, smart-delisting!! WTF?!
if (typeof cursor_pos != "undefined")
$(src).set_selection(cursor_pos,cursor_pos);
update_preview(src);
}
function lister_click(e) {
lister($(this).closest(".kaja-input").children("textarea").get(0), e.data.tag);
}
function help_click() {
var t = $(this).closest(".kaja-input").children(".help-view");
if (t.html() == "")
t.html("Pressing Shift+Enter: <ul><li>Inserts a proper line-break when outside lists (bullets and numbering)</li> <li>Creates a new list-item when inside lists (bounded by 'ul' for bulleted (unordered) and 'ol' for numbered (ordered)).</li></ul>" +
"To convert a simple line-seperated list to an ordered/unodered list, select them and press one of the bulleting or numbering buttons shown above...<br/>" +
"Finally, feel free to press Ctrl+Z to undo any unexpected changes...<br/><br/><span class=\"clear\"></span>");
else
t.html("");
}
function ins_img_click() {
var ki = $(this).closest(".kaja-input");
var src = ki.children("textarea").get(0);
var sel = get_corrected_selection(src);
if (!valid_selection_ends(src, sel)) {
update_preview(src);
return;
}
var d = $("<div />").appendTo(ki);
d.ajaxupload({ /* also adds ax-uploader class to d */
url:'uploader.php',
remotePath:'images/articles/',
maxFiles: 1,
maxFileSize: '2M',
allowExt:['jpg','png'],
maxConnections: 1,
thumbWidth: 500,
thumbHeight: 400,
thumbPostfix: '_resized',
editFilename: true,
finish: function(files) {
var u = $(this.source), img = files[0], exti = img.lastIndexOf('.');
img = img.substring(0, exti) + "_resized" + img.substring(exti);
u.ajaxupload('destroy');
var src = u.closest(".kaja-input").children("textarea").get(0),
sel = $(src).get_selection(),
itag = "<img src=\"/"+ imagesSrc +"/"+img+"\" alt=\""+files[0]+"\"/>";
src.value = src.value.substring(0, sel.start) + itag + src.value.substring(sel.end);
$(src).set_selection(sel.start,sel.start+itag.length);
update_preview(src);
u.remove();
}
});
var browse = $("<input type=button value=Browse />")
.click(function() { $(this).closest(".ax-uploader").find("input.ax-browse").click(); })
.appendTo(d);
$("<input type=button value=Upload />")
.click(function() { $(this).closest(".ax-uploader").ajaxupload('start'); this.disabled=true; })
.appendTo(d);
$("<input type=button value=Cancel />")
.click(function() { $(this).closest(".ax-uploader").ajaxupload('destroy'); })
.appendTo(d);
browse.click();
}
function new_kaja_input(src) {
$(src).wrap("<div class=\"kaja-input\" />");
$("<span/>", {"class": "ki-but", html: "<b>B</b>", title: "Bold"}).click({tag: "b"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<i>I</i>", title: "Italics"}).click({tag: "i"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<u>U</u>", title: "Underline"}).click({tag: "u"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<s>S</s>", title: "Strikeout"}).click({tag: "s"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<q>q</q>", title: "Quotes"}).click({tag: "q"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "X<sup>2</sup>", title: "Superscript"}).click({tag: "sup"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "X<sub>2</sub>", title: "Subscript"}).click({tag: "sub"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<img src=\"images/bull.png\" alt=\"Bulleting\" />", title: "Bulleting"}).click({tag: "ul"}, lister_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<img src=\"images/num.png\" alt=\"Numbering\" />", title: "Numbering"}).click({tag: "ol"}, lister_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<img src=\"images/img.png\" alt=\"Insert image\" />", title: "Insert image"}).click(ins_img_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<a>Internal</a>", title: "Internal Link"}).click({tag: "internal"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "<a>External</a>", title: "External Link"}).click({tag: "external"}, styler_click).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "Preview"}).insertBefore(src);
$("<span/>", {"class": "ki-but", html: "Help"}).click(help_click).insertBefore(src);
$("<span/>", {"class":"clear"}).insertBefore(src);
$("<span/>", {"class":"help-view"}).insertBefore(src);
$("<span/>", {"class":"clear"}).insertAfter(src);
$("<div/>", {"class":"view"}).insertAfter(src);
$(src).blur(function() {
update_preview(this);
});
$(src).keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13)
return enter_pressed(this, e.shiftKey);
});
}
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$error = "";
if(isset($_POST['renameTableSubmit'])) {
$table_id = $_POST['idTable'];
$table_name = $_POST['renameTableInput'];
$rename_query = $mysqli->query("UPDATE calendar_tables SET name = '$table_name' WHERE id = '$table_id'");
if($rename_query) {
header("Location: ../calendar.php?renametable=1");
}
else {
$error = "Renaming failed. Please try again";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h3>Rename Table</h3>
<!--Form for categorization of articles-->
<form action="workspace/calendar/renametable.php?table=<?php echo $_GET['table'];?>" method="POST" name="renameTableForm" id="renameTableForm">
<?php
$table = $_GET['table'];
$get_table = $mysqli->query("SELECT * FROM calendar_tables WHERE id='$table'");
$table = $get_table->fetch_assoc();
echo ' <input id="idTable" name="idTable" type="hidden" value="'.$table['id'].'"/>
<input id="nameTable" name="nameTable" type="hidden" value="'.$table['name'].'"/>
<p>Current Name : '.$table['name'].'</p>
<input id="renameTableInput" name="renameTableInput" type="text" placeholder="Enter new name for table"/>
';
?>
<input id="renameTableSubmit" name="renameTableSubmit" class="button-primary" type="submit" value="Submit">
<?php echo '<p>'.$error.'</p>'; ?>
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#renameTableForm').submit(function() {
var newName = $('#renameTableInput').val();
var oldName = $('#nameTable').val();
if(newName == "") {
alert("Enter a name please");
return false;
}
if(newName == oldName) {
alert("Enter a different name please");
return false;
}
});
</script>
</body>
</html>
<file_sep><?php
session_start();
if(!(isset($_SESSION['login'])) || ($_SESSION['login'] != substr(md5('appletree'), 0, 20))) {
session_destroy();
header('Location:/workspace/login.php');
die();
}
if(substr(basename($_SERVER['PHP_SELF']), 0, -4) == "workspace/workspace") {
if($_SESSION['usertype'] != md5('editor')) {
header('Location:/workspace/login.php');
session_destroy();
die();
}
}
?><file_sep><?php
require_once('./config.php');
require_once("./initialize_database.php");
require_once("./authenticate.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:auto;word-wrap: break-word;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;word-break:normal;}
.tg .tg-s6z2{text-align:center;padding: 0}
</style>
</head>
<body>
<!-- Navigation Bar -->
<?php include("../includes/layout/navbar.php") ?>
<div class="container" style="padding-top:5em">
<div class="twelve columns">
<h5>
<?php
if(isset($_GET['newtable'])) {
if($_GET['newtable'] == 1) {
echo "New table added successfully";
}
}
if(isset($_GET['deletetable'])) {
if($_GET['deletetable'] == 1) {
echo "Table deleted successfully";
}
}
if(isset($_GET['deleterow'])) {
if($_GET['deleterow'] == 1) {
echo "Row deleted successfully";
}
}
if(isset($_GET['renametable'])) {
if($_GET['renametable'] == 1) {
echo "Table renamed successfully";
}
}
?>
</h5>
<form class="six columns" method="POST" action="workspace/calendar/addnewtable.php" id="newTableForm">
<input type="text" name="newTableName" id="newTableName" placeholder="Enter new table name" />
<input type="submit" class="button" href="./workspace/calendar/addnewtable.php" value="Create new table" name="newTableSubmit" id="newTableSubmit">
</form>
</div>
<?php
$table_query = $mysqli->query("SELECT * FROM calendar_tables");
while($table = $table_query->fetch_assoc()) {
echo '
<h3 class="">'.$table['name'].'</h3>
<a class="button" style="width: 20%" href="./workspace/calendar/renametable.php?table='.$table['id'].'">Rename Table</a>
<a class="button" style="width: 20%" href="./workspace/calendar/deletetable.php?table='.$table['id'].'">Delete Table</a>
<br/>
<br/>
<table class="tg" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
<col style="width: 10%">
</colgroup>
<tr>
<th class="tg-s6z2"></th>
<th class="tg-s6z2">Name of Crop</th>
<th class="tg-s6z2">Time and Season</th>
<th class="tg-s6z2">Seeds (g)</th>
<th class="tg-s6z2">Gap between seeds (cm)</th>
<th class="tg-s6z2">Depth (cm)</th>
<th class="tg-s6z2">Sapling Density</th>
<th class="tg-s6z2">Produce (kg)</th>
<th class="tg-s6z2"></th>
<th class="tg-s6z2"></th>
</tr>';
$table_id = $table['id'];
$table_row_query = $mysqli->query("SELECT * FROM `calendar` WHERE `table` = '$table_id'");
while($table_row = $table_row_query->fetch_assoc()) {
echo '
<tr>
<td class="tg-s6z2">'.$table_row['table'].'</td>
<td class="tg-s6z2">'.$table_row['column1'].'</td>
<td class="tg-s6z2">'.$table_row['column2'].'</td>
<td class="tg-s6z2">'.$table_row['column3'].'</td>
<td class="tg-s6z2">'.$table_row['column4'].'</td>
<td class="tg-s6z2">'.$table_row['column5'].'</td>
<td class="tg-s6z2">'.$table_row['column6'].'</td>
<td class="tg-s6z2">'.$table_row['column7'].'</td>
<td class="tg-s6z2"><a class="button" href="./workspace/calendar/editrow.php?id='.$table_row['id'].'">EDIT</a></td>
<td class="tg-s6z2"><a class="button" href="./workspace/calendar/deleterow.php?id='.$table_row['id'].'">DELETE</a></td>
</tr>';
}
echo '</table>
<a class="button" href="./workspace/calendar/addnewrow.php?table='.$table['id'].'">Add a new row</a><br/><br/><br/>';
}
?>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$("#newTableForm").submit(function() {
var newtable = $("#newTableName").val();
if(newtable == "") {
alert("Please enter new table's name");
return false;
}
});
</script>
</body>
</html>
<file_sep>var advancedStatus = false;
var isOpen = isAnimating = false;
$('#advanced_trigger').click(function() {
if(advancedStatus) {
$('#primary_select').val('0');
if ($('#secondary_select').length > 0) {
$('#secondary_select').val('0');
}
$('#advanced').slideUp("slow");
advancedStatus = false;
}
else {
$('#advanced').slideDown("slow");
advancedStatus = true;
}
});
$('.morphsearch-close').click(function() {
$('#advanced').slideUp("fast");
advancedStatus = false;
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$('#advanced').slideUp("fast");
advancedStatus = false;
} // escape key maps to keycode `27`
});
//to populate the primary categories
$.ajax({
type: 'GET',
url: "api/primary.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(data) {
var i;
var menuContent = "";
var selectionContent = '<select id="primary_select" name="primary_select">';
selectionContent += '<option value="0">Select primary category</option>'
for(i = 0; i < data.length; i++) {
menuContent += '<figure class="effect-honey">';
menuContent += '<img src="images/primary/' + data[i]['image'] + '.jpg" alt="img04"/>';
menuContent += '<figcaption>';
menuContent += '<h2>'+ data[i]['name'] +'</h2>';
menuContent += '<a href="'+ data[i]['link'] +'">View more</a>';
menuContent += '</figcaption>';
menuContent += '</figure>';
if(i == 2) continue;
selectionContent += '<option value="'+ data[i]['id'] +'">'+ data[i]['name'] +'</option>';
}
selectionContent += '</select>';
$('#primary_cat').html(selectionContent);
$('#primary').html(menuContent);
},
error: function(jqXHR, textStatus) {
alert("Please check your internet connection");
}
});
//Searching
$('#searchForm').submit(function() {
if(!isOpen) return false;
var searchQuery = $('#searchInput').val();
var primCat = $('#primary_select').val();
if(searchQuery == "") {
alert("Please enter search query.");
return false;
}
var regx = /^[A-Za-z0-9 ]+$/;
if (!regx.test(searchQuery)) {
alert("Only alphabets and numbers allowed");
return false;
}
if(primCat == 0) {
var source = 'api/search.php?query=' + searchQuery;
}
else {
var secCat = $('#secondary_select').val();
if(secCat == 0) {
var source = 'api/search.php?query=' + searchQuery + "&primary=" + primCat + "&secondary=0";
}
else {
var source = 'api/search.php?query=' + searchQuery + "&primary=" + primCat + "&secondary=" + secCat;
}
}
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
var i;
var content = "<div>";
if(data[0]['title'] <= 0) {
content += '<div class="result-item">';
content += "<h3>" + data[0].content + "</h3></div>";
}
else {
for(i=0; i < data.length; i++) {
content += '<div class="result-item"><h3><a href="articles/'+ data[i].link + '">' + data[i].title + '</a></h3>';
content += "<p>" + data[i].content + "</p></div>";
}
}
$('#search_results').html(content);
$('#search_results').slideDown("slow");
},
error: function (jqXHR, textStatus) {
alert(textStatus);
}
});
return false;
});
var data = (function() {
var json = null;
$.ajax({
type: 'GET',
url: 'api/secondary.php ',
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
json = data;
},
error: function (jqXHR, textStatus) {
alert(textStatus);
}
});
return json;
})();
//Populating the secondary dropdown based on the primary selected value
$("#primary_select").change(function() {
/* JSON array fetched from the API*/
var index = $('#primary_select').val() - 1;
$("select option:selected").each(function() {
//alert($('#primary_select').val());
if(index == -1) {
return false;
}
var j = data[index].length;
var i;
var content = ""; //Content for the secondary category dropdown
content += '<select id="secondary_select" name="secondary_select"><option selected value="0">Select Secondary category</option>';
for(i = 0; i < j; i++) {
content += '<option value="' + data[index][i]['id'] + '">' + data[index][i]['name'] + '</option>';
}
content += '</select>';
$('#secondary_cat').html(""); //Clearing the secondary category content
$('#secondary_cat').append(content); //Adding secondary category dropdown*/
});
}).trigger( "change" );
(function() {
var morphSearch = document.getElementById( 'morphsearch' ),
input = morphSearch.querySelector( 'input.morphsearch-input' ),
ctrlClose = morphSearch.querySelector( 'span.morphsearch-close' ),
// show/hide search area
toggleSearch = function(evt) {
// return if open and the input gets focused
input.focus();
if( evt.type.toLowerCase() === 'focus' && isOpen ) return false;
//var offsets = morphsearch.getBoundingClientRect();
if( isOpen ) {
classie.remove( morphSearch, 'open' );
// trick to hide input text once the search overlay closes
/* todo: hardcoded times, should be done after transition ends
/^if( input.value !== '' ) {
setTimeout(function() {
classie.add( morphSearch, 'hideInput' );
input.focus();
setTimeout(function() {
classie.remove( morphSearch, 'hideInput' );
input.value = '';
}, 300 );
}, 500);
}*/
input.blur();
}
else {
classie.add( morphSearch, 'open' );
input.focus();
}
isOpen = !isOpen;
};
// events
input.addEventListener( 'focus', toggleSearch );
ctrlClose.addEventListener( 'click', toggleSearch );
//document.getElementById('searchSubmit').addEventListener('click', toggleSearch );
// esc key closes search overlay
// keyboard navigation events
document.addEventListener( 'keydown', function( ev ) {
var keyCode = ev.keyCode || ev.which;
if( keyCode === 27 && isOpen ) {
toggleSearch(ev);
}
});
/***** for demo purposes only: don't allow to submit the form *****/
//document.getElementById('searchSubmit').addEventListener( 'click', function(ev) { ev.preventDefault(); } );
})();
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});<file_sep><?php
$response = ""; //variable to hold the error message
if(isset($_POST['newArticleSubmit'])) {
$new_article = $_POST['newArticleInput'];
$name_query = $mysqli->query("SELECT page_title FROM page WHERE page_title='$new_article'");
if($name_query->num_rows) {
$response = "<span style='color:red'>The article already exists. Please enter another name.</span>";
}
else {
$name_query = $mysqli->query("INSERT INTO `page` (`page_id`, `prim_cat`, `sec_cat`, `page_title`, `page_creator`, `page_counter`, `page_content`) VALUES (NULL, '0', '0', '$new_article', '$_SESSION[user_id]', NULL, NULL)");
if($name_query) {
$response = "<span style='color:green'>New article created</span>";
}
else {
$response = "<span style='color:red'>Article creation failed</span>";
}
}
}
?><file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("../authenticate.php");
if(isset($_POST['newTableSubmit'])) {
$new_table = htmlspecialchars($_POST['newTableName']);
$add_new_table = $mysqli->query("INSERT INTO `calendar_tables` (`id`, `name`) VALUES (NULL, '$new_table')");
if($add_new_table) {
header("Location: ../calendar.php?newtable=1");
}
else {
echo'Could not add a new table. Please try again';
}
}
else {
header("Location: ../calendar.php");
}
?>
<file_sep><?php
/*require_once("./workspace/config.php");
require_once("./workspace/initialize_database.php");
echo "INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('2', '1', 'B', 'Flowers');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('3', '1', 'C', 'Leaves');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('4', '1', 'D', 'Roots');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('5', '2', 'A', 'Alappuzha');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('6', '2', 'B', 'Ernakulam');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('7', '2', 'C', 'Idukki');";
echo "<br/>INSERT INTO `prototype`.`category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES ('8', '2', 'D', 'Kannur');";
$text = "Lorem ipsum dolor sit amet, consectetur [[Fish]] adipisicing elit, sed do eiusmod [[Harry Potter]]";
//echo $text;
//echo "<br/>";
function verify_internal_link($link) {
global $mysqli;
$title_query = $mysqli->query("SELECT page_title FROM page WHERE page_title='$link'");
if($title_query->num_rows == 0) return FALSE;
else return TRUE;
}
function text_to_link($text) {
preg_match_all("/\[\[[a-zA-Z ]*\]\]/", $text, $output_array);
foreach ($output_array[0] as &$value) {
$len = strlen($value);
$value_new = substr($value, 2, $len-4);
if(verify_internal_link($value_new)) {
$value_link = preg_replace("/[ ]/", "_", $value_new);
$link = '<a href="articles/'.$value_link.'" class="true-link">'.$value_new.'</a>';
$text = str_replace($value, $link, $text);
}
else {
$value_link = preg_replace("/[ ]/", "_", $value_new);
$link = '<a href="#" class="false-link" style="color:red">'.$value_new.'</a>';
$text = str_replace($value, $link, $text);
}
}
return $text;
}
$text = text_to_link($text);
//echo $text;
//echo "<br/>";
/*
function link_to_text($text) {
preg_match_all("/\<a href=\"[a-zA-Z_\/]*\" class=\"[a-zA-Z-]*\">[a-zA-Z ]*<\/a>/", $text, $output_array);
foreach ($output_array[0] as &$value) {
preg_match("/>[a-zA-Z ]*</", $value, $output_value);
$len = strlen($output_value[0]);
$value_new = substr($output_value[0], 1, $len-2);
$value_new = '[['.$value_new.']]';
$text = str_replace($value, $value_new, $text);
}
return $text;
}
$text = text_to_link($text);
echo $text;
echo "<br/>";
$text = link_to_text($text);
echo $text;*/
$var = "Once upon a time in a dense forest Superman lived greatly ever after forever evermore --http://www.example.com++Link title--";
$word = preg_quote("Superman");
$text = preg_match("/--[a-zA-Z\+\.:\/ ]*--/", $var, $matches);
echo count($matches[0]);
?>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
if(isset($_POST['renameCatSubmit'])) {
$primary_cat_id = $_POST['primary_select'];
$new_prim_cat_name = $_POST['renamePrimaryCat'];
$option_exist = $mysqli->query("SELECT * FROM primary_category WHERE cat_id = '$primary_cat_id'");
if($option_exist->num_rows == 0) {
$error = "The option you selected is not present. Kindly choose another one.";
}
else {
$update_primary_cat_name = $mysqli->query("UPDATE primary_category SET `cat_name` = '$new_prim_cat_name' WHERE cat_id = '$primary_cat_id'");
if($update_primary_cat_name) {
header("Location:confirmcatmod.php?status=3");
}
else {
$error = "Updating the name of the Primary Category failed. Please try again.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h3>Categories</h3>
<!--Form for categorization of articles-->
<form action="workspace/cat/renameprimary.php" method="POST" name="renamePrimaryCatForm" id="renamePrimaryCatForm">
<div id="primary_cat">
Primary Category
<select id="primary_select" name="primary_select"> <!--Selection of primary category-->
<?php
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
echo '<option selected value="0">Select category</option>'; //Default option
$primary_category_count = $get_primary->num_rows; //Get number of primary categories
while($get_primary_list = $get_primary->fetch_assoc()) {
echo '<option value="'.$get_primary_list['cat_id'].'">'.$get_primary_list['cat_name'].'</option>';
}
?>
</select>
</div>
<input id="renamePrimaryCat" name="renamePrimaryCat" type="text" />
<input id="renameCatSubmit" name="renameCatSubmit" class="button-primary" type="submit" value="Submit">
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
/* Action at form submit */
$('#renamePrimaryCatForm').submit(function() {
var primCat = $('#primary_select').val();
if(primCat == "0") { //If primary category not selected
alert("Please select Primary category.");
return false;
}
var renamePrimCat = $('#renamePrimaryCat').val();
if(renamePrimCat == "") {
alert("Please enter a name for the selected Primary Category."); //If no new name entered
return false;
}
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$error = "";
if(isset($_POST['deleteCatSubmit'])) {
$primary_cat_id = $_POST['primary_select'];
$option_exist = $mysqli->query("SELECT * FROM primary_category WHERE cat_id = '$primary_cat_id'");
if($option_exist->num_rows == 0) {
$error = "The option you selected has already been deleted. Kindly choose another one.";
}
else {
$default_pages = $mysqli->query("UPDATE page SET prim_cat = '0' , sec_cat = '0' WHERE prim_cat = '$primary_cat_id'");
if($default_pages) {
$delete_secondary_cat = $mysqli->query("DELETE FROM secondary_category WHERE primary_cat = '$primary_cat_id'");
if($delete_secondary_cat) {
$delete_primary_cat = $mysqli->query("DELETE FROM primary_category WHERE cat_id = '$primary_cat_id'");
if($delete_primary_cat) {
header("Location:confirmcatmod.php?status=5");
}
else {
$error = "Deletion of Primary Category failed. Secondary Categories have been deleted. Articles have been uncategorized. Please try again to delete the Crimary Category.";
}
}
else {
$error = "Deletion of Primary Cateogory and corresponding Secondary Categories have failed. Articles have been uncategorized. Please try again to delete the Primary Category";
}
}
else {
$error = "Article uncategorization has failed. Please try again.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h3>Categories</h3>
<!--Form for categorization of articles-->
<form action="workspace/cat/deleteprimary.php" method="POST" name="deletePrimaryCatForm" id="deletePrimaryCatForm">
<div id="primary_cat">
Primary Category
<select id="primary_select" name="primary_select"> <!--Selection of primary category-->
<?php
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
echo '<option selected value="0">Select category</option>'; //Default option
$primary_category_count = $get_primary->num_rows; //Get number of primary categories
while($get_primary_list = $get_primary->fetch_assoc()) {
if($get_primary_list['cat_id'] < 4) continue;
echo '<option value="'.$get_primary_list['cat_id'].'">'.$get_primary_list['cat_name'].'</option>';
}
?>
</select>
</div>
<input id="deleteCatSubmit" name="deleteCatSubmit" class="button-primary" type="submit" value="Submit">
</form>
<h5><?php echo $error; ?></h5>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
/* Action at form submit */
$('#deletePrimaryCatForm').submit(function() {
var primCat = $('#primary_select').val();
if(primCat == "0") { //If primary category not selected
alert("Please select Primary category.");
return false;
}
var selectedCategory = $('#primary_select :selected').text();
return(confirm("Are you sure you want to delete '"+ selectedCategory +"' Category?"));
});
</script>
</body>
</html>
<file_sep><?php
require("../authenticate.php");
?>
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Article Preview</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" type="text/css" href="css/article.css">
<body>
<!-- Navigation Bar -->
<?php include("../layout/navbar.php") ?>
<div id="main_content" class="container" style="padding-top:5rem;padding-bottom:4rem;height:95%"></div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
$(document).ready(function() {
var pathArray = window.location.pathname.split( '/' );
var first = "<?php echo $_GET['page']; ?>";
var source = "/api/content.php?page=" + first;
var tabindex;
var contents;
var navbuttons = "";
var i = 1;
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
var container = $("#main_content");
contents = "";
contents += '<div class="article-head"><h2>'+data['title']+'</h2>';
if(data['name_thumb']) {
contents += '<img src="images/malayalam-names/' + first + '.png" class="name_thumb"/>';
}
contents += '</div><br/><br/>';
if(data['pdf']) {
contents += '<a href="pdf/'+ first +'.pdf" target="_blank">Click here to read the article in Malayalam</a><br/><br/><br/>';
}
for ( i = 1; i < data['sections_count']; i++) {
tabindex = "tab"+(i+1);
contents += '<a class="button article_nav" style="width:auto" href="articles/'+first+'#'+tabindex+'">' + data['section_head'][i] + '</a>';
};
contents += '<br/><br/>';
//container.append(navbuttons);
i=1;
tabindex = "tab"+i;
contents += '<div class="tab_section_intro">';
contents += '<div class="tab_section_intro_content"><p>' + data[tabindex][1] + '</p></div>';
contents += '</div>';
//container.append(contents);
for (i = 2; i <= data['sections_count']; i++) {
tabindex = "tab"+i;
contents += '<div id="'+tabindex+'" class="tab_section">';
contents += '<div class="tab_section_head"><p>' + data[tabindex][0] + '</p></div>';
contents += '<div class="tab_section_content"><p>' + data[tabindex][1] + '</p></div>';
contents += '</div>';
}
container.append(contents);
},
error: function (jqXHR, textStatus) {
alert(textStatus);
}
});
$('.section_drop').click(function() {
$(this).parent().parent().children().slideDown();
});
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
if(isset($_POST['renameCatSubmit'])) {
$primary_cat_id = $_POST['primary_select'];
$secondary_cat_id = $_POST['secondary_select'];
$new_sec_cat_name = $_POST['renameSecondaryCat'];
$option_exist = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_cat_id' AND sub_cat = '$secondary_cat_id'");
if($option_exist->num_rows == 0) {
$error = "The option you selected is not present. Kindly choose another one.";
}
else {
$update_secondary_cat_name = $mysqli->query("UPDATE secondary_category SET `cat_name` = '$new_sec_cat_name' WHERE primary_cat = '$primary_cat_id' AND sub_cat = '$secondary_cat_id'");
if($update_secondary_cat_name) {
header("Location:confirmcatmod.php?status=4");
}
else {
$error = "Updating the name of the Secondary Category failed. Please try again.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h3>Categories</h3>
<!--Form for categorization of articles-->
<form action="workspace/cat/renamesecondary.php" method="POST" name="renameSecondaryCatForm" id="renameSecondaryCatForm">
<div id="primary_cat">
Primary Category
<select id="primary_select" name="primary_select"> <!--Selection of primary category-->
<?php
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
echo '<option selected value="0">Select category</option>'; //Default option
$primary_category_count = $get_primary->num_rows; //Get number of primary categories
while($get_primary_list = $get_primary->fetch_assoc()) {
echo '<option value="'.$get_primary_list['cat_id'].'">'.$get_primary_list['cat_name'].'</option>';
}
?>
</select>
</div>
<div id="secondary_cat"></div>
<input id="renameSecondaryCat" name="renameSecondaryCat" type="text" />
<input id="renameCatSubmit" name="renameCatSubmit" class="button-primary" type="submit" value="Submit">
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
/* Action at form submit */
$('#renameSecondaryCatForm').submit(function() {
var primCat = $('#primary_select').val();
if(primCat == "0") { //If primary category not selected
alert("Please select Primary category.");
return false;
}
var secCat = $('#secondary_select').val();
if(secCat == "0") { //If secondary category not selected
alert("Please select a Secondary category");
return false;
}
var renameSecCat = $('#renameSecondaryCat').val();
if(renameSecCat == "") {
alert("Please enter a name for the selected Secondary Category."); //If no new name entered
return false;
}
});
/* Action at option change */
$("#primary_select").change(function() {
var primary_count = <?php echo $primary_category_count; ?>; //get the primary category count
/* Creating the JSON array for populating secondary category
The array is populated at server side side and inserted into a varible "data"*/
<?php
$i = 0;
$arr = array(); //Variable to hold the json array
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
$arr['primary_count'] = $primary_category_count;
while($get_primary_list = $get_primary->fetch_assoc()) {
$primary_category_id = $get_primary_list['cat_id'];
$primary_category_name = $get_primary_list['cat_name'];
$category = array();
$get_secondary = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_category_id'");
$secondary_category = array();
$category['secondary_count'] = $get_secondary->num_rows;
$options = array();
while($get_secondary_list = $get_secondary->fetch_assoc()) {
$sub_item = array();
array_push($sub_item, $get_secondary_list['sub_cat']);
array_push($sub_item, $get_secondary_list['cat_name']);
array_push($options, $sub_item);
}
$category['options'] = $options;
$arr[$primary_category_id] = $category;
$i++;
}
$json = json_encode($arr);
echo "var data = ".$json;
?>
$( "select option:selected" ).each(function() {
var j = data[$(this).val()]['secondary_count']; //Secondary content count
var i;
var content = ""; //Content for the secondary category dropdown
content += "Secondary Category ";
content += '<select id="secondary_select" name="secondary_select"><option selected value="0">Select category</option>';
for(i = 0; i < j; i++) {
content += '<option value="' + data[$(this).val()]['options'][i][0] + '">' + data[$(this).val()]['options'][i][1] + '</option>';
}
content += '</select>';
$('#secondary_cat').html(""); //Clearing the secondary category content
$('#secondary_cat').append(content); //Adding secondary category dropdown
});
}).trigger( "change" );
</script>
</body>
</html>
<file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
$primary_query = $mysqli->query("SELECT * FROM primary_category");
$arr = array();
while($primary_result = $primary_query->fetch_assoc()) {
$entry = array();
$entry['id'] = $primary_result['cat_id'];
$entry['name'] = $primary_result['cat_name'];
$entry['image'] = str_replace(" ", "_", $primary_result['cat_name']);
switch ($entry['name']) {
case 'Soil Management':
$entry['link'] = $primary_result['cat_page'].".php";
break;
case 'Crop Calendar':
$entry['link'] = $primary_result['cat_page'].".php";
break;
default:
$entry['link'] = $primary_result['cat_page'].'/'.$primary_result['cat_id'].'/';
break;
}
array_push($arr, $entry);
}
print_r(json_encode($arr));
?><file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
require_once($article_link.'functions.php');
$arr = array(); //Array to hold the JSON
if(isset($_GET['query']) ) { //If only query word parameter present
$query = $_GET['query'];
if(preg_match('/^[a-zA-Z0-9 ]+/', $query) && $query != "") { //query has only alphanumeric characters
if(isset($_GET['primary']) AND isset($_GET['secondary'])) { //if primary or secondary categories set
$primary_cat = htmlspecialchars($_GET['primary']);
$secondary_cat = htmlspecialchars($_GET['secondary']);
if($primary_cat == "0"){
//echo '$primary_cat == "0"';
//echo '<br/>';
$sql_query = "SELECT * FROM page WHERE page_title LIKE '%$query%' OR upper(page_content) LIKE '%$query%'";
}
else if($primary_cat != "0" AND $secondary_cat == "0") {
//echo '$primary_cat != "0" AND $secondary_cat == "0"';
//echo '<br/>';
$sql_query = "SELECT * FROM page WHERE (page_title LIKE '%$query%' OR upper(page_content) LIKE '%$query%') AND prim_cat = '$primary_cat'";
}
else {
//echo '$primary_cat != "0" AND $secondary_cat != "0"';
//echo '<br/>';
$sql_query = "SELECT * FROM page WHERE (page_title LIKE '%$query%' OR upper(page_content) LIKE '%$query%') AND prim_cat = '$primary_cat' AND sec_cat = '$secondary_cat'";
}
}
else { //else query with no parameters
$sql_query = "SELECT * FROM page WHERE page_title LIKE '%$query%' OR upper(page_content) LIKE '%$query%'";
}
$search_database = $mysqli->query($sql_query);
if($search_database->num_rows == 0) {
$entry = array();
$entry['title'] = 0;
$entry['content'] = "No results found...";
array_push($arr, $entry);
}
else {
while($search_results = $search_database->fetch_assoc()) {
$entry = array();
$entry['title'] = $search_results['page_title'];
$entry['link'] = str_replace(" ", "_", $search_results['page_title']);
$content = $search_results['page_content'];
$word = preg_quote($query);
$text = preg_match("/[a-zA-Z \.\'\"]{0,40}/m", $content, $matches);
if($text == 0) continue;
$entry['content'] = $matches[0].'...';
array_push($arr, $entry);
}
if(count($arr) == 0) {
$entry = array();
$entry['title'] = 0;
$entry['content'] = "No results found...";
array_push($arr, $entry);
}
}
}
else {
$entry = array();
$entry['title'] = -10;
$entry['content'] = "Please enter a valid search term.";
array_push($arr, $entry);
}
}
$json=json_encode($arr);
print_r($json);
?><file_sep><?php
require_once("../authenticate.php");
$message = "";
$status = $_GET['status'];
if($status == 1) {
$message = "Primary Category created successfully";
}
if($status == 2) {
$message = "Secondary Category created successfully";
}
if($status == 3) {
$message = "Primary Category renamed successfully";
}
if($status == 4) {
$message = "Secondary Category renamed successfully";
}
if($status == 5) {
$message = "Primary Category deleted successfully";
}
if($status == 6) {
$message = "Secondary Category deleted successfully";
}
if($status == 7) {
$message = "Cover image uploaded successfully";
}
?>
<!DOCTYPE html>
<html>
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div class="container">
<div class="row">
<h4><?php echo $message; ?></h4>
</div>
</div>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function closepanel() {
window.close();
}
// use setTimeout() to execute
setTimeout(closepanel, 6000);
});
</script>
</body>
</html><file_sep><?php
require_once('../workspace/config.php');
require_once('../workspace/initialize_database.php');
require_once('../workspace/article/functions.php');
$article_name = str_replace("_", " ", htmlspecialchars($_GET['page']));
$query = "SELECT * FROM `page` WHERE `page_title`='$article_name'";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$arr = array();
$arr['title'] = $row['page_title'];
$desc = str_replace(array('<b>','</b>','<i>','</i>'),' ',$row['page_content']);
$desc = "Introduction||ttl||".$desc;
$desc = text_to_external_link(text_to_link($desc));
$sections = explode("||sec||", $desc);
$arr['sections_count'] = count($sections);
$j=count($sections);
$i=0;
while($i<$j)
{
$indexa = "tab".($i+1);
//$content[$i] = preg_replace('/src=\"/', 'src="http://www.tathva.org/organiser/', $content[$i]);
$tabsplit = explode("||ttl||", $sections[$i]);
$arr["section_head"][$i] = $tabsplit[0];
$arr[$indexa][0] = $tabsplit[0];
$arr[$indexa][1] = $tabsplit[1];
$i = $i + 1;
}
$arr['pdf'] = $row['pdf_status'];
$arr['name_thumb'] = $row['name_png_status'];
$json=json_encode($arr);
print_r($json);
?><file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$primary_cat = "";
$secondary_cat = "";
$error = "";
if(isset($_POST['newCategorySubmit'])) {
$new_category = $_POST['newPrimaryCat'];
$category_query = $mysqli->query("SELECT cat_name FROM primary_category WHERE cat_name = '$new_category'");
if($category_query->num_rows == 0) {
$category_insert = $mysqli->query("INSERT INTO `primary_category` (`cat_id`, `cat_name`) VALUES (NULL, '$new_category')");
header("Location:confirmcatmod.php?status=1");
}
else {
$error = "The primary category name already exists. Please select a new one.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h4>Categories</h4>
<!--Form for adding a new category of articles-->
<form action="workspace/cat/addprimary.php" method="POST" name="addPrimaryCatForm" id="addPrimaryCatForm">
<h3>New Primary Category</h3>
<input name="newPrimaryCat" id="newPrimaryCat" type="text" placeholder="Enter new category" />
<input name="newCategorySubmit" class="button-primary" type="submit" value="Submit">
<p><?php echo $error; ?></p>
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#addPrimaryCatForm').submit(function() {
var newPrimCat = $('#newPrimaryCat').val();
if(newPrimCat == "") {
alert("Enter name of new Primary Category");
return false;
}
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("../authenticate.php");
$error = "";
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
else if (isset($_POST['editRowSubmit'])) {
$id = htmlspecialchars($_POST['id']);
$column1 = htmlspecialchars($_POST['column1Input']);
$column2 = htmlspecialchars($_POST['column2Input']);
$column3 = htmlspecialchars($_POST['column3Input']);
$column4 = htmlspecialchars($_POST['column4Input']);
$column5 = htmlspecialchars($_POST['column5Input']);
$column6 = htmlspecialchars($_POST['column6Input']);
$column7 = htmlspecialchars($_POST['column7Input']);
$update_row = $mysqli->query("UPDATE `calendar` SET `column1` = '$column1', `column2` = '$column2', `column3` = '$column3', `column4` = '$column4', `column5` = '$column5', `column6` = '$column6', `column7` = '$column7' WHERE `id` = '$id'");
if($update_row) {
header("Location: ../calendar.php");
}
else {
$error = "Update failed";
}
}
else {
header("Location: ../calendar.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/">
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php include("../layout/navbar.php") ?>
<div class="container" style="padding-top:5em">
<h4><?php echo $error?></h4>
<form id="rowEditForm" name="rowEditForm" method="POST" action="./workspace/calendar/editrow.php">
<div class="row">
<?php
$row_query = $mysqli->query("SELECT * FROM calendar WHERE id='$id'");
$row = $row_query->fetch_assoc();
echo '<input type="hidden" value="'.$row['id'].'" name="id"/>';
echo '
<div class="twelve columns">
<label for="column1Input">Name of Crop</label>
<input class="u-full-width" type="text" value="'.$row['column1'].'" id="column1Input" name="column1Input">
</div>';
echo '
<div class="twelve columns">
<label for="column2Input">Time and Season</label>
<input class="u-full-width" type="text" value="'.$row['column2'].'" id="column2Input" name="column2Input">
</div>';
echo '
<div class="twelve columns">
<label for="column3Input">Seeds (g)</label>
<input class="u-full-width" type="text" value="'.$row['column3'].'" id="column3Input" name="column3Input">
</div>';
echo '
<div class="twelve columns">
<label for="column4Input">Gap between seeds (cm)</label>
<input class="u-full-width" type="text" value="'.$row['column4'].'" id="column4Input" name="column4Input">
</div>';
echo '
<div class="twelve columns">
<label for="column5Input">Depth (cm)</label>
<input class="u-full-width" type="text" value="'.$row['column5'].'" id="column5Input" name="column5Input">
</div>';
echo '
<div class="twelve columns">
<label for="column6Input">Sapling Density</label>
<input class="u-full-width" type="text" value="'.$row['column6'].'" id="column6Input" name="column6Input">
</div>';
echo '
<div class="twelve columns">
<label for="column7Input">Produce (kg)</label>
<input class="u-full-width" type="text" value="'.$row['column7'].'" id="column7Input" name="column7Input">
</div>';
?>
<input class="button-primary" type="submit" value="Submit" name="editRowSubmit">
</form>
</div>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$("#rowEditForm").submit(function() {
var column1 = $("#column1Input").val();
var column2 = $("#column2Input").val();
var column3 = $("#column3Input").val();
var column4 = $("#column4Input").val();
var column5 = $("#column5Input").val();
var column6 = $("#column6Input").val();
var column7 = $("#column7Input").val();
if((column1 == "") || (column2 == "") || (column3 == "") || (column4 == "") || (column5 == "") || (column6 == "") || (column7 == "")) {
alert("Fill all fields please.");
return false;
}
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$primary_cat = "";
$secondary_cat = "";
$error = "";
if(isset($_POST['newSecondaryCatSubmit'])) {
$primary_category = $_POST['primary_select'];
$new_category = $_POST['newSecondaryCat'];
$check_category = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_category' AND cat_name = '$new_category'");
if($check_category->num_rows != 0) {
$error = "The Secondary Category already exists for the selected primary category. Please provide a new one.";
}
else {
//Incrementing secondary category ID
$get_prev_sub_cat = $mysqli->query("SELECT MAX(sub_cat) AS max_count FROM secondary_category WHERE primary_cat = '$primary_category'");
$get_prev_sub_cat_list = $get_prev_sub_cat->fetch_assoc();
if($get_prev_sub_cat_list['max_count'] != NULL) {
$current_count = $get_prev_sub_cat_list['max_count'] + 1;
}
else {
$current_count = 1;
}
//Adding new secondary category to the list
$update_secondary = $mysqli->query("INSERT INTO `secondary_category` (`cat_id`, `primary_cat`, `sub_cat`, `cat_name`) VALUES (NULL, '$primary_category', '$current_count', '$new_category')");
if($update_secondary) {
header("Location:confirmcatmod.php?status=2");
}
else {
$error = "Adding the new secondary category failed";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div class="container" style="padding-top:5rem">
<h3>New Secondary Category</h3>
<!--Form for adding a new secondary category of articles-->
<form action="workspace/cat/addsecondary.php" method="POST" name="addSecondaryCatForm" id="addSecondaryCatForm">
<div id="primary_cat">
<?php
echo $primary_cat;
echo $secondary_cat;?>
Primary Category
<select id="primary_select" name="primary_select"> <!--Selection of primary category-->
<?php
$get_primary = $mysqli->query("SELECT cat_id, cat_name FROM primary_category");
echo '<option selected value="0">Select category</option>'; //Default option
$primary_category_count = $get_primary->num_rows; //Get number of primary categories
while($get_primary_list = $get_primary->fetch_assoc()) {
echo '<option value="'.$get_primary_list['cat_id'].'">'.$get_primary_list['cat_name'].'</option>';
}
?>
</select>
</div>
<input name="newSecondaryCat" id="newSecondaryCat" type="text" placeholder="Enter new category" />
<input name="newSecondaryCatSubmit" class="button-primary" type="submit" value="Submit">
<p style="color:red"><?php echo $error; ?></p>
</form>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#addSecondaryCatForm').submit(function() {
var primCat = $('#primary_select').val();
if(primCat == 0) {
alert("Select Primary Category.");
return false;
}
var newSecCat = $('#newSecondaryCat').val();
if(newSecCat == "") {
alert("Enter name of new Secondary Category");
return false;
}
});
</script>
</body>
</html>
<file_sep><?php
require_once('./config.php');
require_once("./initialize_database.php");
require_once("./authenticate.php");
$edit_success = "";
if(isset($_GET['success']) && isset($_GET['article'])) {
$edit_success = "Article ".$_GET['article']." edited successfully";
}
require ($article_link."addarticle.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
<meta charset="utf-8">
<title>Workspace</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php require("./layout/navbar.php") ?>
<div class="container">
<!--Here we list all the articles for editting and deleting-->
<?php
echo $edit_success;
echo "<br/><br/>"
?>
<!--New Article addition-->
<div class="row">
<h3>New Article</h3>
<!-- Form to add a new article-->
<form action="workspace/workspace.php" method="POST" name="newArticleForm" id="newArticleForm">
<div class="five columns">
<input class="u-full-width" type="text" placeholder="article name" id="newArticleInput" name="newArticleInput">
</div>
<div class="five columns">
<input class="button-primary" type="submit" value="Submit" name="newArticleSubmit">
</div>
<br/>
<br/>
<div class="five columns">
<?php echo $response; ?>
</div>
</form>
</div>
<!--New Article addition ends here-->
<hr>
<a href="./workspace/calendar.php" class="button">CALENDAR MANAGEMENT</a>
<hr>
<div class="row">
<h3>User Management</h3>
<?php
$unapproved_query = $mysqli->query("SELECT * FROM user WHERE user_status = 0");
if($unapproved_query->num_rows != 0) {
echo
'<table class="tg" style="undefined;table-layout: fixed; width: 100%;">
<colgroup>
<col style="width: 5%">
<col style="width: 35%">
<col style="width: 40%">
<col style="width: 10%">
<col style="width: 10%">
</colgroup>';
while($unapproved_result = $unapproved_query->fetch_assoc()) {
echo
'<tr>
<td class="tg-s6z2">'.$unapproved_result['user_id'].'</td>
<td class="tg-s6z2">'.$unapproved_result['user_real_name'].'</td>
<td class="tg-s6z2">'.$unapproved_result['user_email'].'</td>
<td class="tg-s6z2"><a class="button" href="./workspace/user/execute.php?execute=approve&id='.$unapproved_result['user_id'].'" style="width:auto;padding:0">APPROVE</a></td>
<td class="tg-s6z2"><a class="button" href="./workspace/user/execute.php?execute=delete&id='.$unapproved_result['user_id'].'" style="width:auto;padding:0">REJECT</a></td>
</tr>';
}
echo '</table>';
}
else {
echo "No new Editor Requests";
}
?>
</div>
<hr>
<!--Category Management-->
<div class="row">
<h3>Category Management</h3>
<div class="five columns">
<a href="workspace/cat/addprimary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Add Primary category</a>
</div>
<div class="five columns">
<a href="workspace/cat/addsecondary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Add Secondary category</a>
</div>
<br/>
<br/>
<div class="five columns">
<a href="workspace/cat/renameprimary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Rename Primary category</a>
</div>
<div class="five columns">
<a href="workspace/cat/renamesecondary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Rename Secondary category</a>
</div>
<br/>
<br/>
<div class="five columns">
<a href="workspace/cat/deleteprimary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Delete Primary category</a>
</div>
<div class="five columns">
<a href="workspace/cat/deletesecondary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Delete Secondary category</a>
</div>
<br/>
<br/>
<div class="ten columns">
<a href="workspace/cat/uploadprimary.php" class="button" type="submit" onclick="openCategory(this); return false;" target="_blank">Upload Primary Display Image</a>
</div>
</div>
<!--Category Management ends here-->
<hr>
<!--Article Management-->
<div id="articles_list">
<?php
//Displaying uncategorized articles
$pages_list_query = $mysqli->query("SELECT * FROM page INNER JOIN user ON (page_creator=user_id) WHERE prim_cat = '0' AND sec_cat = '0'");
echo '<h4>Uncategorized</h4>
<table class="tg" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 3%">
<col style="width: 40%">
<col style="width: 22%">
<col style="width: 6%">
<col style="width: 4%">
<col style="width: 4%">
<col style="width: 6%">
<col style="width: 9%">
<col style="width: 6%">
</colgroup>';
while($pages_entry = $pages_list_query->fetch_assoc()) {
echo '<tr>
<td class="tg-s6z2">'.$pages_entry['page_id'].'</td>
<td class="tg-s6z2">'.$pages_entry['page_title'].'</td>
<td class="tg-s6z2">'.$pages_entry['user_real_name'].'</td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'uploadcontents.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" style="width:auto;padding:0">UPLOAD</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'article.php?page='.str_replace(" ", "_", $pages_entry['page_title']).'" style="width:db2_autocommit(connection);padding:0">VIEW</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'editor.php?article='.$pages_entry['page_id'].'" style="width:auto;padding:0">EDIT</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'rename.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" style="width:auto;padding:0">RENAME</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'recategorize.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" target="_blank" style="width:auto;padding:0">CATEGORIZE</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'execute.php?execute=delete&article='.$pages_entry['page_id'].'" style="width:auto;padding:0">DELETE</a></td>
</tr>';
}
echo "</table><hr/>";
//Displaying Articles according to category
$primary_query = $mysqli->query("SELECT * FROM primary_category");
while($primary_query_list = $primary_query->fetch_assoc()) {
$primary_id = $primary_query_list['cat_id'];
$primary_name = $primary_query_list['cat_name'];
echo '<h4>'.$primary_name.'</h4>';
$secondary_query = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_id'");
while($secondary_query_list = $secondary_query->fetch_assoc()) {
$secondary_id = $secondary_query_list['sub_cat'];
echo '<h5>'.$secondary_query_list['cat_name'].'</h5>';
echo '<table class="tg" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 3%">
<col style="width: 40%">
<col style="width: 22%">
<col style="width: 6%">
<col style="width: 4%">
<col style="width: 4%">
<col style="width: 6%">
<col style="width: 9%">
<col style="width: 6%">
</colgroup>';
$pages_list_query = $mysqli->query("SELECT * FROM page INNER JOIN user ON (page_creator=user_id) WHERE prim_cat = '$primary_id' AND sec_cat = '$secondary_id'");
while($pages_entry = $pages_list_query->fetch_assoc()) {
echo '
<tr>
<td class="tg-s6z2">'.$pages_entry['page_id'].'</td>
<td class="tg-s6z2">'.$pages_entry['page_title'].'</td>
<td class="tg-s6z2">'.$pages_entry['user_real_name'].'</td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'uploadcontents.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" style="width:auto;padding:0">UPLOAD</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'article.php?page='.str_replace(" ", "_", $pages_entry['page_title']).'" style="width:auto;padding:0">VIEW</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'editor.php?article='.$pages_entry['page_id'].'" style="width:auto;padding:0">EDIT</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'rename.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" style="width:auto;padding:0">RENAME</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'recategorize.php?article='.$pages_entry['page_id'].'" onclick="openCategory(this); return false;" target="_blank" style="width:auto;padding:0">CATEGORIZE</a></td>
<td class="tg-s6z2"><a class="button" href="'.$article_link.'execute.php?execute=delete&article='.$pages_entry['page_id'].'" style="width:auto;padding:0">DELETE</a></td>
</tr>';
}
echo '</table><hr/>';
}
}
?>
</div> <!--Article management ends here-->
</div> <!--Container ends here-->
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$('#newArticleForm').submit(function() {
var newArticle = $('#newArticleInput').val();
if(newArticle == "") {
alert("Please enter the new article's name.");
return false;
}
});
function openCategory(article) {
var x = screen.width/2 - 700/2;
var y = screen.height/2 - 450/2;
window.open(article.href, 'sharegplus','height=485,width=700,left='+x+',top='+y);
}
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once('../initialize_database.php');
require_once("../authenticate.php");
$error = "";
$error2 = "";
$error3 = "";
if(isset($_POST['pdfSubmit'])) {
$id = $_GET['article'];
if(!empty($_FILES["malayalam_pdf"])) {
$pdf = $_FILES["malayalam_pdf"];
if($pdf["error"] !== UPLOAD_ERR_OK) {
$error = "An error occured during the file upload.";
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $pdf['tmp_name']);
if($mime == "application/pdf") {
$name = $pdf['name'];
$article_query = $mysqli->query("SELECT * FROM page WHERE page_id = '$id'");
$article_result = $article_query->fetch_assoc();
$name = str_replace(" ", "_", $article_result['page_title'].".pdf");
$success = move_uploaded_file($pdf["tmp_name"], UPLOAD_DIR.$name);
if(!$success) {
$error = "Unable to save the file. Please try again.";
}
else {
$update_status = $mysqli->query("UPDATE page SET pdf_status = 1 WHERE page_id = '$id'");
if($update_status) {
chmod(UPLOAD_DIR.$name, 0644);
header("Location: confirm.php?status=2");
}
else {
$error = "Error in updating database. Please try again";
}
}
}
else {
$error = "Incorrect format of the upload";
}
}
else {
$error = "Please select a file to upload.";
}
}
if(isset($_POST['pngSubmit'])) {
$id = $_GET['article'];
if(!empty($_FILES["malayalam_name"])) {
$pdf = $_FILES["malayalam_name"];
if($pdf["error"] !== UPLOAD_ERR_OK) {
$error = "An error occured during the file upload.";
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $pdf['tmp_name']);
if($mime == "image/png") {
$name = $pdf['name'];
$article_query = $mysqli->query("SELECT * FROM page WHERE page_id = '$id'");
$article_result = $article_query->fetch_assoc();
$name = str_replace(" ", "_", $article_result['page_title'].".png");
$success = move_uploaded_file($pdf["tmp_name"], UPLOAD_PNG_DIR.$name);
if(!$success) {
$error2 = "Unable to save the file. Please try again.";
}
else {
$update_status = $mysqli->query("UPDATE page SET name_png_status = 1 WHERE page_id = '$id'");
if($update_status) {
chmod(UPLOAD_PNG_DIR.$name, 0644);
header("Location: confirm.php?status=5");
}
else {
$error2 = "Error in updating database. Please try again";
}
}
}
else {
$error2 = "Incorrect format of the upload";
}
}
else {
$error2 = "Please select a file to upload.";
}
}
if(isset($_POST['jpgSubmit'])) {
$id = $_GET['article'];
if(!empty($_FILES["thumbnail"])) {
$pdf = $_FILES["thumbnail"];
if($pdf["error"] !== UPLOAD_ERR_OK) {
$error = "An error occured during the file upload.";
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $pdf['tmp_name']);
if($mime == "image/jpeg") {
$name = $pdf['name'];
$article_query = $mysqli->query("SELECT * FROM page WHERE page_id = '$id'");
$article_result = $article_query->fetch_assoc();
$name = str_replace(" ", "_", $article_result['page_title'].".jpg");
$success = move_uploaded_file($pdf["tmp_name"], UPLOAD_THUMBNAIL_DIR.$name);
if(!$success) {
$error3 = "Unable to save the file. Please try again.";
}
else {
$update_status = $mysqli->query("UPDATE page SET thumbnail_status = 1 WHERE page_id = '$id'");
if($update_status) {
chmod(UPLOAD_THUMBNAIL_DIR.$name, 0644);
header("Location: confirm.php?status=6");
}
else {
$error3 = "Error in updating database. Please try again";
}
}
}
else {
$erro3 = "Incorrect format of the upload";
}
}
else {
$erro3 = "Please select a file to upload.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/"/>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<div style="padding-top:5rem">
<div class="container">
<h4>Upload Malayalam PDF</h4>
<!--Form for adding a new category of articles-->
<form action="workspace/article/uploadcontents.php?article=<?php echo $_GET['article']; ?>" method="POST" name="uploadPDFForm" id="uploadPDFForm" enctype="multipart/form-data">
<input type="file" name="malayalam_pdf" id="malayalam_pdf"/>
<span class="malayalam-pdf-filename">No PDF selected</span>
<br/>
<input type="submit" value="Upload" name="pdfSubmit">
<p><?php echo $error; ?></p>
</form>
<h4>Upload Malayalam Name png</h4>
<form action="workspace/article/uploadcontents.php?article=<?php echo $_GET['article']; ?>" method="POST" name="uploadPNGForm" id="uploadPNGForm" enctype="multipart/form-data">
<input type="file" name="malayalam_name" id="malayalam_name"/>
<span class="malayalam-name-filename">No PNG selected</span>
<br/>
<input type="submit" value="Upload" name="pngSubmit">
<p><?php echo $error2; ?></p>
</form>
<h4>Upload Thumbnail</h4>
<form action="workspace/article/uploadcontents.php?article=<?php echo $_GET['article']; ?>" method="POST" name="uploadJPGForm" id="uploadJPGForm" enctype="multipart/form-data">
<input type="file" name="thumbnail" id="thumbnail"/>
<span class="thumbnail-filename">No JPG selected</span>
<br/>
<input type="submit" value="Upload" name="jpgSubmit">
<p><?php echo $error3; ?></p>
</form>
</div>
</div>
<script src="scripts/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#thumbnail").change(function (){
var fileName = $(this).val();
$(".thumbnail-filename").html(fileName);
});
$("#malayalam_name").change(function (){
var fileName = $(this).val();
$(".malayalam-name-filename").html(fileName);
});
$("#malayalam_pdf").change(function (){
var fileName = $(this).val();
$(".malayalam-pdf-filename").html(fileName);
});
});
</script>
</body>
</html>
<file_sep><?php
require_once('../config.php');
require_once("../initialize_database.php");
require_once("../authenticate.php");
if(isset($_GET['table'])) {
$table = $_GET['table'];
$add_new_row = $mysqli->query("INSERT INTO `calendar` (`id`, `table`, `column1`, `column2`, `column3`, `column4`, `column5`, `column6`, `column7`) VALUES (NULL, '$table', 'NIL', 'NIL', 'NIL', 'NIL', 'NIL', 'NIL', 'NIL')");
if($add_new_row) {
header("Location: ../calendar.php?newtable=1");
}
else {
echo "Adding a new row failed. Please try again";
}
}
else {
header("Location: ../calendar.php?newtable=1");
}
?><file_sep><?php
require_once('./workspace/config.php');
require_once("./workspace/initialize_database.php");
$category = 2;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Krishipurra</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FONT -->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<!-- CSS -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/skeleton.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/landmarks.css">
<!-- Favicon -->
<link rel="icon" type="image/png" href="">
</head>
<body>
<!-- Navigation Bar -->
<?php require("./includes/layout/navbar.php") ?>
<div style="padding-top:5rem">
<div class="container">
<img src="images/kerala.png" width="768" height="1024" usemap="#kerala" alt="" style="width:65%;height:auto;padding-left:35%">
<map name="kerala">
<area alt="Kasaragode" title="Kasaragode" href="#kasaragode" shape="poly" coords="23,20,51,11,108,49,149,88,164,102,169,113,135,125,103,139,91,153,89,166,60,108" style="outline:5px solid #000;">
<area alt="Kannur" title="Kannur" href="#kannur" shape="poly" coords="95,165,104,175,130,194,151,221,174,245,188,248,205,234,227,223,248,210,269,199,292,192,293,171,261,157,226,142,202,126,189,118,175,107,148,122,120,129,101,137,94,148" style="outline:5px solid #000;">
</map>
<div id="articles_list">
<?php
$primary_query = $mysqli->query("SELECT * FROM primary_category WHERE cat_id = $category");
while($primary_query_list = $primary_query->fetch_assoc()) {
$primary_id = $primary_query_list['cat_id'];
$primary_name = $primary_query_list['cat_name'];
$secondary_query = $mysqli->query("SELECT * FROM secondary_category WHERE primary_cat = '$primary_id'");
while($secondary_query_list = $secondary_query->fetch_assoc()) {
$secondary_id = $secondary_query_list['sub_cat'];
echo '<a name="'.strtolower($secondary_query_list['cat_name']).'"></a> ';
//echo '<h4>'.$secondary_query_list['cat_name'].'</h4>';
echo '<table class="" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 100%">
</colgroup>';
$pages_list_query = $mysqli->query("SELECT * FROM page INNER JOIN user ON (page_creator=user_id) WHERE prim_cat = '$primary_id' AND sec_cat = '$secondary_id'");
while($pages_entry = $pages_list_query->fetch_assoc()) {
echo '
<tr>
<td class="tg-s6z2"><a href="articles/'.str_replace(" ", "_", $pages_entry['page_title']).'">'.$pages_entry['page_title'].'</a></td>
</tr>
';
}
echo " </table>";
}
}
?>
</div>
</div>
</div>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.rwdImageMaps.min.js"></script>
<script type="text/javascript" src="scripts/landmarks.js"></script>
</body>
</html>
| 45d66d5b5e32b726388ce929959c8a243a738df8 | [
"JavaScript",
"Markdown",
"PHP"
] | 45 | PHP | arunjohnkuruvilla/agrodb | b6bcc6023d5bb662840ffb69d25d79a5777f20eb | 45310bf38288a9e950c3e5db3dc4ac53b91ccd08 |
refs/heads/main | <file_sep>package com.bridgelabz.program;
public class Person {
String firstName;
String lastName;
String address;
String city;
int zipCode;
String phoneNumber;
String email;
public Person(String firstName, String lastName, String address, String city, int zipCode, String phoneNumber, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
this.phoneNumber = phoneNumber;
this.email = email;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", address=" + address + ", city=" + city
+ ", zipCode=" + zipCode + ", phoneNumber=" + phoneNumber + ", email=" + email + "]";
}
}
| f3d99960e180ade5d573806d774ad111216ad90f | [
"Java"
] | 1 | Java | Cs07041997/Day_28_AnnotationCsv | e3d2ad3747309c7297caba617e0fb2fa73619f99 | 2b2c7403f62f223954dc602c5138f26e6f7aab80 |
refs/heads/master | <repo_name>AjithJayanthi/FSDFinalAssignment<file_sep>/ProjectManager.PresentationLayer/Presentation/src/app/add-project/add-project.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AddProjectComponent } from './add-project.component';
import { ApiService } from '../api.service';
import {ApiServiceMock} from'../api.servicemock';
import { FormsModule, ReactiveFormsModule,} from '@angular/forms';
import {MatButtonModule, MatCheckboxModule,MatFormFieldModule,MatSliderModule} from '@angular/material';
import {MatDatepickerModule} from '@angular/material/datepicker';
import { AddProjectModel } from '../models/add-project.model';
describe('AddProjectComponent', () => {
let component: AddProjectComponent;
let fixture: ComponentFixture<AddProjectComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule,MatButtonModule,MatFormFieldModule,MatSliderModule, FormsModule,MatCheckboxModule,MatDatepickerModule],
declarations: [ AddProjectComponent ],
providers:[{provide :ApiService,useClass:ApiServiceMock}]
})
.compileComponents().then(()=>{
//fixture=TestBed.createComponent(AddProjectComponent);
//component=fixture.componentInstance;
});
}));
// beforeEach(() => {
// fixture = TestBed.createComponent(AddProjectComponent);
// component = fixture.componentInstance;
// fixture.detectChanges();
// });
it('should get one project', async(() => {
expect(0).toEqual(0);
}));
});
| 5dd75e5bf1a60c9cb2ff60779672ebf13e91a6a3 | [
"TypeScript"
] | 1 | TypeScript | AjithJayanthi/FSDFinalAssignment | 8178a0514f8e7f7cfac7d18fa14ca2d9c7a9ef87 | 9765996f3c614c24065b876a320d4c8fb5ab0b99 |
refs/heads/master | <repo_name>masa23/gotail<file_sep>/README.md
# gotail [](https://godoc.org/github.com/masa23/gotail) [](https://raw.githubusercontent.com/hyperium/hyper/master/LICENSE)
gotail is Go library for reading data from realtime updating file , read like "tail -f" command.
See https://godoc.org/github.com/masa23/gotail for the API document.
## License
MIT
## Example
```
// init construct
const (
LogFile = "./test.log"
PosFile = "./test.log.pos"
)
func main() {
go func() {
fd, err := os.OpenFile(LogFile, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
defer fd.Close()
fd.Truncate(0)
fd.Seek(0, 0)
for {
t := time.Now().String()
fd.WriteString(t + "\n")
fd.Sync()
time.Sleep(time.Second)
}
}()
tail, err := gotail.Open(LogFile, PosFile)
if err != nil {
panic(err)
}
for tail.Scan() {
b := tail.Text()
fmt.Println(b)
}
if err = tail.Err(); err != nil {
panic(err)
}
}
```
<file_sep>/go.mod
module github.com/masa23/gotail
go 1.15
require gopkg.in/yaml.v2 v2.4.0
<file_sep>/tail.go
package gotail
import (
"errors"
"io"
"io/ioutil"
"os"
"syscall"
"time"
"gopkg.in/yaml.v2"
)
var (
// DefaultBufSize is default buffer size
// If one line of log is too long, please adjust
DefaultBufSize = 2008
// If true, there is no pos file Start reading from the end of the file
InitialReadPositionEnd = false
// timeout for readLine
ReadLineTimeout = 200 * time.Millisecond
)
// Tail is tail file struct
type Tail struct {
file string
fileFd *os.File
posFile string
posFd *os.File
Stat Stat
buf []byte
start int
end int
n int
offset1 int64
offset2 int64
nextStart int
eofCount int
isEnd bool
bufEmpty bool
init bool
err error
isCreatePosFile bool
InitialReadPositionEnd bool // deprecated
}
// Stat tail stats infomation struct
type Stat struct {
Inode uint64 `yaml:"Inode"`
Offset int64 `yaml:"Offset"`
Size int64 `yaml:"Size"`
}
// Open file and position files.
func Open(file string, posfile string) (*Tail, error) {
var err error
posStat := Stat{}
t := Tail{
file: file,
posFile: posfile,
init: true,
bufEmpty: true,
}
// compatibility maintenance
if t.InitialReadPositionEnd {
InitialReadPositionEnd = true
}
// create buffer
t.buf = make([]byte, DefaultBufSize)
// open position file
if t.posFile != "" {
t.posFd, err = os.OpenFile(t.posFile, os.O_RDWR, 0644)
if err != nil && !os.IsNotExist(err) {
return &t, err
} else if os.IsNotExist(err) {
t.posFd, err = os.OpenFile(t.posFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return &t, err
}
t.isCreatePosFile = true
}
posdata, err := ioutil.ReadAll(t.posFd)
if err != nil {
return &t, err
}
err = yaml.Unmarshal(posdata, &posStat)
if err != nil {
return &t, err
}
}
// open tail file.
t.fileFd, err = os.Open(t.file)
if err != nil {
return &t, err
}
// get file stat
fdStat, err := t.fileFd.Stat()
if err != nil {
return &t, err
}
stat := fdStat.Sys().(*syscall.Stat_t)
// file stat
t.Stat.Inode = stat.Ino
t.Stat.Size = stat.Size
if stat.Ino == posStat.Inode && stat.Size >= posStat.Size {
// If the inode is not changed, restart from the subsequent Offset.
t.Stat.Offset = posStat.Offset
t.offset1 = posStat.Offset
} else {
// If the file size is small, set the offset to 0.
t.Stat.Offset = 0
}
// update position file
err = t.PositionUpdate()
if err != nil {
return &t, err
}
// tail seek posititon.
_, err = t.fileFd.Seek(t.Stat.Offset, io.SeekStart)
if err != nil {
return &t, err
}
return &t, nil
}
// Close is file and position file close.
func (t *Tail) Close() error {
err := t.posFd.Close()
if err != nil {
return err
}
err = t.fileFd.Close()
if err != nil {
return err
}
return nil
}
// PositionUpdate is pos file update
func (t *Tail) PositionUpdate() error {
if t.posFile == "" {
return nil
}
t.posFd.Truncate(0)
t.posFd.Seek(0, io.SeekStart)
yml, err := yaml.Marshal(&t.Stat)
if err != nil {
return err
}
_, err = t.posFd.Write(yml)
if err != nil {
return err
}
err = t.posFd.Sync()
if err != nil {
return err
}
return nil
}
// Bytes is get one line bytes.
func (t *Tail) Bytes() []byte {
return t.buf[t.start:t.end]
}
// Text is get one line strings.
func (t *Tail) Text() string {
return string(t.Bytes())
}
// Err is get Scan error
func (t *Tail) Err() error {
return t.err
}
// scanInit is only executed the first time Scan is run
func (t *Tail) scanInit() {
if t.init {
// there is no pos file Start reading from the end of the file
if (InitialReadPositionEnd && t.isCreatePosFile) ||
(InitialReadPositionEnd && t.posFile == "") {
t.offset1, _ = t.fileFd.Seek(0, io.SeekEnd)
}
t.init = false
}
}
// Scan is start scan.
func (t *Tail) Scan() bool {
var err error
// Executed only the first time
t.scanInit()
// Change start to new position
t.start = t.nextStart
for {
// buffer empty
if t.bufEmpty {
// change offset
t.offset2, _ = t.fileFd.Seek(t.offset1, io.SeekStart)
// read file
t.n, err = t.fileFd.Read(t.buf)
if t.n == 0 || errors.Is(err, io.EOF) {
// EOF file check
t.eofCount++
if t.eofCount > 5 {
t.eofCount = 0
t.fileCheck()
continue
}
// sleep & next buffer read
time.Sleep(ReadLineTimeout / 5)
continue
} else if err != nil {
t.err = err
}
t.bufEmpty = false
}
t.eofCount = 0
// search newline
for i := t.start; i < t.n; i++ {
if t.buf[i] == '\n' {
t.end = i
t.nextStart = i + 1
t.isEnd = false
return true
}
}
// not found newline
// Move offset to last newline
t.offset1 = t.offset1 + int64(t.end)
t.bufEmpty = true
// If offset1 and offset2 are the same, the file has not been updated,
// so wait a certain amount of time and read it again
if t.offset1 == t.offset2 {
if !t.isEnd {
t.isEnd = true
time.Sleep(ReadLineTimeout)
continue
}
t.isEnd = false
t.end = t.n
// possiton update
t.Stat.Offset = t.offset1 - 1
t.PositionUpdate()
return true
} else {
// Move offset by line feed code
t.offset1++
t.start = 0
t.end = 0
t.nextStart = 0
}
}
}
func (t *Tail) fileCheck() error {
// status update
fdstat, err := t.fileFd.Stat()
if err != nil {
return err
}
s := fdstat.Sys().(*syscall.Stat_t)
t.Stat.Inode = s.Ino
t.Stat.Size = s.Size
t.Stat.Offset = t.offset1 - 1
// update position file
err = t.PositionUpdate()
if err != nil {
return err
}
// find new file
for {
// open file
fd, err := os.Open(t.file)
if os.IsNotExist(err) {
// sleep & next file check
time.Sleep(time.Second)
continue
} else if err != nil {
return err
}
newFdStat, err := fd.Stat()
if err != nil {
return err
}
newStat := newFdStat.Sys().(*syscall.Stat_t)
// If there is no change in inode and size, wait a little longer
if t.Stat.Inode == newStat.Ino && t.Stat.Size == newStat.Size {
fd.Close()
time.Sleep(100 * time.Millisecond)
continue
}
// Replace any inode changes with new files
if t.Stat.Inode != newStat.Ino {
t.Stat.Inode = newStat.Ino
t.Stat.Offset = 0
t.offset1 = 0
t.Stat.Size = newStat.Size
t.fileFd.Close()
t.fileFd = fd
break
}
// If the size is smaller, move the SEEK position back to the beginning
if newStat.Size < t.Stat.Size {
_, err = t.fileFd.Seek(0, io.SeekStart)
if err != nil {
return err
}
t.Stat.Size = newStat.Size
fd.Close()
break
}
if newStat.Size > t.Stat.Size {
_, err := t.fileFd.Seek(t.Stat.Offset, io.SeekStart)
if err != nil {
return err
}
fd.Close()
break
}
}
return nil
}
<file_sep>/example/example.go
package main
import (
"fmt"
"os"
"time"
"github.com/masa23/gotail"
)
// init construct
const (
LogFile = "./test.log"
PosFile = "./test.log.pos"
)
func main() {
go func() {
fd, err := os.OpenFile(LogFile, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
defer fd.Close()
fd.Truncate(0)
fd.Seek(0, 0)
for {
t := time.Now().String()
fd.WriteString(t + "\n")
fd.Sync()
time.Sleep(time.Second)
}
}()
tail, err := gotail.Open(LogFile, PosFile)
if err != nil {
panic(err)
}
for tail.Scan() {
b := tail.Text()
fmt.Println(b)
}
if err = tail.Err(); err != nil {
panic(err)
}
}
<file_sep>/tail_test.go
package gotail
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"testing"
"time"
)
var tmp string
func TestMain(m *testing.M) {
var err error
tmp, err = ioutil.TempDir("", "gotail_test")
if err != nil {
panic(err)
}
defer os.RemoveAll(tmp)
// generate test log file
go func() {
path := filepath.Join(tmp, "test.txt")
fd, err := os.Create(path)
if err != nil {
panic(err)
}
defer fd.Close()
i := 0
for {
now := time.Now()
fd.WriteString(strconv.Itoa(i) + " ")
fd.WriteString(now.Format("random mojiretsu"))
fd.WriteString("\n")
i++
}
}()
time.Sleep(time.Millisecond)
ret := m.Run()
os.RemoveAll(tmp)
os.Exit(ret)
}
func TestOpen(t *testing.T) {
path := filepath.Join(tmp, "test.txt")
posPath := filepath.Join(tmp, "test.txt.pos")
_, err := Open(path, posPath)
if err != nil {
t.Fatal(err)
}
}
func TestScan(t *testing.T) {
path := filepath.Join(tmp, "test.txt")
tail, err := Open(path, "")
if err != nil {
t.Fatal(err)
}
defer tail.Close()
if !tail.Scan() {
t.Fatal(fmt.Errorf("scan error"))
}
}
func TestBytes(t *testing.T) {
path := filepath.Join(tmp, "test.txt")
posPath := filepath.Join(tmp, "test.txt.pos")
tail, err := Open(path, posPath)
InitialReadPositionEnd = true
if err != nil {
t.Fatal(err)
}
defer tail.Close()
i := 0
for tail.Scan() {
if err := tail.Err(); err != nil {
t.Fatal(err)
}
if !bytes.Contains(tail.Bytes(), []byte(strconv.Itoa(i)+" random mojiretsu")) {
t.Fatal(strconv.Itoa(i)+" lines read miss match", "sample:"+strconv.Itoa(i)+" random mojiretsu", "read:"+string(tail.Bytes()))
}
if i > 100000 {
break
}
i++
}
if err := tail.Err(); err != nil {
t.Fatal(err)
}
}
| f759839d1ac0bdd20d50302e4725785282de14ec | [
"Markdown",
"Go Module",
"Go"
] | 5 | Markdown | masa23/gotail | f4952b21933c1d4a126f3ca5f389ae3028fe61d6 | 56735ef3464a556e0f2d23ce1e28b446a0116106 |
refs/heads/main | <file_sep>
# Hint - Your trip starts here!
[PORT] Compartilhar dicas, ler uma review de algum meio de hospedagem
ou restaurante, postar fotos de viagens, conhecer outros viajantes…
Uma rede social criada para atender várias necessidades de vianjates mundo a fora.
[ENG] Sharing advice, reading hotel/restaurant reviews,
posting pictures, finding travel buddies…
A social network created to meet various needs of travelers around the world.
## Índice
- [1. Introdução](#1-prefácio)
- [2. Resumo do projeto](#2-resumo-do-projeto)
- [3. Objetivos de aprendizagem](#3-objetivos-de-aprendizagem)
- [4. Considerações gerais](#4-considerações-gerais)
- [5. Critérios de aceitação mínimos do projeto](#5-criterios-de-aceitação-mínimos-do-projeto)
- [6. Hacker edition](#6-hacker-edition)
- [7. Entrega](#7-entrega)
- [8. Guias, dicas e leituras complementares](#8-guias-dicas-e-leituras-complementares)
---
## 1. Introdução
Hint é uma rede social criada pelas alunas da Laboratória <NAME> e <NAME>.
Trata-se de uma aplicação de página única (Single Page Application - SPA), utilizando
sistema de autenticação fornecido pelo Firebase. A lógica do projeto é
implementada em JavaScript (ES6+), HTML e CSS.
<file_sep>import {
likePost, deslikePost, delPost, editPost,
} from '../services/index.js';
export const card = (objPost) => {
const idUser = firebase.auth().currentUser.uid;
let classLike = 'muda-cor';
if (objPost.like.includes(idUser)) {
classLike = 'curtido';
} else {
classLike = 'descurtido';
}
const infoDiv = document.createElement('div');
const contentCard = `
<h2>${objPost.autora}</h2>
<p>Visited Place: ${objPost.local}</p>
<div data-text="${objPost.id}">${objPost.mensagem}</div>
<button class="like-button ${classLike}" data-like="${objPost.id}">Like</button>
<button class="del-button" data-del="${objPost.id}">Delete</button>
<button class="edit-button" data-edit="${objPost.id}">Edit</button>
<button class="save-button" data-save="${objPost.id}">Save</button>
`;
infoDiv.innerHTML = contentCard;
// LIKE / DESLIKE
const likeBtn = infoDiv.querySelector(`[data-like="${objPost.id}"]`);
likeBtn.addEventListener('click', () => {
console.log(likeBtn);
if (objPost.like.includes(idUser)) {
deslikePost(idUser, objPost.id).then(() => {
likeBtn.classList.add('descurtido');
likeBtn.classList.remove('curtido');
});
} else {
likePost(idUser, objPost.id).then(() => {
likeBtn.classList.remove('descurtido');
likeBtn.classList.add('curtido');
});
}
});
// DELETE
const delBtn = infoDiv.querySelector(`[data-del="${objPost.id}"]`);
delBtn.addEventListener('click', () => {
window.alert('Tem certeza que deseja Deletar o post?');
delPost(objPost.id).then(() => {
const deleteBtn = delBtn.parentNode;
deleteBtn.remove();
});
});
// UPDATE
const editMsg = infoDiv.querySelector(`[data-text="${objPost.id}"]`);
const editBtn = infoDiv.querySelector(`[data-edit="${objPost.id}"]`);
editBtn.addEventListener('click', () => {
console.log(editMsg);
editMsg.setAttribute('contentEditable', '');
editMsg.focus();
});
const saveBtn = infoDiv.querySelector(`[data-save="${objPost.id}"]`);
saveBtn.addEventListener('click', () => {
editPost(objPost.id, editMsg.innerText).then(() => {
editMsg.removeAttribute('contentEditable', '');
});
});
return infoDiv;
};
<file_sep># HINT
### Uma rede social para viajantes
- [1. Resumo do projeto](#1-resumo-do-projeto)
- [2. Pesquisa](#2-pesquisa)
- [3. Histórias de usuário](#3-histórias-de-usuário)
---
<h1>
<img src="src/images/hint-green.png">
</h1>
## 1. Resumo do projeto
Nosso projeto se chama HINT (uma Rede Social) para viajantes e/ou pessoas que gostariam de viajar.
No HINT você pode dar dicas de lugares que você já viajou, sozinho, com o parceiro(a) e/ou visualizar dicas de pessoas que já viajaram para algum lugar que você deseja ir.
## 2. Pesquisa
Fizemos uma breve pesquisa de usuário:
<h1>
<img src="src/images/pesquisausuario.gif">
</h1>
### Protótipo de alta fidelidade
<h1>
<img src="src/images/prototipo.png">
</h1>
---
## 3. Histórias de usuário
- Tela Inicial:
- Quando o usuário acessar a página HINT, encontrará a página de login;
- Caso o usuário queira entrar pela conta do Google, basta clicar no botão _Login with Google_ e será direcionado ao Feed;
<h1>
<img src="src/images/Inicio.png">
</h1>
- Tela Register
- Se o usuário preferir poderá fazer o cadastro por e-mail e senha clicando no campo _Register Here!_;
- Na página de cadastro o usuário colocará _Nome de Usuário_ , _E-mail_ e _Senha_ e terá que retornar a página inicial, colocar os dados cadastrados e então será direcionado ao Feed;
<h1>
<img src="src/images/Cadastro.png">
</h1>
- Feed
- No Feed o usuário encontrará o campo para colocar o nome do Lugar/Cidade/País que viajou e/ou gostaria de viajar; em seguida colocará a mensagem e clicará no botão _Submit_ para enviar;
- Em seguida a mensagem aparecerá no Feed e o usuário poderá _Curtir_ , _Deletar_ , _Editar_ e _Salvar_ o comentário que o mesmo fez.
<h1>
<img src="src/images/Feed.png">
</h1>
Colaboração:
[<NAME>](https://github.com/marirr86) e
[<NAME>](https://github.com/RafaelaCugini)<file_sep>const db = firebase.firestore();
// Creating Posts
export const postarMensagem = (postagem) => db.collection('postagens').add(postagem);
// Reading Post
export const readPost = () => db.collection('postagens').get();
// Delete posts
export const delPost = (idPost) => firebase.firestore().collection('postagens').doc(idPost).delete();
// likes
export const likePost = (idUser, idPost) => firebase
.firestore()
.collection('postagens')
.doc(idPost)
.update({ like: firebase.firestore.FieldValue.arrayUnion(idUser) });
// Deslike
export const deslikePost = (idUser, idPost) => firebase
.firestore()
.collection('postagens')
.doc(idPost)
.update({ like: firebase.firestore.FieldValue.arrayRemove(idUser) });
// Update post
export const editPost = (idPost, novaMensagem) => firebase
.firestore()
.collection('postagens')
.doc(idPost)
.update({
mensagem: novaMensagem,
});
/* .then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, ' => ', doc.data());
});
})
.catch((error) => {
console.log('Error getting documents: ', error);
}); */
/* docRef.get().then((doc) => {
if (doc.exists) {
console.log('Document data:', doc.data());
} else {
// doc.data() will be undefined in this case
console.log('No such document!');
}
}).catch((error) => {
console.log('Error getting document:', error);
});
// Observing user
/* firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
}); */
| dd9f75e7c44b0301a1fd8ba6798db660a7dce727 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | marirr86/SAP006-social-network | 20f7dfc5b9004fd2eb8a06bbbb1ceca608592cf2 | f370fe4e99b5b9b17ebde38aa9e158f9b03aa36a |
refs/heads/master | <repo_name>nateslo/recursion<file_sep>/src/getElementsByClassName.js
// If life was easy, we could just do things the easy way:
// var getElementsByClassName = function (className) {
// return document.getElementsByClassName(className);
// };
// But instead we're going to implement it from scratch:
var getElementsByClassName = function(className) {
var results = [];
// Function check current node for class and recursively check children
var recursiveSearchNodes = function(node) {
if (node.nodeType === document.ELEMENT_NODE && node.classList.contains(className)) {
results.push(node);
}
for(var i = 0; i < node.childNodes.length; i++ ) {
recursiveSearchNodes(node.childNodes[i]);
}
};
// call recursive function, starting at document.body
recursiveSearchNodes(document.body);
return results;
};<file_sep>/src/stringifyJSON.js
// this is what you would do if you liked things to be easy:
// var stringifyJSON = JSON.stringify;
// but you don't so you're going to write it from scratch:
var stringifyJSON = function(obj) {
var tempstring;
// Recursively stringify nested elements
var recursiveStringify = function(prop) {
// Handle null
if(prop === null) {
return 'null';
}
// Handle Arrays
if (Array.isArray(prop)) {
tempstring= "";
// Loop through array elems, calling recursive function of each, adding comma
for (var j = 0; j < prop.length; j ++) {
tempstring += recursiveStringify(prop[j]) + ",";
}
// Remove trailing comma and return with square brackets
tempstring = tempstring.substring(0, tempstring.length - 1);
return "[" + tempstring + "]";
}
// Handle objects
if (typeof prop === 'object') {
tempstring ="";
// Loop through properties, calling recurive function on each
// Ignoring functions and undefined values
for(var i in prop) {
if (typeof prop[i] !== 'function' && typeof prop[i]!== 'undefined') {
tempstring += recursiveStringify(i) +
":" + recursiveStringify(prop[i]) + ",";
}
}
// Remove trailing comma and return with curly brackets
tempstring = tempstring.substring(0, tempstring.length - 1);
return "{" + tempstring + "}";
}
// Handle Strings
if (typeof prop === 'string') {
return '"' + prop + '"';
}
// Handle Primitives
return prop.toString();
};
// Initial call to recursiveStringify
return recursiveStringify(obj);
};
| 446b7fc37cd1a3566d91a1a08bf4b714b1ebd2dd | [
"JavaScript"
] | 2 | JavaScript | nateslo/recursion | a8c5ef5dcc9cb7487a8ac4e43f1bddc92563a7f2 | b35cdebdf8fa527c0e10289231ba6ebfc2f472ae |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.