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 | <file_sep>import {LitElement, html} from 'lit-element';
import {css, injectGlobal} from 'emotion';
const styles = css`
color: red;
background-color: purple;
border: solid orange 10px;
`
injectGlobal`
lrs-button {
display: block;
}
`
class Button extends LitElement {
render() {
return html`<p class=${styles}>hello world!</p>`
}
}
customElements.define('lrs-button', Button); | ce5b904e01a683fa10df56c2e78eb6ce9e4004d1 | [
"JavaScript"
] | 1 | JavaScript | o-t-w/litmotion | 89d9e17491b436f94de52974f3c4c6a8d3ed2a64 | dc10303d18ce399af726ff04bc2997eb139a92b4 |
refs/heads/master | <repo_name>mmm141023/shopapp<file_sep>/src/main/resources/db.properties
jdbc.username=root
jdbc.password=<PASSWORD>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/shop?characterEncoding=utf-8
imageHost=http://localhost:8080/<file_sep>/src/main/java/com/fendou/controller/UserController.java
package com.fendou.controller;
import com.fendou.pojo.User;
import com.fendou.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//点击显示注册账号的页面
@RequestMapping("/addUserTo")
public String addUserTo(@Param("category") String category, Model model){
model.addAttribute("category", category);
return "forward:/administrator/reToMain";
}
/**
* 点击注册按钮将用户信息加入数据库
*/
@RequestMapping("/addUser")
public String addUser(User user, Model model){
boolean addFlag = userService.addUser(user);
model.addAttribute("addFlag", addFlag);
return "forward:/index.jsp";
}
}
<file_sep>/src/main/java/com/fendou/service/UserService.java
package com.fendou.service;
import com.fendou.pojo.User;
public interface UserService {
boolean addUser(User user);
}
<file_sep>/src/main/java/com/fendou/controller/JumpToController.java
package com.fendou.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/jumpto")
public class JumpToController {
@RequestMapping("/loginPage")
public String loginPage(){
return "login";
}
}
| 8c26ac8e671335c96b3ea0f43983067e6dd2112d | [
"Java",
"INI"
] | 4 | INI | mmm141023/shopapp | bba522c305dbff4d1c5ae59d03fab16443f82139 | c95bbf89aa54d9ecddc617bbf8175a2f762ca7f1 |
refs/heads/master | <file_sep>import paho.mqtt.client as mqtt
import random
import time
#습도를 30~95까지 받아들이는 함수
def getMsg():
msg = str(random.randrange(30, 95))
return msg
mqttc = mqtt.Client()
# YOU NEED TO CHANGE THE IP ADDRESS OR HOST NAME
mqttc.connect("192.168.43.125")
#mqttc.connect("localhost")
mqttc.loop_start()
try:
while True:
t = getMsg()
print("sending humidity value : "+t+"%")
(result, m_id) = mqttc.publish("environment/humidity", t)
time.sleep(2)
except KeyboardInterrupt:
print("Finished!")
mqttc.loop_stop()
mqttc.disconnect()
<file_sep>import paho.mqtt.client as mqtt
import random
import time
#20~35까지 온도를 랜덤하게 받아들이는 함수
def getMsg():
msg = str(random.randrange(20, 35))
return msg
mqttc = mqtt.Client()
# YOU NEED TO CHANGE THE IP ADDRESS OR HOST NAME
#연결할 ip주소
mqttc.connect("192.168.43.125")
#mqttc.connect("localhost")
mqttc.loop_start()
try:
while True:
t = getMsg()
print("sending temperature value : "+t)
(result, m_id) = mqttc.publish("environment/temperature", t)
time.sleep(2)
except KeyboardInterrupt:
print("Finished!")
mqttc.loop_stop()
mqttc.disconnect()
<file_sep>import paho.mqtt.client as mqtt
#습도 온도 불쾨지수값을 저장하기 위한 전역변수들
humidity = 0.0
temperature = 0.0
value = 0.0
def on_connect(client, userdata, rc):
client.subscribe("environment/temperature")
client.subscribe("environment/humidity")
def on_message(client, userdata, msg):
global humidity
global temperature
global value
if msg.topic == "environment/humidity":
humidity = float(msg.payload)/100
elif msg.topic == "environment/temperature":
temperature = float(msg.payload)
value = 9*temperature/5 - 0.55*(1 - humidity)*(9*temperature/5 -26) + 32
if value >= 80:
print(str(value)+"(Very High)[temperature: "+ str(temperature) + ", humidity: "+str(humidity) )
elif value >= 75 and value < 80:
print(str(value)+"(High)[temperature: "+ str(temperature) + ", humidity: "+str(humidity) )
elif value >= 68 and value < 75:
print(str(value)+"(Mid)[temperature: "+ str(temperature) + ", humidity: "+str(humidity) )
elif value < 68:
print(str(value)+"(Low)[temperature: "+ str(temperature) + ", humidity: "+str(humidity) )
if value >= 75:
client.publish("controller","Start")
elif value < 68:
client.publish("controller","Stop")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# YOU NEED TO CHANGE THE IP ADDRESS OR HOST NAME
client.connect("192.168.43.125", 1883, 60)
#client.connect("localhost")
try:
client.loop_forever()
except KeyboardInterrupt:
print("Finished!")
client.unsubscribe(["environment/temperature", "environment/humidity"])
client.disconnect()
<file_sep>import paho.mqtt.client as mqtt
def on_connect(client, userdata, rc):
client.subscribe("controller")
def on_message(client, userdata, msg):
if msg.topic == "controller":
if msg.payload == "Start":
print("Start air conditioning")
elif msg.payload == "Stop":
print("Stop air conditioning")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# YOU NEED TO CHANGE THE IP ADDRESS OR HOST NAME
client.connect("192.168.43.125", 1883, 60)
#client.connect("localhost")
try:
client.loop_forever()
except KeyboardInterrupt:
print("Finished!")
client.unsubscribe(["controller"])
client.disconnect()
| 2b55b4f094f7132d0c00b28803959f0bd255981e | [
"Python"
] | 4 | Python | appleeji/IoT | 9cc64fae93a050d782adceaee41b810f2c609126 | fa32a282c3ce955c7b9e06db6754f6e8f16dedeb |
refs/heads/master | <file_sep>using System.Collections.Generic;
namespace DanishNews.Models
{
public class Feed
{
public string Name { get; set; }
public IEnumerable<Post> Posts { get; set; }
}
}
<file_sep>using System;
namespace DanishNews.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public Uri Link { get; set; }
public DateTimeOffset PublicationDate { get; set; }
public string UniqueId { get; set; }
}
}
<file_sep>using System.Threading.Tasks;
using DanishNews.Services.Abstractions;
using Microsoft.AspNetCore.Mvc;
namespace DanishNews.Controllers
{
public class HomeController : Controller
{
private readonly INewsService newsService;
public HomeController(INewsService newsService)
{
this.newsService = newsService;
}
public async Task<IActionResult> Index()
{
return View(await newsService.GetFeedsAsync());
}
public IActionResult Error()
{
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DanishNews.Models;
namespace DanishNews.Services.Abstractions
{
public interface INewsService : IDisposable
{
Task<IEnumerable<Feed>> GetFeedsAsync();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using DanishNews.Models;
using DanishNews.Services.Abstractions;
namespace DanishNews.Services
{
public class RssNewsService : INewsService
{
private readonly HttpClient httpClient = new HttpClient();
private readonly Dictionary<string, string> feeds;
public RssNewsService()
{
feeds = new Dictionary<string, string>
{
{"DR", "http://www.dr.dk/nyheder/service/feeds/allenyheder"},
{"avisen.dk", "http://www.avisen.dk/Handlers/GetFeed.ashx?type=Nyeste20Alle"},
{"Børsen", "http://borsen.dk/rss/"},
{"Information", "https://www.information.dk/feed"},
{"Kristeligt Dagblad", "http://www.kristeligt-dagblad.dk/rss/nyheder"},
{"TV2", "http://feeds.tv2.dk/nyheder/rss"},
{"Politiken", "http://politiken.dk/rss/senestenyt.rss"},
{"Jyllands Posten", "http://jyllands-posten.dk/?service=rssfeed"},
{"Berlingske", "http://www.b.dk/seneste/rss"}
};
}
public async Task<IEnumerable<Feed>> GetFeedsAsync()
{
return await Task.WhenAll(feeds.Select(feed => GetFeedAsync(feed.Key, feed.Value)));
}
private async Task<Feed> GetFeedAsync(string name, string uri)
{
return new Feed {Name = name, Posts = await GetPostsFromFeedAsync(uri, 3)};
}
private async Task<IEnumerable<Post>> GetPostsFromFeedAsync(string feed, int numberOfPosts = 25)
{
var posts = new List<Post>();
var httpResponseMessage = await httpClient.GetAsync(feed);
if (!httpResponseMessage.IsSuccessStatusCode)
return posts;
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var document = XDocument.Parse(content.Trim());
var channels = document.Root.Elements(XName.Get("channel"));
var index = 0;
foreach (var channel in channels)
{
var items = channel.Elements(XName.Get("item"));
foreach (var item in items)
{
var title = item.Element(XName.Get("title")).Value;
var link = new Uri(item.Element(XName.Get("link")).Value);
var publicationDate = DateTimeOffset.Parse(item.Element(XName.Get("pubDate")).Value);
// TODO: Find a way to create a unique id for the post.
posts.Add(new Post
{
Title = title,
Link = link,
PublicationDate = publicationDate,
});
if (++index == numberOfPosts)
return posts;
}
}
return posts;
}
public void Dispose()
{
httpClient.Dispose();
}
}
}
| 9c9ff7d04a9b85bab0a8f66a5f98889c435f6c09 | [
"C#"
] | 5 | C# | Eonix/DanishNews | 3899771233aa33bbf57e85988cd650c2b752a52e | 1332dad4948d556961fdc384bbb01b1618a6aab0 |
refs/heads/master | <repo_name>eidmannt/spotifydiscovery<file_sep>/login.py
# import spotipy
# from spotipy.oauth2 import SpotifyClientCredentials
# import spotipy.util as util
#
#
# cid ="576665c63aa04da1a8f2a359ef5c43d3"
# secret = "ae671197233541b693ca6c9e776e201f"
# username = ""
# client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
# sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# scope = 'user-library-read playlist-read-private'
# token = util.prompt_for_user_token(username, scope)
# if token:
# sp = spotipy.Spotify(auth=token)
# else:
# print("Can't get token for", username)
import configparser
import spotipy
import spotipy.oauth2 as oauth2
config = configparser.ConfigParser()
config.read('config.cfg')
client_id = config.get('SPOTIFY', 'CLIENT_ID')
client_secret = config.get('SPOTIFY', 'CLIENT_SECRET')
auth = oauth2.SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret
)
token = auth.get_access_token()
spotify = spotipy.Spotify(auth=token)
| 24d574472844184468434ce30fd69de9576c7328 | [
"Python"
] | 1 | Python | eidmannt/spotifydiscovery | 9f2378c75e7ed243376046d2c7303c2d516b389a | fe2e85928aee20cd185a75a81ff6efa8aa76ea7d |
refs/heads/master | <file_sep>from setuptools import find_packages, setup
from pip.req import parse_requirements
def get_requirements(filename):
try:
from pip.download import PipSession
session = PipSession()
except ImportError:
session = None
reqs = parse_requirements(filename, session=session)
return [str(r.req) for r in reqs]
def get_install_requires():
return get_requirements('requirements.txt')
setup_args = dict(
name='foo',
version='0.0.1',
packages=['foo', 'foo.plugins'],
install_requires=get_install_requires(),
)
if __name__ == '__main__':
setup(**setup_args)
<file_sep># -- Python Wheels
FROM python:3 as wheels
COPY packages/foo/requirements.txt /foo/requirements.txt
RUN pip wheel --wheel-dir /wheels -r /foo/requirements.txt
# -- Final Image
FROM python:3
COPY packages/foo /var/foo
COPY --from=wheels /wheels /wheels
RUN cd /var/foo && pip install --no-index --find-links=/wheels -r requirements.txt
RUN cd /var/foo && python setup.py install
COPY packages/foo-bar /var/foo-bar
RUN cd /var/foo-bar && python setup.py install
RUN python -c "import sys; print(sys.path); import foo.plugins"
<file_sep>docker-py==1.7.2
gevent==1.2.0
Flask==0.10.1
requests[security]>=2.18, <2.19
ipaddress==1.0.16
backports.ssl-match-hostname==3.5.0.1
| fe5c11d52c11fdca21786138cadbedbeeb028985 | [
"Python",
"Text",
"Dockerfile"
] | 3 | Python | dustinlacewell/namespaces | 2e61abfa45fa14dca5091c2f55dfbc730190bb1f | 713323e74038c262189b55b6fb07ea639f7f250d |
refs/heads/master | <file_sep>"""Google organizational unit management."""
from psugle import creds
import gdata.apps.organization.service
class OrgUnit:
"""Google organizational unit management."""
def __init__(self, domain=None, adminuser=None, password=None, g_client=None):
"""New OrgUnit object. Google <domain> required. <adminuser> and
<password> will override module defaults.
A <g_client> of type gdata.apps.organization.service.OrganizationService
can be specified to re-use an existing client."""
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not password:
password = creds.google[domain]["password"]
if g_client:
self.g_client = g_client
else:
self.g_client = gdata.apps.organization.service.OrganizationService(
domain=domain
,email="%s@%s" % (adminuser, domain)
,password=<PASSWORD>
)
self.g_client.ProgrammaticLogin()
self.customer_id = self.g_client.RetrieveCustomerId()["customerId"]
def create(self, name=None, description=None, parent_org_unit_path="/"):
"""Create a new Organizational Unit with a given <name> and <description>.
A <parent_org_unit_path> can be specified. Find them with list_all()."""
return self.g_client.CreateOrgUnit(
self.customer_id, name, parent_org_unit_path, description
)
def delete(self, org_unit_path=None):
"""Delete a given Organizational Unit, given its <org_unit_path>."""
return self.g_client.DeleteOrgUnit(
self.customer_id, org_unit_path
)
def list_users_in(self, org_unit_path=None):
"""List all users in a given <org_unit_path>."""
addresses = self.g_client.RetrieveOrgUnitUsers(self.customer_id, org_unit_path)
return [ a["orgUserEmail"].split('@')[0] for a in addresses ]
def list_all(self):
"""List all Organizational Units, their paths and descriptions."""
orgunits = self.g_client.RetrieveAllOrgUnits(self.customer_id)
return [ {'org_unit_path':orgunit['org_unit_path']\
,'description':orgunit['description']} for orgunit in orgunits ]
def move_user(self, user=None, org_unit_path="/"):
"""Move a <user> to a new <org_unit_path>. Moves to the root by default."""
return self.g_client.UpdateOrgUser(
self.customer_id, "%s@%s" % (user, self.domain), org_unit_path
)
def query_user(self, user=None):
"""Reports which Organizational Unit a given <user> resides."""
user_status = self.g_client.RetrieveOrgUser(self.customer_id, "%s@%s" % (user, self.domain))
if user_status["org_unit_path"] == None:
user_status["org_unit_path"] = "/" # Make more consistent--moving requires a path.
return user_status
<file_sep>I have essentially got to the point where I am runing into this error:
www.mail-archive.com/<EMAIL>/msg01752.html
However, in our case, it's working with the gam command line tool, just not
sending a direct Atom XML request with the change. It looks like a pretty
current issue. I have written some code to implement when they do allow the
API to modify groupsettings, but it won't work when calling it from the app
right now, I keep getting Error 503: Service Unavailable.
Confusing thing is, when I go from the python shell, and use the exact same
library, same env, it totally does work.
<file_sep>from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class auth_help( models.Model ):
#i had to make this model so that i could create a permission.
#this is the permission that determines whether a user can use
#the app. it is called 'psu_gcal', so referencing it is: psu_gcal.psu_gcal
field = models.CharField( max_length=1 )
class Meta:
permissions = (
( 'psu_gcal', 'can use the app' ),
)
<file_sep>"""Google user management."""
from psugle import creds
import gdata.apps.service
import gdata.apps
class User:
"""Google user management."""
def __init__(self, domain=None, adminuser=None, password=None, g_client=None):
"""New User object. Google <domain> required. <adminuser> and
<password> will override module defaults.
A <g_client> of type gdata.apps.service.AppsService
can be specified to re-use an existing client."""
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not password:
password = creds.google[domain]["password"]
if g_client:
self.g_client = g_client
else:
self.g_client = gdata.apps.service.AppsService(
domain=domain
,email="%s@%s" % (adminuser, domain)
,password=<PASSWORD>
)
self.g_client.ProgrammaticLogin()
def query_alias(self, alias=None):
"""For a given <alias>, returns a dict regarding existence
and real user."""
try:
alias_data = self.g_client.RetrieveNickname(alias)
return {"exists": True, "real_name": alias_data.login.user_name}
except gdata.apps.service.AppsForYourDomainException, err:
if err.error_code == 1301:
return {"exists": False, "real_name": None}
def query_user(self, user_name=None):
"""For a given <user_name>, returns a dict regarding existence
and enabled/disabled status"""
try:
user_disabled = self.g_client.RetrieveUser(user_name).login.suspended
if user_disabled == 'false':
return {"exists": True, "enabled": True}
elif user_disabled == 'true':
return {"exists": True, "enabled": False}
except gdata.apps.service.AppsForYourDomainException, err:
if err.error_code == 1301:
return {"exists": False, "enabled": False}
def status(self, user_name=None):
"""For a given <user_name>, returns a dict regarding existence,
type (user|alias), real username, and enabled/disabled status"""
alias = self.query_alias(user_name)
if alias["exists"] == True:
real_name = alias["real_name"]
else:
real_name = user_name
user = self.query_user(real_name)
return {"exists": user["exists"]
,"enabled": user["enabled"]
,"is_alias": alias["exists"]
,"real_name": real_name
}
def create(self, user_name=None, given_name=None, family_name=None, user_suspended=False, password_hash=None, hash_algorithm="SHA-1"):
"""Creates a Google user given the attributes. Expects a
pre-computed password hash. <pw_hash> is either 'MD5' or
'SHA-1' (default)"""
self.g_client.CreateUser(
user_name = user_name
,family_name = family_name
,given_name = given_name
,password = <PASSWORD>
,password_hash_function = <PASSWORD>_algorithm
,suspended = str(user_suspended).lower()
)
def rename(self, user_name=None, new_user_name=None, new_given_name=None, new_family_name=None):
"""Changes a user's given_name, family_name, or user_name.
Only specify the attributes you wish to change. Those left
unspecified will be untouched."""
user_record = self.g_client.RetrieveUser(user_name = user_name)
if new_user_name:
user_record.login.user_name = new_user_name
if new_given_name:
user_record.login.given_name = new_given_name
if new_family_name:
user_record.login.family_name = new_family_name
if new_user_name or new_given_name or new_family_name:
self.g_client.UpdateUser(user_name = user_name, user_entry = user_record)
def create_alias(self, user_name=None, alias=None):
"""Creates an alias for a user."""
self.g_client.CreateNickname(
user_name = user_name
,nickname = alias
)
def reset_password(self, user_name=None, password_hash=None, hash_algorithm="SHA-1"):
"""Resets a Google user's password. Expects a pre-computing
password hash. <pw_hash> is either 'MD5' or 'SHA-1' (default)"""
user_record = self.g_client.RetrieveUser(user_name = user_name)
user_record.login.password = <PASSWORD>
user_record.login.hash_function_name = hash_algorithm
self.g_client.UpdateUser(user_name, user_record)
def enable(self, user_name=None):
"""Re-enables a suspended user."""
self.g_client.RestoreUser(user_name = user_name)
def disable(self, user_name=None):
"""Disables an enabled user."""
self.g_client.SuspendUser(user_name = user_name)
def delete(self, user_name=None):
"""Deletes a user."""
self.g_client.DeleteUser(user_name = user_name)
def delete_alias(self, alias=None):
"""Deletes an alias for a user."""
self.g_client.DeleteNickname(nickname = alias)
<file_sep>'''/var/www/psu_gcal/support/alias_util.py'''
from psugle.user import User
from subprocess import call
from tempfile import TemporaryFile
def create_alias(alias, uid):
'''this method will create the alias in google's system via gam'''
user_client = User('pdx.edu','ops-cal','Utdedd7twod%')#User('pdx.edu','ops-cal','Utdedd7twod%')
uid_exists = user_client.query_user(uid)
if False in uid_exists.values():
#if the uid doesn't exist or is disnabled, then we can't use it.
#terminal failure
return "the uid: {0} is not an existing user.".format(uid)
else:
alias_is_uid = user_client.query_user(alias)
if True in alias_is_uid.values():
#if the alias-to-be is an existing username, we can't
#use it. terminal failure.
return "the alias: {0} is a uid.".format(alias)
else:
alias_exists = user_client.query_alias(alias)
if True in alias_exists.values():
#if the alias is an existing alias for someone else
#we can't use it. terminal failure.
return("The alias: {0} is already an alias for uid: {1}".format(alias,uid))
else:
#if neither uid or alias are taken in any way. then try and
#add it as prescribed. First choice: psugle
user_client.create_alias(uid, alias)
#check results:
with TemporaryFile() as temp:
call(['/var/www/env/bin/python2.6',
'/var/www/psu_gcal/gam.py', 'info', 'user', uid],
stdout=temp)
temp.seek(0)
results = temp.read()
if alias in results:
return('Successfully created alias: {0} for user: {1}.'
.format(alias, uid))
else:
#if the first time doesn't go through, try again
#print('Google alias creation with psugle failed.' + \
# 'Attempting with gam.py.')
with TemporaryFile() as temp:
call(['/var/www/env/bin/python2.6',
'/var/www/psu_gcal/gam.py', 'create', 'alias',
alias, 'user', uid], stdout=temp)
temp.seek(0)
results = temp.read()
if not 'Creating alias <EMAIL> for user <EMAIL>'.format(alias, uid) in results:
pass #print('incorrect gam print statement.')
#one last check here to make sure the alias was added.
with TemporaryFile() as temp:
call(['/var/www/env/bin/python2.6',
'/var/www/psu_gcal/gam.py', 'info', 'user', uid],
stdout=temp)
temp.seek(0)
results = temp.read()
if alias in results:
return 'Successfully created alias: {0} for user: {1}'.format(alias, uid)
else:
return 'Could not create the alias: {0} for user: {1}'.format(alias, uid)+'\n'+str(results)
<file_sep>"""Google user profile management."""
from psugle import creds
import gdata.contacts.client
import gdata.contacts.data
import gdata.gauth
class Profile:
"""Google user profile management."""
def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None):
"""New profile object. Google <domain> required. <adminuser> and
<oauth_secret> will override module defaults.
A <g_client> of type gdata.contacts.client.ContactsClient
can be specified to re-use an existing client."""
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not oauth_secret:
oauth_secret = creds.google[domain]["oauth_secret"]
if g_client:
self.g_client = g_client
else:
self.g_client = gdata.contacts.client.ContactsClient(
source = "pdx-edu-user-profile-client"
,domain=domain
)
self.g_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
consumer_key=domain
,consumer_secret=oauth_secret
,requestor_id="%s@%s" % (adminuser, domain)
)
def get_gal_visibility(self, user=None):
"""Queries the given <user>'s current visibility setting in Google's
global address list."""
user_uri = "https://www.google.com/m8/feeds/profiles/domain/%s/full/%s"\
% (self.domain, user)
profile = self.g_client.GetProfile(uri=user_uri)
for element in profile.extension_elements:
if element.attributes.has_key("indexed"): # indexed == "show in GAL"
if element.attributes["indexed"] == "true":
return True
else:
return False
else: # If the field is missing, we're at a loss.
return None
def set_gal_visibility(self, user=None, visible=False):
"""Changes a given <user>'s visibility setting in Google's global
address list."""
user_uri = "https://www.google.com/m8/feeds/profiles/domain/%s/full/%s"\
% (self.domain, user)
if self.get_gal_visibility(user) != visible: # Change required
new_setting = str(visible).lower()
profile = self.g_client.GetProfile(uri=user_uri)
for element in profile.extension_elements:
if element.attributes.has_key("indexed"): # indexed == "show in GAL"
element.attributes["indexed"] = new_setting
new_profile = self.g_client.UpdateProfile(profile) # Apply
for element in new_profile.extension_elements:
if element.attributes.has_key("indexed"): # indexed == "show in GAL"
if element.attributes["indexed"] == new_setting: # Did it take?
return True
else:
return False
else: # No change required
return True
<file_sep>'''/psu_gcal/mysite/test.py'''
import sys
sys.path.append('/var/www/psu_gcal/')
sys.path.append('/var/www/psu_gcal/mysite/')
from support.calendar_util import calendar_validate, calendar_already_owner, \
process_calendar, calendar_process_requestor, calendar_add_owner, \
calendar_process_form
from support.group_util import group_validate, group_already_owner, \
process_group, group_process_requestor, group_add_owner, \
group_process_form
from psugle.calresource import CalendarResource
from psugle.group import Group
from random import randint
from hashlib import md5
from time import sleep
from nose.tools import with_setup
#@with_setup(initialize_cals, cleanup_cals)
class calendar_test:
'''test class for calendar operations'''
def __init__(self):
'''init the client obj and the new cal's name to null'''
self.client = None
self.cal_name = ''
def setUp(self):
'''set the client obj to a new client, and set the cal name to the name we\'re using'''
self.client = CalendarResource('gtest.pdx.edu')
self.cal_name = 'new_cal_name'
def tearDown(self):
'''delete the newly created calendar object as well as the client we were using'''
try:
self.client.g_res_client.delete_resource(md5('new_cal_name').hexdigest())
except:
print 'error deleting the cal with name "new_cal_name"'
del self.client
def test_calendar_validate_existing(self):
'''this function tests running calendar_validate on a known existing
calendar'''
calendar_already_exists, success, acl = \
calendar_validate('abc_calendar', self.client)
assert (calendar_already_exists == True)
assert (success == False)
assert (len(acl)>0)
def test_calendar_validate_new(self):
'''this function tests running calendar_validate on a new calendar'''
calendar_already_exists, success, acl = \
calendar_validate(self.cal_name, self.client)
assert (calendar_already_exists == False)
assert (success == True)
assert ((len(acl)==2) or (len(acl)==0))
def test_calendar_already_owner_true(self):
'''this function tests running calendar_already_owner on a calendar where we
know that the given user is already an owner'''
_, _, acl = calendar_validate('abc_calendar', self.client)
owner_already = calendar_already_owner('magarvey', acl, self.client)
assert owner_already
def test_calendar_already_owner_false(self):
'''this function tests running calendar_already_owner on a calendar where we
know that the given user is not already an owner'''
_, _, acl = calendar_validate('abc_calendar', self.client)
owner_already = calendar_already_owner('phony_phony_phony', acl, self.client)
assert (owner_already == False)
def test_process_calendar_existing(self):
'''this function tests running the process_calendar method on a known
existing calendar'''
response = process_calendar('calendar_name', True, False)
assert (response == 'calendar_name (existing calendar)')
def test_process_calendar_new(self):
'''this function tests running the process_calendar method on a new
calendar'''
response = process_calendar('calendar_name', False, True)
assert (response == 'calendar_name (new calendar)')
def test_process_calendar_error(self):
'''this function tests running the process_calendar method on invalid
input; indicating failure to create calendar'''
response = process_calendar('calendar_name', False, False)
assert (response == 'could not make calendar: calendar_name')
def test_process_reqiuestor_existing(self):
'''this function tests the calendar_process_requestor method on a requestor
that is already the owner of the calendar'''
response = calendar_process_requestor('magarvey',
'abc_calendar',
True,
self.client)
assert (response == '\n<br/>magarvey (already owner)')
def test_calendar_process_requestor_new(self):
'''this function tests the calendar_process_requestor method on a requestor
that is already the owner of the calendar'''
__a__ = md5()
__a__.update(str(randint(0, 5000000)))
user = 'test_user-'+str(__a__.hexdigest())
response = calendar_process_requestor(user, 'abc_calendar', False, self.client)
assert (response == '\n<br/>' + user + ' (new owner)')
def test_calendar_process_requestor_invalid(self):
'''this function tests the calendar_process_requestor method on a requestor with
some invalid chars in the requestor's name (... to trigger the exception)'''
response = calendar_process_requestor('', 'abc_calendar', False, self.client)
assert (response.startswith('\n<br/> is invalid user'))
def test_calendar_add_owner_existing(self):
'''this function tests the calendar_add_owner method on a calendar that the user
is already owner of'''
calendar_already_exists, success, acl = \
calendar_validate('abc_calendar', self.client)
calendar_already_owner_start = calendar_already_owner('magarvey', acl, self.client)
try:
calendar_add_owner('magarvey', 'abc_calendar', self.client)
calendar_add_owner_success = True
except:
calendar_add_owner_success = False
assert calendar_already_exists
assert calendar_already_owner_start
assert (success == False)
assert (calendar_add_owner_success == False)
def test_calendar_add_owner_invalid(self):
'''this function tests the calendar_add_owner method on a user that is not in the
gtest.pdx.edu system'''
calendar_already_exists, success, acl = \
calendar_validate('abc_calendar', self.client)
calendar_already_owner_start = calendar_already_owner('?//%/$/#@', acl, self.client)
try:
calendar_add_owner('?//%/$/#@', 'abc_calendar', self.client)
calendar_add_owner_success = True
except:
calendar_add_owner_success = False
assert calendar_already_exists
assert (calendar_already_owner_start == False)
assert (success == False)
assert (calendar_add_owner_success == False)
def test_calendar_add_owner_new(self):
'''this function tests the calendar_add_owner method for a valid user not already
owner of the calendar'''
self.client.create(self.cal_name)
calendar_already_exists, success, acl = \
calendar_validate(self.cal_name, self.client)
calendar_already_owner_start = calendar_already_owner('magarvey', acl, self.client)
try:
calendar_add_owner('magarvey', self.cal_name, self.client)
calendar_add_owner_success = True
except Exception, err:
print err
calendar_add_owner_success = False
calendar_already_exists, success, acl = \
calendar_validate(self.cal_name, self.client)
calendar_already_owner_end = calendar_already_owner('magarvey', acl, self.client)
assert calendar_already_exists
assert (calendar_already_owner_start == False)
assert (success == False)
assert calendar_add_owner_success
assert calendar_already_owner_end
class Form():
'''a dummy form object for use with test_calendar_process_form function'''
def __init__(self):
'''this is the init method for the dummy form object
we've defined here'''
self.cleaned_data = {'calendar_name':'some_cal_name',
'calendar_requestor_1':'some_cal_user',
'calendar_requestor_2':'other_cal_user'}
def contents(self):
'''return the contents of cleaned data'''
return self.cleaned_data
def add(self, key, value):
'''set a key, value pair'''
self.cleaned_data[key] = value
def test_calendar_process_form(self):
'''this function tests the process form function... just make sure
it gets the right stuff from an object with the same contents
as the one we're dealing with'''
this_form = self.Form()
calendar_name, requestor_1, requestor_2 = calendar_process_form(this_form)
assert (calendar_name == 'some_cal_name')
assert (requestor_1 == 'some_cal_user')
assert (requestor_2 == 'other_cal_user')
class group_test:
'''test class for groups'''
def __init__(self):
'''init client and group_name to none'''
self.client = None
self.group_name = None
def setUp(self):
'''set up the group client and set the group name'''
self.client = Group('gtest.pdx.edu')
self.group_name = 'new_test_group'
def tearDown(self):
'''delete the newly created test group and the client object'''
try:
self.client.delete(group_name='new_test_group')
except:
print "error deleting group: 'new_test_group'"
del self.client
def test_group_validate_existing(self):
'''this function tests running group_validate on a known existing
group'''
group_already_exists, success = \
group_validate('abc_group', '', self.client)
assert (group_already_exists == True)
assert (success == False)
def test_group_validate_new(self):
'''this function tests running calendar_validate on a new calendar'''
group_already_exists, success = \
group_validate(self.group_name, '', self.client)
assert (group_already_exists == False)
assert (success == True)
def test_group_already_owner_true(self):
'''this function tests running group_already_owner on a group where we
know that the given user is already an owner'''
owner_already = group_already_owner('magarvey', 'abc_group', self.client)
assert owner_already
def test_group_already_owner_false(self):
'''this function tests running group_already_owner on a group where we
know that the given user is not already an owner'''
owner_already = group_already_owner('phony_phony_phony', 'abc_group', self.client)
assert (owner_already == False)
def test_process_group_existing(self):
'''this function tests running the process_group method on a known
existing group'''
response = process_group('group_name', '', True, False)
meaningful_response = response.split('\n')[0]
print meaningful_response
assert (meaningful_response == 'group name: group_name (existing group)')
def test_process_group_new(self):
'''this function tests running the process_group method on a new
group'''
response = process_group('group_name', '', False, True)
meaningful_response = response.split('\n')[0]
print meaningful_response
assert (meaningful_response == 'group name: group_name (new group)')
def test_process_group_error(self):
'''this function tests running the process_group method on invalid
input; indicating failure to create group'''
response = process_group('group_name', '', False, False)
meaningful_response = response.split('\n')[0]
print meaningful_response
assert (meaningful_response == 'could not make group: group_name')
def test_group_process_reqiuestor_existing(self):
'''this function tests the group_process_requestor method on a requestor
that is already the owner of the calendar'''
response = group_process_requestor('magarvey',
'abc_group',
True,
self.client)
assert (response == '\n<br/>magarvey (already owner)')
def test_group_process_requestor_new(self):
'''this function tests the calendar_process_requestor method on a requestor
that is not already the owner of the calendar'''
self.client.create(self.group_name)
response = group_process_requestor('magarvey', self.group_name, False, self.client)
print response
assert (response == '\n<br/>magarvey (new owner)')
def test_group_process_requestor_invalid(self):
'''this function tests the group_process_requestor method on a requestor with
some invalid chars in the requestor's name (... to trigger the exception)'''
response = group_process_requestor('', 'abc_group', False, self.client)
assert (response.startswith('\n<br/> is invalid user'))
def test_group_add_owner_existing(self):
'''this function tests the group_add_owner method on a group that the user
is already owner of'''
group_already_exists, success = \
group_validate('abc_calendar', '', self.client)
group_already_owner_start = group_already_owner('magarvey', 'abc_group', self.client)
try:
group_add_owner('magarvey', 'abc_group', self.client)
group_add_owner_success = True
except:
group_add_owner_success = False
group_already_owner_end = group_already_owner('magarvey','abc_group',self.client)
assert group_already_exists
assert group_already_owner_start
assert group_already_owner_end
assert (success == False)
assert (group_add_owner_success == True)
def test_group_add_owner_invalid(self):
'''this function tests the group_add_owner method on a user that is not in the
gtest.pdx.edu system'''
group_already_exists, success = \
group_validate('abc_group', '', self.client)
try:
group_already_owner_start = group_already_owner('?//%/$/#@', 'abc_group', self.client)
except:
group_already_owner_start = False
try:
subscribed, owner = group_add_owner('?//%/$/#@', 'abc_group', self.client)
group_add_owner_success = True
except:
group_add_owner_success = False
assert group_already_exists
assert (group_already_owner_start == False)
assert (success == False)
assert (group_add_owner_success == True)
assert (subscribed == False)
assert (owner == False)
def test_group_add_owner_new(self):
'''this function tests the group_add_owner method for a valid user not already
owner of the group'''
self.client.create(self.group_name)
group_already_exists, success = \
group_validate(self.group_name, '', self.client)
group_already_owner_start = group_already_owner('magarvey', self.group_name, self.client)
try:
subscribed, owner = group_add_owner('magarvey', self.group_name, self.client)
group_add_owner_success = True
except:
group_add_owner_success = False
group_already_exists, success = \
group_validate(self.group_name, '', self.client)
sleep(5)
group_already_owner_end = group_already_owner('magarvey', self.group_name, self.client)
'''DEBUGGIN'''
print str(self.client.status(self.group_name))
print str(group_already_owner('magarvey',self.group_name,self.client))
assert group_already_exists
assert (group_already_owner_start == False)
assert (success == False)
assert group_add_owner_success
assert subscribed
assert owner
assert group_already_owner_end
<file_sep>'''/psu_gcal/mysite/psu_gcal/support/general_util.py'''
from psugle.user import User
def requestor_validate( requestor, client ):
'''this method makes sure the user exists in the system'''
try:
user = User( client.domain )
except:
return False
try:
if user.query_user( requestor )['exists']:
return True
else:
return False
except TypeError, err:
raise Exception('couldn\'t query username: '+str(requestor)+', please contact requestor or look up user in ldap.')
<file_sep>'''A simple little lib for getting oauth, and doing the boogie into gdata.'''
import os
import pickle
import gdata
import sys
import gdata.apps
import gdata.apps.groupsettings
import gdata.apps.groupsettings.service
#a hard coded version in case we get errors
__this_dir__ = '/var/www/psu_gcal'
def try_oauth(gdata_object):
'''try oauth attempts to find the oauth file and verify that it's good
to make api calls'''
oauth_filename = 'oauth.txt'
try:
oauth_filename = os.environ['OAUTHFILE']
except KeyError:
pass
if os.path.isfile(get_path() + oauth_filename):
oauthfile = open(get_path() + oauth_filename, 'rb')
print oauthfile.read() #debug
oauthfile.seek(0) #debug
domain = oauthfile.readline()[0:-1]
try:
token = pickle.load(oauthfile)
oauthfile.close()
# Deals with tokens created by windows on old GAM versions.
#Rewrites them with binary mode set
except ImportError:
oauthfile = open(get_path() + oauth_filename, 'r')
domain = oauthfile.readline()[0:-1]
token = pickle.load(oauthfile)
oauthfile.close()
file_desc = open(get_path() + oauth_filename, 'wb')
file_desc.write('%s\n' % (domain,))
pickle.dump(token, file_desc)
file_desc.close()
gdata_object.domain = domain
gdata_object.SetOAuthInputParameters(
gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
consumer_key=token.oauth_input_params._consumer.key,
consumer_secret=token.oauth_input_params._consumer.secret)
token.oauth_input_params = gdata_object._oauth_input_params
gdata_object.SetOAuthToken(token)
return True
else:
return False
def get_path():
'''get the path to gam, used to find oauth.txt'''
if os.name == 'windows' or os.name == 'nt':
divider = '\\'
else:
divider = '/'
try:
print 'path to look for oauth: {0}'.format(os.getcwd()+divider)
#return os.getcwd()+divider
return __this_dir__+divider
except:
print 'path to look for oauth: {0}'.format(os.getcwd()+divider)
#print os.path.dirname(os.path.realpath(__this_dir__))+divider #debug
return os.path.dirname(os.path.realpath(__this_dir__))+divider
def group_settings_object():
groupsettings = gdata.apps.groupsettings.service.GroupSettingsService()
if not try_oauth(groupsettings):
#doRequestoauth()
try_oauth(groupsettings)
#groupsettings = commonAppsObjInit(groupsettings)
return groupsettings
def set_archived_status(group_email):
print 'group_email: {0}'.format(group_email)
print 'get_path(): {0}'.format(get_path())
gdata_object = group_settings_object()
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:googleapis.com,2010:apps:groupssettings:GROUP:NNN</id>
<title>Groups Resource Entry</title>
<author>
<name>Google</name>
</author>
<apps:id>%s</apps:id>
<apps:email>%s</apps:email>
''' % (group_email, group_email)
xml += '<apps:isArchived>true</apps:isArchived></entry>'
print 'xml: {0}'.format(xml) #debug
uri = '/groups/v1/groups/{0}?alt=atom'.format(group_email)
print 'uri: {0}'.format(uri) #debug
try:
gdata_object.Put(uri=uri,data=xml)
print 'change went through.'
except Exception, err:
print 'setting archived bit failed: {0}'.format(err)
if __name__ == "__main__":
print 'sys.argv: ' + str(sys.argv) #debug
print 'get_path(): ' + str(get_path()) #debug
gdata_object = group_settings_object()
try:
#this one works, but I'm going to try and do it with just XML going
#through the authed gdata agent.
'''allow_external_members = allow_google_communication = None
allow_web_posting = archive_only = custom_reply_to = None
default_message_deny_notification_text = description = None
is_archived = max_message_bytes = members_can_post_as_the_group = None
message_display_font = message_moderation_level = name = None
primary_language = reply_to = send_message_deny_notification = None
show_in_group_directory = who_can_invite = who_can_join = None
who_can_post_message = who_can_view_group = None
who_can_view_membership = None'''
#gdata_object.UpdateGroupSettings(sys.argv[1],allow_external_members=allow_external_members, allow_google_communication=allow_google_communication, allow_web_posting=allow_web_posting, archive_only=archive_only, custom_reply_to=custom_reply_to, default_message_deny_notification_text=default_message_deny_notification_text, description=description, is_archived='true', max_message_bytes=max_message_bytes, members_can_post_as_the_group=members_can_post_as_the_group, message_display_font=message_display_font, message_moderation_level=message_moderation_level, name=name, primary_language=primary_language, reply_to=reply_to, send_message_deny_notification=send_message_deny_notification, show_in_group_directory=show_in_group_directory, who_can_invite=who_can_invite, who_can_join=who_can_join, who_can_post_message=who_can_post_message, who_can_view_group=who_can_view_group, who_can_view_membership=who_can_view_membership)
#here's a way to change the is_archived setting via a raw atom XML message
#going to the API thru an oauth-ed gdata client with groupsettings enabled
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:googleapis.com,2010:apps:groupssettings:GROUP:NNN</id>
<title>Groups Resource Entry</title>
<author>
<name>Google</name>
</author>
<apps:id>%s</apps:id>
<apps:email>%s</apps:email>
''' % (sys.argv[1], sys.argv[1])
xml += '<apps:isArchived>true</apps:isArchived></entry>'
uri = '/groups/v1/groups/%s?alt=atom' % sys.argv[1]
gdata_object.Put(uri=uri,data=xml)
print 'change went through' #debug
except Exception, err:
print 'error setting archived bit: {0}'.format(err)
#pass
<file_sep>'''/psu_gcal/mysite/psu_gcal/support/calendar_validate.py'''
from psugle.user import User
def calendar_validate( calendar_name, client ):
'''this function takes a calendar name and a client object and returns
a boo telling whether the cal exists, and a boo if we're successful in
creating a new cal if it doesn't. Also, the acl is retrieved'''
#does cal with name == calendar_name already exist?
calendar_already_exists = False
existing_cals = client.get_all_resources()
for cal in existing_cals:
if cal['name'] == calendar_name:
calendar_already_exists = True
break
#if not existing, create new. successful create?
success = False
if not calendar_already_exists:
try:
client.create( name=str(calendar_name) )
success = True
except Exception, err:
success = str(err)
#pass
#get acl
if calendar_already_exists or success:
try:
acl = client.get_acl_by_name( calendar_name )
except:
acl = []
else:
acl = []
#print 'debug3'
return calendar_already_exists, success, acl
def calendar_already_owner( requestor, acl, client ):
'''this function takes a requestor name an acl and a client and returns
a boolean as to whether the requestor is already an owner'''
for entry in acl:
if entry[0] == (requestor+'@'+str( client.domain )):
return True
return False
def process_calendar( calendar_name, calendar_already_exists, success ):
'''this function generates the part of the success message dealing with
the calendar'''
response = calendar_name
if success:
response += ' (new calendar)'
elif calendar_already_exists:
response += ' (existing calendar)'
else:
response = 'could not make calendar: '+calendar_name
return response
def calendar_process_requestor( requestor_name, calendar_name, already_owner, client ):
'''this function generates the part of the success message dealing with
a requestor'''
response = '\n<br/>'+requestor_name
if already_owner:
response += ' (already owner)'
else:
try:
calendar_add_owner(requestor_name, calendar_name, client)
response += ' (new owner)'
except Exception, err:
response += ' is invalid user: <br/> '+str(err)
return response
def calendar_add_owner( requestor_name, calendar_name, client ):
'''this method adds a new owner to a calendar'''
client.set_owner_by_name(name=calendar_name,owner=requestor_name)
def calendar_process_form( form ):
'''this method gets the different fields from the calendar form'''
#print 'form.cleaned_data: ' + str(form.cleaned_data)
return form.cleaned_data['calendar_name'], form.cleaned_data['calendar_requestor_1'], form.cleaned_data['calendar_requestor_2']
<file_sep>"""Google email settings management."""
from psugle import creds
import gdata.apps.emailsettings.client
import gdata.gauth
class EmailSettings:
"""Google email settings management."""
def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None):
"""New EmailSettings object. Google <domain> required. <adminuser> and
<oauth_secret> will override module defaults.
A <g_client> of type gdata.apps.emailsettings.client.EmailSettingsClient
can be specified to re-use an existing client."""
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not oauth_secret:
oauth_secret = creds.google[domain]["oauth_secret"]
if g_client:
self.g_client = g_client
else:
self.g_client = gdata.apps.emailsettings.client.EmailSettingsClient(domain=domain)
self.g_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
consumer_key=self.domain
,consumer_secret=oauth_secret
,requestor_id="%s@%s" % (adminuser, domain)
)
def get_forwarding(self, user=None):
"""Returns a dictionary for a given <user>:
{"forwarding_enabled":boolean,"forwarding_address":email_address}"""
user_uri = "https://www.google.com/a/feeds/emailsettings/2.0/%s/%s/forwarding"\
% (self.domain, user)
enabled = False
address = None
settings = self.g_client.GetEntry(uri=user_uri)
for element in settings.extension_elements:
try:
if element.attributes["name"] == "enable": # Is forwarding enabled?
if element.attributes["value"] == "true":
enabled = True
else:
enabled = False
elif element.attributes["name"] == "forwardTo": # Forwarding address
address = element.attributes["value"]
except KeyError: # Sometimes we get empty dicts.
pass
return {"forwarding_enabled":enabled, "forwarding_address":address}
def set_forwarding(self, user=None, enable=False, forwarding_address=None, action="KEEP"):
"""Sets forwarding for a given <user>.
<forward_address> must be one of the following:
1. It belongs to the same domain,
2. It belongs to a subdomain of the same domain, or
3. It belongs to a domain alias configured as part of the same Google Apps account.
<actions> are one of the following strings:
KEEP (in inbox), ARCHIVE, or DELETE (send to spam), or MARK_READ (marked as read)"""
self.g_client.UpdateForwarding(
username=user
,enable=enable
,forward_to=forwarding_address
,action=action
)
def set_webclip(self, user=None, enable=False):
"""Enabled or disables webclips for a given <user>."""
self.g_client.UpdateWebclip(username=user, enable=enable)
<file_sep>"""Google calendar resource management."""
from gdata.calendar_resource.client import CalendarResourceClient
from gdata.calendar.client import CalendarClient
from gdata.calendar.data import CalendarAclEntry
from gdata.acl.data import AclRole, AclScope
from hashlib import md5
from urllib import quote
from psugle import creds
class CalendarResource:
"""Google calendar resource management."""
def __init__(self, domain=None, adminuser=None, password=<PASSWORD>, g_cal_client=None, g_res_client=None):
"""New orgunit object. Google <domain> required. <adminuser> and
<password> will override module defaults.
A <g_cal_client> of gdata.calendar.client.CalendarClient and
A <g_res_client> of gdata.calendar_resource.client.CalendarResourceClient
can be specified to re-use an existing client."""
self.domain = domain
cal_id = "pdx-calendar-sync-1.0"
res_id = "pdx-resource-sync-1.0"
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not password:
password = creds.google[domain]["password"]
if g_cal_client:
self.g_cal_client = g_cal_client
else:
self.g_cal_client = CalendarClient(domain=self.domain)
self.g_cal_client.ClientLogin(
"%s@%s" % (adminuser, domain)
,password
,cal_id
)
if g_res_client:
self.g_res_client = g_res_client
else:
self.g_res_client = CalendarResourceClient(domain=self.domain)
self.g_res_client.ClientLogin(
"%s@%s" % (adminuser, domain)
,password
,res_id
)
def create(self, name=None, resource_type=None, description=None):
"""Create a new calendar resource. <name> required.
<resource_type> and <description> are optional free-form strings."""
self.g_res_client.CreateResource(
resource_id=md5(name).hexdigest()
,resource_common_name=name
,resource_type=resource_type
,resource_description=description
)
def get_all_resources(self):
"""Dump a list of all existing calendar resources, each resource
is a dict, {"name","email"}."""
feed = self.g_res_client.GetResourceFeed()
resource_entries = feed.entry
while feed.get_next_link() != None:
feed = self.g_res_client.GetNext(feed)
resource_entries.extend(feed.entry)
return [{"name":entry.GetResourceCommonName()\
,"email":entry.GetResourceEmail()} for entry in resource_entries]
def get_acl_by_name(self, name=None):
"""Retrieve the ACLs for a resource, given its <name>."""
resource = self.g_res_client.GetResource(
resource_id=md5(name).hexdigest()
)
return self.get_acl_by_resource_email(
resource_email=resource.GetResourceEmail()
)
def get_acl_by_resource_email(self, resource_email=None):
"""Retrieve the ACLs for a resource, given its <resource_email>
address."""
acluri = "https://www.google.com/calendar/feeds/%s/acl/full" \
% quote(resource_email)
acl_feed = self.g_cal_client.GetCalendarAclFeed(uri=acluri)
return [(entry.scope.value, entry.role.value)\
for entry in acl_feed.entry]
def get_resource_by_name(self, name):
"""gets a resource object by its name"""
resource = self.g_res_client.GetResource(
resource_id=md5(name).hexdigest()
)
return resource
def set_owner_by_name(self, name=None, owner=None):
"""Add <owner> to the list of a resource's owners, given the
resource's <name>."""
resource = self.g_res_client.GetResource(
resource_id=md5(name).hexdigest()
)
self.set_owner_by_resource_email(
resource_email=resource.GetResourceEmail(), owner=owner
)
def set_owner_by_resource_email(self, resource_email=None, owner=None):
"""Add <owner> to the list of a resource's owners, given the
resource's <resource_email>."""
newrule = CalendarAclEntry()
newrule.scope = AclScope(
value="%s@%s" % (owner, self.domain)
,type='user'
)
newrole = 'http://schemas.google.com/gCal/2005#%s' % ('owner')
newrule.role = AclRole(value=newrole)
acluri = "https://www.google.com/calendar/feeds/%s/acl/full" \
% quote(resource_email)
self.g_cal_client.InsertAclEntry(new_acl_entry=newrule, insert_uri=acluri)
<file_sep>"""Google group management."""
from psugle import creds
import gdata.apps.groups.service
import gdata.apps
class Group:
"""Google group management."""
def __init__(self, domain=None, adminuser=None, password=None, g_client=None):
"""New Group object. Google <domain> required. <adminuser> and
<password> will override module defaults.
A <g_client> of type gdata.apps.groups.service.GroupsService
can be specified to re-use an existing client."""
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]["adminuser"]
if not password:
password = creds.google[domain]["password"]
if g_client:
self.g_client = g_client
else:
self.g_client = gdata.apps.groups.service.GroupsService(
domain=domain
,email="%s@%s" % (adminuser, domain)
,password=<PASSWORD>
)
self.g_client.ProgrammaticLogin()
def status(self, group_name=None):
"""For a given <group_name>, returns a dict to indicate existence
and other data."""
try:
group_status = self.g_client.RetrieveGroup(group_name)
return {"exists": True, "data": group_status}
except gdata.apps.service.AppsForYourDomainException, err:
if err.error_code == 1301:
return {"exists": False, "data": None}
def create(self, group_name=None, description=None, open_membership=False):
"""Creates a Google group given the attributes.
open_membership == True allows anyone to subscribe, False
requires owner approval."""
if open_membership == True:
permissions = gdata.apps.groups.service.PERMISSION_ANYONE
else:
permissions = gdata.apps.groups.service.PERMISSION_OWNER
self.g_client.CreateGroup(
group_id = group_name
,group_name = group_name
,description = description
,email_permission = permissions
)
def subscribe(self, group_name=None, user_name=None):
"""Subscribes a user to a group."""
user_email = "%s@%s" % (user_name, self.domain)
if self.g_client.IsMember(user_email, group_name) == False:
self.g_client.AddMemberToGroup(user_email, group_name)
def unsubscribe(self, group_name=None, user_name=None):
"""Unsubscribes a user to a group."""
user_email = "%s@%s" % (user_name, self.domain)
if self.g_client.IsMember(user_email, group_name) == True:
self.g_client.RemoveMemberFromGroup(user_email, group_name)
def make_owner(self, group_name=None, user_name=None):
"""Makes a user an group owner. If <memberAlso> if False, user
will not be able to post or recieve group email."""
user_email = "%s@%s" % (user_name, self.domain)
if self.g_client.IsOwner(user_email, group_name) == False:
self.g_client.AddOwnerToGroup(user_email, group_name)
def remove_owner(self, group_name=None, user_name=None):
"""Removes a user's group ownership. If <memberAlso> if False, user
will not be able to post or recieve group email."""
user_email = "%s@%s" % (user_name, self.domain)
if self.g_client.IsOwner(user_email, group_name) == True:
self.g_client.RemoveOwnerFromGroup(user_email, group_name)
def delete(self, group_name=None):
"""Deletes a group."""
self.g_client.DeleteGroup(group_id = group_name)
<file_sep>'''/psu_gcal/mysite/psu_gcal/support/group_util.py'''
from psugle.user import User
from subprocess import call
import sys
import os
import oauth_to_gdata
def group_validate( group_name, group_description, client ):
'''this function takes a group name and a client object and returns
a boo telling whether the group exists, and a boo if we're successful in
creating a new group if it doesn't.'''
#does cal with name == calendar_name already exist?
group_already_exists = False
group_status = client.status(group_name)
if group_status['exists']:
group_already_exists = True
#if not existing, create new. successful create?
success = False
if not group_already_exists:
try:
client.create( group_name=group_name, description=group_description )
success = True
except:
pass
if success:
try:
#print 'os.getcwd(): {0}'.format(os.getcwd()) #debug
#print 'sys.path: {0}'.format(sys.path) #debug
#print 'os.listdir(os.getcwd()): {0}'.format(os.listdir(os.getcwd())) #debugi
#print '"{<EMAIL>".format(group_name): '+"{<EMAIL>".format(group_name) #debug
#print 'group_name+"@"+client.domain: {}'.format(str(group_name+'@'+client.domain)) #debug
#print group_name+'@'+client.domain
group_email = group_name+'@'+client.domain
#oauth_to_gdata.set_archived_status(group_email)
call(['/var/www/env/bin/python2.6','/var/www/psu_gcal/gam.py','update','group',"{<EMAIL>".format(group_name),'settings','is_archived','True'])
except Exception, err:
print 'Error: {}'.format(err)
return group_already_exists, success
def group_already_owner( requestor, group_name, client ):
'''this function takes a requestor name a group name and a client and returns
a boolean as to whether the requestor is already an owner'''
return client.g_client.IsOwner(owner_email=requestor+'@'+client.domain, group_id=group_name+'@'+client.domain)
def process_group( group_name, group_description, group_already_exists, success ):
'''this function generates the part of the success message dealing with
the group'''
response = 'group name: ' + group_name
if success:
response += ' (new group)'
elif group_already_exists:
response += ' (existing group)'
else:
response = 'could not make group: ' + group_name
response += '\n<br/>group description: ' + group_description
return response
def group_process_requestor( requestor_name, group_name, already_owner, client ):
'''this function generates the part of the success message dealing with
a requestor'''
response = '\n<br/>'+requestor_name
if already_owner:
response += ' (already owner)'
else:
try:
subscribed, owner = group_add_owner(requestor_name, group_name, client)
if owner:
response += ' (new owner)'
else:
response += ' is invalid user'
except Exception, err:
response += ' is invalid user'
return response
def group_add_owner( requestor_name, group_name, client ):
'''this method adds a new owner to a group'''
try:
client.subscribe(group_name=group_name, user_name=requestor_name)
subscribed = True
except:
subscribed = False
try:
client.make_owner(group_name=group_name, user_name=requestor_name)
owner = True
except:
owner = False
return subscribed, owner
def group_process_form( form ):
'''this method gets the different fields from the calendar form'''
return form.cleaned_data['group_email'], form.cleaned_data['group_name'], form.cleaned_data['group_description'], form.cleaned_data['group_requestor_1'], form.cleaned_data['group_requestor_2']
<file_sep>from django import forms
#the calendar form, just a couple requestors and a cal name
class CalendarForm(forms.Form):
calendar_name = forms.CharField(max_length=100) #cal name
calendar_requestor_1 = forms.CharField(max_length=100, required=False) #requestor 1
calendar_requestor_2 = forms.CharField(max_length=100, required=False) #requestor 2
class GroupForm(forms.Form):
group_name = forms.CharField(max_length=100) #group name
group_description = forms.CharField(max_length=100) #group description
group_requestor_1 = forms.CharField(max_length=100, required=True) #group requestor 1
group_requestor_2 = forms.CharField(max_length=100, required=True) #group requestor 2
class AliasForm( forms.Form ):
alias = forms.CharField(max_length=100, required=True) #alias
uid = forms.CharField(max_length=100, required=True) #uid
<file_sep>'''psu_gcal/mysite/psu_gcal/views.py'''
import sys
sys.path.append("/home/maxgarvey/projects/psu_gcal/live_version/mysite")
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, Context, loader
from django.contrib.auth.decorators import login_required
from my_forms import CalendarForm, GroupForm, AliasForm
try:
from psugle.calresource import CalendarResource
from psugle.group import Group
from psugle.creds import google, group, calendar
except:
from mysite.psugle.calresource import CalendarResource
from mysite.psugle.group import Group
from mysite.psugle.creds import google, group, calendar
from support.calendar_util import calendar_validate, calendar_already_owner, \
process_calendar, calendar_process_requestor, calendar_process_form
from support.general_util import requestor_validate
from support.group_util import group_validate, group_already_owner, \
process_group, group_process_requestor
from support.alias_util import create_alias
#for debug
import logging
__logger__ = logging.getLogger(__name__)
@login_required
def index(request):
'''this is the index method, it serves and handles the calendar creation
owner addition functionality'''
#check for correct permission
if not request.user.has_perm('mysite.psu_gcal'):
return render_to_response('invalid.html')
else:
#check if form submitted
if not request.method == 'POST':
#if the user wants the calendar form
if request.path == '/calendar_form/':
calendar_form = CalendarForm()
template = loader.get_template("calendar_form.html")
context = Context()
return render_to_response('calendar_form.html', {'calendar_form': calendar_form}, context_instance=RequestContext(request))
#if the user wants the group form
elif request.path == '/group_form/':
group_form = GroupForm()
template = loader.get_template("group_form.html")
context = Context()
return render_to_response('group_form.html', {'group_form': group_form}, context_instance=RequestContext(request))
#no more alias form... handled with the other alias create scripts
#alias_form = AliasForm()
#the generic case
else:
template = loader.get_template( 'index.html' )
context = Context()
return render_to_response( 'index.html', {},
context_instance=RequestContext(request) )
#if it's the calendar form that they submitted
elif (u'calendar_name' in request.POST.keys()):
form = CalendarForm( request.POST )
#check if form valid
if not form.is_valid():
return HttpResponse("form not valid...")
#handle form submission
else:
calendar_name, calendar_requestor_1, calendar_requestor_2 = \
calendar_process_form(form)
print 'calendar_name: {0}'.format(calendar_name)#debug
print 'calendar_requestor_1: {0}'.format(calendar_requestor_1)#debug
print 'calendar_requestor_2: {0}'.format(calendar_requestor_2)#debug
try:
#client = CalendarResource( google.keys()[0] )
client = CalendarResource(domain=calendar.keys()[0],adminuser=calendar[calendar.keys()[0]]['adminuser'],password=calendar[calendar.keys()[0]]['password'])
print 'client: {0}'.format(client)#debug
#print str(client) #debug
try:
calendar_already_exists, success, acl = \
calendar_validate( calendar_name, client )
__logger__.info('calendar_already_exists: '+str(calendar_already_exists)+'\nsuccess: '+str(success)+'\nclient: '+str(client)) #debug
except Exception, err:
__logger__.info('err: '+str(err)) #debug
#create success message
response = process_calendar(
calendar_name, calendar_already_exists, success )
__logger__.info('response: '+response) #debug
if calendar_requestor_1:
if requestor_validate( calendar_requestor_1, client ):
requestor_1_already_owner = calendar_already_owner(
calendar_requestor_1,
acl,
client )
response += calendar_process_requestor(
calendar_requestor_1,
calendar_name,
requestor_1_already_owner,
client )
else:
response += '\n<br/>' + calendar_requestor_1 + \
' is not a valid user'
if calendar_requestor_2:
if requestor_validate( calendar_requestor_2, client ):
requestor_2_already_owner = calendar_already_owner(
calendar_requestor_2,
acl,
client )
response += calendar_process_requestor(
calendar_requestor_2,
calendar_name,
requestor_2_already_owner,
client )
else:
response += '\n<br/>' + calendar_requestor_2 + \
' is not a valid user'
__logger__.info('user: ' + str(request.user) + \
' has made the following request:\n' + str(response) + \
'\n')
#return HttpResponse( response )
template = loader.get_template("success.html")
context = Context()
return render_to_response('success.html', {'success_msg': response}, context_instance=RequestContext(request))
except Exception, err:
response = str(err)
response += '\n<br/>calendar name: ' + str(calendar_name)
response += '\n<br/>requestor_1: ' + str(calendar_requestor_1)
response += '\n<br/>requestor_2: ' + str(calendar_requestor_2)
template = loader.get_template("success.html")
context = Context()
return render_to_response('success.html', {'success_msg': response}, context_instance=RequestContext(request))
#return HttpResponse( response )'''
#if its the groups form that was submitted
elif (u'group_name' in request.POST.keys()):
form = GroupForm( request.POST )
#check if form valid
if not form.is_valid():
return HttpResponse("form not valid...")
#handle form submission
else:
group_name = form.cleaned_data['group_name']
group_description = form.cleaned_data['group_description']
group_requestor_1 = form.cleaned_data['group_requestor_1']
group_requestor_2 = form.cleaned_data['group_requestor_2']
try:
#client = Group( google.keys()[0] )
client = Group(domain=group.keys()[0],adminuser=group[group.keys()[0]]['adminuser'],password=group[group.keys()[0]]['password'])
group_already_exists, success = group_validate(
group_name, group_description, client )
#create success message
response = process_group(
group_name, group_description,
group_already_exists, success )
if group_requestor_1:
try:
if requestor_validate( group_requestor_1, client ):
requestor_1_already_owner = group_already_owner(
group_requestor_1,
group_name,
client )
response += group_process_requestor(
group_requestor_1,
group_name,
requestor_1_already_owner,
client )
else:
response += '\n<br/>' + group_requestor_1 + \
' is not a valid user'
except Exception, err:
response += '\n<br/>' + str(err)
if group_requestor_2:
try:
if requestor_validate( group_requestor_2, client ):
requestor_2_already_owner = group_already_owner(
group_requestor_2,
group_name,
client )
response += group_process_requestor(
group_requestor_2,
group_name,
requestor_2_already_owner,
client )
else:
response += '\n<br/>' + group_requestor_2 + \
' is not a valid user'
except Exception, err:
response += '\n<br/>' + str(err)
__logger__.info('user: ' + str(request.user) + \
' has made the following request:\n' \
+ str(response) + '\n')
template = loader.get_template("success.html")
context = Context()
return render_to_response('success.html', {'success_msg': response}, context_instance=RequestContext(request))
#return HttpResponse( response )
except Exception, err:
response = str(err)
response += '\n<br/>There was an error.'
response += '\n<br/>group name: ' + str(group_name)
response += '\n<br/>description:' + str(group_description)
response += '\n<br/>requestor 1: ' + str(group_requestor_1)
response += '\n<br/>requestor 2: ' + str(group_requestor_2)
template = loader.get_template("success.html")
context = Context()
return render_to_response('success.html', {'success_msg': response}, context_instance=RequestContext(request))
<file_sep>'''mysite/urls.py'''
from django.conf.urls.defaults import patterns, url
# admin is at the global urls level, not this subdir one
urlpatterns = patterns('',
url(r'^$', 'mysite.views.index'),
url(r'^accounts/login/$', 'django_cas.views.login'),
url(r'^accounts/logout/$', 'django_cas.views.logout'),
)
<file_sep>from django.conf.urls.defaults import patterns, include, url
#for debug
from django.views import static as my_static
#from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^calendar_form/$', include('mysite.urls')),
url(r'^group_form/$', include('mysite.urls')),
url(r'^cal/$', include('mysite.urls')),
url(r'^group/$', include('mysite.urls')),
url(r'^alias/$', include('mysite.urls')),
url(r'^$', include('mysite.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^accounts/login/$', 'django_cas.views.login'),
url(r'^accounts/logout/$', 'django_cas.views.logout'),
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url':'static/favicon.ico'}),
url(r'^static/(?P<path>.*)$', my_static.serve, {'document_root': '/home/maxgarvey/projects/psu_gcal/live_version/mysite/static/'}),
)
#debug also
#urlpatterns += staticfiles_urlpatterns()
| 43c3e2125286bb6085b446ce9965e62f39d95e10 | [
"Python",
"Text"
] | 18 | Python | maxgarvey/psu_gcal | a82b88a4be6c17fe298549d0e753f14555ee60a3 | d9a9deac7603f6568dac5798d59091dac47d5896 |
refs/heads/main | <repo_name>dpaopao9913/EncryptedWordExtractionFromGitHubRepos<file_sep>/README.md
# EncryptedWordExtractionFromGitHubRepos
GitHub 上にあるファイルから、暗号化文字列(例:APIキーなど)を自動抽出する<br>
Auto extraction program of encrypted strings (i.e. API key) from any files on GitHub.
<br>
以下の暗号化文字列の抽出アルゴリズムは一旦それっぽい文字列を抽出できるように書いていますが、適宜お好みで変更して使ってください。<br>
The following excrypted word extraction algorithm is just my preference, please change when you use based on your preferences.
<br>
```python
################# 独自のアルゴリズム ################################
temp_list = re.findall('[a-z0-9\+=]+', code_line, flags=re.IGNORECASE)
for word in temp_list:
if word_length_lower_limit <= len(word) and len(word) <= word_length_upper_limit: # 文字列の長さをチェック
isIncludeDigit = bool(re.search(r'\d', word))
isIncludeAlphabet = bool(re.search(r'[a-zA-Z]', word))
if isIncludeDigit and isIncludeAlphabet: # 文字列に英字と数字両方あるかどうかチェック
encrypted_word_list.append(word)
#######################################################################
```
<br>
# Usage
以下の行のコードをご自身のものに置き換えてご利用ください。<br>
Please replace the following specific names to yours.
- 'chrome driver path'
- 'repository name'
- \<api access token\>
<br>
```python
chrome_driver_path = 'chrome driver path'
# git関連の設定
repository_path = 'repository name'
if not os.path.isdir(repository_path):
git.Git().clone("https://<api access token>:x-oauth-basic@github.com/<your github domain>/" + repository_path + ".git")
else:
pass
```
<file_sep>/test-scraping-from-github_release.py
import json
import requests
import csv
import time
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
import re
import os
import git
g_year = ["2018", "2019", "2020", "2021"]
g_month = ["01","02","03","04","05","06","07","08","09","10","11","12"]
g_language = ["Python"]
g_sleep_intreval = 7
chrome_driver_path = 'chrome driver path'
# git関連の設定
repository_path = 'repository name'
if not os.path.isdir(repository_path):
git.Git().clone("https://<api access token>:x-oauth-basic@github.com/<your github domain>/" + repository_path + ".git")
else:
pass
# ファイル出力パス
filename_encrypted_words = 'encrypted_words.csv'
filename_extracted_repos = 'extracted_repos.csv'
g_encrypted_words_path = os.getcwd() + '/' + filename_encrypted_words
g_extracted_repos_path = os.getcwd() + '/' + filename_extracted_repos
# 前回までで暗号化抽出済みのレポジトリURLがあれば読み込む
g_already_searched_repos_list = []
if os.path.isfile(filename_extracted_repos):
with open(filename_extracted_repos) as f:
reader = csv.reader(f, delimiter='\n')
for row in reader:
g_already_searched_repos_list.append(row[0])
print(g_already_searched_repos_list)
else:
print('暗号化抽出済みのレポジトリURLリストはありません')
def git_push(filename):
"""
addしてcommitしてpushする関数
"""
try:
repo = git.Repo.init()
repo.index.add(filename)
commit_phrase = 'add ' + filename
repo.index.commit(commit_phrase)
origin = repo.remote(name="origin")
origin.push()
return "Success"
except:
return "Error"
###################################################### 本番用関数 ######################################################
# driver が開いているURLに含まれるリンクをすべて再帰的に走査して、コードが書かれているファイルをすべてリスト code_file_name_list に追加する
def getCodeFileNameList(driver_current_url, code_lines, links_in_repo, code_file_name_list):
if len(code_lines) != 0: # コードファイルである
code_file_name_list.append(driver_current_url)
else: # コードファイルではない
# 再帰的にこのリンクを辿っていき、コードファイルを見つけたら、そのURLをリストに追加
for link in links_in_repo:
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument("--no-sandbox")
options.add_argument("--log-level=3")
options.add_argument("--disable-dev-shm-usage")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver_2 = webdriver.Chrome(chrome_driver_path, options=options) # 今は chrome_options= ではなく options=
driver_2.get(link)
################## 再帰中のエラー'StaleElementReferenceException'回避用に準備 ##################
driver_current_url_2 = driver_2.current_url
# code_lines の要素があれば、driver が開いているURLはコードファイル
code_lines_2 = driver_2.find_elements_by_xpath('//table[@class="highlight tab-size js-file-line-container"]')
# links_in_repo の要素があれば、driver が開いているURLはフォルダ(またはその他ファイル)
aaa = driver_2.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
# 'StaleElementReferenceException'エラー回避用
try:
links_in_repo_2 = [i.get_attribute('href') for i in aaa]
except StaleElementReferenceException:
print("StaleElementReferenceException が再帰中に発生しました。再試行します")
aaa = driver_2.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
links_in_repo_2 = [i.get_attribute('href') for i in aaa]
##################################################################################################
# リンク先のファイル数が多すぎたら、処理時間の都合上スキップする
max_link_num = 30
if len(links_in_repo_2) <= max_link_num:
getCodeFileNameList(driver_current_url_2, code_lines_2, links_in_repo_2, code_file_name_list)
else:
print('%s のリンク数が多すぎる(%d 個)ためスキップ' % (link, len(links_in_repo_2)))
driver_2.close()
# code_line に暗号化された文字列が含まれているかどうかチェック
# IsEncrypted : F=含まれていない, T=含まれている
# encrypted_word_list : 暗号化された文字列(Fの場合は'')
def checkEncryptedWord(code_line):
IsEncrypted = False
encrypted_word_list = []
# 暗号化文字列の特例に使うパラメータ
word_length_lower_limit = 25
word_length_upper_limit = 45
isIncludeDigit = False
isIncludeAlphabet = False
################# 独自のアルゴリズム ################################
temp_list = re.findall('[a-z0-9\+=]+', code_line, flags=re.IGNORECASE)
for word in temp_list:
if word_length_lower_limit <= len(word) and len(word) <= word_length_upper_limit: # 文字列の長さをチェック
isIncludeDigit = bool(re.search(r'\d', word))
isIncludeAlphabet = bool(re.search(r'[a-zA-Z]', word))
if isIncludeDigit and isIncludeAlphabet: # 文字列に英字と数字両方あるかどうかチェック
encrypted_word_list.append(word)
#######################################################################
if len(encrypted_word_list) != 0:
IsEncrypted = True
return IsEncrypted, encrypted_word_list
#####################################################################################################
#
# Scraping code from GitHub repositories
# https://blog.codecamp.jp/python-github-autoaggregate / https://www.youtube.com/watch?v=xfcgLHselcY
# API sample_URL = "https://api.github.com/search/repositories?q=created%3A" + 2018-01 + "+language%3A" + Dart
#
#####################################################################################################
def extractEncryptedStringFromGithub():
for l in g_language:
print(l)
for y in g_year:
for m in g_month:
for page_n in range(10):
check_point = y + "年" + m + "月"
print(check_point)
url = "https://api.github.com/search/repositories?q=created%3A" + y + "-" + m + "+language%3A" + l + "&per_page=100&page=" + str(page_n+1)
print('query: %s' % url)
# 時間計測開始
start_page_n = time.time()
response = requests.get(url)
data = json.loads(response.text)
print("total_count: %d" % (data['total_count']))
print("result num: %d" % (len(data['items'])))
for person_n in range(len(data['items'])):
# [n]番目の人物のレポジトリURLを取得
repos_url = data['items'][person_n]['owner']['repos_url']
# [n]番目の人物のユーザー名とレポジトリ名を取得
user_name = data['items'][person_n]['owner']['login']
repository_name = data['items'][person_n]['name']
print("repo url[%d]: %s" % (person_n, repos_url))
print("user name: %s" % (user_name))
print("repo name: %s" % (repository_name))
# 時間計測開始
start_person_n = time.time()
# レポジトリURLから言語が「Python」であるURLを取得
response = requests.get(repos_url)
data2 = json.loads(response.text)
# 言語「Python」のリポジトリ数をカウント
counter = 0
list_rep_urls = []
for i in range(len(data2)):
if data2[i]['language'] == l:
counter += 1
temp_url = data2[i]['html_url']
print(temp_url)
list_rep_urls.append(temp_url)
print('lang: %s, repo num: %d' % (l, counter))
# レポジトリURLからコードファイルを抽出
for rep_url in list_rep_urls:
# レポジトリをチェック済みかどうか確認
isAlreadyCheckedRepo = False
for r_url in g_already_searched_repos_list:
if r_url == rep_url:
isAlreadyCheckedRepo = True
print('レポジトリURL: %s をスキップ' % (rep_url))
break
if isAlreadyCheckedRepo:
continue
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument("--no-sandbox")
options.add_argument("--log-level=3")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(chrome_driver_path, options=options) # 今は chrome_options= ではなく options=
driver.get(rep_url)
print('レポジトリURL(ルート): %s' % (driver.current_url))
######################################################################################
#
# HTMLコードの中に、
# <a class="js-navigation-open Link--primary" があれば、このタグ<a>のテキストはファイルリンク
# <table class='highlight tab-size js-file-line-container があれば、このタグ<table>のテキストはプログラミングコード
#
######################################################################################
# レポジトリ内のファイルリンクを取得
links_in_root_repo = driver.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
print('レポジトリURL(ルート)に含まれるファイル&フォルダ数: %d' % (len(links_in_root_repo)))
# stale element reference: element is not attached to the page documentエラー
# https://buralog.jp/python-selenium-stale-element-reference-element-is-not-attached-to-the-page-document-error/
try:
links_in_root_repo_ = [a.get_attribute('href') for a in links_in_root_repo]
except StaleElementReferenceException:
print("StaleElementReferenceException がルート1で発生しました。再試行します")
links_in_root_repo = driver.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
links_in_root_repo_ = [a.get_attribute('href') for a in links_in_root_repo]
# 各ファイル名(またはフォルダ名)を取得
for link in links_in_root_repo_:
driver_tmp = webdriver.Chrome(chrome_driver_path, options=options)
driver_tmp.get(link)
print(' レポジトリURL: %s' % link)
################## 再帰中のエラー'StaleElementReferenceException'回避用に準備 ##################
driver_current_url = driver_tmp.current_url
# code_lines の要素があれば、driver が開いているURLはコードファイル
code_lines = driver_tmp.find_elements_by_xpath('//table[@class="highlight tab-size js-file-line-container"]')
# links_in_repo の要素があれば、driver が開いているURLはフォルダ(またはその他ファイル)
aaa = driver_tmp.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
# 'StaleElementReferenceException'エラー回避用
try:
links_in_repo = [i.get_attribute('href') for i in aaa]
except StaleElementReferenceException:
print("StaleElementReferenceException がルート2で発生しました。再試行します")
aaa = driver_tmp.find_elements_by_xpath('//a[@class="js-navigation-open Link--primary"]')
links_in_repo = [i.get_attribute('href') for i in aaa]
##################################################################################################
code_file_name_list = []
getCodeFileNameList(driver_current_url, code_lines, links_in_repo, code_file_name_list)
print(' コードファイルの数(再帰): %d' % (len(code_file_name_list)))
# code_file_name_list の各コードファイルURLにあるプログラミングコードから暗号化された文字列を抽出する
for code_file_url in code_file_name_list:
driver_tmp2 = webdriver.Chrome(chrome_driver_path, options=options)
driver_tmp2.get(code_file_url)
code_lines = driver_tmp2.find_elements_by_xpath('//table[@class="highlight tab-size js-file-line-container"]') # コードの行
# 1行ずつコードを確認して、暗号化文字列があるかどうか捜索
for cl in code_lines:
# print('line: %s' % cl.text) # テキストの確認
IsEncrypted, encrypted_word_list = checkEncryptedWord(cl.text)
if IsEncrypted: # 暗号化された文字列を見つけたら、ファイルへ出力
print(' *** 暗号化文字列を発見: *** ')
with open(g_encrypted_words_path, "a", encoding='utf-8') as f:
f.write(code_file_url + ",")
for encrypted_word in encrypted_word_list:
f.write(encrypted_word + ",")
print(' %s' % encrypted_word)
f.write("\n")
# githubへ出力ファイルをプッシュ
git_push(g_encrypted_words_path)
driver_tmp2.close()
driver_tmp.close()
driver.close()
# 暗号化文字列の抽出が完了したレポジトリURLをファイルに書き出す
with open(g_extracted_repos_path, "a", encoding='utf-8') as f:
f.write(rep_url + "\n")
# githubへ出力ファイルをプッシュ
git_push(g_extracted_repos_path)
# 時間計測終了
elapsed_time_person_n = time.time() - start_person_n
print ("経過時間:{0}".format(elapsed_time_person_n) + "[sec]")
# スリープするかどうかチェック
if elapsed_time_person_n < g_sleep_intreval:
time.sleep(g_sleep_intreval - elapsed_time_person_n) # API呼び出し制限:6回/分
# 時間計測終了
elapsed_time_page_n = time.time() - start_page_n
print ("経過時間:{0}".format(elapsed_time_page_n) + "[sec]")
# スリープするかどうかチェック
if elapsed_time_page_n < g_sleep_intreval:
time.sleep(g_sleep_intreval - elapsed_time_page_n) # API呼び出し制限:6回/分
if __name__=='__main__':
extractEncryptedStringFromGithub() | b472168990e11998b4f6934671bffd83b75ea8a0 | [
"Markdown",
"Python"
] | 2 | Markdown | dpaopao9913/EncryptedWordExtractionFromGitHubRepos | dfff7e4e547a6a700db9162371c3ad8e28c134ef | d206bf35cbfa6bd66137763e26e93aeba2ae6da1 |
refs/heads/master | <repo_name>HaoXin0206/HaoXinLearFlink<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>HaoXinLearFlink</groupId>
<artifactId>HaoXinLearFlink</artifactId>
<version>1.0-SNAPSHOT</version>
<repositories>
<repository>
<id>aliyun</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<properties>
<scala.version>2.11</scala.version>
<flink.version>1.7.2</flink.version>
<hadoop.version>2.7.2</hadoop.version>
<hbase.version>2.0.2</hbase.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients_${scala.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-scala_${scala.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka-0.9_2.11</artifactId>
<version>${flink.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.flink/flink-table -->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-table_${scala.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-jdbc_${scala.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>${hbase.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-parquet</artifactId>
<version>1.7.0</version>
</dependency>
<!-- parquet -->
<!-- https://mvnrepository.com/artifact/org.apache.flink/flink-parquet -->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-parquet</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.parquet</groupId>
<artifactId>parquet-avro</artifactId>
<version>1.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.flink/flink-parquet -->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-parquet_2.11</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- scala 打包插件 -->
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</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>HaoXin.LearFlink.Streamin.waterMarkDemo</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/main/Scala/HaoXin/LearFlink/Streamin/CustomSource/Option.java
package HaoXin.LearFlink.Streamin.CustomSource;
import scala.Serializable;
import java.io.SerializablePermission;
/**
* @ClassName: HaoXin.LearFlink.Streamin.CustomSource.Option
* @Author: 郝鑫
* @Data: 2019/7/6/7:57
* @Descripition:
*/
public class Option implements Serializable {
public final String mysqlDriver="com.mysql.jdbc.Driver";
public final String mysqlUrl="jdbc:mysql://localhost:3306/haoxin";
public final String mysqlUserName="root";
public final String mysqlPasswd="<PASSWORD>";
public final String mysqlInsertSQL="insert into UserInfo(time,name,phone) values(?,?,?)";
}
| 343d8ca87411254e5639fe89513ea12b9b5941a7 | [
"Java",
"Maven POM"
] | 2 | Maven POM | HaoXin0206/HaoXinLearFlink | 6183b6b875bda38c6740a885c4396185816f0dbf | 6d42a9c733cb9dff9ffdca38c3310180118c134d |
refs/heads/master | <file_sep>#ifndef __NoOneDies_Base_H__
#define __NoOneDies_Base_H__
#include<iostream>
#include<cocos2d.h>
USING_NS_CC;
class Base
{
public:
};
#endif // __NoOneDies_Base_H__<file_sep>#ifndef __NoOneDies_GameOverScene_H__
#define __NoOneDies_GameOverScene_H__
#include<iostream>
#include<cocos2d.h>
#include"ui\CocosGUI.h"
using namespace ui;
USING_NS_CC;
class GameOverScene : public LayerColor
{
private:
Size visibleSize;
public:
virtual bool init()
{
LayerColor::initWithColor(Color4B::YELLOW);
visibleSize = Director::getInstance()->getVisibleSize();
auto btn_continue = Button::create("btn-continue.png");
btn_continue->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - 50));
btn_continue->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){
if (type == Widget::TouchEventType::ENDED){
auto transition = TransitionSplitRows::create(2.0, HelloWorld::createScene());
Director::getInstance()->pushScene(transition);
}
});
addChild(btn_continue);
return true;
}
CREATE_FUNC(GameOverScene);
static Scene* createScene(int Score)
{
auto s = Scene::create();
GameOverScene* layer = GameOverScene::create();
Size visibleSize = Director::getInstance()->getVisibleSize();
auto label = Label::create();
char tmp[30];
sprintf(tmp, "Game Over \n Score %d", Score);
label->setPosition(visibleSize.width / 2, visibleSize.height / 2);
label->setString(tmp);
label->setSystemFontSize(40);
label->setColor(Color3B::BLACK);
layer->addChild(label);
s->addChild(layer);
return s;
}
};
#endif // __NoOneDies_Base_H__
<file_sep>#ifndef __NoOneDies_MyFlashTool_H__
#define __NoOneDies_MyFlashTool_H__
#include<iostream>
#include<cocos2d.h>
USING_NS_CC;
class MyFlashTool
{
public:
static Animate * readJsonSpriteSheet(std::string jsonFile, float delayPerUnit);
static Animate * readPlistAnimate(std::string jsonFile, float delayPerUnit);
};
#endif // __NoOneDies_MyFlashTool_H__<file_sep>//
//#ifndef __NoOneDies__FlashTool__
//#define __NoOneDies__FlashTool__
//
//#include <iostream>
//#include <cocos2d.h>
//
//USING_NS_CC;
//
//class FlashTool {
//
//public:
// static Animate * readJsonSpriteSheet(std::string jsonFile,float delayPerUnit);
//};
//
//
//#endif /* defined(__NoOneDies__FlashTool__) */
<file_sep>#ifndef __NoOneDies_Edge_H__
#define __NoOneDies_Edge_H__
#include<iostream>
#include"cocos2d.h"
USING_NS_CC;
class Edge :public Node
{
public:
virtual bool init();
CREATE_FUNC(Edge);
};
#endif // __NoOneDies_Edge_H__<file_sep>#ifndef __NoOneDies_GameController_H__
#define __NoOneDies_GameController_H__
#include<iostream>
#include<cocos2d.h>
#include"Edge.h"
#include"Hero.h"
#include"Block.h"
USING_NS_CC;
class GameController : public Ref
{
private :
Layer *_layer;
float _positionY;
Size visibleSize;
int currentFrameIndex;
int nextFrameCount;
Edge *edge;
Hero *hero;
private:
void resetFrames();
void addBlock();
public:
virtual bool init(Layer* layer, float positionY, std::string fileName);
void onUpdate(float dt);
bool hitTestPoint(Vec2 point);
void onUserTouch();
static GameController* create(Layer* layer, float positionY, std::string fileName);
//CREATE_FUNC(GameController);
};
#endif // __NoOneDies_GameController_H__ <file_sep>#include "Hero.h"
#include "MyFlashTool.h"
bool Hero::init()
{
Sprite::init();
Size s = Size(45 ,50);
//Sprite::createWithSpriteFrameName("farmers_default.png");
//runAction(RepeatForever::create(MyFlashTool::readJsonSpriteSheet("Hero.json", 0.3f)));
runAction(RepeatForever::create(MyFlashTool::readPlistAnimate("Ino",0.05f)));
setPhysicsBody(PhysicsBody::createBox(s));
setContentSize(s);
getPhysicsBody()->setRotationEnable(false);
getPhysicsBody()->setContactTestBitmask(1);
return true;
}
void Hero::setHeroSkin(std::string fileName)
{
runAction(RepeatForever::create(MyFlashTool::readPlistAnimate(fileName, 0.05f)));
}
//getPhysicsBody()->setrotat<file_sep>#ifndef __NoOneDies_Hero_H__
#define __NoOneDies_Hero_H__
#include<iostream>
#include<cocos2d.h>
USING_NS_CC;
class Hero : public Sprite
{
public:
virtual bool init();
virtual void setHeroSkin(std::string fileName);
CREATE_FUNC(Hero);
};
#endif // __NoOneDies_Hero_H__<file_sep>#include "HelloWorldScene.h"
#include"GameOverScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics();
//scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
scene->getPhysicsWorld()->setGravity(Vec2(0,-1000));
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !LayerColor::initWithColor(Color4B(0,0,0,0)))
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
_labelSorce = Label::createWithTTF("Sorce 0", "arial.ttf", 30);
this->addChild(_labelSorce);
_labelSorce->setPosition(Vec2(visibleSize.width / 2, visibleSize.height - _labelSorce->getContentSize().height));
this->schedule(CC_CALLBACK_1(HelloWorld::timeScore, this), 1.0f, "test_key");
gcs.insert(0, GameController::create(this, 0,"Sakura"));
gcs.insert(0, GameController::create(this, 200,"Ino"));
gcs.insert(0, GameController::create(this, 400,"Karin"));
//gcs.insert(0, GameController::create(this, 450));
//gcs.pushBack(GameController::create(this, 180));
scheduleUpdate();
auto listener = EventListenerPhysicsContact::create();
listener->onContactBegin = [this](PhysicsContact & contact)
{
this->unscheduleUpdate();
this->unschedule("test_key");
Director::getInstance()->replaceScene(GameOverScene::createScene(scoreCount));
return true;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = [this](Touch *touch , Event *event)
{
for (auto it = gcs.begin(); it != gcs.end();it++)
{
if ((*it)->hitTestPoint(touch->getLocation()))
{
(*it)->onUserTouch();
break;
}
}
return false;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener,this);
return true;
}
void HelloWorld::update(float dt)
{
for (auto it = gcs.begin(); it != gcs.end();it++)
{
(*it)->onUpdate(dt);
}
}
void HelloWorld::timeScore(float dt)
{
scoreCount++;
char tmp[10];
sprintf(tmp, "Score %d", scoreCount);
_labelSorce->setString(tmp);
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
<file_sep>#ifndef __NoOneDies_Block_H__
#define __NoOneDies_Block_H__
#include<iostream>
#include<cocos2d.h>
USING_NS_CC;
class Block :public Sprite
{
public:
virtual bool init();
virtual void update(float delta);
CREATE_FUNC(Block);
};
#endif // __NoOneDies_Block_H__<file_sep>#include "MyFlashTool.h"
#include <json/document.h>
Animate * MyFlashTool::readJsonSpriteSheet(std::string jsonFile, float delayPerUnit){
rapidjson::Document doc;
std::string fileContent = FileUtils::getInstance()->getStringFromFile(jsonFile);
fileContent.erase(0, fileContent.find_first_of('{'));
doc.Parse<0>(fileContent.c_str());
std::string imgFileName = doc["meta"]["image"].GetString();
auto &frames = doc["frames"];
auto sfc = SpriteFrameCache::getInstance();
Vector<AnimationFrame*> animFrames;
for (auto m = frames.MemberonBegin(); m != frames.MemberonEnd(); m++) {
auto frameName = m->name.GetString();
auto & frameProperties = m->value["frame"];
auto & spriteSourceSize = m->value["spriteSourceSize"];
auto sf = sfc->getSpriteFrameByName(frameName);
if (!sf) {
sf = SpriteFrame::create(imgFileName, Rect(frameProperties["x"].GetInt(), frameProperties["y"].GetInt(), frameProperties["w"].GetInt(), frameProperties["h"].GetInt()), m->value["rotated"].GetBool(), Vec2(spriteSourceSize["x"].GetInt(), spriteSourceSize["y"].GetInt()), Size(spriteSourceSize["w"].GetInt(), spriteSourceSize["h"].GetInt()));
sfc->addSpriteFrame(sf, frameName);
}
ValueMap vm;
animFrames.pushBack(AnimationFrame::create(sf, delayPerUnit, vm));
//animFrames.pushBack(AnimationFrame::create(sf, delayPerUnit, ValueMapNull));
}
return nullptr;
}
Animate * MyFlashTool::readPlistAnimate(std::string fileName, float delayPerUnit){
Vector<SpriteFrame*> arr;
for (int i = 1; i <= 6;i++)
{
std::string str = StringUtils::format("%s_Walk_0%d.png", fileName.c_str(), i);
auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str);
arr.pushBack(frame);
}
auto animation = Animation::createWithSpriteFrames(arr, delayPerUnit);
return Animate::create(animation);
}<file_sep># LCJNoOneDie
Just a test project of use cocos2d-x framework<file_sep>#include "GameController.h"
GameController* GameController::create(cocos2d::Layer *layer, float positionY,std::string fileName)
{
auto _ins = new GameController();
_ins->init(layer, positionY, fileName);
_ins->autorelease();
return _ins;
}
bool GameController::init(cocos2d::Layer *layer, float positionY, std::string fileName)
{
_layer = layer;
_positionY = positionY;
visibleSize = Director::getInstance()->getVisibleSize();
edge = Edge::create();
edge->setPosition(visibleSize.width / 2, visibleSize.height / 2+positionY);
edge->setContentSize(visibleSize);
layer->addChild(edge);
auto ground = Sprite::create();
ground->setTextureRect(Rect(0,0,visibleSize.width,3));
ground->setColor(Color3B::WHITE);
ground->setPosition(visibleSize.width/2,1.5+positionY);
layer->addChild(ground);
hero = Hero::create();
hero->setPosition(50, hero->getContentSize().height/2+positionY);
hero->setHeroSkin(fileName);
layer->addChild(hero);
resetFrames();
return true;
}
void GameController::addBlock()
{
auto b = Block::create();
_layer->addChild(b);
b->setPositionY(b->getContentSize().height/2+_positionY);
}
void GameController::onUpdate(float dt)
{
currentFrameIndex++;
if (currentFrameIndex>=nextFrameCount)
{
resetFrames();
addBlock();
}
}
void GameController::resetFrames()
{
currentFrameIndex = 0;
nextFrameCount = (rand()%120) + 100;
}
bool GameController::hitTestPoint(Vec2 point)
{
return edge->getBoundingBox().containsPoint(point);
}
void GameController::onUserTouch()
{
hero->getPhysicsBody()->setVelocity(Vec2(0,400));
}<file_sep>#include "AppDelegate.h"
#include "HelloWorldScene.h"
#include"GameMenuScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("My Game");
director->setOpenGLView(glview);
}
//glview->setDesignResolutionSize(480,800,ResolutionPolicy::SHOW_ALL);
//glview->setFrameSize(640,960);
Size frameSize = glview->getFrameSize();
log("frameSize.width : %f", frameSize.width);
log("frameSize height : %f", frameSize.height);
/*Size winSize = Size(640.0, 960.0);
float widthRate = frameSize.width / winSize.width;
float heightRate = frameSize.height / winSize.height;*/
glview->setDesignResolutionSize(640.0, 960.0, ResolutionPolicy::FIXED_HEIGHT); //设计分辨率大小及模式
//如果是if中的语句,说明逻辑的高度有点大了,就把逻辑的高缩小到和宽度一样的比率
//if (widthRate > heightRate)
//{
// log("winSize.height*heightRate / widthRate : %f ", winSize.height*heightRate / widthRate);
// glview->setDesignResolutionSize(winSize.width, winSize.height*heightRate / widthRate, ResolutionPolicy::NO_BORDER); //设计分辨率大小及模式
//}
//else
//{
// log("winSize.width*widthRate / heightRate : %f ", winSize.width*widthRate / heightRate);
// glview->setDesignResolutionSize(winSize.width*widthRate / heightRate, winSize.height, ResolutionPolicy::NO_BORDER); //设计分辨率大小及模式
//}
//glview->setFrameSize(1080,1920);
SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Ino.plist");
SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Sakura.plist");
SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Karin.plist");
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
auto scene = GameMenuScene::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
| e121e35904a22e1427884bdfbe0e98a56a8a4254 | [
"Markdown",
"C++"
] | 14 | C++ | linchangjian/LCJNoOneDie | 9aab3d24b188302178c0a6df0dcd3520cd6ebd06 | face7e6b56103b12a85093812a01ad215898f1de |
refs/heads/master | <repo_name>DziLean/savva3<file_sep>/requirements.txt
beautifulsoup4==4.6.3
Django==2.1.2
django-bootstrap-form==3.4
django-crispy-forms==1.7.2
django-embed-video
django-extensions==2.1.3
django-filter==2.0.0
django-markdown-filter==0.0.1
django-menu
graphene
graphene_django
django-meta
django-sitetree
Markdown
mdx_linkify
<file_sep>/events/views.py
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.core.serializers import serialize
from django.contrib import messages
from django.core.mail import mail_managers
from .models import Event
from .forms import InviteForm
from .models import Event
# Create your views here.
def invite(request):
success = False
if request.method == 'POST':
formset = InviteForm(request.POST)
if formset.is_valid():
formset.save()
messages.success(request, 'Ваше приглашение отправлено')
success = True
formset = None
# Вот тут надо сформировать письмо со всей информацией отправить менеджерам и Савватееву
mail_managers("Invite",'check admin')
else:
fromset = formset
context = {
'formset':formset,
'success':success
}
else:
formset = InviteForm
context = {
'formset': formset
}
return render(request, 'events/invite.html', context)
def archive(request):
events=Event.objects.all()
context={'events':events}
return render(request, 'events/archive.html', context)
def events(request):
# Переадресуем на вики
return redirect('https://wiki.savvateev.xyz/doku.php?id=лекции')
events=Event.future.all()
context={'events':events}
return render(request, 'events/events.html',context)
def event(request, event_id):
event=Event.objects.get(id=event_id)
context={
'event':event,
'meta':event.as_meta(),
}
return render(request, 'events/event.html', context)
<file_sep>/events/tests.py
from django.test import TestCase
from django.test import Client
from django.test.utils import override_settings
from django.conf import settings
from django.urls import reverse
from .models import Event
from django.utils import timezone
# Create your tests here.
class EventsTestCase(TestCase):
def setUp(self):
self.date=timezone.now()
a=Event()
a.title='test'
a.start = self.date
a.city = "Moscow"
a.save()
self.c=Client()
def test_where_and_when_method(self):
obj=Event.objects.first()
expect = "%s, %s" % (obj.city, obj.start.strftime('%d %B %Y %H:%M'))
self.assertEqual(obj.where_and_when(),expect)
def test_index(self):
r=self.c.get('/events/')
self.assertEqual(r.status_code,200)
def test_archive(self):
r=self.c.get('/events/archive/')
self.assertEqual(r.status_code,200)
def test_event(self):
obj = Event.objects.first()
url = reverse('events:event',args=[obj.id])
r=self.c.get(url)
self.assertEqual(r.status_code,200)
| 6a57a41eab172b0f322bfbf9c6edb56ba7ef355d | [
"Python",
"Text"
] | 3 | Text | DziLean/savva3 | abd2fc99e083487c7bca6d78aba368b26491e37c | 8b98ed13db7c853e6feae4a235df465b862ddff2 |
refs/heads/master | <repo_name>asaklex/TodoListing<file_sep>/TodoListing.Auth/TokenAuth/TokenAuthOptions.cs
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Text;
namespace TodoListing.Auth.TokenAuth
{
public class TokenAuthOptions : AuthenticationSchemeOptions
{
public const string DefaultScheme = "Token Auth";
public string[] AuthKeys { get; set; }
}
}
<file_sep>/TodoListing.DAL/TodoListingDbContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using TodoListing.DAL.Models;
namespace TodoListing.DAL
{
public class TodoListingDbContext:DbContext
{
public TodoListingDbContext(DbContextOptions<TodoListingDbContext> options) : base(options) { }
public DbSet<Todo> Todos { get; set; }
}
}
<file_sep>/TodoListing.Api/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TodoListing.Api.Middlewares;
using TodoListing.Auth;
using TodoListing.Auth.TokenAuth;
using TodoListing.DAL;
using TodoListing.Services.DataServices;
namespace TodoListing.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = TokenAuthOptions.DefaultScheme;
options.DefaultChallengeScheme = TokenAuthOptions.DefaultScheme;
})
.AddTokenAuth(options => {
var apikeys = Configuration.GetSection("ApiKeys")
.AsEnumerable()
.Where(x => !string.IsNullOrEmpty(x.Value))
.Select(x => x.Value)
.ToArray();
options.AuthKeys = apikeys;
});
//add Entity Framework
var connectionString = Configuration.GetConnectionString("TodoListingDbContext");
services.AddDbContext<TodoListingDbContext>(options => options.UseSqlServer(connectionString));
services.AddSingleton<ITodoDataServices, TodoDataServices>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseTodoException();
app.UseAuthentication();
app.UseMvc();
}
}
}
<file_sep>/README.md
# TodoListing
Simple Todo API
Todo API using .Net Core 2 / Entity Framework
This API uses custom Authentification Scheme using "ApiKey" header provided in request.
ApiKey is compared towards hardcoded values in appsettings.json.
All api keys can be found under "ApiKeys" section of appsettings.json.
Entity Framework is used for CRUD .
Update Connection String "TodoListingDbContext" in appsettings.config to use any SQL Database.
Then Run "update-database" from package manager console to create dataBase.
"ApiKey" header needs to be provided with one of the hardcoded values in order to authenticate with each API Request
<file_sep>/TodoListing.Services/DataServices/TodoDataServices.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using TodoListing.DAL;
using TodoListing.DAL.DTO;
using TodoListing.DAL.Models;
namespace TodoListing.Services.DataServices
{
public class TodoDataServices : ITodoDataServices
{
TodoListingDbContext _dbContext;
public TodoDataServices(TodoListingDbContext dbContext)
{
_dbContext = dbContext;
}
public Todo AddTodo(TodoDTO todoDto)
{
var todo = new Todo
{
Title = todoDto.Title,
Description = todoDto.Description
};
_dbContext.Todos.Add(todo);
_dbContext.SaveChanges();
return todo;
}
public Todo UpdateTodo(int id, TodoUpdateDTO todo)
{
var existing = _dbContext.Todos.Find(id);
if(existing != null)
{
if(!string.IsNullOrEmpty(todo.Description) && !todo.Description.Equals(existing.Description))
existing.Description = todo.Description;
if (!string.IsNullOrEmpty(todo.Title) && !todo.Title.Equals(existing.Title))
existing.Title = todo.Title;
_dbContext.Entry(existing).State = EntityState.Modified;
_dbContext.SaveChanges();
}
return existing;
}
public void RemoveTodo(int id)
{
var existing = _dbContext.Todos.Find(id);
if (existing != null)
{
_dbContext.Todos.Remove(existing);
_dbContext.SaveChanges();
}
}
}
}
<file_sep>/TodoListing.Api/Controllers/TodoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TodoListing.DAL;
using TodoListing.DAL.Models;
using TodoListing.Services.DataServices;
using TodoListing.Api.Filters;
using TodoListing.DAL.DTO;
namespace TodoListing.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TodoController : ControllerBase
{
private TodoListingDbContext _todoListingDbContext;
private ITodoDataServices _todoDataServices;
public TodoController(TodoListingDbContext todoListingDbContext, ITodoDataServices todoDataServices)
{
_todoListingDbContext = todoListingDbContext;
_todoDataServices = todoDataServices;
}
// GET: api/Todo
[HttpGet]
public IEnumerable<Todo> Get()
{
return _todoListingDbContext.Todos;
}
// GET: api/Todo/5
[HttpGet("{todoId}", Name = "Get")]
public Todo Get(int todoId)
{
return _todoListingDbContext.Todos.Find(todoId);
}
// POST: api/Todo
[HttpPost]
[ValidatorActionFilter]
public void Post([FromBody] TodoDTO todo)
{
_todoDataServices.AddTodo(todo);
}
// PUT: api/Todo/5
[HttpPut("{todoId}")]
public void Put(int todoId, [FromBody] TodoUpdateDTO todo)
{
_todoDataServices.UpdateTodo(todoId, todo);
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{todoId}")]
public void Delete(int todoId)
{
_todoDataServices.RemoveTodo(todoId);
}
}
}
<file_sep>/TodoListing.Services/DataServices/ITodoDataServices.cs
using System;
using System.Collections.Generic;
using System.Text;
using TodoListing.DAL.DTO;
using TodoListing.DAL.Models;
namespace TodoListing.Services.DataServices
{
public interface ITodoDataServices
{
Todo AddTodo(TodoDTO todo);
void RemoveTodo(int id);
Todo UpdateTodo(int id, TodoUpdateDTO todo);
}
}
<file_sep>/TodoListing.Api/Middlewares/MiddlewareExtensions.cs
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoListing.Api.Middlewares
{
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseTodoException(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TodoExceptionMiddleware>();
}
}
}
<file_sep>/TodoListing.Auth/AuthenticationBuilderExtensions.cs
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Text;
using TodoListing.Auth.TokenAuth;
namespace TodoListing.Auth
{
public static class AuthenticationBuilderExtensions
{
public static AuthenticationBuilder AddTokenAuth(this AuthenticationBuilder builder, Action<TokenAuthOptions> configureOptions)
{
// Add custom authentication scheme with custom options and custom handler
return builder.AddScheme<TokenAuthOptions, TokenAuthHandler>(TokenAuthOptions.DefaultScheme, configureOptions);
}
}
}
| 933679eda5ac89b769b9813ed0d6f872b2e91f3e | [
"Markdown",
"C#"
] | 9 | C# | asaklex/TodoListing | 1596ee9e447f70976ce15543f40fc8665e57bf52 | e3b0113d86ffc75a35157ca4a9726172313863be |
refs/heads/master | <file_sep>package com.google.buzz.parser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import com.google.buzz.exception.BuzzIOException;
import com.google.buzz.exception.BuzzParsingException;
import com.google.buzz.model.BuzzFeedEntry;
import com.google.buzz.parser.handler.FeedEntryHandler;
/**
* Parser for element: <b>feed entry<b/>.
*
* @author roberto.estivill
*/
public class BuzzFeedEntryParser {
/**
* Parse an xml string into a BuzzFeedEntry model object.
*
* @param xmlResponse
* to be parsed.
* @return a feed entry.
* @throws BuzzIOException
* if any IO error occurs.
* @throws BuzzParsingException
* if a parsing error occurs.
*/
public static BuzzFeedEntry parseFeedEntry(String xmlResponse) throws BuzzParsingException,
BuzzIOException {
FeedEntryHandler handler;
XMLReader xr;
try {
xr = XMLReaderFactory.createXMLReader();
handler = new FeedEntryHandler(xr);
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
xr.parse(new InputSource(new ByteArrayInputStream(xmlResponse.getBytes("UTF-8"))));
} catch (SAXException e) {
throw new BuzzParsingException(e);
} catch (IOException e) {
throw new BuzzIOException(e);
}
return handler.getBuzzFeedEntry();
}
}<file_sep>package com.google.buzz.model;
/**
* Model class to represent a Content
*
* @author roberto.estivill
*/
public class BuzzContent {
/**
* The content itself
*/
private String text;
/**
* The content type
*/
private String type;
/**
* @return the content
*/
public String getText() {
return text;
}
/**
* @param text
* the content to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type
* the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* Overwrite the default toString method
*
* @return the string representation of the object
*/
@Override
public String toString() {
return toString("\n");
}
/**
* Print the object in a pretty way.
*
* @param indent
* to print the attributes
* @return a formatted string representation of the object
*/
public String toString(String indent) {
StringBuilder sb = new StringBuilder();
String newIndent = indent + "\t";
sb.append(indent + "BuzzContent:");
sb.append(newIndent + "Text: " + text);
sb.append(newIndent + "Type: " + type);
return sb.toString();
}
}
<file_sep>package com.toby.btt;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;
import com.google.buzz.MyBuzz;
import com.google.buzz.model.BuzzFeed;
import com.google.buzz.model.BuzzFeedEntry;
import com.google.buzz.model.BuzzFeedEntryStorge;
import com.google.buzz.model.BuzzUser;
import com.toby.btt.storge.PMF;
import com.toby.buzz.BuzzClient;
/**
* 定时触发doGET方法,由GAE的corn负责定时执行,在WEB─INF/corn.xml中配置
* @author toby
*
*/
public class BuzzToTwitter extends HttpServlet {
private final Logger logger = Logger.getLogger(BuzzToTwitter.class
.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(BuzzUser.class);
//获取当前需自动同步的buzz user
List<BuzzUser> users = (List<BuzzUser>) query.execute();
if (users.size() > 0) {
for (BuzzUser buzzUser : users) {
String userId = buzzUser.getBuzzId().trim();
MyBuzz buzz = null;
BuzzFeed feed = null;
int tryTimes = 8;
//获取buzz user 的public post,由于目前api不完善,对于一些reshare类的post在google返回时有一定概率会导致xml
//解析报错,此处反复尝试8次,任何一次成功,流程继续
while (feed == null && tryTimes > 0) {
try {
buzz = new MyBuzz(userId);
feed = buzz.getPosts(BuzzFeed.Type.PUBLIC);
} catch (Exception e) {
tryTimes--;
buzz = null;
feed = null;
}
}
if (feed == null || feed.getEntries().isEmpty()) {
continue;
}
//获取user已经同步的post,GAE持久化
List<BuzzFeedEntryStorge> buzzFeedEntryStorges = BuzzClient
.getBuzzFeedEntryStorges(userId);
Date lastSyncTime = buzzFeedEntryStorges.get(0)
.getPostDate();
//根据用户提交的api key 建立twitter更新机器人
OAuthSignpostClient oauthClient = new OAuthSignpostClient(
buzzUser.getConsumerKey(), buzzUser
.getConsumerSecret(), buzzUser
.getAccessToken(), buzzUser
.getAccessTokenSecret());
Twitter jtwit = new Twitter(buzzUser.getTwitterId(),
oauthClient);
for (BuzzFeedEntry entry : feed.getEntries()) {
boolean isSynced = true;
//判断当前的post publish time是否在最后一条已经同步的post之后
if (entry.getPublished().after(lastSyncTime)) {
try {
//post时间晚于最后一次同步时间,需向twitter同步
jtwit.setStatus(entry.getTitle() + " source: "
+ entry.getSourceLink());
} catch (Exception e) {
//若twitter更新状态失败,则记录信息,留待下次同步在补充执行
isSynced = false;
e.printStackTrace();
logger.log(Level.SEVERE, "send twitter error",
e);
}
}
//将已经同步过的post持久化
BuzzClient.saveBuzzFeedEntryStorge(entry, isSynced,
userId);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>package com.google.buzz.oauth;
import java.net.URLConnection;
import java.net.URLEncoder;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import com.google.buzz.exception.BuzzAuthenticationException;
/**
* This class is intended to be use as a wrapper of OAuth library tasks, facilitating the execution
* of OAuth methods to the main Buzz class.
*
* @author roberto.estivill
*/
public class BuzzOAuth {
/**
* OAuth google endpoint to retrieve an access token
*/
public static final String GET_ACCESS_TOKEN_URL = "https://www.google.com/accounts/OAuthGetAccessToken";
/**
* OAuth google endpoint to retrieve an request token
*/
public static final String GET_REQUEST_TOKEN_URL = "https://www.google.com/accounts/OAuthGetRequestToken";
/**
* OAuth google endpoint to authorize the token
*/
public static final String AUTHORIZE_TOKEN_URL = "https://www.google.com/buzz/api/auth/OAuthAuthorizeToken";
/**
* The OAuth consumer ( Third party application )
*/
private DefaultOAuthConsumer consumer;
/**
* The OAuth provider ( Google ).
*/
private OAuthProvider provider;
/**
* This page is going to be used by the user to allow third parties applications access his/her
* Google Buzz information and activities.
*
* @param scope
* either BUZZ_SCOPE_READONLY or BUZZ_SCOPE_WRITE
* @param consumerKey
* to retrieve the request token
* @param consumerSecret
* to retrieve the request token
* @param callbackUrl
* the url google should redirect the user after a successful login
* @return the authentication url for the user to log in
*/
public String getAuthenticationUrl(String method, String scope, String consumerKey,
String consumerSecret, String callbackUrl) throws BuzzAuthenticationException {
String authUrl = null;
consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
try {
provider = new DefaultOAuthProvider(GET_REQUEST_TOKEN_URL + "?scope="
+ URLEncoder.encode(scope, "utf-8"), GET_ACCESS_TOKEN_URL, AUTHORIZE_TOKEN_URL
+ "?scope=" + URLEncoder.encode(scope, "utf-8") + "&domain=" + consumerKey);
authUrl = provider.retrieveRequestToken(consumer, callbackUrl);
} catch (Exception e) {
throw new BuzzAuthenticationException(e);
}
return authUrl;
}
/**
* Retrieves the access token that will be used to sign requests by the consumer.<br/>
*
* @param accessToken
* to sign requets
* @throws BuzzAuthenticationException
* if any OAuth error occurs
*/
public void setAccessToken(String accessToken) throws BuzzAuthenticationException {
try {
provider.retrieveAccessToken(consumer, accessToken);
} catch (Exception e) {
throw new BuzzAuthenticationException(e);
}
}
/**
* Sign the request to be send. <br/> <b>BuzzOAuth.setAccessToken</b> method should be called
* before this method.
*
* @param request
* to be signed with the access token
* @throws BuzzAuthenticationException
* if an OAuth problem occurs
*/
public void signRequest(URLConnection request) throws BuzzAuthenticationException {
try {
consumer.sign(request);
} catch (Exception e) {
throw new BuzzAuthenticationException(e);
}
}
} | 20a60d9a7ae0e41f51fb4b6bff6f381e9a63b3e2 | [
"Java"
] | 4 | Java | toby941/btt | 90b9e1e3c20762c45dcf98ce0b4e0aeb6e01a57b | 343f69aa9b2250314fd25fc557387dc7205b81bf |
refs/heads/master | <file_sep>// Begin Library
function box(el) {
return el.getBoundingClientRect();
}
function x(el) {
return box(el).left;
}
function y(el) {
return box(el).top;
}
function width(el) {
return box(el).width;
}
function height(el) {
return box(el).height;
}
function t(el) {
return box(el).top;
}
function b(el) {
return box(el).bottom;
}
function l(el) {
return box(el).left;
}
function r(el) {
return box(el).right;
}
function d(el) {
return document.getElementById(el);
}
outclicks = [];
function outclickpush(elem, func) {
outclicks.push([elem,func]);
}
document.addEventListener('click' ,function(e) {
var miss;
var tmp = [];
while(true) {
miss = outclicks.pop();
if(miss === undefined) break;
if(typeof miss == "object" && typeof miss[0] == "object" && typeof miss[1] == "function") {
if(ab(miss[i], e.target)) {
tmp.push(miss);
} else {
if(miss[1](e) === false) tmp.push(miss);
else break;
}
}
}
for(var i = 0; i<tmp.length; i++) {
outclicks.push(tmp[i]);
}
});
navigator.sayswho= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!== null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!== null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
navigator.browser= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!== null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
return M[1];
})();
function getTouchByID(e, id) {
for(var i=0; i<e.touches.length; i++) {
if(e.touches[i].identifier == id) return e.touches[i];
}
return null;
}
function ab(a, b, n) {
if(n === undefined) {
while(a.parentElement !== null) {
if(a==b) return true; else a = a.parentElement;
}
} else {
for(var i=0; i<n; i++) {
if(a.parentElement===null) break;
if(a==b) return true; else a = a.parentElement;
}
}
return false;
}
// End Library
// Begin EventListeners
window.addEventListener('load', function () {
//#icon-cont
d('icons-cont').addEventListener( 'wheel', function(e) {menuScroll(e.deltaY, true);});
window.addEventListener( 'resize', menuResize);
d('icons-cont').addEventListener( 'mousedown', function(e) {iconsDown(e.pageY, e.target);});
d('icons-cont').addEventListener( 'pointerdown', function(e) {iconsDown(e.pageY, e.target);});
d('icons-cont').addEventListener( 'touchstart', function(e) {iconsDown(e.targetTouches[0].pageY, e.targetTouches[0].target);iti=e.targetTouches[0].identifier;});
document.addEventListener( 'mousemove', function(e) {iconsMove(e.pageY);});
document.addEventListener( 'pointermove', function(e) {iconsMove(e.pageY);});
document.addEventListener( 'touchmove', function(e) {if(iconsD) {e.preventDefault();iconsMove(getTouchByID(e, iti).pageY);}});
document.addEventListener( 'mouseup', function() {iconsUp();});
document.addEventListener( 'pointerup', function() {iconsUp();});
document.addEventListener( 'touchend', function() {iconsUp();});
//#icon-menu
d('icon-menu').addEventListener( 'mousedown', function(e) {menuDown(e.pageX);});
d('icon-menu').addEventListener( 'pointerdown', function(e) {menuDown(e.pageX);});
d('icon-menu').addEventListener( 'touchstart', function(e) {menuDown(e.targetTouches[0].pageX);mti=e.targetTouches[0].identifier;});
document.addEventListener( 'mousemove', function(e) {menuMove(e.pageX);});
document.addEventListener( 'pointermove', function(e) {menuMove(e.pageX);});
document.addEventListener( 'touchmove', function(e) {if(menuD) {e.preventDefault();menuMove(getTouchByID(e, mti).pageX);}});
document.addEventListener( 'mouseup', function(e) {menuUp(e.target, false);});
document.addEventListener( 'pointerup', function(e) {menuUp(e.target, false);});
document.addEventListener( 'touchend', function(e) {menuUp(e.target, true);});
d('icon-menu').addEventListener( 'click', menuToggle);
d('icon-menu').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-menu'));});
d('icon-menu').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-menu'));});
d('icon-menu').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-menu'));});
//#icon-add
d('icon-add').addEventListener( 'click', iconAdd);
d('icon-add').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-add'));});
d('icon-add').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-add'));});
d('icon-add').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-add'));});
//#icon-search
d('icon-search').addEventListener( 'click', iconSearch);
d('icon-search').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-search'));});
d('icon-search').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-search'));});
d('icon-search').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-search'));});
//#icon-adjust
d('icon-adjust').addEventListener( 'click', iconAdjust);
d('icon-adjust').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-adjust'));});
d('icon-adjust').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-adjust'));});
d('icon-adjust').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-adjust'));});
//#icon-diff
d('icon-diff').addEventListener( 'click', iconDiff);
d('icon-diff').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-diff'));});
d('icon-diff').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-diff'));});
d('icon-diff').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-diff'));});
//#icon-account
d('icon-account').addEventListener( 'click', iconAccount);
d('icon-account').addEventListener( 'mouseenter', function(e) {tryTip(d('tip-icon-account'));});
d('icon-account').addEventListener( 'mouseleave', function(e) {stopTip(d('tip-icon-account'));});
d('icon-account').addEventListener( 'contextmenu', function(e) {ctxTip(e, d('tip-icon-account'));});
//#icon-settings
d('icon-settings').addEventListener('click', iconSettings);
d('icon-settings').addEventListener('mouseenter', function(e) {tryTip(d('tip-icon-settings'));});
d('icon-settings').addEventListener('mouseleave', function(e) {stopTip(d('tip-icon-settings'));});
d('icon-settings').addEventListener('contextmenu', function(e) {ctxTip(e, d('tip-icon-settings'));});
});
// End EventListeners
//#icon-menu
var mti;
var iti;
var toolx = 0, tooly = 0;
var tooltiptimeout;
var tooltimeout;
var i;
var b;
var irs;
var bls;
var s;
var ic;
var tool;
var cs;
var title;
window.addEventListener('load', function() {
i = d('icon-menu');
b = d('body');
irs = d('icons-right-shadow');
bls = d('body-left-shadow');
s = d('sidebar');
ic = d('icons-cont');
tool = d('tooltips');
cs = d('content-shade');
title = d('title');
});
var menuPos;
var menuD = false;
var menuS;
var menuM = false;
var rm = 70;
var sm = 0;
var iconsD = false;
var iconsPos;
function menuToggle() {
if(!menuM) {
if(s.className == 't') {
s.className = '';
b.className = '';
bls.className = 'i';
tool.style.transform = 'translate(' + (toolx = 0) + 'px, -' + tooly + 'px)';
cs.className = 'i';
irs.style.opacity = 1;
bls.style.opacity = 0;
title.style.transform = '';
} else {
s.className = 't';
b.className = 't';
bls.className = 'i t';
tool.style.transform = 'translate(' + (toolx = 281) + 'px, -' + tooly + 'px)';
irs.style.opacity = 0;
bls.style.opacity = 1;
cs.className = 'i s';
title.style.transform = 'translate(40px)';
}
}
menuM = false;
}
function menuDown(e) {
menuD = true;
menuPos = e;
rm = r(s);
menuS = rm;
}
function menuMove(e) {
if(menuD) {
// t = performance.now();
menuM = true;
document.body.className = 'g';
m = e-menuPos;
s.className = 'm';
b.className = 'm';
tool.className = 'i m';
cs.className = 'i m';
title.className = 'u m';
irs.className = 'i m';
bls.className = 'i m';
if(m+menuS>70) {
if(m+menuS<350) {
s.style.transform = 'translate(-' + (350 - m - menuS) + 'px)';
b.style.transform = 'translate(' + (m + menuS - 70)*6/7 + 'px)';
bls.style.transform = 'translate(' + (m + menuS - 70) + 'px)';
tool.style.transform = 'translate(' + (toolx = m + menuS - 70) + 'px, -' + tooly + 'px)';
cs.style.opacity = (m+menuS-70)/281*0.2;
title.style.transform = 'translate(' + (m + menuS - 70)/7 + 'px)';
if(m+menuS-70<140) {
irs.style.opacity = 1 - (m+menuS-70)/140;
bls.style.opacity = 0;
} else {
bls.style.opacity = (m+menuS-210)/140;
irs.style.opacity = 0;
}
rm = m + menuS;
} else {
s.className = 'm t';
s.style.transform = '';
b.className = 'm t';
b.style.transform = '';
bls.className = 'i m t';
bls.style.transform = '';
tool.style.transform = 'translate(' + (toolx = 281) + 'px, -' + tooly + 'px)';
irs.style.opacity = '0';
cs.style.opacity = '0.2';
cs.className = 'i m s';
title.style.transform = 'translate(40px)';
bls.style.opacity = '1';
rm = 351;
}
} else {
s.style.transform = '';
b.style.transform = '';
bls.style.transform = '';
tool.style.transform = 'translate(' + (toolx = 0) + 'px, -' + tooly + 'px)';
irs.style.opacity = '1';
cs.style.opacity = '';
title.style.transform = '';
bls.style.opacity = '0';
rm = 70;
}
// console.log('menuMove took ' + (performance.now()-t) + ' milliseconds to run');
}
}
function menuUp(e) {
if(menuM) {
document.body.className = '';
irs.className = 'i';
bls.className = 'i';
title.className = 'u';
tool.className = 'i';
title.style.className = '';
title.style.transform = '';
if(s.className == 'm') {
s.className = '';
b.className = '';
bls.className = 'i';
cs.className = 'i';
} else if(s.className == 'm t') {
s.className = 't';
b.className = 't';
bls.className = 'i t';
cs.className = 'i s';
title.style.transform = 'translate(40px)';
}
if(rm>=210) {
s.className = 't';
b.className = 't';
bls.className = 'i t';
tool.style.transform = 'translate(' + (toolx = 281) + 'px, -' + tooly + 'px)';
title.style.transform = 'translate(40px)';
} else tool.style.transform = 'translate(' + (toolx = 0) + 'px, -' + tooly + 'px)';
s.style.transform = '';
b.style.transform = '';
bls.style.transform = '';
}
cs.style.opacity = '';
if(s.className == 't') {
irs.style.opacity = 0;
cs.className = 'i s';
bls.style.opacity = 1;
} else {
irs.style.opacity = 1;
cs.className = 'i';
bls.style.opacity = 0;
}
menuD = false;
if(e !== i && menuM) {
menuM = false;
}
}
function menuScroll(d, b) {
if(ic.offsetHeight > icons.offsetHeight) {
// sm += e.deltaY * 16;
if(navigator.browser == 'Firefox' && b === true) {
sm += d * 16;
} else {
sm += d;
}
if(sm + icons.offsetHeight < ic.offsetHeight && sm > 0) {
ic.style.transform = 'translate(0,-' + sm + 'px)';
tool.style.transform = 'translate(' + toolx + 'px, -' + (tooly = sm) + 'px)';
} else if(sm + icons.offsetHeight >= ic.offsetHeight) {
sm = ic.offsetHeight - icons.offsetHeight;
ic.style.transform = 'translate(0,-' + sm + 'px)';
tool.style.transform = 'translate(' + toolx + 'px, -' + (tooly = sm) + 'px)';
} else if(sm < 0) {
ic.style.transform = '';
sm = 0;
tool.style.transform = 'translate(' + toolx + 'px, -' + (tooly = sm) + 'px)';
}
}
}
function menuResize() {
if(sm + icons.offsetHeight >= ic.offsetHeight) {
sm = ic.offsetHeight - icons.offsetHeight;
ic.style.marginTop = '-' + sm + 'px';
tool.style.transform = 'translate(' + toolx + 'px, -' + (tooly = sm) + 'px)';
}
if(sm < 0) {
ic.style.marginTop = '0';
sm = 0;
tool.style.transform = 'translate(' + toolx + 'px, -' + (tooly = sm) + 'px)';
}
}
function iconsDown(e, t) {
if(!ab(t, i, 2)) {
iconsD = true;
iconsPos = e;
}
}
function iconsMove(e) {
if(iconsD) {
document.body.className = 'g';
menuScroll(iconsPos-e, false);
iconsPos = e;
}
}
function iconsUp() {
document.body.className = '';
iconsD = false;
}
function tryTip(t) {
tooltiptimeout = setTimeout(function() {t.className = 'tip h';}, 1000);
}
function ctxTip(e, t) {
e.preventDefault();
t.className = 'tip h';
}
function stopTip(t) {
clearTimeout(tooltiptimeout);
t.className = 'tip';
}
//end #icon-menu
function iconAdd() {
}
function iconSearch() {
}
function iconAdjust() {
}
function iconDiff() {
}
function iconAccount() {
}
function iconSettings() {
}
//Begin Functions
//End Functions
| 63b3c47249d673af19c7d2b679a4c71ebeb10aa5 | [
"JavaScript"
] | 1 | JavaScript | dqsully/bb | d534459f68a1bdb5a37fa8fa024202be56dc7381 | 33aa3c0e27b8611f15016e01d226cb8c6858c4bc |
refs/heads/main | <repo_name>DryDragon10/PyChatbot<file_sep>/main.py
import discord
from discord.ext import commands
from prsaw import RandomStuff
api_key = str(input("Api key: "))
channel_id = int(input("Channel id: "))
bot_token = str(input("BOT token: "))
bot = commands.Bot(command_prefix="C")
rs = RandomStuff(async_mode=True, api_key = api_key)
def merge_dicts(l):
if len(l) == 1:
return l[0]
return {**l[0], **merge_dicts(l[1:])}
@bot.event
async def on_ready():
print("Chat BOT is online")
@bot.event
async def on_message(message):
if bot.user == message.author:
return
if message.channel.id ==channel_id:
r = await rs.get_ai_response(message.content)
response = merge_dicts(r)
await message.reply(response['message'])
await bot.process.commands(message)
bot.run(bot_token)
<file_sep>/README.md
# Note
Now the bot needs an api key to work
get ur api key from [here](https://api-info.pgamerx.com/register)
# Installation
[Video on how to set it up](https://youtu.be/owgf1KmZaPI)
OR Follow the steps bellow
#### clone the repo
$ git clone https://github.com/L-eviH-AckermanYT/PyChatbot
#### change the working directory to PyChatbot
$ cd Python-Chatbot
#### download the requirements
$ pip3 install -r requirements.txt
#### run the program
$ python3 main.py
| 9f28378be7b52c9f6d8f1549fef53f0520c521b9 | [
"Markdown",
"Python"
] | 2 | Python | DryDragon10/PyChatbot | f5f54cd5293f035ce72f83e27248a1fbb0a3b7f2 | 26e802c79e3deeab8dcb1d30b91a8c8d04918af1 |
refs/heads/master | <repo_name>kharindev/wdd<file_sep>/functions.php
<?php
function memegen_build_image( $args = array() ) {
list( $width, $height ) = getimagesize( $args['memebase'] );
$args['textsize'] = empty( $args['textsize'] ) ? round( $height/10 ) : $args['textsize'];
extract( $args );
$im = imagecreatefromjpeg( $args['memebase'] );
$black = imagecolorallocate( $im, 0, 0, 0 );
imagecolortransparent( $im, $black );
$textcolor = imagecolorallocate( $im, 255, 255, 255 );
$angle = 0;
$top_text = mb_strtoupper( trim( $args['top_text'] ) );
$bottom_text = mb_strtoupper( trim( $args['bottom_text'] ) );
$fit = isset( $textfit ) ? $textfit : true;
extract( memegen_font_size_guess( $textsize, ($width-$padding*2), $font, $top_text, $fit ) );
$from_side = ($width - $box_width)/2;
$from_top = $box_height + $padding;
memegen_imagettfstroketext( $im, $fontsize, $angle, $from_side, $from_top, $textcolor, $black, $font, $top_text, 1 );
extract( memegen_font_size_guess( $textsize, ($width-$padding*2), $font, $bottom_text, $fit ) );
$from_side = ($width - $box_width)/2;
$from_top = $height - $padding;
memegen_imagettfstroketext( $im, $fontsize, $angle, $from_side, $from_top, $textcolor, $black, $font, $bottom_text, 1 );
$basename = basename( $args['memebase'], '.jpg' );
header('Content-Type: image/jpeg');
header('Content-Disposition: filename="'. $basename .'-'. $filename .'.jpg"');
imagejpeg( $im );
imagedestroy( $im );
}
function memegen_font_size_guess( $fontsize, $imwidth, $font, $text, $fit ) {
$angle = 0;
$_box = imageftbbox( $fontsize, $angle, $font, $text );
$box_width = $_box[4] - $_box[6];
$box_height = $_box[3] - $_box[5];
if ( $box_width > $imwidth && $fit ) {
$sub = 1;
$fontsize = $fontsize - $sub;
return memegen_font_size_guess( $fontsize, $imwidth, $font, $text, $fit );
}
return compact( 'fontsize', 'box_width', 'box_height' );
}
function memegen_imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
$bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}
function memegen_sanitize( $input ) {
$input = preg_replace( '/[^a-zA-Z0-9-_]/', '-', $input );
$input = preg_replace( '/--*/', '-', $input );
return $input;
}
<file_sep>/index.php
<?php
require_once( 'functions.php' );
$top_text = isset( $_GET['top_text'] ) ? $_GET['top_text'] : 'напиши';
$bottom_text = isset( $_GET['bottom_text'] ) ? $_GET['bottom_text'] : 'текст';
$url = isset( $_GET['url'] ) ? $_GET['url'] : 'https://pp.userapi.com/c637126/v637126216/399ad/mXrcczefp-k.jpg';
$filename = memegen_sanitize( $bottom_text ? $bottom_text : $top_text );
// setup args for image
$args = array(
'top_text' => $top_text,
'bottom_text' => $bottom_text,
'filename' => $filename,
'font' => dirname(__FILE__) .'/font.ttf',
'memebase' => $url,
'textsize' => 40,
'textfit' => true,
'padding' => 10,
);
// create and output image
memegen_build_image( $args );
| 3c3a09b3f464bf780802db7db397e7fa9186b85e | [
"PHP"
] | 2 | PHP | kharindev/wdd | 10e44da1635c8e77fc33b528fe5b555141c5cd69 | 56e17e19ea361942aabada6dcdd08a3741bf9ca1 |
refs/heads/master | <repo_name>woutdp/stream-viewer<file_sep>/requirements.txt
alembic==1.0.0
certifi==2018.8.24
chardet==3.0.4
click==6.7
Flask==1.0.2
Flask-Migrate==2.2.1
git+https://github.com/mitsuhiko/flask-oauth
Flask-Script==2.0.6
Flask-SQLAlchemy==2.3.2
gunicorn==19.9.0
httplib2==0.11.3
idna==2.7
itsdangerous==0.24
Jinja2==2.10
Mako==1.0.7
MarkupSafe==1.0
oauth2==1.9.0.post1
psycopg2==2.7.5
python-dateutil==2.7.3
python-editor==1.0.3
python-engineio==2.2.0
python-socketio==2.0.0
requests==2.19.1
six==1.11.0
SQLAlchemy==1.2.11
urllib3==1.23
Werkzeug==0.14.1<file_sep>/src/app.py
import os
import requests
from dateutil.parser import parse
from flask import Flask, render_template, redirect, url_for, session, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_oauth import OAuth
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.constants import SECRET_KEY, DATABASE_URL, SCOPE, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, API_KEY
from src.utils import get_or_create, get_messages, get_stream
app = Flask(__name__)
app.secret_key = SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
db = SQLAlchemy(app)
DbSession = sessionmaker(bind=create_engine(DATABASE_URL))
# Import after creation of app and db
from src.models import Message, User, Stream
google = OAuth().remote_app(
'google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={
'scope': SCOPE,
'response_type': 'code'
},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET
)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/authenticate/')
def login():
return google.authorize(callback=url_for('authorized', _external=True))
@app.route('/oauth2callback')
@google.authorized_handler
def authorized(response):
session['access_token'] = response['access_token']
return redirect(url_for('index'))
@app.route('/api/google_api_key/')
def google_api_key():
return jsonify({'key': API_KEY})
@app.route('/api/access_token/')
def access_token():
access_token = session.get('access_token', None)
if access_token is None:
return jsonify({})
return jsonify({'access_token': access_token})
@app.route('/api/create_messages/', methods=['POST'])
def create_messages():
stream_id = request.get_json()['streamId']
stream = get_stream(stream_id)
messages = get_messages(stream['items'][0]['liveStreamingDetails']['activeLiveChatId'])
db_session = DbSession()
stream = get_or_create(
db_session,
Stream,
identifier=stream_id,
name=stream['items'][0]['snippet']['channelTitle']
)
for message in messages:
user = get_or_create(
db_session, User,
username=message['authorDetails']['displayName'],
identifier=message['authorDetails']['channelId']
)
message = get_or_create(
db_session,
Message,
identifier=message['id'],
content=message['snippet']['displayMessage'],
timestamp=parse(message['snippet']['publishedAt']),
user_id=user.id,
stream_id=stream.id
)
return jsonify(messages)
@app.route('/api/messages/<stream_id>')
def messages(stream_id):
db_session = DbSession()
stream = db_session.query(Stream).filter_by(identifier=stream_id).first()
messages = db_session.query(Message).filter_by(stream_id=stream.id)
return jsonify([
{**message.as_dict(),
**message.user.as_dict()} for message in messages
])
@app.route('/api/streams/')
def streams():
streams = DbSession().query(Stream).all()
return jsonify([
{**stream.as_dict(),
'message_count': len(stream.messages)} for stream in streams
])
if __name__ == '__main__':
app.run()
<file_sep>/src/constants.py
from os import environ
GOOGLE_CLIENT_ID = environ.get('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = environ.get('GOOGLE_CLIENT_SECRET')
SECRET_KEY = environ.get('SECRET_KEY')
API_KEY = environ.get('API_KEY')
DATABASE_URL = environ.get('DATABASE_URL', default='sqlite:///app.db')
SCOPE = 'https://www.googleapis.com/auth/userinfo.profile ' \
'https://www.googleapis.com/auth/youtube.readonly'<file_sep>/src/models.py
from sqlalchemy import ForeignKey, DateTime, Column, String, Integer
from sqlalchemy.orm import relationship
from src.manage import db, app
class Message(db.Model):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
identifier = Column(String(256), unique=True)
content = Column(String(512))
timestamp = Column(DateTime, nullable=False)
user_id = Column(Integer, ForeignKey('users.id'))
stream_id = Column(Integer, ForeignKey('streams.id'))
user = relationship('User', back_populates='messages')
stream = relationship('Stream', back_populates='messages')
def __repr__(self):
return f'<Message by {self.user} - {self.timestamp}: {self.content}>'
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
identifier = Column(String(256), unique=True)
username = Column(String(128))
messages = relationship('Message', back_populates='user')
def __repr__(self):
return f'<User: {self.username}>'
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Stream(db.Model):
__tablename__ = 'streams'
id = Column(Integer, primary_key=True)
identifier = Column(String(256), unique=True)
name = Column(String(128))
messages = relationship('Message', back_populates='stream')
def __repr__(self):
return f'<Stream: {self.name}>'
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
<file_sep>/src/utils.py
import requests
from src.constants import API_KEY
def get_or_create(session, model, **kwargs):
"""
Get or create a database model. If it already exists, simply returns it.
"""
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
else:
instance = model(**kwargs)
session.add(instance)
session.commit()
return instance
def get_stream(stream_id):
"""
Requests info about a certain stream.
"""
return requests.get(
'https://www.googleapis.com/youtube/v3/videos',
params={
'part': 'snippet,liveStreamingDetails',
'id': stream_id,
'key': API_KEY
}
).json()
def get_messages(chat_id):
"""
Requests the last 200 messages of a chat.
"""
return requests.get(
'https://www.googleapis.com/youtube/v3/liveChat/messages',
params={
'liveChatId': chat_id,
'part': 'snippet,authorDetails',
'key': API_KEY
}
).json()['items']
<file_sep>/README.md
# Stream viewer
Single Page Application to view a list of active Youtube livestreams + watch them + interact with chat.
Has Google OAuth authentication to interact with the chat.
Built in about 15 hours spread over 2 weeks, including configuring Heroku, setting up dev environment, etc.
## Demo
https://streamviewer-streamlabs.herokuapp.com/
## Technologies used
- Backend: Python/Flask
- Frontend: Vue using single file components. Using webpack for the frontend compilation. Using bootstrap for quick styling.
- Deployment: Heroku.
## Design choices
All design decisions were made with a 8 hour time constraint in mind.
Because of this I've had to cut away every piece of overhead I could think of.
For the backend I debated making it in Django but decided to go with Flask instead.
I'm more comfortable with Django, but Django provides a lot of overhead that I didn't need.
Flask is perfect for this because it's so lightweight. Really happy with this choice in the end.
Bootstrap for styling was an easy choice, didn't want to spend too much time on this and bootstrap gives you something ok to look at really quickly.
Vue for the frontend. This was a straigthforward choice for me. I've got some, but very little experience with Vue/React/Angular and I love the way Vue handles things.
Also knew about Vue's Single File Components and I really like the concept.
Didn't have experience with it yet though, but decided it was the right choice for this project.
Implemented the Google Authentication on the backend. I simply provide the google access token to the frontend by an API call.
Decided to do it this way instead of the frontend since I'm more comfortable with Python and the Flask backend compared to Javascript and Vue.
Given the time constraint, this seemed like the right approach.
To fill the stats page, every time someone visits a livestream, the last 200 messages of that stream get stored in the database.
This is a pretty naive solution but it gets the job done. A better solution would be to work with websockets and feed the chat to the frontend through that.
Then store every message that gets sent/received in the database. This would have involved a bit more time to set it up so I didn't go for this approach.
For my database I have 3 basic models:
- User
- primary key
- identifier (identifier for external service, in this case google)
- username
- Stream
- primary key
- identifier (identifier for external service, in this case google)
- name
- Message
- primary key
- identifier (identifier for external service, in this case google)
- content
- timestamp
- foreign key to User
- foreign key to Stream
All fields and relations are defined in the `models.py` file.
## Extra things I would like to have added with more time
- Remove some of the code duplication. The Stats and StatsStream Vue view share some code, I think the table could be made into a single component. This would clean it up a bit
- Dockerize the app for easier development and deployment.
- Better UX on the frontend. For example when you first log in, you're redirected back to the log in page which is very user unfriendly.
- Add unit tests for Python and Vue.
| 5aa6ff221e586da9e2536a63519586537887f28f | [
"Markdown",
"Python",
"Text"
] | 6 | Text | woutdp/stream-viewer | 558db168b84b6ab687e1337781245bfa5c0b15b7 | d0dbf460f60ec012d5698f3b24aea8b4dfb0a7cf |
refs/heads/master | <repo_name>rahul151993/servlet_jsp_practice<file_sep>/first/src/com/servlet/practice/MyServlet2.java
package com.servlet.practice;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServlet2
*/
public class MyServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(request.getParameter("name")+" you are able to login successfully");
out.println("The Common application specific Data is as following");
Enumeration<String> e1 = getServletConfig().getServletContext().getInitParameterNames();
while(e1.hasMoreElements()) {
String applicationSpecificKey = e1.nextElement();
out.println("servletcontext key = "+applicationSpecificKey+" value = "+getServletConfig().getServletContext().getInitParameter(applicationSpecificKey));
}
out.println("the key = "+getServletConfig().getServletContext().getAttribute("delta"));
request.getRequestDispatcher("/googlesearch.jsp").include(request,response);
}
}
<file_sep>/loginappwithdatabase/src/com/context/listener/MyContextListener.java
package com.context.listener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements ServletContextListener{
public static Connection con = null;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
try {
Statement st = con.createStatement();
if(st.execute("DROP TABLE login")) {
System.out.println("Dropped table successfully");
}
con.close();
System.out.println("Connection is closed successfully");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practice","root","root");
System.out.println("Connection Successful");
Statement st = con.createStatement();
st.execute("create table login(id int auto_increment, name varchar(20) not null, password varchar(20) not null,primary key(id))");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/loginapp/src/com/login/app/Profile.java
package com.login.app;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Profile
*/
//@WebServlet("/Profile")
public class Profile extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if(session.getAttribute("userName")!=null) {
request.getRequestDispatcher("profile.jsp").include(request,response);
out.println("This is Profile Page");
}
else {
request.getRequestDispatcher("welcome.jsp").include(request, response);
out.println("Please Log in first");
}
}
}
<file_sep>/loginappwithdatabase/src/com/loginapp/service/RegisterUserService.java
package com.loginapp.service;
import com.loginapp.model.User;
public interface RegisterUserService {
public boolean addUser(User user);
}
<file_sep>/loginappwithdatabase/src/com/loginapp/serviceimpl/RegistrationUserServiceImpl.java
package com.loginapp.serviceimpl;
import com.loginapp.dao.RegisterUserDao;
import com.loginapp.model.User;
import com.loginapp.service.RegisterUserService;
public class RegistrationUserServiceImpl implements RegisterUserService{
@Override
public boolean addUser(User user) {
RegisterUserDao dao = new RegisterUserDao();
return dao.addUser(user);
}
}
<file_sep>/first/src/com/servlet/practice/MyServlet.java
package com.servlet.practice;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String uName = request.getParameter("name");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
Enumeration<String> e = getServletConfig().getInitParameterNames();
while(e.hasMoreElements()) {
String key = e.nextElement();
out.println("The name is = "+key);
out.println("The Valus is = "+getServletConfig().getInitParameter(key));
}
out.println("The Common application specific Data is as following");
Enumeration<String> e1 = getServletConfig().getServletContext().getInitParameterNames();
while(e1.hasMoreElements()) {
String applicationSpecificKey = e1.nextElement();
out.println("servletcontext key = "+applicationSpecificKey+" value = "+getServletConfig().getServletContext().getInitParameter(applicationSpecificKey));
}
getServletConfig().getServletContext().setAttribute("delta", "charlie");
if(password.equals("<PASSWORD>")) {
request.getRequestDispatcher("./MS2").forward(request, response);
}
else {
out.println("<div>");
out.println("<p>"+"Wrong Password"+"</p>");
out.println("</div>");
request.getRequestDispatcher("/index.jsp").include(request, response);
}
}
}
| 55c406b6cc57a5e0533a1ec246c70b78f87f7d2c | [
"Java"
] | 6 | Java | rahul151993/servlet_jsp_practice | 6159002eed68bc74f5429b3f421a4815f13184e9 | 85794271e00f6ed6abec5085fdb03b5c3ab33323 |
refs/heads/main | <file_sep>var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var ParkModel = require('./parkSchema');
const db = 'mongodb+srv://READER:<EMAIL>/national-parks?retryWrites=true&w=majority';
mongoose.Promise = global.Promise;
mongoose.connect(db, {useNewUrlParser: true, useUnifiedTopology: true}, function(error){
if(error){
console.log("Error! " + error);
}
});
router.get('/national-parks', (req, res) => {
ParkModel.find((err, data) => {
if(err){
console.log(err);
}else{
res.send(data);
}
});
});
module.exports = router;<file_sep># National Parks Api
an api that can deliver data about national parks in supported countries.
## Contents
- Technologies
- Features
## Technologies
- Node.js
- Express.js
- MongoDB
## Features
The currently has 3 endpoints,
- all parks in the database
- all parks in country depending on iso_a2 code
- an autocomplete route
returned fields include:
- a unique id
- location data
- country
- iso_a2
- latitiude
- longitude
- annotation data
- park name
- native name
- counties / region
- area in km^2
- area in m^2
- when the park was officially formed
- sources of the data
## Supported Countries
- United Kingdom / GB
- Ireland / IE
- France / FR
- New Zealand / NZ
HEROKU LINK - https://nationalparks-api.herokuapp.com/
| bb7667e4fb940428dfdefb810ea126724791d6ca | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | LOglieve/national_parks_api | 13d0537bf5c2549a96a6b18349e09aad7f292ffd | 27bdbd75ce56fc33e39e9918d852aa57d6b4b6a5 |
refs/heads/master | <file_sep>package id.untad.projectdeteksidiniresikokehamilan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import id.untad.projectdeteksidiniresikokehamilan.Adapter.RecyclerViewAdapter;
import id.untad.projectdeteksidiniresikokehamilan.Database.DeteksiHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizContract;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizDbHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.RegisterHelper;
import id.untad.projectdeteksidiniresikokehamilan.Model.Deteksi;
import id.untad.projectdeteksidiniresikokehamilan.Model.Question;
import id.untad.projectdeteksidiniresikokehamilan.Model.Register;
import id.untad.projectdeteksidiniresikokehamilan.R;
import static android.widget.LinearLayout.VERTICAL;
public class ProfileActivity extends AppCompatActivity {
private QuizDbHelper dbHelper;
private RegisterHelper reghelp;
private ImageButton back, update;
private TextView namaibu, Tanggallahir,umur, agama, pekerjaanibu, pendidikanibu, golongandarah, alamat, namasuami,pekerjaansuami, pendidikansuami, nohpibu, nohpsuami;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dbHelper = new QuizDbHelper(getBaseContext());
update = findViewById(R.id.update);
back = findViewById(R.id.back);
namaibu = findViewById(R.id.nama);
Tanggallahir = findViewById(R.id.tanggallahir);
umur = findViewById(R.id.umur);
agama = findViewById(R.id.agama);
pekerjaanibu = findViewById(R.id.pekerjaanIbu);
pendidikanibu = findViewById(R.id.PendidikanIbu);
golongandarah = findViewById(R.id.golonganDarah);
alamat = findViewById(R.id.alamat);
namasuami = findViewById(R.id.namaSuami);
pekerjaansuami = findViewById(R.id.pekerjaanSuami);
pendidikansuami = findViewById(R.id.pendidikanSuami);
nohpibu = findViewById(R.id.noHpIbu);
nohpsuami = findViewById(R.id.noHpSuami);
reghelp = new RegisterHelper(getBaseContext());
RegisterHelper dbHelper = new RegisterHelper(this);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent Intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(Intent);
}
});
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Register person = new Register();
person.setNama_ibu(namaibu.getText().toString());
person.setTanggal_lahir(Tanggallahir.getText().toString());
person.setUmur(umur.getText().toString());
person.setAgama(agama.getText().toString());
person.setPekerjaan_ibu(pekerjaanibu.getText().toString());
person.setPendidikan_ibu(pendidikanibu.getText().toString());
person.setGolongan_darah(golongandarah.getText().toString());
person.setAlamat(alamat.getText().toString());
person.setNama_suami(namasuami.getText().toString());
person.setPekerjaan_suami(pekerjaansuami.getText().toString());
person.setPendidikan_suami(pendidikansuami.getText().toString());
person.setNo_hp_ibu(nohpibu.getText().toString());
person.setNo_hp_suami(nohpsuami.getText().toString());
// SQLiteDatabase ReadData = reghelp.getReadableDatabase();
// ReadData.execSQL("DROP TABLE IF EXISTS " + QuizContract.Register.TABLE_NAME);
Intent moveWithObjectIntent = new Intent(ProfileActivity.this, UpdateProfile.class);
moveWithObjectIntent.putExtra(UpdateProfile.EXTRA_PERSON, person);
startActivity(moveWithObjectIntent);
}
});
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("select * from register where _id='"+1+"'",null, null);
// String s1 = c.getString(2);
c.moveToPosition(0);
String itemname = c.getString(c.getColumnIndex("nama_ibu"));
namaibu.setText(itemname);
String tanggallahir= c.getString(c.getColumnIndex("tanggal_lahir"));
Tanggallahir.setText(tanggallahir);
String Umur = c.getString(c.getColumnIndex("umur"));
umur.setText(Umur);
String Agama = c.getString(c.getColumnIndex("agama"));
agama.setText(Agama);
String PekerjaanIbu = c.getString(c.getColumnIndex("pekerjaan_ibu"));
pekerjaanibu.setText(PekerjaanIbu);
String PendidikanIbu = c.getString(c.getColumnIndex("pendidikan_ibu"));
pendidikanibu.setText(PendidikanIbu);
String GolonganDarah = c.getString(c.getColumnIndex("golongan_darah"));
golongandarah.setText(GolonganDarah);
String Alamat = c.getString(c.getColumnIndex("alamat"));
alamat.setText(Alamat);
String NamaSuami = c.getString(c.getColumnIndex("nama_suami"));
namasuami.setText(NamaSuami);
String PekerjaanSuami = c.getString(c.getColumnIndex("pekerjaan_suami"));
pekerjaansuami.setText(PekerjaanSuami);
String PendidikanSuami = c.getString(c.getColumnIndex("pendidikan_suami"));
pendidikansuami.setText(PendidikanSuami);
String NoHpIbu = c.getString(c.getColumnIndex("no_hp_ibu"));
nohpibu.setText(NoHpIbu);
String NoHpSuami = c.getString(c.getColumnIndex("no_hp_suami"));
nohpsuami.setText(NoHpSuami);
c.close();
}
@Override
public void onBackPressed() {
Intent Intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(Intent);
}
}<file_sep>package id.untad.projectdeteksidiniresikokehamilan.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import id.untad.projectdeteksidiniresikokehamilan.Model.Question;
public class CrossHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyAwesomeQuiz.db";
private static final int DATABASE_VERSION = 4;
private SQLiteDatabase db;
public CrossHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuizContract.QuestionsTable.TABLE_NAME + " ( " +
QuizContract.QuestionsTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QuizContract.QuestionsTable.COLUMN_QUESTION + " TEXT, " +
QuizContract.QuestionsTable.COLUMN_OPTION1 + " TEXT, " +
QuizContract.QuestionsTable.COLUMN_OPTION2 + " TEXT, " +
QuizContract.QuestionsTable.COLUMN_ANSWER_NR + " INTEGER" +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillQuestionsTable();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + QuizContract.QuestionsTable.TABLE_NAME);
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.setVersion(oldVersion);
}
private void fillQuestionsTable() {
Question q1 = new Question("Apakah Anda Hamil Terlalu Muda ( <=16 tahun ) ?", "YA", "TIDAK", 4);
addQuestion(q1);
Question q2 = new Question("Apakah Anda Terlalu lambat hamil I, kawin >= 4 th ", "YA", "TIDAK", 4);
addQuestion(q2);
Question q3 = new Question("Terlalu tua, hamil I >= 35 th", "YA", "TIDAK", 4);
addQuestion(q3);
Question q4 = new Question("Terlalu cepat hamil lagi (<= 2 th)", "YA", "TIDAK", 4);
addQuestion(q4);
Question q5 = new Question("Apakah Anda Terlalu lama hamil lagi (>= 10 th)", "YA", "TIDAK", 4);
addQuestion(q5);
Question q6 = new Question("Apakah Anda Memiliki Anak Lebih Dari 4 ?", "YA", "TIDAK", 4);
addQuestion(q6);
Question q7 = new Question("Apakah Umur Anda Lebih Dari 35 Tahun ?", "YA", "TIDAK", 4);
addQuestion(q7);
Question q8 = new Question("Apakah Tinggi Badan Anda Kurang dari 145cm ?", "YA", "TIDAK", 4);
addQuestion(q8);
Question q9 = new Question("Apakah Anda Pernah Mengalami Kegagalan Kehamilan ?", "YA", "TIDAK", 4);
addQuestion(q9);
Question q10 = new Question("Apakah Anda Pernah Melahirkan Dengan Tarikan Tang/Vakum ?", "YA", "TIDAK", 4);
addQuestion(q10);
Question q11 = new Question("Apakah Anda pernah melahirkan dengan Uri Dirogoh ?", "YA", "TIDAK", 4);
addQuestion(q11);
Question q12 = new Question("Apakah Anda Pernah Melahirkan dengan Diberi Infus/Transfusi Darah ?", "YA", "TIDAK", 4);
addQuestion(q12);
Question q13 = new Question("Apakah Anda Pernah Melahirkan Melalui Operasi Sesar ?", "YA", "TIDAK", 8);
addQuestion(q13);
Question q14 = new Question("Apakah Anda Punya Penyakit Kurang Darah ?", "YA", "TIDAK", 4);
addQuestion(q14);
Question q15 = new Question("Apakah Anda Punya Penyakit TBC Paru ?", "YA", "TIDAK", 4);
addQuestion(q15);
Question q16 = new Question("Apakah Anda Punya Penyakit Jantung Lemah ?", "YA", "TIDAK", 4);
addQuestion(q16);
Question q17 = new Question("Apakah Anda Punya Penyakit Kencing Manis / Diabetes ?", "YA", "TIDAK", 4);
addQuestion(q17);
Question q18 = new Question("Apakah Anda Punya Penyakit Menular Seksual ?", "YA", "TIDAK", 4);
addQuestion(q18);
Question q19 = new Question("Apakah Anda Bengkak pada Muka/Tungkai dan Tekanan Darah Tinggi ?", "YA", "TIDAK", 4);
addQuestion(q19);
Question q20 = new Question("Apakah Anda Hamil Kembar 2 Atau Lebih ?", "YA", "TIDAK", 4);
addQuestion(q20);
Question q21 = new Question("Apakah Anda Hamil Kembar Air (Hydraminon) ?", "YA", "TIDAK", 4);
addQuestion(q21);
Question q22 = new Question("Apakah Anda Pernah Mengalami Bayi Mati dalam Kandungan ?", "YA", "TIDAK", 4);
addQuestion(q22);
Question q23 = new Question("Apakah Kehamilan Anda Kelebihan Bulan ?", "YA", "TIDAK", 4);
addQuestion(q23);
Question q24 = new Question("Apakah Letak Bayi Anda Sungsang ?", "YA", "TIDAK", 8);
addQuestion(q24);
Question q25 = new Question("Apakah Letak Bayi Anda Lintang ?", "YA", "TIDAK", 8);
addQuestion(q25);
Question q26 = new Question("Apakah Anda Pernah Mengalami Pendarahan Pada Kehamilan Ini ?", "YA", "TIDAK", 8);
addQuestion(q26);
Question q27 = new Question("Apakah Anda Pre-eklampsia berat/kejang-kejang ?", "YA", "TIDAK", 8);
addQuestion(q27);
}
private void addQuestion(Question question) {
ContentValues cv = new ContentValues();
cv.put(QuizContract.QuestionsTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuizContract.QuestionsTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuizContract.QuestionsTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuizContract.QuestionsTable.COLUMN_ANSWER_NR, question.getAnswerNr());
db.insert(QuizContract.QuestionsTable.TABLE_NAME, null, cv);
}
public List<Question> getAllQuestions() {
List<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + QuizContract.QuestionsTable.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuizContract.QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuizContract.QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuizContract.QuestionsTable.COLUMN_OPTION2)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuizContract.QuestionsTable.COLUMN_ANSWER_NR)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
return questionList;
}
}
<file_sep>package id.untad.projectdeteksidiniresikokehamilan;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizContract;
import id.untad.projectdeteksidiniresikokehamilan.Database.RegisterHelper;
public class HalamanRegisterAwal extends AppCompatActivity implements DatePickerFragment.DialogDateListener {
public static final String EXTRA_DATE = "extra_date";
public static final String SHARED_DATE = "sharedDate";
public static final String KEYA_DATE = "keyDate";
public static final String EXTRA_MONTH = "extra_month";
public static final String SHARED_MONTH = "sharedmonth";
public static final String KEY_MONTH = "keymonth";
public static final String EXTRA_YEAR = "extra_year";
public static final String SHARED_YEAR = "sharedYear";
public static final String KEY_YEAR = "keyyear";
public static final String EXTRA_NAMA = "extraScore";
final String DATE_PICKER_TAG1 = "DatePicker1";
final String DATE_PICKER_TAG2 = "DatePicker2";
private EditText nama_ibu, tanggal_lahir, umur, alamat, nama_suami, no_hp_ibu, no_hp_suami, perkiraan_hamil;
private String SETNAMAIBU, SETTANGGALLAHIR, SETUMUR, SETAGAMA, SETPEKERJAANIBU, SETPENDIDIKANIBU, SETGOLONGANDARAH, SETALAMAT, SETNAMASUAMI, SETPEKERJAANSUAMI, SETPENDIDIKANSUAMI, SETNOHPIBU, SETNOHPSUAMI, SETEMAIL;
private Spinner agama, pekerjaan_ibu, pendidikan_ibu, golongan_darah, pekerjaan_suami, pendidikan_suami;
private RegisterHelper reghelp;
private Button btnsimpan;
private TextView vb;
private boolean bol;
private int register = 400;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_halaman_register_awal);
nama_ibu = findViewById(R.id.edt_namaibuupdate);
tanggal_lahir = findViewById(R.id.edt_tanggal_lahir_update);
umur = findViewById(R.id.edt_umur_update);
agama = findViewById(R.id.spin_agama_update);
tanggal_lahir = findViewById(R.id.edt_tanggal_lahir_update);
pekerjaan_ibu = findViewById(R.id.spin_pekerjaan_ibu_update);
pendidikan_ibu = findViewById(R.id.spin_pendidikan_ibu_update);
golongan_darah = findViewById(R.id.spin_golongan_darah_update);
alamat = findViewById(R.id.edt_alamat_update);
nama_suami = findViewById(R.id.edt_nama_suami_update);
pekerjaan_suami = findViewById(R.id.spin_pekerjaan_suami_update);
pendidikan_suami = findViewById(R.id.spin_pendidikan_suami_update);
no_hp_ibu = findViewById(R.id.edt_no_hp_ibu_update);
no_hp_suami = findViewById(R.id.edt_no_hp_suami_upadte);
reghelp = new RegisterHelper(getBaseContext());
btnsimpan = findViewById(R.id.btn_submit_update);
RegisterHelper dbHelper = new RegisterHelper(this);
bol = dbHelper.check();
// dbHelper.getAllQuestions();
tanggal_lahir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.show(getSupportFragmentManager(), DATE_PICKER_TAG1);
}
});
btnsimpan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (nama_ibu.getText().toString().length() == 0) {
nama_ibu.setError("Mohon Di Isi");
} else if (tanggal_lahir.getText().toString().length() == 0) {
tanggal_lahir.setError("Mohon Di Isi");
} else if (umur.getText().toString().length() == 0) {
umur.setError("Mohon Di Isi");
} else if (alamat.getText().toString().length() == 0) {
alamat.setError("Mohon Di Isi");
} else if (nama_suami.getText().toString().length() == 0) {
nama_suami.setError("Mohon Di Isi");
} else if (no_hp_ibu.getText().toString().length() == 0) {
no_hp_ibu.setError("Mohon Di Isi");
} else if (no_hp_suami.getText().toString().length() == 0) {
no_hp_suami.setError("Mohon Di Isi");
} else {
setData();
saveData();
}
}
});
}
private void setData() {
SETNAMAIBU = nama_ibu.getText().toString();
SETTANGGALLAHIR = tanggal_lahir.getText().toString();
SETUMUR = umur.getText().toString();
SETAGAMA = agama.getSelectedItem().toString();
SETPEKERJAANIBU = pekerjaan_ibu.getSelectedItem().toString();
SETPENDIDIKANIBU = pendidikan_ibu.getSelectedItem().toString();
SETGOLONGANDARAH = golongan_darah.getSelectedItem().toString();
SETALAMAT = alamat.getText().toString();
SETNAMASUAMI = nama_suami.getText().toString();
SETPEKERJAANSUAMI = pekerjaan_suami.getSelectedItem().toString();
SETPENDIDIKANSUAMI = pendidikan_suami.getSelectedItem().toString();
SETNOHPIBU = no_hp_ibu.getText().toString();
SETNOHPSUAMI = no_hp_suami.getText().toString();
}
//Berisi Statement-Statement Untuk Menyimpan Data Pada Database
private void saveData() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder
.setTitle("Apakah Data Yang Anda Masukkan Sudah Benar ?")
.setIcon(R.mipmap.ic_launcher)
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Mendapatkan Repository dengan Mode Menulis
SQLiteDatabase create = reghelp.getWritableDatabase();
//Membuat Map Baru, Yang Berisi Nama Kolom dan Data Yang Ingin Dimasukan
ContentValues values = new ContentValues();
values.put(QuizContract.Register.NAMA_IBU, SETNAMAIBU);
values.put(QuizContract.Register.TANGGAL_LAHIR, SETTANGGALLAHIR);
values.put(QuizContract.Register.UMUR, SETUMUR);
values.put(QuizContract.Register.AGAMA, SETAGAMA);
values.put(QuizContract.Register.PEKERJAAN_IBU, SETPEKERJAANIBU);
values.put(QuizContract.Register.PENDIDIKAN_IBU, SETPENDIDIKANIBU);
values.put(QuizContract.Register.GOLONGAN_DARAH, SETGOLONGANDARAH);
values.put(QuizContract.Register.ALAMAT, SETALAMAT);
values.put(QuizContract.Register.NAMA_SUAMI, SETNAMASUAMI);
values.put(QuizContract.Register.PEKERJAAN_SUAMI, SETPEKERJAANSUAMI);
values.put(QuizContract.Register.PENDIDIKAN_SUAMI, SETPENDIDIKANSUAMI);
values.put(QuizContract.Register.NO_HP_IBU, SETNOHPIBU);
values.put(QuizContract.Register.NO_HP_SUAMI, SETNOHPSUAMI);
values.put(QuizContract.Register.EMAIL, SETEMAIL);
//Menambahkan Baris Baru, Berupa Data Yang Sudah Diinputkan pada Kolom didalam Database
create.insert(QuizContract.Register.TABLE_NAME, null, values);
Intent resultIntent = new Intent();
resultIntent.putExtra(EXTRA_NAMA, register);
setResult(RESULT_OK, resultIntent);
Toast.makeText(HalamanRegisterAwal.this, "Data Telah Tersimpan", Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// membuat alert dialog dari builder
AlertDialog alertDialog = alertDialogBuilder.create();
// menampilkan alert dialog
alertDialog.show();
}
@SuppressLint("SetTextI18n")
@Override
public void onDialogDateSet(String tag, int year, int month, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd - MM - yyyy", Locale.getDefault());
tanggal_lahir.setText(dateFormat.format(calendar.getTime()));
tanggal_lahir.setFocusable(false);
//Set Tanggal Lahir
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DATE, dayOfMonth);
thatDay.set(Calendar.MONTH, month); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, year);
//Menghitung Umur
Calendar today = Calendar.getInstance();
long diff = (today.get(Calendar.YEAR)) - (thatDay.get(Calendar.YEAR));
String yearString = Long.toString(diff);
umur.setText(yearString + " Tahun");
}
}
<file_sep>package id.untad.projectdeteksidiniresikokehamilan.Model;
import android.os.Parcel;
import android.os.Parcelable;
public class Deteksi {
private String pertanyaan;
private String jawaban;
public Deteksi() {
}
public Deteksi(String pertanyaan, String jawaban) {
this.pertanyaan = pertanyaan;
this.jawaban = jawaban;
}
public String getPertanyaan() {
return pertanyaan;
}
public void setPertanyaan(String pertanyaan) {
this.pertanyaan = pertanyaan;
}
public String getJawaban() {
return jawaban;
}
public void setJawaban(String jawaban) {
this.jawaban = jawaban;
}
}<file_sep>package id.untad.projectdeteksidiniresikokehamilan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import id.untad.projectdeteksidiniresikokehamilan.Adapter.RecyclerViewAdapter;
import id.untad.projectdeteksidiniresikokehamilan.Database.CrossHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.DeteksiHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizContract;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizDbHelper;
import id.untad.projectdeteksidiniresikokehamilan.Model.Deteksi;
import id.untad.projectdeteksidiniresikokehamilan.Model.Question;
public class CrossCheck extends AppCompatActivity {
public static final String EXTRA_DETECT = "extra_detect";
public static final String SHARED_PREFS = "sharedPrefs";
public static final String KEY_HIGHSCORE = "keyHighscore";
private CrossHelper detek;
private Button simpan, batal;
private int get=0;
private int get1=0;
private RecyclerViewAdapter adapter;
private ArrayList<Deteksi> dataList;
private TextView tvKonfirmasi;
private List<Question> questionList;
private int questionCountTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cross_check);
dataList = new ArrayList<>();
detek = new CrossHelper(getBaseContext());
simpan = findViewById(R.id.buttonsimpan);
batal = findViewById(R.id.buttonbatal);
tvKonfirmasi = findViewById(R.id.tvkonfirmasi);
RecyclerView recyclerView = findViewById(R.id.rv_note);
QuizDbHelper dbHelper = new QuizDbHelper(this);
questionList = dbHelper.getAllQuestions();
questionCountTotal = questionList.size();
getData();
//Menggunakan Layout Manager, Dan Membuat List Secara Vertical
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(dataList);
//Memasang Adapter pada RecyclerView
recyclerView.setAdapter(adapter);
//Membuat Underline pada Setiap Item Didalam List
DividerItemDecoration itemDecoration = new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL);
itemDecoration.setDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.line));
recyclerView.addItemDecoration(itemDecoration);
get = getIntent().getIntExtra(EXTRA_DETECT, 0);
updateHighscore(get);
simpan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Hapus();
}
});
batal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Batal();
}
});
}
private void updateHighscore(int HighscoreNew) {
get = HighscoreNew;
get1 = ((get * questionCountTotal)/100);
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(KEY_HIGHSCORE, get1);
editor.apply();
}
protected void Hapus(){
//Mengambil Repository dengan Mode Membaca
SQLiteDatabase ReadData = detek.getReadableDatabase();
ReadData.execSQL("DROP TABLE IF EXISTS " + QuizContract.Deteksi.TABLE_NAME);
Toast.makeText(this, "Jawaban Anda Telah Tersimpan", Toast.LENGTH_SHORT).show();
Intent moveWithDataIntent = new Intent(CrossCheck.this, MainActivity.class);
moveWithDataIntent.putExtra(MainActivity.EXTRA_DETECT_MAIN, get);
startActivity(moveWithDataIntent);
//cursor.moveToFirst();//Memulai Cursor pada Posisi Awal
//Melooping Sesuai Dengan Jumlan Data (Count) pada cursor
}
protected void Batal(){
//Mengambil Repository dengan Mode Membaca
Toast.makeText(this, "Jawaban Anda Telah Dibatalkan", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(CrossCheck.this, MainActivity.class);
startActivity(intent);
//cursor.moveToFirst();//Memulai Cursor pada Posisi Awal
//Melooping Sesuai Dengan Jumlan Data (Count) pada cursor
}
//Berisi Statement-Statement Untuk Mengambi Data dari Database
@SuppressLint("Recycle")
protected void getData(){
//Mengambil Repository dengan Mode Membaca
SQLiteDatabase ReadData = detek.getReadableDatabase();
Cursor cursor = ReadData.rawQuery("SELECT * FROM "+ QuizContract.Deteksi.TABLE_NAME,null);
cursor.moveToFirst();//Memulai Cursor pada Posisi Awal
//Melooping Sesuai Dengan Jumlan Data (Count) pada cursor
for(int count=0; count < cursor.getCount(); count++){
cursor.moveToPosition(count);//Berpindah Posisi dari no index 0 hingga no index terakhir
//Memasukan semua data dari variable NIM, Nama dan Jurusan ke parameter Class DataFiter
dataList.add(new Deteksi(cursor.getString(1), cursor.getString(2)));
}
}
}<file_sep>package id.untad.projectdeteksidiniresikokehamilan;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.DataInput;
import java.util.List;
import id.untad.projectdeteksidiniresikokehamilan.Database.DeteksiHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizContract;
import id.untad.projectdeteksidiniresikokehamilan.Database.QuizDbHelper;
import id.untad.projectdeteksidiniresikokehamilan.Database.RegisterHelper;
import id.untad.projectdeteksidiniresikokehamilan.Model.Deteksi;
import id.untad.projectdeteksidiniresikokehamilan.Model.Question;
public class TambahDeteksiActivity extends AppCompatActivity {
public static final String EXTRA_SCORE = "extraScore";
private String SETPERTANYAAN, SETJAWABAN;
private static final int REQUEST_CODE_CROSS= 1;
private TextView textViewQuestion;
private TextView textViewScore, set;
private TextView textViewQuestionCount;
private RadioGroup rbGroup;
private RadioButton rb1;
private RadioButton rb2;
private ImageView imbak;
private Button buttonConfirmNext;
private DeteksiHelper detekhelp;
private ColorStateList textColorDefaultRb;
private List<Question> questionList;
private int questionCounter;
private int questionCountTotal;
private Question currentQuestion;
private int score = 2;
private String tes = "D";
private boolean answered, bol;
private long backPressedTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah_deteksi);
set = findViewById(R.id.set);
textViewQuestion = findViewById(R.id.text_view_question);
textViewScore = findViewById(R.id.text_view_score);
textViewQuestionCount = findViewById(R.id.text_view_question_count);
rbGroup = findViewById(R.id.radio_group);
rb1 = findViewById(R.id.radio_button1);
rb2 = findViewById(R.id.radio_button2);
imbak = findViewById(R.id.imback);
buttonConfirmNext = findViewById(R.id.button_confirm_next);
textColorDefaultRb = rb1.getTextColors();
QuizDbHelper dbHelper = new QuizDbHelper(this);
questionList = dbHelper.getAllQuestions();
questionCountTotal = questionList.size();
detekhelp = new DeteksiHelper(getBaseContext());
DeteksiHelper detekhelpk = new DeteksiHelper(this);
bol = detekhelpk.check();
//Collections.shuffle(questionList);
showNextQuestion();
buttonConfirmNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!answered) {
if (rb1.isChecked() || rb2.isChecked()) {
checkAnswer();
}
} else {
showNextQuestion();
}
}
});
imbak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent Intent = new Intent(TambahDeteksiActivity.this, MainActivity.class);
startActivity(Intent);
}
});
}
private void showNextQuestion() {
rb1.setTextColor(textColorDefaultRb);
rb2.setTextColor(textColorDefaultRb);
rbGroup.clearCheck();
if (questionCounter < questionCountTotal) {
currentQuestion = questionList.get(questionCounter);
textViewQuestion.setText(currentQuestion.getQuestion());
rb1.setText(currentQuestion.getOption1());
rb2.setText(currentQuestion.getOption2());
questionCounter++;
textViewQuestionCount.setText("Question: " + questionCounter + "/" + questionCountTotal);
answered = false;
//buttonConfirmNext.setText("Confirm");
} else {
finishQuiz();
}
}
private void checkAnswer() {
answered = true;
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int answerNr = rbGroup.indexOfChild(rbSelected) + 1;
if (answerNr == 1) {
score = (int) (score + currentQuestion.getAnswerNr());
textViewScore.setText("Score: " + score);
tes = "YA";
showNextQuestion();
setData();
saveData();
} else if (answerNr == 2) {
//score = (int) -currentQuestion.getAnswerNr();
//textViewScore.setText("Score: " + score);
tes = "TIDAK";
showNextQuestion();
setData();
saveData();
}
}
private void finishQuiz() {
Intent moveWithDataIntent = new Intent(TambahDeteksiActivity.this, CrossCheck.class);
moveWithDataIntent.putExtra(CrossCheck.EXTRA_DETECT, score );
startActivity(moveWithDataIntent);
}
private void setData() {
SETPERTANYAAN = textViewQuestion.getText().toString();
SETJAWABAN = tes;
}
private void saveData() {
SQLiteDatabase create = detekhelp.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(QuizContract.Deteksi.PERTANYAAN, SETPERTANYAAN);
values.put(QuizContract.Deteksi.JAWABAN, SETJAWABAN);
create.insert(QuizContract.Deteksi.TABLE_NAME, null, values);
}
protected void DeleteDeteksi() {
SQLiteDatabase ReadData = detekhelp.getReadableDatabase();
ReadData.execSQL("DROP TABLE IF EXISTS " + QuizContract.Deteksi.TABLE_NAME);
Intent Intent = new Intent(TambahDeteksiActivity.this, MainActivity.class);
startActivity(Intent);
}
protected void DeleteQuiz() {
SQLiteDatabase ReadData = detekhelp.getReadableDatabase();
ReadData.execSQL("DROP TABLE IF EXISTS " + QuizContract.QuestionsTable.TABLE_NAME);
}
@Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
DeleteDeteksi();
// DeleteQuiz();
// finishQuiz();
} else {
Toast.makeText(this, "Press back again to finish", Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
}<file_sep>package id.untad.projectdeteksidiniresikokehamilan.Database;
import android.provider.BaseColumns;
public final class QuizContract {
private QuizContract() {
}
public static class QuestionsTable implements BaseColumns {
public static final String TABLE_NAME = "quiz_questions";
public static final String COLUMN_QUESTION = "question";
public static final String COLUMN_OPTION1 = "option1";
public static final String COLUMN_OPTION2 = "option2";
public static final String COLUMN_ANSWER_NR = "answer_nr";
}
public static class Register implements BaseColumns {
public static final String TABLE_NAME = "register";
public static final String NAMA_IBU = "nama_ibu";
public static final String TANGGAL_LAHIR = "tanggal_lahir";
public static final String UMUR = "umur";
public static final String AGAMA = "agama";
public static final String PEKERJAAN_IBU = "pekerjaan_ibu";
public static final String PENDIDIKAN_IBU = "pendidikan_ibu";
public static final String GOLONGAN_DARAH = "golongan_darah";
public static final String ALAMAT = "alamat";
public static final String NAMA_SUAMI = "nama_suami";
public static final String PEKERJAAN_SUAMI = "pekerjaan_suami";
public static final String PENDIDIKAN_SUAMI = "pendidikan_suami";
public static final String NO_HP_IBU = "no_hp_ibu";
public static final String NO_HP_SUAMI = "no_hp_suami";
public static final String EMAIL = "email";
}
public static class Deteksi implements BaseColumns {
public static final String TABLE_NAME = "deteksi";
public static final String PERTANYAAN = "pertanyaan";
public static final String JAWABAN = "jawaban";
}
}
| 8d555ee86d4e046abb4d91c70444f923a8709b75 | [
"Java"
] | 7 | Java | adyatma-project/EDPROffline | 87efca6d2b6fd9586a4daffc4ef7b0d2ee22686c | 14c3f59323c4013fd71052a93a5dff780cc5d9cc |
refs/heads/master | <file_sep>import { getModelForClass, prop } from '@typegoose/typegoose';
export class User {
@prop({ required: 'Name is required!' })
name: string;
@prop({ required: 'Email is required!' })
email: string;
@prop({ required: 'Password is required!' })
password: string;
}
export const UserModel = getModelForClass(User, {
schemaOptions: { timestamps: true },
});
<file_sep>import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
export const toErrorMap = (
errors: { field: string; message: string }[]
): Record<string, string> => {
const errorMap: Record<string, string> = {};
errors.forEach(({ field, message }) => {
errorMap[field] = message;
});
return errorMap;
};
export const useAuth = () => {
const history = useHistory();
useEffect(() => {
const token = sessionStorage.getItem('cc_token');
if (!token) history.push('/login');
}, [history]);
};
export const setAccessToken = (token: string) => {
sessionStorage.setItem('cc_token', token);
};
export const getAccessToken = () => {
return sessionStorage.getItem('cc_token');
};
<file_sep>// Env
import cookieParser from 'cookie-parser';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import { createServer } from 'http';
import { verify } from 'jsonwebtoken';
import mongoose from 'mongoose';
import { Server } from 'socket.io';
import { logger } from './middleware';
import { MessageModel, UserModel } from './models';
import { chatRoomsRoute } from './routes/chatRooms.route';
import { userRouter } from './routes/users.route';
import { Socket } from './types';
dotenv.config();
const port = process.env.PORT ? parseInt(process.env.PORT) : 5000;
const app = express();
// Express middleware
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(logger);
app.use(
cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true,
})
);
// Routers
app.use('/users', userRouter);
app.use('/chats', chatRoomsRoute);
const http = createServer(app);
http.listen(port, async () => {
console.log(`Server is listening on ${process.env.HOST_URL}:${port}`);
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('Connected to MongoDB!');
});
const io = new Server(http, {
cors: {
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
},
});
io.use((socket: Socket, next: any) => {
const token = socket.handshake.query.token as string;
try {
const payload = verify(token, process.env.JWT_SECRET) as { id: string };
socket.payload = payload;
return next();
} catch (e) {
console.log('unauth');
}
});
io.on('connection', (socket: Socket) => {
if (socket.payload?.id) {
console.log('Connected: ' + socket.payload?.id);
socket.on('joinRoom', ({ id }) => {
socket.join(id);
console.log('A user joined chatroom: ' + id);
});
socket.on('leaveRoom', ({ id }) => {
socket.leave(id);
console.log('A user left chatroom: ' + id);
});
socket.on(
'newChatRoomMessage',
async ({
chatRoomId,
message,
}: {
message: string;
chatRoomId: string;
}) => {
if (message.trim()) {
const user = await UserModel.findById(socket.payload?.id);
const newMessage = await MessageModel.create({
chatRoomId,
message,
userId: user?._id,
});
if (user)
io.to(chatRoomId).emit('newMessage', {
_id: newMessage._id,
chatRoomId: newMessage.chatRoomId,
message: newMessage.message,
user,
});
console.log('emitted: ' + message);
}
}
);
socket.on('disconnect', () => {
console.log('Disconnected: ' + socket.payload?.id);
});
}
});
<file_sep>import { getModelForClass, mongoose, prop, Ref } from '@typegoose/typegoose';
import { ChatRoom } from '../ChatRoom';
import { User } from '../User';
export class Message {
@prop({ required: 'Chat room id is required', type: mongoose.Types.ObjectId })
chatRoomId: Ref<ChatRoom>;
@prop({ required: 'User id is required', type: mongoose.Types.ObjectId })
userId: Ref<User>;
@prop({ required: 'Name is required!' })
message: string;
}
export const MessageModel = getModelForClass(Message, {
schemaOptions: { timestamps: true },
});
| 6515e223e41e5a8b322ace4c48f81cfd908a6b9c | [
"TypeScript"
] | 4 | TypeScript | Knat-Dev/mern-socketio-chat | 98be57cf272c4b6f92644535b3218702da454fd3 | 2d476331d992256d61c27cb9804c8c212e053823 |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
export const QuizScoreView = ({score, totalQuestions}) =>
<div className="quiz-score-view">
<h3>Congratulations!</h3>
<p>You got {score} correct out of {totalQuestions}</p>
</div>
;
QuizScoreView.propTypes = {
score: PropTypes.number.isRequired,
totalQuestions: PropTypes.number.isRequired,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './QuizQuestionsView.css';
export const QuizQuestionsView = ({
answer,
choices,
handleChoiceClick,
question,
questionId,
userAnswers,
showAnswers,
totalQuestions
}) =>
<div className="QuizQuestionsView">
<div className="quiz-question">
<span>{questionId + 1} / {totalQuestions}</span>
<h3>{question}</h3>
</div>
<div className="quiz-choices">
{choices.map((choice, index) =>
<div
className={`quiz-choice ${index === userAnswers.get(questionId) ? 'checked' : ''} ${index === answer ? 'right-answer' : ''}`}
key={`q${questionId}-i${index}`}
>
<label>
<input
type="radio"
value={index}
name={`q${questionId}-choice`}
defaultChecked={index === userAnswers.get(questionId)}
disabled={showAnswers}
onClick={() => handleChoiceClick(questionId, index)}
/>
{choice}
</label>
</div>
)}
</div>
</div>
;
QuizQuestionsView.propTypes = {
answer: PropTypes.number,
choices: PropTypes.array.isRequired,
handleChoiceClick: PropTypes.func.isRequired,
questionId: PropTypes.number.isRequired,
question: PropTypes.string.isRequired,
userAnswers: PropTypes.object.isRequired,
showAnswers: PropTypes.bool,
totalQuestions: PropTypes.number.isRequired
};
<file_sep>export function handleSubmitClick() {
return () => {
this.setState({
quizState: 'end'
});
this.setScore();
};
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './QuizProgress.css';
export const QuizProgress = ({
quizState,
questionId,
totalQuestions
}) =>
(quizState === 'progress' || quizState === 'check') &&
<div className="QuizProgress">
<div style={{width: `${((questionId + 1) / totalQuestions) * 100}%`}}></div>
</div>
;
QuizProgress.propTypes = {
quizState: PropTypes.string.isRequired,
questionId: PropTypes.number.isRequired,
totalQuestions: PropTypes.number.isRequired
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './QuizTitle.css';
export const QuizTitle = ({ content }) =>
<h2 className="QuizTitle">{content}</h2>;
QuizTitle.propTypes = {
content: PropTypes.string.isRequired
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
export const QuizStartView = ({ intro }) =>
<div className="quiz-start-view">
<p>{intro}</p>
</div>
;
QuizStartView.propTypes = {
intro: PropTypes.string.isRequired
};
<file_sep>export function handleBackClick(quizData) {
return () => {
this.setState(prevState => {
if (this.state.questionId !== 0) {
const questionId = prevState.questionId - 1;
let nextState = {
questionId,
question: quizData.questions[questionId].question,
choices: quizData.questions[questionId].choices
};
if (this.state.quizState === 'check') {
nextState = Object.assign(nextState, { answer: quizData.questions[questionId].answer })
}
return nextState;
}
});
this.setQuestionState();
};
}
<file_sep>export function handleStartClick() {
return () => {
this.setState({
quizState: 'progress',
});
this.setQuestionState();
};
}
<file_sep># Quiz Structure
## Components
### Static Components
- Quiz Title
### Dynamic Components
- Quiz Progress
- Quiz Content
- Start Page
- Questions Page
- Question
- Choices
- Score Page
- Quiz Nav
## States
### For Quiz Content Component
- Begin
- Start Page
- Progress
- Questions Page
- End
- Score Page
- CheckAnswers
- Questions Page: Choices disabled
### For Quiz Nav Component
- Begin
- Start Btn
- Progress
- First Question
- Next Btn Only
- Other Questions
- Back Btn
- Next Btn
- Last Questions
- Back Btn
- Submit Btn
- Warn => if Answers.length != Questions.length
- End
- Check Answers Btn
- CheckAnswers
- Back Btn
- Next Btn
<file_sep># vquiz
A quiz generation utility using reactjs.
## Demo
<https://vquiz.netlify.com/>
## Features
### App
- Quiz Title
- Start-page:
- Intro to the Quiz
- In questions page:
- The progress of the quiz is indicated using a progress bar.
- Current question's number and total number of questions are displayed.
- Question and choices for its answer are displayed.
- Navigation to previous and next questions is provided.
- In the score page,
- Total number of correct answers of the user is shown.
- A link to check the user's answers against the correct answers is be provided.
### Development
- The file `src/data/quiz-data.js` can be used to customize following parameters of the quiz:
1. Title
2. Intro
3. Questions
4. Choices for each question (as an Array)
5. Correct answer for each question (as the index of the correct answer in the Choices Array)
- All questions can only be in multiple-choice format where only one choice can be opted as answer.
- Answers (opted choices) can be reviewed before submitting the quiz.
- Upon the submition of the quiz:
- A score page will be shown and
- A link to check the user's answers against the correct answers will be provided.
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './QuizNav.css';
export const QuizNav = ({
handleBackClick,
handleCheckClick,
handleStartClick,
handleExitClick,
handleNextClick,
handleSubmitClick,
questionState,
quizState
}) => {
const start = <button onClick={handleStartClick} className="align-center">Start</button>;
const back = <button onClick={handleBackClick} className="align-left">⇦ Back</button>;
const next = <button onClick={handleNextClick} className="align-right">Next ⇨</button>;
const submit = <button onClick={handleSubmitClick} className="align-right">Submit</button>;
const check = <button onClick={handleCheckClick} className="align-center">Check Answers</button>;
const exit = <button onClick={handleExitClick} className="align-right">Exit</button>;
return (
<div className="QuizNav">
{ quizState === 'begin' && start}
{ ['progress', 'check'].includes(quizState) && questionState !== 'first' && back }
{ ['progress', 'check'].includes(quizState) && questionState !== 'last' && next }
{ quizState === 'progress' && questionState === 'last' && submit }
{ quizState === 'check' && questionState === 'last' && exit }
{ quizState === 'end' && check}
</div>
);
};
QuizNav.propTypes = {
quizState: PropTypes.string.isRequired,
questionState: PropTypes.string.isRequired,
handleStartClick: PropTypes.func.isRequired,
handleBackClick: PropTypes.func.isRequired,
handleNextClick: PropTypes.func.isRequired,
handleSubmitClick: PropTypes.func.isRequired,
handleCheckClick: PropTypes.func.isRequired,
handleExitClick: PropTypes.func.isRequired,
};
<file_sep>export const quizData = {
title: 'On Sandhi\'s in Sanskrit',
intro: 'This is a quiz on Sandhi\'s in Sanskrit',
questions: [
{
question: 'Which of these contain only मृदुव्यञ्जनs?',
choices: ['सीतारामः', 'कल्याणरामः', 'बलरामः', 'परशुरामः'],
answer: 2
},
{
question: '"एचोऽयवायावः" is the पाणिणिसूत्र for which सन्धि?',
choices: ['यण्-सन्धिः', 'यान्तावान्तादेश-सन्धिः', 'श्चुत्व-सन्धिः', 'अनुनासिक-सन्धिः'],
answer: 1
},
{
question: 'Which of the words missing "अवग्रह-चिह्न"?',
choices: ['रामोपि', 'गैर्वाणि', 'ष्टुत्वसन्धिः', 'रामायणम्'],
answer: 0
},
{
question: 'What is the सन्धि in the word "पुरुषोत्तमः"?',
choices: ['वृद्धि-सन्धिः', 'गुण-सन्धिः', 'सवर्णदीर्घ-सन्धिः', 'यण्-सन्धिः'],
answer: 1
},
{
question: 'What is लोपः?',
choices: ['वर्णाणां आगमनम्', 'वर्णाणां आदेशम्', 'वर्णाणां विक्षेपणम्', 'वर्णाणां अदर्शनम्'],
answer: 3
},
{
question: 'What is an अव्यय?',
choices: [
'That which does not change in vibhakti, vachana, linga, etc.',
'That which does change in vibhakti, vachana, linga, etc.',
'That which has no vibhakti, vachana, linga, etc.',
'That which is not destroyed.'
],
answer: 0
},
{
question: 'Which of these is not a "हल्-सन्धि"?',
choices: ['अनुनासिक-सन्धिः', 'जश्त्व-सन्धिः', 'वृद्धि-सन्धिः', 'अव्ययीभाव-सन्धिः'],
answer: 2
},
{
question: 'How can the word "भवनम्" be split under proper सन्धि rules?',
choices: ['भू + अनम्', 'भो + अनम्', 'भौ + अनम्', 'भव् + अनम्'],
answer: 2
}
]
};
<file_sep>export function handleChoiceClick() {
return (questionId, choiceId) => {
this.setState(prevState => ({
answers: prevState.userAnswers.set(questionId, choiceId)
}));
};
}
<file_sep>import React from 'react';
import './index.css';
import './App.css';
import { quizData } from './data/quiz-data';
import { QuizTitle } from './components/QuizTitle';
import { QuizProgress } from './components/QuizProgress';
import { QuizContent } from './components/QuizContent';
import { QuizNav } from './components/QuizNav';
import { handleStartClick } from './actions/handleStartClick';
import { handleBackClick } from './actions/handleBackClick';
import { handleNextClick } from './actions/handleNextClick';
import { handleSubmitClick } from './actions/handleSubmitClick';
import { handleCheckClick } from './actions/handleCheckClick';
import { handleChoiceClick } from './actions/handleChoiceClick';
import { handleExitClick } from './actions/handleExitClick';
const totalQuestions = quizData.questions.length;
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
answer: -1,
choices: quizData.questions[0].choices,
question: quizData.questions[0].question,
questionId: 0,
questionState: '',
quizState: 'begin',
score: 0,
userAnswers: new Map()
};
this.baseState = { ...this.state };
this.handleStartClick = handleStartClick.bind(this)();
this.handleBackClick = handleBackClick.bind(this)(quizData);
this.handleNextClick = handleNextClick.bind(this)(quizData);
this.handleSubmitClick = handleSubmitClick.bind(this)();
this.handleCheckClick = handleCheckClick.bind(this)(quizData);
this.handleChoiceClick = handleChoiceClick.bind(this)();
this.handleExitClick = handleExitClick.bind(this)();
}
setQuestionState() {
this.setState(prevState =>
prevState.questionId === 0 ?
{ questionState: 'first' } :
prevState.questionId === (totalQuestions - 1) ?
{ questionState: 'last' } :
{ questionState: 'middle' }
);
}
setScore() {
let score = 0;
this.state.userAnswers.forEach((userAnswer, questionId) => {
const question = quizData.questions[questionId];
if (question) {
score = userAnswer === question.answer ? score + 1 : score;
}
}
);
this.setState({
score
})
}
render() {
return (
<main className="App">
<h1>A Quiz</h1>
<div className="QuizContainer">
<QuizTitle content={quizData.title}/>
<QuizProgress
questionId={this.state.questionId}
quizState={this.state.quizState}
totalQuestions={totalQuestions}
/>
<QuizContent
handleChoiceClick={this.handleChoiceClick}
intro={quizData.intro}
totalQuestions={totalQuestions}
{...this.state}
/>
<QuizNav
handleBackClick={this.handleBackClick}
handleCheckClick={this.handleCheckClick}
handleNextClick={this.handleNextClick}
handleSubmitClick={this.handleSubmitClick}
handleStartClick={this.handleStartClick}
handleExitClick={this.handleExitClick}
questionState={this.state.questionState}
quizState={this.state.quizState}
/>
</div>
</main>
);
}
}
| 06ab003b4393f19c81189c526c72588517be459b | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | vipranarayan14/vquiz-react | 6760881679361b98b37088f4b281d47973ff04fa | c803fb1f47565a245eb84857d30261972512d8e1 |
refs/heads/main | <repo_name>SamChinellato/k8s-sync<file_sep>/cmd/cleanup.go
/*
Copyright © 2020 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"bytes"
"context"
"fmt"
"log"
"path/filepath"
"os"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
yamlutil "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
var cleanupCmd = &cobra.Command{
Use: "cleanup",
Short: "Delete a yaml/json file/directory against your current cluster context",
Long: `Delete a yaml/json file/directory against your current cluster context.
To delete resources in a file or directory:
k8s-sync cleanup -f <path-to-file-or-dir>
If a directory is specified, k8s-sync will try to delete all resources in the directory and any subdirectories from the current cluster
context Kubernetes cluster. `,
Run: func(cmd *cobra.Command, args []string) {
filename, err := cmd.Flags().GetString("file")
if err != nil {
log.Fatal(err)
}
if filename == "" {
fmt.Println("Please set a file or directory with: \n 'k8s-sync cleanup -f <target>' ")
os.Exit(2)
}
fileInfo := FileCheck(filename)
home := homedir.HomeDir()
kubeconfig := filepath.Join(home, ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
dynamicSet, err := dynamic.NewForConfig(config)
if err != nil {
panic(err.Error())
}
if fileInfo.IsDir() {
// Create an array for all file->bytes
dirBytesArray, err := DirToBytes(filename)
if err != nil {
log.Fatal(err)
}
gvkUnstructuredObjMap := make(map[*schema.GroupVersionKind]*unstructured.Unstructured)
groupResource, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
if err != nil {
log.Fatal(err)
}
// For each fileBytes array, generate a map of gvk and JSON object. Append it to gvkUnstructuredObjMap
for _, fileBytes := range dirBytesArray {
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(fileBytes), 100)
tempMap := FileBytesToUnstructuredObjGVKMap(decoder, fileBytes)
for key, value := range tempMap {
gvkUnstructuredObjMap[key] = value
}
}
mapper := restmapper.NewDiscoveryRESTMapper(groupResource)
for groupVersionKind, unstructuredObj := range gvkUnstructuredObjMap {
K8sDelete(mapper, groupVersionKind, dynamicSet, unstructuredObj)
}
} else {
// file logic
fileBytes, err := FileToBytes(filename)
if err != nil {
fmt.Printf("Unable to read %s", filename)
log.Fatal(err)
}
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(fileBytes), 100)
groupResource, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
if err != nil {
log.Fatal(err)
}
gvkUnstructuredObjMap := FileBytesToUnstructuredObjGVKMap(decoder, fileBytes)
mapper := restmapper.NewDiscoveryRESTMapper(groupResource)
for groupVersionKind, unstructuredObj := range gvkUnstructuredObjMap {
K8sDelete(mapper, groupVersionKind, dynamicSet, unstructuredObj)
}
}
if err != nil {
log.Fatal("eof ", err)
}
fmt.Println("cleaned up all resources against the cluster!")
},
}
// K8sDelete Takes in a mapper, gvk and Ustructured obj and applies it against the cluster.
func K8sDelete(mapper meta.RESTMapper, groupVersionKind *schema.GroupVersionKind, dynamicSet dynamic.Interface, unstructuredObj *unstructured.Unstructured) {
mapping, err := mapper.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version)
if err != nil {
log.Fatal(err)
}
var dynamicResourceInterface dynamic.ResourceInterface
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
if unstructuredObj.GetNamespace() == "" {
unstructuredObj.SetNamespace("default")
}
dynamicResourceInterface = dynamicSet.Resource(mapping.Resource).Namespace(unstructuredObj.GetNamespace())
} else {
dynamicResourceInterface = dynamicSet.Resource(mapping.Resource)
}
err = dynamicResourceInterface.Delete(context.Background(), unstructuredObj.GetName(), metav1.DeleteOptions{})
if err != nil {
log.Println("failed to delete", unstructuredObj.GetKind(), "/", unstructuredObj.GetName(), err)
} else {
fmt.Printf("deleted %s/%s \n", unstructuredObj.GetKind(), unstructuredObj.GetName())
}
}
func init() {
rootCmd.AddCommand(cleanupCmd)
cleanupCmd.Flags().StringP("file", "f", "", "A YAML or JSON file to pass to the reconciler")
}
<file_sep>/go.mod
module github.com/SamChinellato/k8s-sync
go 1.15
require (
github.com/imdario/mergo v0.3.11 // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/afero v1.5.1 // indirect
github.com/spf13/cobra v1.1.1
github.com/spf13/viper v1.7.1
k8s.io/apimachinery v0.19.0
k8s.io/client-go v0.19.0
k8s.io/utils v0.0.0-20201110183641-67b214c5f920 // indirect
)
<file_sep>/cmd/reconcile.go
/*
Copyright © 2020 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"path/filepath"
"regexp"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
yamlutil "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
// reconcileCmd represents the reconcile command
var reconcileCmd = &cobra.Command{
Use: "reconcile",
Short: "Reconcile a yaml/json file/directory against your current cluster context",
Long: `Reconcile a yaml/json file/directory against your current cluster context.
Target resources using the -f flag:
k8s-sync reconcile -f <path-to-file-or-dir>
If a directory is selected, k8s-sync will try to apply all resources within it. It will also parse down any subdirectories.
To reapply resources every 10 seconds against your curent cluster context:
k8s-sync reconcile -f <path-to-file-or-dir> -i 10`,
Run: func(cmd *cobra.Command, args []string) {
interval, err := cmd.Flags().GetInt("interval")
if err != nil {
log.Fatal(err)
}
filename, err := cmd.Flags().GetString("file")
if err != nil {
log.Fatal(err)
}
if filename == "" {
fmt.Println("Please set a file or directory with: \n 'k8s-sync reconcile -f <target>' ")
os.Exit(2)
}
fileInfo := FileCheck(filename)
// Setup START
home := homedir.HomeDir()
kubeconfig := filepath.Join(home, ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
dynamicSet, err := dynamic.NewForConfig(config)
if err != nil {
panic(err.Error())
}
if fileInfo.IsDir() {
// Create an array for all file->bytes
dirBytesArray, err := DirToBytes(filename)
if err != nil {
log.Fatal(err)
}
gvkUnstructuredObjMap := make(map[*schema.GroupVersionKind]*unstructured.Unstructured)
groupResource, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
if err != nil {
log.Fatal(err)
}
// For each fileBytes array, generate a map of gvk and JSON object. Append it to gvkUnstructuredObjMap
for _, fileBytes := range dirBytesArray {
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(fileBytes), 100)
tempMap := FileBytesToUnstructuredObjGVKMap(decoder, fileBytes)
for key, value := range tempMap {
gvkUnstructuredObjMap[key] = value
}
}
mapper := restmapper.NewDiscoveryRESTMapper(groupResource)
SyncGVKUnstructuredObjMapToK8s(gvkUnstructuredObjMap, mapper, dynamicSet, interval)
} else {
// file logic
fileBytes, err := FileToBytes(filename)
if err != nil {
fmt.Printf("Unable to read %s", filename)
log.Fatal(err)
}
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(fileBytes), 100)
groupResource, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
if err != nil {
log.Fatal(err)
}
gvkUnstructuredObjMap := FileBytesToUnstructuredObjGVKMap(decoder, fileBytes)
mapper := restmapper.NewDiscoveryRESTMapper(groupResource)
SyncGVKUnstructuredObjMapToK8s(gvkUnstructuredObjMap, mapper, dynamicSet, interval)
}
if err != nil {
log.Fatal("eof ", err)
}
fmt.Println("reconciled all resources against the cluster!")
},
}
// FileCheck returns a os.FileInfo object if file is found
func FileCheck(filename string) os.FileInfo {
fileInfo, err := os.Stat(filename)
if os.IsNotExist(err) {
log.Fatal(err)
}
return fileInfo
}
// FileToBytes takes in a string and returns a byte array
func FileToBytes(filename string) ([]byte, error) {
fileBytes, err := ioutil.ReadFile(filename)
return fileBytes, err
}
// AddTrailingSlash takes a string and adds a trailing slash if not found
func AddTrailingSlash(dirname string) string {
match, err := regexp.MatchString("\\/$", dirname)
if err != nil {
log.Fatal(err)
}
if match != true {
dirname = dirname + "/"
}
return dirname
}
// DirToBytes takes a directory as string ang returns an array of byt Arrays
func DirToBytes(dirname string) ([][]byte, error) {
files, err := ioutil.ReadDir(dirname)
var dirBytes [][]byte
for _, file := range files {
checkedDir := AddTrailingSlash(dirname)
filename := checkedDir + file.Name()
fileInfo := FileCheck(filename)
// if file is a directory, parse down it recursively
if fileInfo.IsDir() {
fmt.Printf("%s is a directory, reading... \n", filename)
subDirBytes, err := DirToBytes(filename)
if err != nil {
log.Fatal(err)
}
for _, fileBytes := range subDirBytes {
dirBytes = append(dirBytes, fileBytes)
}
} else {
fileBytes, err := FileToBytes(filename)
if err != nil {
fmt.Printf("ignoring %s : %e \n", file.Name(), err)
} else if filepath.Ext(file.Name()) != (".yaml") && filepath.Ext(file.Name()) != (".yml") && filepath.Ext(file.Name()) != (".json") {
fmt.Printf("%s is not a YAML or JSON file, ignoring... \n", file.Name())
} else {
dirBytes = append(dirBytes, fileBytes)
}
}
}
return dirBytes, err
}
// FileBytesToUnstructuredObjGVKMap takes a yaml Decoder and file bytes and returns a map of gvk[unstructuredObj]
func FileBytesToUnstructuredObjGVKMap(decoder *yamlutil.YAMLOrJSONDecoder, fileByte []byte) map[*schema.GroupVersionKind]*unstructured.Unstructured {
var unstructuredObjGVKMap = make(map[*schema.GroupVersionKind]*unstructured.Unstructured)
for {
var rawObj runtime.RawExtension
if err := decoder.Decode(&rawObj); err != nil {
break
}
obj, groupVersionKind, err := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).Decode(rawObj.Raw, nil, nil)
if err != nil {
fmt.Printf("unable to decode YAML from %s! Ignoring... \n", fileByte)
} else {
unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
log.Fatal(err)
}
unstructuredObj := &unstructured.Unstructured{Object: unstructuredMap}
unstructuredObjGVKMap[groupVersionKind] = unstructuredObj
}
}
return unstructuredObjGVKMap
}
// K8sApply applies a given resource interface and unstructured object to k8s. retryObj = true if some dependencies are not found.
func K8sApply(dynamicResourceInterface dynamic.ResourceInterface, unstructuredObj *unstructured.Unstructured) bool {
retryObj := false
_, err := dynamicResourceInterface.Create(context.Background(), unstructuredObj, metav1.CreateOptions{})
switch {
case err == nil:
// is there is no error, assume resource creation was successful
fmt.Printf("%s/%s created \n", unstructuredObj.GetKind(), unstructuredObj.GetName())
case errors.IsAlreadyExists(err):
// if the object already exists print out info
fmt.Printf("%s/%s already exists \n", unstructuredObj.GetKind(), unstructuredObj.GetName())
case errors.IsNotFound(err):
// if an object is not found, it may be a missing dependency. Retry here
log.Println(unstructuredObj.GetKind(), "/", unstructuredObj.GetName(), err)
retryObj = true
default:
// if there is another error, log it to the user
log.Println("failed to create", unstructuredObj.GetKind(), "/", unstructuredObj.GetName(), err)
}
return retryObj
}
// ApplyGVKUnstructuredObjMap iterates a map of gvk[unstructuredObj] and applies the object to k8s
func ApplyGVKUnstructuredObjMap(mapper meta.RESTMapper,
dynamicSet dynamic.Interface,
groupVersionKind *schema.GroupVersionKind,
unstructuredObj *unstructured.Unstructured) bool {
mapping, err := mapper.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version)
if err != nil {
log.Fatal(err)
}
var dynamicResourceInterface dynamic.ResourceInterface
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
if unstructuredObj.GetNamespace() == "" {
unstructuredObj.SetNamespace("default")
}
dynamicResourceInterface = dynamicSet.Resource(mapping.Resource).Namespace(unstructuredObj.GetNamespace())
} else {
dynamicResourceInterface = dynamicSet.Resource(mapping.Resource)
}
retryObj := K8sApply(dynamicResourceInterface, unstructuredObj)
return retryObj
}
// SyncGVKUnstructuredObjMapToK8s reapplies objects that failed due to not found dependencies
func SyncGVKUnstructuredObjMapToK8s(
gvkUnstructuredObjMap map[*schema.GroupVersionKind]*unstructured.Unstructured,
mapper meta.RESTMapper,
dynamicSet dynamic.Interface,
interval int) {
allResourceCount := len(gvkUnstructuredObjMap)
for len(gvkUnstructuredObjMap) >= 1 {
for groupVersionKind, unstructuredObj := range gvkUnstructuredObjMap {
retryObj := ApplyGVKUnstructuredObjMap(mapper, dynamicSet, groupVersionKind, unstructuredObj)
if retryObj == false {
delete(gvkUnstructuredObjMap, groupVersionKind)
} else {
createdResourceCount := allResourceCount - len(gvkUnstructuredObjMap)
fmt.Printf("%d of %d resources created... \n", createdResourceCount, allResourceCount)
fmt.Printf("could not reconcile all objects against the cluster, retrying in %d seconds...\n", interval)
applyInterval := rand.Int31n(int32(interval))
time.Sleep(time.Duration(applyInterval) * time.Second)
}
}
}
}
func init() {
rootCmd.AddCommand(reconcileCmd)
reconcileCmd.Flags().StringP("file", "f", "", "A YAML or JSON file to pass to the reconciler")
reconcileCmd.Flags().IntP("interval", "i", 5, "Set the interval at which resources should be created")
}
<file_sep>/cmd/reconcile_test.go
package cmd
import (
"bytes"
"fmt"
"k8s.io/apimachinery/pkg/util/yaml"
"reflect"
"testing"
)
func TestFileCheck(t *testing.T) {
// arrange
file := "../tests/test-manifests/test.yaml"
//act
got := reflect.TypeOf(FileCheck(file)).String()
want := "*os.fileStat"
//assert
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
func TestFileToBytes(t *testing.T) {
// arrange
file := "../tests/test-manifests/test.yaml"
//act
got, _ := FileToBytes(file)
gotType := reflect.TypeOf(got).String()
wantType := "[]uint8"
//assert
if gotType != wantType {
t.Errorf("got %q want %q", gotType, wantType)
}
}
func TestAddTrailingSlash(t *testing.T) {
//arrange
filename := "./test-manifests"
//act
got := AddTrailingSlash(filename)
want := "./test-manifests/"
//assert
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
func TestDirToBytes(t *testing.T) {
//arrange
dir := "../tests/test-manifests/"
//act
got, _ := DirToBytes(dir)
gotType := reflect.TypeOf(got).String()
wantType := "[][]uint8"
gotLen := len(got)
wantLen := 4
//assert
if gotType != wantType {
t.Errorf("got %q want %q", gotType, wantType)
}
if gotLen != wantLen {
t.Errorf("got %q want %q", gotLen, wantLen)
}
}
func TestFileBytesToUnstructuredObjGVKMap(t *testing.T) {
filename := "../tests/test-manifests/test.yaml"
fileBytes, _ := FileToBytes(filename)
fmt.Println(fileBytes)
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(fileBytes), 100)
got := FileBytesToUnstructuredObjGVKMap(decoder, fileBytes)
gotType := reflect.TypeOf(got).String()
wantType := "map[*schema.GroupVersionKind]*unstructured.Unstructured"
if gotType != wantType {
t.Errorf("got %q want %q", gotType, wantType)
}
gotLen := len(got)
fmt.Println(got)
wantLen := 4
if gotLen != wantLen {
t.Errorf("got %q want %q", gotLen, wantLen)
}
}
<file_sep>/README.md
# K8S-SYNC
k8s-sync is a simple CLI to reconcile a yaml file or directory against the cluster. When working with manifests designed for GitOps deployment, it can be quite time consuming to manually apply manifests in a specific order using `kubectl`. `k8s-sync` allows you to reconcile objects defined in a YAML or
JSON file (or a directory containing them) against a Kubernetes cluster following a GitOps pattern.
`k8s-sync will` try to create target resources against your current cluster context, and, if some of the object dependencies are not found on the cluster,
it will reapply failed objects against the cluster until success. If the state of your YAML/JSON resources is eventually
consistant, you should be good to go!
---
## Install
To install the project using go:
go get -v github.com/SamChinellato/k8s-sync
---
## Reconcile a file or directory
To reconcile a resource against your current cluster context:
k8s-sync reconcile -f <path-to-file-or-dir>
To set the reapply interval to 10 seconds:
k8s-sync reconcile -f <path-to-file-or-dir> -i 10
`k8s-sync` will then reapply the selected resources until eventual state consistency is reached. If there are any subdirectories in the target directory, `k8s-sync` will automatically parse down them and apply YAML/JSON resources.
---
## Delete a file or directory
To delete resources in a file or directory:
k8s-sync cleanup -f <path-to-file-or-dir>
If a directory is specified, k8s-sync will try to delete all resources in the directory and any subdirectories from the current cluster context Kubernetes cluster.
---
<file_sep>/cmd/root.go
/*
Copyright © 2020 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "k8s-sync",
Short: "Sync YAML or JSON resources against a k8s cluster",
Long: `k8s-sync allows you to reconcile objects defined in a YAML or
JSON file (or a directory containing them) against a Kubernetes cluster following a GitOps pattern.
k8s-sync will try to create target resources against your current cluster context, and, if some of the object dependencies are not found on the cluster,
it will reapply failed objects against the cluster until success. If the state of your YAML/JSON resources is eventually
consistant, you should be good to go!`,
}
// Execute executes a cobra command
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.k8s-sync.yaml)")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".k8s-sync" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".k8s-sync")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
| a48964420f2dd9b5265a2e18b61737aa44b370f6 | [
"Markdown",
"Go Module",
"Go"
] | 6 | Go | SamChinellato/k8s-sync | cec69233676f4c5a1396d10af827fb6dd6ef2d8f | 87d60a0c074bb3b8b1497b8f9ef8b97ea5ba8cd0 |
refs/heads/master | <file_sep>//
// ConversionViewController.swift
// WorldTrotter
//
// Created by <NAME> on 04.03.20.
// Copyright © 2020 <NAME>. All rights reserved.
//
//import Foundation
import UIKit
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
}
class ConversionViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var fahrenheitField: UITextField!
@IBOutlet weak var celsiusLabel: UILabel!
var fahrenheitValue: Measurement<UnitTemperature>? {
didSet {
updateCelsiusValue()
}
}
var celsiusValue: Measurement<UnitTemperature>? {
if let fahrenheitValue = fahrenheitValue {
return fahrenheitValue.converted(to: .celsius)
}
else {
return nil
}
}
var numberFormatter: NumberFormatter {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}
override func viewDidLoad() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
updateCelsiusValue()
}
override func viewWillAppear(_ animated: Bool) {
self.view.backgroundColor = .random()
}
@IBAction func fahrenheitFieldEditChanged(_ sender: Any) {
// if let text = fahrenheitField.text, let value = Double(text) {
// fahrenheitValue = Measurement(value: value, unit: .fahrenheit)
// }
if let text = fahrenheitField.text, let number = numberFormatter.number(from: text) {
fahrenheitValue = Measurement(value: number.doubleValue, unit: .fahrenheit)
} else {
fahrenheitValue = nil
}
}
func updateCelsiusValue() {
if let celsiusValue = celsiusValue {
celsiusLabel.text = numberFormatter.string(from: NSNumber(value: celsiusValue.value))
}
else {
celsiusLabel.text = "???"
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentLocale = Locale.current
let decimalSeparator = currentLocale.decimalSeparator ?? "."
let existingTextHasDecimalSeparator = textField.text?.range(of: decimalSeparator)
let replacementTextHasDecimalSeparator = string.range(of: decimalSeparator)
// bronze challenge chapter 4
let allowedCharacters = CharacterSet(charactersIn: "0123456789.,")
let replacementStringCharacters = CharacterSet(charactersIn: string)
if !replacementStringCharacters.isSubset(of: allowedCharacters) {
return false
}
if existingTextHasDecimalSeparator != nil,
replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
}
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
}
<file_sep>//
// MapViewController.swift
// WorldTrotter
//
// Created by <NAME> on 23.03.20.
// Copyright © 2020 <NAME>. All rights reserved.
//
//import Foundation
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, CLLocationManagerDelegate {
var mapView: MKMapView!
let locationManager = CLLocationManager()
var showLocation: Bool = false
var nextAnnotation = 1
let button = UIButton(frame: CGRect(x: 280, y: 700, width: 150, height: 50))
let annotationsButton = UIButton(frame: CGRect(x: 280, y: 750, width: 150, height: 50))
override func loadView() {
mapView = MKMapView()
view = mapView
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
let standardString = NSLocalizedString("Standard", comment: "Standard map view")
let hybridString = NSLocalizedString("Hybrid", comment: "Hybrid map view")
let satelliteString = NSLocalizedString("Satellite", comment: "Satellite map view")
let segmentedControl = UISegmentedControl(items: [standardString, hybridString, satelliteString])
segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_:)), for: .valueChanged)
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedControl)
let topConstraint = segmentedControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8)
let margins = view.layoutMarginsGuide
let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
topConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
}
override func viewDidLoad() {
button.backgroundColor = .blue
button.setTitle("Show location", for: .normal)
button.addTarget(self, action: #selector(showCurrentLocationButtonClicked), for: .touchUpInside)
self.view.addSubview(button)
annotationsButton.backgroundColor = .green
annotationsButton.setTitle("Show annotations", for: .normal)
annotationsButton.addTarget(self, action: #selector(showAnnotation), for: .touchUpInside)
self.view.addSubview(annotationsButton)
print("MapViewController loaded")
}
@objc func mapTypeChanged(_ segControl: UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .hybrid
case 2:
mapView.mapType = .satellite
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "User"
annotation.subtitle = "current location"
mapView.addAnnotation(annotation)
if showLocation == true {
print(locations)
} else {
print("Show Location switched off")
}
// let userLocation: CLLocation = locations[0]
}
@objc func showAnnotation() {
var latitude: CLLocationDegrees
var longitude: CLLocationDegrees
showLocation = false
switch nextAnnotation {
case 1:
latitude = 48.3392
longitude = 7.8781
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Lahr"
annotation.subtitle = "City of birth"
mapView.addAnnotation(annotation)
nextAnnotation = 2
case 2:
// button.sendActions(for: .touchUpInside)
latitude = 48.6791
longitude = 8.8957
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Aidlingen"
annotation.subtitle = "Where I currently live"
mapView.addAnnotation(annotation)
nextAnnotation = 1
nextAnnotation = 3
case 3:
latitude = 37.5665
longitude = 126.9780
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "Seoul"
annotation.subtitle = "Best city"
mapView.addAnnotation(annotation)
nextAnnotation = 1
default:
break
}
}
@objc func showCurrentLocationButtonClicked(sender: UIButton!) {
print("button clicked")
print(showLocation)
if showLocation == false {
locationManager.startUpdatingLocation()
showLocation = true
} else {
locationManager.stopUpdatingLocation()
showLocation = false
}
}
}
<file_sep>//
// webViewController.swift
// WorldTrotter
//
// Created by <NAME> on 23.03.20.
// Copyright © 2020 <NAME>. All rights reserved.
//
//import Foundation
import UIKit
import WebKit
class WebViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string:"https://www.dhbw-stuttgart.de")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 64ae7f61c7f09e4437a9244fc5c472c50610199e | [
"Swift"
] | 3 | Swift | Joachim-Goennheimer/SwiftCourseWorldtrotter | b2fca8a7f5494760099f78bf7d4e8d943678a90a | 9b2be16c4ccf95fbd7094575c221a074ff6b796d |
refs/heads/master | <file_sep>#! /bin/sh
youtube-dl -ci -o "%(title)s-%(id)s.%(ext)s" --write-info-json "https://www.youtube.com/watch?v=uwmeH6Rnj2E"
zenc
<file_sep># Daemon
this depends on
- https://github.com/tahoe-lafs/zfec
- youtube-dl
| f482aacab8d2fd433aa2daf36669e44e0105176e | [
"Markdown",
"Shell"
] | 2 | Shell | laserbot/daemon | f85f76696d76f647bf7e125e56a9c5a778bec561 | 0eebed660c7b5911ccda65c468d8b1223c1d9705 |
refs/heads/master | <file_sep>//
// ViewController.swift
// About Me
//
// Created by <NAME> on 6/18/19.
// Copyright © 2019 <EMAIL>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var IntroduceButton: UIButton!
@IBOutlet weak var textView : UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func introduceMe() {
let name = "<NAME>"
let homeTown = "Mount Vernon, NY"
let favoriteColor = "Red"
let favoriteFood = "Fried Jumbo Shrimp"
let hobbies = "Brazillian Jiu-Jitsu, Video Games, Anime, and Technology."
let message = """
Name: \(name)
Home town: \(homeTown)
Favorite Color: \(favoriteColor)
Favorite Food: \(favoriteFood)
Hobbies: \(hobbies)
"""
print(message)
textView.text = message
IntroduceButton.isHidden = true
}
}
| 9bfccfabd9572ed0ae3fd3bf010d6eb3d8e4d272 | [
"Swift"
] | 1 | Swift | Blackcloud12/AboutMe | 0c5cdd80ee3c0368a4d4c9379090ab94bd072ac3 | 2b0efef7f4a0535ffb6887ca07a206d187ff78c0 |
refs/heads/master | <repo_name>Arvin723/cpp-exercise<file_sep>/sort/insert_sort.cpp
#include<iostream>
using namespace std;
void insert_sort(int ar[], int n);
int main()
{
int a[10] = {3, 1, 8, 2, 4, 9, 0, 5, 7, 6};
insert_sort(a,10);
for (int i = 0; i < 10; i++)
{
cout<<a[i];
cout<<" ";
}
cout<<endl;
}
void insert_sort(int ar[], int n)
{
int key = 0;
for (int i = 1; i< n; i++)
{
key = ar[i];
int j = i;
while(j > 0)
{
if(key < ar[j-1])
{
ar[j] = ar[j-1];
}
else
{
break ;
}
j--;
}
ar[j] = key;
}
}<file_sep>/sort/整合/sort.h
#pragma once
void insert_sort(int ar[], int n);//插入排序
void merge_sort(int * a, int p, int r);//归并排序
void merge_sort(int * a, int p, int r, int *t);//归并排序-附求逆序数t
void bubble_sort(int* a, int n);//冒泡排序
void search_sort(int * a, int n);//选择排序
int HeapSort(int* a, int n);//堆排序
void QuickSort(int * a, int p, int r);//快速排序
void CountSort(int * a, int n);//计数排序
void RadixSort(int * a, int n, int maxBit);//基数排序
void merge(int * a, int p, int q, int r);//归并
void merge(int * a, int p, int q, int r, int *t);//归并-附求逆序数t
//int HeapSort(int* a, int n);//堆排序
int MaxHeapify(int* a, int i, int n);//维护堆性质
int BuildMaxHeap(int* a, int n);//建堆
int Parent(int i);
int Left(int i);
int Right(int i);
int Partition(int * a, int p, int r);//原址重排-快速排序
int MaxNum(int * a, int n);
//用于基数排序
bool lessCpr(int x, int y, int bit);
<file_sep>/sort/整合/RadixSort.cpp
#include<iostream>
#include<cmath>
#include"sort.h"
void RadixSort(int * a, int n, int maxBit)
{
for (int k = 1; k <= maxBit; k++)
{
//使用一个稳定的排序,此处应使用时间复杂度小的
//暂使用插入排序(这将导致运行时间很长)
///*insert sort
int key = 0;
for (int i = 1; i< n; i++)
{
key = a[i];
int j = i;
while (j > 0)
{
//if (key < a[j - 1])
if (lessCpr(key, a[j - 1], k))
{
a[j] = a[j - 1];
}
else
{
break;
}
j--;
}
a[j] = key;
}
//*/
}
}
//按位比较是否小于
bool lessCpr(int x, int y, int bit)
{
if (bit == 1)
{
x = x % 10;
y = y % 10;
return x < y ? true : false;
}
else
{
x = (x / (int)pow(10, (bit - 1))) % 10;
y = (y / (int)pow(10, (bit - 1))) % 10;
return x < y ? true : false;
}
}<file_sep>/sort/MaxPriorityQueue.c
#include<stdio.h>
#define BuildMaxHeap BuildMaxPriorityQueue//定义MaxHeap为MaxPriorityQueue
#define MAXNUN 100//MaxPriorityQueue的size会变化,故设定最大值
int Insert(int* a, int* n, int key);//把元素x插入到MaxPriorityQueue
int MaxImum(int* a, int n);//返回MaxPriorityQueue中的最大值
int ExtractMax(int* a, int *n);//去掉并返回MaxPriorityQueue中的最大值
int IncreaseKey(int* a, int n, int i, int key);//将元素i的关键值提升到key
int MaxHeapify(int* a, int i, int n);//维护堆性质
int BuildMaxHeap(int* a, int n);//建堆
int Parent(int i);
int Left(int i);
int Right(int i);
int main()
{
int a[MAXNUN] = {1, 8, 3, 6, 7, 5, 4, 2, 10, 9, 0, 14, 13 ,11, 12};
int n = 15;
BuildMaxPriorityQueue(a, n);
for (int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
printf("MaxImum:%d\n",MaxImum(a,n));//MaxImum
printf("ExtractMax:%d\n",ExtractMax(a, &n));//ExtractMax
printf(" ");
for (int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
printf("IncreaseKey:%d\n",IncreaseKey(a, n, 5, 15));//IncreaseKey
printf(" ");
for (int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
printf("Insert:%d\n",Insert(a, &n, 14));//Insert
printf(" ");
for (int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
int MaxHeapify(int* a, int i, int n)
{
int largest = i;
int l = Left(i);
int r = Right(i);
if (l < n && a[l] > a[i])
{
largest = l;
}
else
{
largest = i;
}
if (r < n && a[r] > a[largest])
{
largest = r;
}
if (largest != i)
{
int tem = a[i];
a[i] = a[largest];
a[largest] = tem;
MaxHeapify(a, largest, n);
}
}
int BuildMaxHeap(int* a, int n)
{
for (int i = n/2-1; i >= 0; i--)//" >= 0 "
{
MaxHeapify(a, i, n);
}
}
int Parent(int i)
{
return ((i - 1) / 2);
}
int Left(int i)
{
return (2 * i + 1);
}
int Right(int i)
{
return (2 * i + 2);
}
/***************** MaxPriorityQueue **********************************/
int Insert(int* a, int* n, int key)//n传地址
{
(*n)++;
a[*n-1] = key;
int i = *n-1;
/*loop is same as IncreaseKey*/
while(a[i] > a[Parent(i)] && i > 0)
{
int tem = a[i];
a[i] = a[Parent(i)];
a[Parent(i)] = tem;
i = Parent(i);
}
/*loop is same as IncreaseKey*/
return a[i];
}
int MaxImum(int* a, int n)
{
return a[0];
}
int ExtractMax(int* a, int *n)//n传地址
{
if (*n < 1)
{
printf("heap underflow\n");
return -1;
}
int ret = a[0];
a[0] = a[(*n)-1];
(*n)--;
MaxHeapify(a, 0, *n);
return ret;
}
int IncreaseKey(int* a, int n, int i, int key)
{
if (key < a[i])
{
printf("new key is smaller then current key");
return a[i];
}
a[i] = key;
while(a[i] > a[Parent(i)] && i > 0)
{
int tem = a[i];
a[i] = a[Parent(i)];
a[Parent(i)] = tem;
i = Parent(i);
}
printf("%d",i);
return a[i];
}
/***************** MaxPriorityQueue **********************************/<file_sep>/sort/整合/MergeSort.cpp
#include<iostream>
#include"sort.h"
using namespace std;
void merge_sort(int * a, int p, int r)
{
if (p < r)
{
int q = (r + p) / 2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
merge(a, p, q, r);
}
else
{
return;
}
}
void merge(int * a, int p, int q, int r)
{
int L_len = q - p + 1;
int R_len = r - q;
int n = r - p + 1;
//int L_ar[L_len];
//int R_ar[R_len];
int *L_ar = new int(L_len);
int *R_ar = new int(R_len);
int i = 0;//a的下标
int j = 0;//L_ar的下标
int k = 0;//R_ar的下标
//copy
for (i = 0; i < L_len; i++)
{
L_ar[i] = a[p + i];
}
for (i = 0; i < R_len; i++)
{
R_ar[i] = a[q + i + 1];
}
for (i = p; i < r + 1; i++)//归并
{
if (j == L_len)
{
a[i] = R_ar[k];
k++;
}
else if (k == R_len)
{
a[i] = L_ar[j];
j++;
}
else if (L_ar[j] <= R_ar[k])
{
a[i] = L_ar[j];
j++;
}
else
{
a[i] = R_ar[k];
k++;
}
}
}
void merge_sort(int * a, int p, int r, int *t)
{
if (p < r)
{
int q = (r + p) / 2;
merge_sort(a, p, q, t);
merge_sort(a, q + 1, r, t);
merge(a, p, q, r, t);
}
else
{
return;
}
}
void merge(int * a, int p, int q, int r, int *t)
{
int L_len = q - p + 1;
int R_len = r - q;
int n = r - p + 1;
//int L_ar[L_len];
//int R_ar[R_len];
int *L_ar = new int(L_len);
int *R_ar = new int(R_len);
int i = 0;//a的下标
int j = 0;//L_ar的下标
int k = 0;//R_ar的下标
//copy
for (i = 0; i < L_len; i++)
{
L_ar[i] = a[p + i];
}
for (i = 0; i < R_len; i++)
{
R_ar[i] = a[q + i + 1];
}
for (i = p; i < r + 1; i++)//归并
{
if (j == L_len)
{
a[i] = R_ar[k];
k++;
}
else if (k == R_len)
{
a[i] = L_ar[j];
j++;
}
else if (L_ar[j] <= R_ar[k])
{
a[i] = L_ar[j];
j++;
}
else
{
a[i] = R_ar[k];
k++;
(*t) += (L_len - j);
}
}
return;
}<file_sep>/sort/整合/RandomizeInPlace.h
#pragma once
void RandomizeInPlace(int * a, int n);<file_sep>/随机排列/randomize_in_place.cpp
#include<iostream>
#include<cstdlib>
//#include<time.h>
#include<ctime>
using namespace std;
/*将数组a中的元素随机排列*/
void RandomizeInPlace(int * a, int n);
int main()
{
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
RandomizeInPlace(a, 10);
for (int i = 0; i < 10; i++)
{
cout<<a[i]<<' ';
}
cout<<'\n';
}
void RandomizeInPlace(int * a, int n)
{
int tmp;
int m;
time_t t;
time(&t);
for (int i = 0; i < n; i++)
{
srand(i+t);
m = rand()%(n-i) + i;
tmp = a[i];
a[i] = a[m];
a[m] = tmp;
}
}<file_sep>/sort/search_sort.c
#include<stdio.h>
void search_sort(int * a,int n);
int main()
{
int a[10] = {3, 1, 8, 2, 4, 9, 0, 5, 7, 6};
search_sort(a, 10);
for ( int i = 0; i <10; i++)
{
printf("%d ",a[i]);
}
}
void search_sort(int * a,int n)
{
for (int j = 0; j < n-1; j++)
{
int _min = j;
for (int i = j+1; i < n; i++)
{
if (a[i] < a[_min])
{
_min = i;
}
}
int tem = a[_min];
a[_min] = a[j];
a[j] = tem;
}
}<file_sep>/sort/整合/HeapSort.cpp
#include<iostream>
#include"sort.h"
using namespace std;
int HeapSort(int* a, int n)
{
BuildMaxHeap(a, n);
int heapSize = n;
for (int i = n; i > 0; i--)//" > 0 "
{
int tem = a[0];
a[0] = a[heapSize - 1];
a[heapSize - 1] = tem;
heapSize--;
MaxHeapify(a, 0, heapSize);
}
return 0;
}
int MaxHeapify(int* a, int i, int n)
{
int largest = i;
int l = Left(i);
int r = Right(i);
if (l < n && a[l] > a[i])
{
largest = l;
}
else
{
largest = i;
}
if (r < n && a[r] > a[largest])
{
largest = r;
}
if (largest != i)
{
int tem = a[i];
a[i] = a[largest];
a[largest] = tem;
MaxHeapify(a, largest, n);
}
return 0;
}
int BuildMaxHeap(int* a, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)//" >= 0 "
{
MaxHeapify(a, i, n);
}
return 0;
}
int Parent(int i)
{
return ((i - 1) / 2);
}
int Left(int i)
{
return (2 * i + 1);
}
int Right(int i)
{
return (2 * i + 2);
}<file_sep>/sort/整合/CountSort.cpp
#include<iostream>
#include"sort.h"
void CountSort(int * a, int n)
{
int k = MaxNum(a, n);
int * b = new int[n];
//数组a中最小为0,最大数为k,故c的大小为k+1
int * c = new int[k+1];
for (int i = 0; i < k+1; i++)
{
c[i] = 0;
}
for (int i = 0; i < n; i++)
{
b[i] = 0;
}
//数字a[i]共有c[a[i]]个
for (int i = 0; i < n; i++)
{
c[a[i]]++;
}
//小于等于 c[i] 的有 i 个
for (int i = 1; i < k+1; i++)
{
c[i] += c[i - 1];
}
//排序到数组 b
for (int i = 0; i < n; i++)
{
b[c[a[i]]-1] = a[i];
c[a[i]]--;
}
//复制到数组a
for (int i = 0; i < n; i++)
{
a[i] = b[i];
}
delete[] c;
delete[] b;
}
int MaxNum(int * a, int n)
{
int ret = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > ret)
{
ret = a[i];
}
}
return ret;
}<file_sep>/sort/整合/RandomizeInPlace.cpp
#include<iostream>
#include<cstdlib>
#include<ctime>
#include"RandomizeInPlace.h"
void RandomizeInPlace(int * a, int n)
{
int tmp;
int m;
time_t t;
time(&t);
for (int i = 0; i < n; i++)
{
srand(i + t);
m = rand() % (n - i) + i;
tmp = a[i];
a[i] = a[m];
a[m] = tmp;
}
}<file_sep>/sort/merge_sort_t.c
#include<stdio.h>
//将数组 a 从a[p]到a[r]部分进行排序
void merge_sort(int * a, int p, int r, int *t);
//将数组 a 左(a[p]~a[q])右(a[q+1]~a[r]) 两边进行归并,
//若左右两部分已排好序,则归并后的数组 a 将是排号序的
void merge(int * a, int p, int q,int r, int *t);
/***************************
void merge_sort(int * a, int p, int r, int *t)
:参数 t 为逆序数
使用方法:
先声明 int t = 0;
再将 t 的地址代入merge_sort
排序完成后,t 既为 排序前 序列的逆序数
原理:
每一次归并时,若取 右边 的数据,
则 逆序数对 增加 左边剩余 数据的个数。
***************************/
int main()
{
int t = 0;//储存逆序数
int a[40] = {1, 5, 4, 3, 2, 29, 0, 55, 7, 6, 12, 13, 31, 40, 25, 23, 26, 28, 3, 7,
33, 31, 38, 32, 34, 39, 30, 35, 37, 36, 42, 43, 41, 40, 45, 43, 46, 48, 33, 37
};
int n = 40;
merge_sort(a, 0, 40, &t);
for ( int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n%d", t);
}
void merge_sort(int * a, int p, int r, int *t)
{
if (p < r)
{
int q = (r + p)/2;
merge_sort(a, p, q, t);
merge_sort(a, q + 1, r, t);
merge(a, p, q, r, t);
}
else
{
return;
}
}
void merge(int * a, int p, int q, int r, int *t)
{
int L_len = q - p + 1;
int R_len = r - q;
int n = r - p + 1;
int L_ar[L_len];
int R_ar[R_len];
int i = 0;//a的下标
int j = 0;//L_ar的下标
int k = 0;//R_ar的下标
//copy
for (i = 0; i < L_len; i++)
{
L_ar[i] = a[p + i];
}
for (i = 0; i < R_len; i++)
{
R_ar[i] = a[q + i + 1];
}
for (i = p; i < r + 1; i++)//归并
{
if (j == L_len)
{
a[i] = R_ar[k];
k++;
}
else if (k == R_len)
{
a[i] = L_ar[j];
j++;
}
else if (L_ar[j] <= R_ar[k])
{
a[i] = L_ar[j];
j++;
}
else
{
a[i] = R_ar[k];
k++;
(*t) += (L_len-j);
}
}
return;
}<file_sep>/sort/整合/quicksort.cpp
#include<iostream>
#include"sort.h"
void QuickSort(int * a, int p, int r)
{
if (p < r)
{
int q = Partition(a, p, r);
QuickSort(a, p, q - 1);
QuickSort(a, q + 1, r);
}
}
int Partition(int * a, int p, int r)
{
int x = a[r];
int i = p;
for (int j = p; j < r; j++)
{
if (a[j] <= x)
{
int tem = a[i];
a[i] = a[j];
a[j] = tem;
i++;
}
}
int temp = a[i];
a[i] = a[r];
a[r] = temp;
return i;
}
/*
int Partition(int * a, int p, int r)
{
int x = a[r];
int i = p - 1;
for (int j = p; j < r; j++)
{
if (a[j] <= x)
{
i++;
int tem = a[i];
a[i] = a[j];
a[j] = tem;
}
}
int temp = a[i+1];
a[i+1] = a[r];
a[r] = temp;
return i + 1;
}
*/
<file_sep>/sort/HeapSort.c
#include<stdio.h>
int HeapSort(int* a, int n);//¶ÑÅÅÐò
int MaxHeapify(int* a, int i, int n);//ά»¤¶ÑÐÔÖÊ
int BuildMaxHeap(int* a, int n);//½¨¶Ñ
int Parent(int i);
int Left(int i);
int Right(int i);
int main()
{
int a[15] = {1, 8, 3, 6, 7, 5, 4, 2, 10, 9, 0, 14, 13 ,11, 12};
HeapSort(a, 15);
for (int i = 0; i < 15; i++)
{
printf("%d ",a[i]);
}
}
int HeapSort(int* a, int n)
{
//printf("********BuildMaxHeap begin********\n");
BuildMaxHeap(a, n);
//printf("********BuildMaxHeap end ********\n");
//printf("********HeapSort begin********\n");
int heapSize = n;
for (int i = n; i > 0; i-- )//" > 0 "
{
int tem = a[0];
a[0] = a[heapSize-1];
a[heapSize-1] = tem;
heapSize--;
MaxHeapify(a, 0, heapSize);
}
//printf("********HeapSort end ********\n");
}
int MaxHeapify(int* a, int i, int n)
{
int largest = i;
int l = Left(i);
int r = Right(i);
if (l < n && a[l] > a[i])
{
largest = l;
}
else
{
largest = i;
}
if (r < n && a[r] > a[largest])
{
largest = r;
}
if (largest != i)
{
int tem = a[i];
a[i] = a[largest];
a[largest] = tem;
MaxHeapify(a, largest, n);
}
/*
for (int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
*/
}
int BuildMaxHeap(int* a, int n)
{
for (int i = n/2-1; i >= 0; i--)//" >= 0 "
{
MaxHeapify(a, i, n);
}
}
int Parent(int i)
{
return ((i - 1) / 2);
}
int Left(int i)
{
return (2 * i + 1);
}
int Right(int i)
{
return (2 * i + 2);
}<file_sep>/sort/整合/SearchSort.cpp
#include<iostream>
#include"sort.h"
using namespace std;
void search_sort(int * a, int n)
{
for (int j = 0; j < n - 1; j++)
{
int _min = j;
for (int i = j + 1; i < n; i++)
{
if (a[i] < a[_min])
{
_min = i;
}
}
int tem = a[_min];
a[_min] = a[j];
a[j] = tem;
}
}<file_sep>/sort/整合/main_for_test.cpp
#include<iostream>
#include"sort.h"
#include"RandomizeInPlace.h"
#include<time.h>
#define N 100
using namespace std;
void print(int * a, int n)
{
for (int i = 0; i < n; i++)
{
cout <<fixed<< a[i] << " ";
}
cout << endl;
}
int main()
{
int a[N];
for (int i = 0; i < N; i++)
{
a[i] = i;
}
//数组随机排列
RandomizeInPlace(a, N);
cout << "排序前 :" << endl;
print(a, N);
clock_t start, end;
start = clock();
//HeapSort(a, N);
QuickSort(a, 0, N-1);
//bubble_sort(a, N);
//CountSort(a, N);
//RadixSort(a, N, 3);
end = clock();
cout << "排序后 :" << endl;
print(a, N);
time_t timeOfSort = end - start;
cout << "运行时间:"<<(double)timeOfSort << endl;
}<file_sep>/sort/merge_sort.c
#include<stdio.h>
//将数组 a 从a[p]到a[r]部分进行排序
void merge_sort(int * a, int p, int r);
//将数组 a 左(a[p]~a[q])右(a[q+1]~a[r]) 两边进行归并,
//若左右两部分已排好序,则归并后的数组 a 将是排号序的
void merge(int * a, int p, int q,int r);
int main()
{
int a[40] = {3, 11, 8, 52, 4, 29, 0, 55, 7, 6, 12, 13, 31, 40, 25, 23, 26, 28, 3, 7,
33, 31, 38, 32, 34, 39, 30, 35, 37, 36, 42, 43, 41, 40, 45, 43, 46, 48, 33, 37
};
int n = 40;
merge_sort(a, 0, n-1);
for ( int i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void merge_sort(int * a, int p, int r)
{
if (p < r)
{
int q = (r + p)/2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
merge(a, p, q, r);
}
else
{
return ;
}
}
void merge(int * a, int p, int q, int r)
{
int L_len = q - p + 1;
int R_len = r - q;
int n = r - p + 1;
int L_ar[L_len];
int R_ar[R_len];
int i = 0;//a的下标
int j = 0;//L_ar的下标
int k = 0;//R_ar的下标
//copy
for (i = 0; i < L_len; i++)
{
L_ar[i] = a[p + i];
}
for (i = 0; i < R_len; i++)
{
R_ar[i] = a[q + i + 1];
}
for (i = p; i < r + 1; i++)//归并
{
if (j == L_len)
{
a[i] = R_ar[k];
k++;
}
else if (k == R_len)
{
a[i] = L_ar[j];
j++;
}
else if (L_ar[j] <= R_ar[k])
{
a[i] = L_ar[j];
j++;
}
else
{
a[i] = R_ar[k];
k++;
}
}
}<file_sep>/sort/整合/insert_sort.cpp
#include<iostream>
#include"sort.h"
using namespace std;
void insert_sort(int ar[], int n)
{
int key = 0;
for (int i = 1; i< n; i++)
{
key = ar[i];
int j = i;
while (j > 0)
{
if (key < ar[j - 1])
{
ar[j] = ar[j - 1];
}
else
{
break;
}
j--;
}
ar[j] = key;
}
}<file_sep>/sort/bubble_sort.c
#include<stdio.h>
void bubble_sort(int* a, int n);
int main()
{
int a[10] = {4, 6, 1, 2, 8, 9, 0, 5, 3, 7};
bubble_sort(a, 10);
for (int i = 0; i < 10; i++)
printf("%d ",a[i]);
}
void bubble_sort(int* a, int n)
{
int tem = 0;
for (int j = n; j > 0; j--)
{
for (int i = 1; i < n; i++)
{
if (a[i] < a[i-1])
{
tem = a[i];
a[i] = a[i-1];
a[i-1] = tem;
}
}
}
}<file_sep>/sort/整合/BubleSort.cpp
#include<iostream>
#include"sort.h"
using namespace std;
void bubble_sort(int* a, int n)
{
int tem = 0;
for (int j = n; j > 1; j--)
{
for (int i = 1; i < j; i++)
{
if (a[i] < a[i - 1])
{
tem = a[i];
a[i] = a[i - 1];
a[i - 1] = tem;
}
}
}
}<file_sep>/README.md
# cpp-exercise
| 883d4bb1163249c5528d98b30a92d9b8377448a2 | [
"Markdown",
"C",
"C++"
] | 21 | C++ | Arvin723/cpp-exercise | ec512e9c5ad8d86fac5a8a424d50acd875282d03 | 8438c631a9fa5be8cc3085e5d1874f8d207a404a |
refs/heads/master | <repo_name>yeison94/crozono-free<file_sep>/src/attacks/wps_attack.py
import os
import pexpect
from poormanslogging import info, warn, error
import src.settings as settings
def check():
cmd_wps = pexpect.spawn('wash -i {0}'.format(settings.INTERFACE_MON))
cmd_wps.logfile = open(settings.LOG_FILE, 'wb')
cmd_wps.expect([settings.TARGET_BSSID, pexpect.TIMEOUT, pexpect.EOF], 30)
cmd_wps.close()
wps = False
parse_log_wps = open(settings.LOG_FILE, 'r')
for line in parse_log_wps:
if line.find(settings.TARGET_BSSID) != -1:
wps = True
parse_log_wps.close()
os.remove(settings.LOG_FILE)
return wps
def pixiedust():
info("Trying PixieDust attack")
cmd_reaver = pexpect.spawn(
'reaver -i {0} -c {1} -b {2} -s n -K 1 -vv'.format(settings.INTERFACE_MON, settings.TARGET_CHANNEL, settings.TARGET_BSSID))
cmd_reaver.logfile = open(settings.LOG_FILE, 'wb')
cmd_reaver.expect(['WPS pin not found!', pexpect.TIMEOUT, pexpect.EOF], 30)
cmd_reaver.close()
parse_log_crack = open(settings.LOG_FILE, 'r')
for line in parse_log_crack:
if line.find('WPA PSK: ') != -1:
settings.TARGET_KEY = line[line.find("WPA PSK: '") + 10:-1]
parse_log_crack.close()
os.remove(settings.LOG_FILE)
<file_sep>/crozono.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
----------------------------------------------------------------------------
CROZONO - 22.02.16.20.00.00 - www.crozono.com - <EMAIL>
----------------------------------------------------------------------------
!!! The authors are not responsible for any misuse of the application !!!
"""
# ## LIBRARIES ##
import os
import socket
import subprocess
from poormanslogging import info, warn, error
import src.settings as settings
import src.utils.sys_check as checks
import src.utils.device_manager as device_mgr
import src.utils.lan_manager as lan_mgr
import src.attacks.airodump_scan as airodump
# ## CONTEXT VARIABLES ##
version = '0.1'
def parse_args():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--essid', type=str, help="ESSID to target. Surround in quotes if it has spaces!")
parser.add_argument('-k', '--key', type=str, help="Key to use for connect to ESSID")
parser.add_argument('-a', '--attack', type=str, help="Attack to perform")
parser.add_argument('-d', '--dest', type=str, help="Destination to where to send info (attacker's IP)")
parser.add_argument('-i', '--interface', type=str, help="Interface to use for attacks/connecting")
return parser.parse_args()
def banner():
global version
from pyfiglet import figlet_format
b = figlet_format(" CROZONO") + \
''' Free Version - {v}
www.crozono.com - <EMAIL>
'''.format(v=version)
print(b)
def main():
banner()
if not checks.check_root():
error('You need root privileges to run CROZONO!\n')
exit(1)
if not checks.check_wlan_attacks_dependencies():
exit(1)
args = parse_args()
info("CROZONO running...")
settings.OS_PATH = os.getcwd()
settings.INTERFACE = args.interface if args.interface is not None else settings.INTERFACE
settings.INTERFACE = device_mgr.get_ifaces()[0] if settings.INTERFACE is None else settings.INTERFACE
settings.TARGET_ESSID = args.essid if args.essid is not None else settings.TARGET_ESSID
settings.TARGET_KEY = args.key if args.key is not None else settings.TARGET_KEY
settings.IP_ATTACKER = args.dest if args.dest is not None else settings.IP_ATTACKER
settings.ATTACK = args.attack if args.attack is not None else settings.ATTACK
if settings.TARGET_ESSID is not None:
if settings.TARGET_KEY is not None:
ap_target = None
lan_mgr.connect_to_lan()
else:
device_mgr.hardware_setup()
ap_target = airodump.scan_targets()
else:
device_mgr.hardware_setup()
ap_target = airodump.scan_targets()
# -------------------- Infiltrate wifi --------------------
if ap_target is not None:
settings.TARGET_ESSID = ap_target.get('ESSID').strip()
settings.TARGET_BSSID = ap_target.get('BSSID').strip()
settings.TARGET_CHANNEL = ap_target.get('channel').strip()
settings.TARGET_PRIVACY = ap_target.get('Privacy').strip()
info("Target selected: " + settings.TARGET_ESSID)
if settings.TARGET_PRIVACY == 'WEP':
from src.attacks import wep_attack
info("Cracking {e} access point with WEP privacy...".format(e=settings.TARGET_ESSID))
wep_attack.run()
if settings.TARGET_KEY is None:
error("Key not found! :(")
exit()
else:
info("Key found!: {k} ".format(k=settings.TARGET_KEY))
lan_mgr.save_key()
lan_mgr.connect_to_lan()
elif settings.TARGET_PRIVACY == 'WPA' or settings.TARGET_PRIVACY == 'WPA2' or settings.TARGET_PRIVACY == 'WPA2 WPA':
from src.attacks import wpa_attack,wps_attack
info("Cracking {e} access point with {p} privacy...".format(e=settings.TARGET_ESSID, p=settings.TARGET_PRIVACY))
wps = wps_attack.check()
if wps:
info("WPS is enabled")
wps_attack.pixiedust()
if settings.TARGET_KEY is None:
warn("PIN not found! Trying with conventional WPA attack...")
wpa_attack.run()
else:
warn("WPS is not enabled")
wpa_attack.run()
if settings.TARGET_KEY is None:
error("Key not found! :(")
exit(1)
else:
info("Key found!: {k} ".format(k=settings.TARGET_KEY))
lan_mgr.save_key()
lan_mgr.connect_to_lan()
else:
info("Open network!")
lan_mgr.connect_to_lan()
# -------------------- Acquired LAN range -----------------------------------------
lan_mgr.lan_range()
lan_mgr.get_gateway()
# -------------------- Connect to attacker and relay NMap info --------------------
if os.path.exists(settings.OS_PATH + '/cr0z0n0_nmap'):
os.remove(settings.OS_PATH + '/cr0z0n0_nmap')
if not checks.check_lan_attacks_dependencies():
exit(1)
if settings.IP_ATTACKER is not None:
info("Sending information about network to attacker ({ip}) and running attacks...".format(ip=settings.IP_ATTACKER))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((settings.IP_ATTACKER, settings.PORT_ATTACKER))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
banner()
info("Hello! :)")
info("Executing Nmap...")
subprocess.call(['nmap', '-O', '-sV', '-oN', 'cr0z0n0_nmap', '--exclude', settings.IP_LAN, settings.LAN_RANGE], stderr=subprocess.DEVNULL)
else:
warn("Attacker not defined! Ending up...")
exit()
# -------------------- Attacks --------------------
if settings.ATTACK == 'sniffing-mitm':
from src.attacks import sniffing_mitm
sniffing_mitm.run()
elif settings.ATTACK == 'metasploit':
from src.attacks import metasploit
metasploit.run()
else:
warn("Attack not defined!")
s.shutdown(1)
info("CROZONO has finished! Good bye! ;)")
main()
<file_sep>/src/attacks/wep_attack.py
import os
import time
import pexpect
import subprocess
from subprocess import Popen
from poormanslogging import info, error
import src.settings as settings
def run():
if os.path.exists(settings.OS_PATH + '/cr0z0n0_attack-01.csv'):
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.csv')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.cap')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.kismet.csv')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.kismet.netxml')
proc_airodump = subprocess.Popen(['airodump-ng', '--bssid', settings.TARGET_BSSID, '-c', settings.TARGET_CHANNEL, '-w', 'cr0z0n0_attack', settings.INTERFACE_MON],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
cmd_auth = pexpect.spawn('aireplay-ng -1 0 -e "{0}" -a {1} -h {2} {3}'.format(settings.TARGET_ESSID, settings.TARGET_BSSID, settings.NEW_MAC, settings.INTERFACE_MON))
cmd_auth.logfile = open(settings.LOG_FILE, 'wb')
cmd_auth.expect(['Association successful', pexpect.TIMEOUT, pexpect.EOF], 20)
cmd_auth.close()
parse_log_auth = open(settings.LOG_FILE, 'r')
for line in parse_log_auth:
if line.find('Association successful') != -1:
info("Association successful")
parse_log_auth.close()
os.remove(settings.LOG_FILE)
proc_aireplay = subprocess.Popen(['aireplay-ng', '-3', '-e', '"' + settings.TARGET_ESSID + '"', '-b', settings.TARGET_BSSID, '-h', settings.NEW_MAC, settings.INTERFACE_MON],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(settings.WEP_AIREPLAY_TIME)
cmd_crack = pexpect.spawn('aircrack-ng cr0z0n0_attack-01.cap')
cmd_crack.logfile = open(settings.LOG_FILE, 'wb')
cmd_crack.expect(['KEY FOUND!', 'Failed', pexpect.TIMEOUT, pexpect.EOF], 30)
cmd_crack.close()
parse_log_crack = open(settings.LOG_FILE, 'r')
for line in parse_log_crack:
where = line.find('KEY FOUND!')
if where > -1:
if line.find('ASCII') != -1:
where2 = line.find('ASCII')
key_end = line.find(')')
settings.TARGET_KEY = line[where2 + 6:key_end]
else:
key_end = line.find(']')
settings.TARGET_KEY = line[where + 13:key_end]
parse_log_crack.close()
os.remove(settings.LOG_FILE)
<file_sep>/src/attacks/metasploit.py
import subprocess
from poormanslogging import info, warn, error
def run():
info("Executing Metasploit...")
proc = subprocess.call(["msfconsole"], stderr=subprocess.DEVNULL)
<file_sep>/src/attacks/sniffing_mitm.py
import time
import random
import subprocess
import pexpect
from poormanslogging import info, warn, error
import src.settings as settings
def get_target_mitm():
targets = []
nmap_report = open(settings.OS_PATH + '/cr0z0n0_nmap', 'r')
for line in nmap_report:
if line.startswith('Nmap scan report for'):
ip = line.split(" ")[-1]
if ip.startswith(("192", "172", "10")) and ip != settings.GATEWAY and ip != settings.IP_LAN:
targets.append(ip)
return random.choice(targets)
def run():
settings.TARGET_MITM = get_target_mitm()
info("Executing MITM and Sniffing attacks between {g} and {m}...".format(g=settings.GATEWAY, m=settings.TARGET_MITM))
cmd_ettercap = pexpect.spawn(
'ettercap -T -M arp:remote /{g}/ /{m}/ -i {i}'.format(g=settings.GATEWAY, m=settings.TARGET_MITM, i=settings.INTERFACE))
time.sleep(2)
# cmd_tshark = pexpect.spawn('tshark -i {i} -w cr0z0n0_sniff'.format(i=settings.INTERFACE))
proc = subprocess.call(["tshark", "-i", settings.INTERFACE], stderr=subprocess.DEVNULL)
<file_sep>/src/attacks/wpa_attack.py
import os
import time
import pexpect
import subprocess
import src.settings as settings
from poormanslogging import info, warn, error
def run():
if os.path.exists(settings.OS_PATH + '/cr0z0n0_attack-01.csv'):
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.csv')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.cap')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.kismet.csv')
os.remove(settings.OS_PATH + '/cr0z0n0_attack-01.kismet.netxml')
proc_airodump = subprocess.Popen(['airodump-ng', '--bssid', settings.TARGET_BSSID, '-c', settings.TARGET_CHANNEL, '-w', 'cr0z0n0_attack', settings.INTERFACE_MON],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
cmd_aireplay = pexpect.spawn('aireplay-ng -0 10 -a {0} {1}'.format(settings.TARGET_BSSID, settings.INTERFACE_MON))
time.sleep(10)
cmd_aireplay.close()
time.sleep(settings.WPA_EXPECT_HANDSHAKE_TIME)
cmd_crack = pexpect.spawn('aircrack-ng -w dic cr0z0n0_attack-01.cap')
cmd_crack.logfile = open(settings.LOG_FILE, 'wb')
cmd_crack.expect(['KEY FOUND!', 'Failed', pexpect.TIMEOUT, pexpect.EOF])
cmd_crack.close()
parse_log_crack = open(settings.LOG_FILE, 'r')
for line in parse_log_crack:
where = line.find('KEY FOUND!')
if where > -1:
key_end = line.find(']')
settings.TARGET_KEY = line[where + 13:key_end]
parse_log_crack.close()
os.remove(settings.LOG_FILE)
<file_sep>/src/utils/sys_check.py
import os
from poormanslogging import error
import subprocess
lan_deps = ["nmap", "ettercap", "tshark", "msfconsole"]
wlan_deps = ["aircrack-ng", "reaver", "pixiewps"]
def check_lan_attacks_dependencies():
for d in lan_deps:
if subprocess.call(["which", d],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0:
error("Required binary for {bin} not found. Refer to the INSTALL document for requirements for running CROZONO.".format(bin=d))
return False
return True
def check_wlan_attacks_dependencies():
for d in wlan_deps:
if subprocess.call(["which", d],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0:
error("Required binary for {bin} not found. Refer to the INSTALL document for requirements for running CROZONO.".format(bin=d))
return False
return True
def check_root():
return os.geteuid() == 0
| 05f80e254404da2965fb330fbff715d2061e4244 | [
"Python"
] | 7 | Python | yeison94/crozono-free | 6a51669fae0a6775ebec6604a19b639bde542a9e | a26624b918059ddbf1b1c9a20eb5d2383d61788f |
refs/heads/master | <repo_name>aagamjain50000/calculator<file_sep>/main.js
const txt = document.getElementById("txt")
const dark = document.getElementById('dark')
const calc = document.getElementById("calc")
function dis(val) {
txt.value += val
}
function clr() {
txt.value = ''
}
function solve() {
a = txt.value;
b = eval(a);
txt.value = b
}
function backspace() {
aa = txt.value.slice(0, -1)
txt.value = aa;
}
function darkness() {
calc.classList.toggle("dark-theme");
} | 6784aab0092dd50320aed50c720f46c83b0bd0ea | [
"JavaScript"
] | 1 | JavaScript | aagamjain50000/calculator | fec7e76416af9c70a454f2609257c86fb0b23061 | 39f483046506ed523c3532d983ab1f59f7a1af74 |
refs/heads/master | <file_sep>#ifndef LISTA_H
#define LISTA_H
#include <stdbool.h>
#include <stddef.h>
/* ******************************************************************
* DEFINICION DE LOS TIPOS DE DATOS
* *****************************************************************/
/* La lista está planteada como una lista de punteros genéricos. */
//struct lista;
typedef struct lista lista_t;
typedef struct lista_iter lista_iter_t;
/* ******************************************************************
* PRIMITIVAS DE LA LISTA
* *****************************************************************/
// Crea una lista.
// Post: devuelve una nueva lista vacía.
lista_t *lista_crear(void);
// Destruye la lista. Si se recibe la función destruir_dato por parámetro,
// para cada uno de los elementos de la lista llama a destruir_dato.
// Pre: la lista fue creada. destruir_dato es una función capaz de destruir
// los datos de la lista, o NULL en caso de que no se la utilice.
// Post: se eliminaron todos los elementos de la lista.
void lista_destruir(lista_t *lista, void destruir_dato(void *));
// Devuelve verdadero o falso, según si la lista tiene o no elementos.
// Pre: la lista fue creada.
bool lista_esta_vacia(const lista_t *lista);
// Agrega un nuevo elemento a la lista en la primera posición.
// Devuelve falso en caso de error.
// Pre: la lista fue creada.
// Post: se agregó un nuevo elemento a la lista, valor se encuentra al
// principio de la lista.
bool lista_insertar_primero(lista_t *lista, void *dato);
// Agrega un nuevo elemento a la lista en la última posición.
// Devuelve falso en caso de error.
// Pre: la lista fue creada.
// Post: se agregó un nuevo elemento a la lista, valor se encuentra al
// final de la lista.
bool lista_insertar_ultimo(lista_t *lista, void *dato);
// ELimina el primer elemento de la lista y lo devuelve. Si esta vacía
// devuelve NULL.
// Pre: la lista fue creada.
// Post: si la lista no está vacia, se elimina el primer elemento.
void *lista_borrar_primero(lista_t *lista);
// Obtiene el valor del primer elemento de la lista. Si la lista tiene
// elementos, se devuelve el valor del primero, si está vacía devuelve NULL.
// Pre: la lista fue creada.
// Post: se devolvió el primer elemento de la lista, cuando no está vacía.
void *lista_ver_primero(const lista_t *lista);
// Obtiene el valor del último elemento de la lista. Si la lista tiene
// elementos, se devuelve el valor del último, si está vacía devuelve NULL.
// Pre: la lista fue creada.
// Post: se devolvió el último elemento de la lista, cuando no está vacía.
void *lista_ver_ultimo(const lista_t* lista);
// Devuelve la cantidad de elementos de la lista.
// Pre: la lista fue creada.
// Post: devuelve la cantidad de elementos (0 para lista vacía).
size_t lista_largo(const lista_t *lista);
/* ******************************************************************
* PRIMITIVAS DEL ITERADOR EXTERNO
* *****************************************************************/
// Crea un iterador asociado a una lista. Si la lista tiene elementos el
// iterador apunta al primer elemento, en caso contrario apunta al último
// Pre: una lista creada
// Post: devuelve un iterador asociado a la lista
lista_iter_t *lista_iter_crear(lista_t *lista);
// El iterador se mueve una posicion. Devuelve false en caso de que el
// iterador está al final.
// Pre: un iterador creado.
// Post: el iterador avanzó un lugar (en caso de true).
bool lista_iter_avanzar(lista_iter_t *iter);
// Devuelve el puntero del actual. En caso de estar al final devuelve
// NULL.
// Pre: un iterador creado.
// Post: devuelve el dato del actual.
void *lista_iter_ver_actual(const lista_iter_t *iter);
// Devuelve true si el iterador se encuentra al final.
// Pre: un iterador creado.
bool lista_iter_al_final(const lista_iter_t *iter);
// Destruye el iterador.
// Pre: un iterador creado.
void lista_iter_destruir(lista_iter_t *iter);
// Inserta el dato en la lista en la posicion actual del iterador.
// Devuelve false si no se pude insertar el dato.
// Pre: iter creado.
// Post: si es true el elemento fue insertado.
bool lista_iter_insertar(lista_iter_t *iter, void *dato);
// Borra el elemento apuntado por el iter en la posicion actual y devuelve
// el valor. Si el iter está al final devuelve NULL.
// Pre:iter creado.
// Post: devuelve valor o NULL.
void *lista_iter_borrar(lista_iter_t *iter);
/* ******************************************************************
* PRIMITIVA DEL ITERADOR INTERNO
* *****************************************************************/
// Aplica la funcion visitar a cada elemento de la lista hasta que devuelva
// false o no haya mas elementos. El extra se usa para cualquier proposito que
// se crea necesario.
// Pre: una lista.
// Post: lista con la funcion visitar apliada.
void lista_iterar(lista_t *lista, bool (*visitar)(void *dato, void *extra), void *extra);
/* *****************************************************************
* PRUEBAS UNITARIAS
* *****************************************************************/
// Realiza pruebas sobre la implementación del alumno.
// Para la implementación de las pruebas se debe emplear la función
// print_test(), como se ha visto en TPs anteriores.
void pruebas_lista_alumno(void);
#endif // LISTA_H
<file_sep># lista tp algo 2
<file_sep>#include "lista.h"
#include <stdlib.h>
#include <stdio.h>
/* ******************************************************************
* DEFINICION DE ESTRUCTURAS
* *****************************************************************/
typedef struct nodo_lista {
void* dato;
struct nodo_lista* siguiente;
}nodo_lista_t;
struct lista {
nodo_lista_t* primero;
nodo_lista_t* ultimo;
size_t largo;
};
struct lista_iter{
nodo_lista_t* actual;
nodo_lista_t* anterior;
lista_t* lista;
};
/* *****************************************************************
* PRIMITIVAS DE LA LISTA
* *****************************************************************/
lista_t *lista_crear(void){
lista_t* lista= malloc(sizeof(lista_t));
if (lista == NULL) {
return NULL;
}
lista->primero=NULL;
lista->ultimo=NULL;
lista->largo=0;
return lista;
}
nodo_lista_t * nodo_crear(void){
nodo_lista_t* nodo = malloc(sizeof(nodo_lista_t));
if (nodo == NULL ) {
return NULL;
}
nodo->siguiente=NULL;
return nodo;
}
void lista_destruir(lista_t *lista, void destruir_dato(void *)){
if (lista == NULL) return;
while ( !lista_esta_vacia(lista)){
void* p = lista_borrar_primero(lista);
if (destruir_dato != NULL){
destruir_dato(p);
}
}
free(lista);
}
bool lista_esta_vacia(const lista_t *lista){
if (lista==NULL) return true;
if (lista->primero == NULL){
return true;
}
return false;
}
bool lista_insertar_primero(lista_t *lista, void *dato){
if (lista==NULL) return false;
nodo_lista_t* nodo = nodo_crear();
if (nodo == NULL){
return false;
}
nodo->dato = dato;
nodo->siguiente = lista->primero;
lista->primero = nodo;
if (lista_largo(lista)== 0){
lista->ultimo = nodo;
}
lista->largo++;
return true;
}
bool lista_insertar_ultimo(lista_t *lista, void *dato){
if (lista==NULL) return false;
nodo_lista_t* nodo = nodo_crear();
if (nodo == NULL){
return false;
}
nodo->dato = dato;
if (lista_largo(lista)== 0){
lista->primero = nodo;
}
else{
lista->ultimo->siguiente= nodo;
}
lista->ultimo= nodo;
lista->largo++;
return true;
}
void *lista_borrar_primero(lista_t *lista){
if (lista_esta_vacia(lista)){
return NULL;
}
nodo_lista_t* aux= lista->primero;
lista->primero= aux->siguiente;
void* dato= aux->dato;
if (aux->siguiente == NULL){// solo un elemento
lista->ultimo= NULL;
}
lista->largo--;
free(aux);
return dato;
}
void *lista_ver_primero(const lista_t *lista){
if (lista_esta_vacia(lista)){
return NULL;
}
return lista->primero->dato;
}
void *lista_ver_ultimo(const lista_t* lista){
if (lista_esta_vacia(lista)){
return NULL;
}
return lista->ultimo->dato;
}
size_t lista_largo(const lista_t *lista){
if (lista_esta_vacia(lista)) return 0;
return lista->largo;
}
/* *****************************************************************
* PRIMITIVAS DEl ITERADOR EXTERNO
* *****************************************************************/
lista_iter_t *lista_iter_crear(lista_t *lista){
lista_iter_t* iter= malloc(sizeof(lista_iter_t));
if (iter == NULL || lista == NULL){
return NULL;
}
//si lista vacia, primero = NULL.
iter->lista = lista;
iter->actual= lista->primero;
iter->anterior= NULL;
return iter;
}
bool lista_iter_avanzar(lista_iter_t *iter){
if (iter->lista == NULL || lista_iter_al_final(iter)){
return false;
}
iter->anterior= iter->actual;
iter->actual= iter->actual->siguiente;
return true;
}
void *lista_iter_ver_actual(const lista_iter_t *iter){
if (lista_esta_vacia(iter->lista) || lista_iter_al_final(iter)){
return NULL;
}
return iter->actual->dato;
}
bool lista_iter_al_final(const lista_iter_t *iter){
if (iter->actual== NULL || lista_esta_vacia(iter->lista) ){
return true;
}
return false;
}
void lista_iter_destruir(lista_iter_t *iter){
if (iter != NULL){
free(iter);
}
}
bool lista_iter_insertar(lista_iter_t *iter, void *dato){
nodo_lista_t* nodo = nodo_crear();
if (nodo == NULL){
return false;
}
nodo->dato = dato;
if (lista_iter_al_final(iter)){
iter->lista->ultimo=nodo;
}
nodo->siguiente= iter->actual;
iter->actual=nodo;
//si esta al principio
if (iter->anterior == NULL){
iter->lista->primero=nodo;
}
else{
iter->anterior->siguiente=nodo;
}
iter->lista->largo++;
return true;
}
void *lista_iter_borrar(lista_iter_t *iter){
//si está al final de la lista o si lista vacia
if (lista_iter_al_final(iter) || lista_esta_vacia(iter->lista) ){
return NULL;
}
nodo_lista_t* aux = iter->actual;
void* dato= aux->dato;
//si el iter está en el último elemento de la lista
if (iter->actual == iter->lista->ultimo){
iter->lista->ultimo= iter->anterior;
}
iter->actual= aux->siguiente;
//si el iter está al principio de la lista
if (iter->anterior == NULL){
iter->lista->primero= iter->actual;
}
else{
iter->anterior->siguiente= iter->actual;
}
iter->lista->largo--;
free(aux);
return dato;
}
/* *****************************************************************
* PRIMITIVAS DEl ITERADOR INTERNO
* *****************************************************************/
void lista_iterar(lista_t *lista, bool (*visitar)(void *dato, void *extra), void *extra){
nodo_lista_t* aux=lista->primero;
while(aux != NULL && visitar(aux->dato,extra)){
aux=aux->siguiente;
}
}
<file_sep>#include "lista.h"
#include "testing.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
/* ******************************************************************
* PRUEBAS UNITARIAS ALUMNO
* *****************************************************************/
void prueba_null(){
printf("~~~ PRUEBA NULL ~~~\n");
lista_t* lista= NULL;
print_test("Insertar lista principio NULL= false",lista_insertar_primero(lista,NULL)==false);
print_test("Insertar lista final NULL= false", lista_insertar_ultimo(lista,NULL)==false);
print_test("Borrar lista NULL = NULL", lista_borrar_primero(lista)==NULL);
print_test("Tamaño Lista = 0", lista_largo(lista)==0);
printf("~~~ PRUEBA VACIA ~~~\n");
lista=lista_crear();
print_test("Borrar lista Vacia = NULL", lista_borrar_primero(lista)==NULL);
print_test("Tamaño Lista = 0", lista_largo(lista)==0);
lista_destruir(lista, NULL);
}
void prueba_un_elemento(){
printf("~~~ PRUEBA 1 ELEMENTO ~~~\n");
//variables
int a=1;
lista_t* lista = lista_crear();
if (lista != NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
//inserto un elemento al principio
if (lista_insertar_primero(lista,&a)){
printf("Insertar lista primero elemento 1 = True \n");
print_test("Lista NO esta vacia", lista_esta_vacia(lista) == false );
print_test("Tamaño Lista = 1", lista_largo(lista)==1);
print_test("Elemento 1 esta primero", lista_ver_primero(lista) == &a);
print_test("Elemento 1 esta ultimo", lista_ver_ultimo(lista) == &a);
print_test("Borrar primer elemento = 1",lista_borrar_primero(lista) == &a);
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
print_test("Tamaño Lista = 0", lista_largo(lista)==0);
}
//inserto un elemento al final
if (lista_insertar_ultimo(lista,&a)){
printf("Insertar lista ultimo elemento 1 = True \n");
print_test("Lista NO esta vacia", lista_esta_vacia(lista) == false );
print_test("Elemento 1 esta primero", lista_ver_primero(lista) == &a);
print_test("Elemento 1 esta ultimo", lista_ver_ultimo(lista) == &a);
print_test("Borrar primer elemento = 1",lista_borrar_primero(lista) == &a);
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
}
//destruyo la lista
lista_destruir(lista, NULL);
}
}
void prueba_elementos(){
printf("~~~ PRUEBA VARIOS ELEMENTOS ~~~\n");
printf("En stack \n");
//variables
int a=1,b=2,c=3;
lista_t* lista = lista_crear();
if (lista != NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
//inserto algunos elementos 1->2->3
if (lista_insertar_primero(lista,&a)){
printf("elemento 1 al principio de la lista = True \n");
}
if (lista_insertar_ultimo(lista,&b)){
printf("elemento 2 al final de la lista = True \n");
}
if (lista_insertar_ultimo(lista,&c)){
printf("elemento 3 al final de la lista = True \n");
}
print_test("Tamaño Lista = 3", lista_largo(lista)==3);
print_test("ver primero = 1 ",lista_ver_primero(lista)== &a);
print_test("ver ultimo = 3 ", lista_ver_ultimo(lista)== &c);
print_test("Borrar primer elemento = 1",lista_borrar_primero(lista) == &a);
print_test("ver primero = 2 ",lista_ver_primero(lista)== &b);
print_test("ver ultimo = 3 ", lista_ver_ultimo(lista)== &c);
print_test("Borrar primer elemento = 2",lista_borrar_primero(lista) == &b);
print_test("ver primero = 3 ",lista_ver_primero(lista)== &c);
print_test("ver ultimo = 3 ", lista_ver_ultimo(lista)== &c);
print_test("Borrar primer elemento = 3",lista_borrar_primero(lista) == &c);
print_test("ver primero = NULL ",lista_ver_primero(lista)== NULL);
print_test("ver ultimo = NULL", lista_ver_ultimo(lista)== NULL);
//inserto algunos elementos 3->2->1
if (lista_insertar_ultimo(lista,&a)){
printf("elemento 1 al final de la lista = True \n");
}
if (lista_insertar_primero(lista,&b)){
printf("elemento 2 al principio de la lista = True \n");
}
if (lista_insertar_primero(lista,&c)){
printf("elemento 3 al principio de la lista= True \n");
}
print_test("ver primero = 3 ",lista_ver_primero(lista)== &c);
print_test("ver ultimo = 1 ", lista_ver_ultimo(lista)== &a);
print_test("Borrar primer elemento = 3",lista_borrar_primero(lista) == &c);
print_test("ver primero = 2 ",lista_ver_primero(lista)== &b);
print_test("ver ultimo = 1 ", lista_ver_ultimo(lista)== &a);
print_test("Borrar primer elemento = 2",lista_borrar_primero(lista) == &b);
print_test("ver primero = 1 ",lista_ver_primero(lista)== &a);
print_test("ver ultimo = 1 ", lista_ver_ultimo(lista)== &a);
print_test("Borrar primer elemento = 1",lista_borrar_primero(lista) == &a);
print_test("ver primero = NULL ",lista_ver_primero(lista)== NULL);
print_test("ver ultimo = NULL", lista_ver_ultimo(lista)== NULL);
//destruyo la lista
lista_destruir(lista, NULL);
}
}
void prueba_destruccion(){
printf("~~~ PRUEBA DE DESTRUCCION ~~~\n");
//variables
int a=1;
lista_t* lista = lista_crear();
if (lista != NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
// inserto algunos elementos
for(int i=0; i<5; i++){
lista_insertar_primero(lista, &a);
}
printf("Se apilaron algunos elementos \n");
//destruyo lista
lista_destruir(lista, NULL);
}
printf("En heap \n");
//variables
int* b= malloc(sizeof(int));
int* c= malloc(sizeof(int));
int* d= malloc(sizeof(int));
lista_t* lista2 = lista_crear();
*b=3;
*c=4;
*d=5;
if (lista2 != NULL){
print_test("lista esta vacia", lista_esta_vacia(lista2) == true );
//inserto algunos punteros
lista_insertar_primero(lista2, b);
lista_insertar_primero(lista2, c);
lista_insertar_primero(lista2, d);
printf("Se apilaron punteros \n");
//destruyo la lista
lista_destruir(lista2, free);
}
}
void prueba_volumen(){
printf("~~~ PRUEBA DE VOLUMEN ~~~\n");
//variables
int a=1;
lista_t* lista = lista_crear();
if (lista != NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
//inserto muchos elementos elementos
printf("insertando muchos elementos\n");
for(int i=0; i<80; i++){
lista_insertar_ultimo(lista, &a);
}
print_test("Lista NO esta vacia", lista_esta_vacia(lista) == false );
//destruyo la lista
lista_destruir(lista, NULL);
}
printf("En heap\n");
lista= lista_crear();
if (lista != NULL ){
for (int i=0; i<1000; i++){
int*p =malloc(sizeof(int));
*p=i;
lista_insertar_primero(lista,p);
}
//destrucción
lista_destruir(lista, free);
}
}
void prueba_un_elemento_iter(){
printf("~~~ PRUEBA 1 ELEMENTO CON ITER~~~\n");
//variables
int a=1;
lista_t* lista = lista_crear();
lista_iter_t* iter=lista_iter_crear(lista);
if (lista != NULL && iter != NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
print_test("Iter al final", lista_iter_al_final(iter)== true);
print_test("Avanzar = False", lista_iter_avanzar(iter) == false);
print_test("Insertar valor 1", lista_iter_insertar(iter,&a)== true);
print_test("Inserción correcta",lista_ver_primero(lista)== &a);
print_test("Tamaño Lista = 1", lista_largo(lista)==1);
print_test("Avanzar = true", lista_iter_avanzar(iter) == true);
print_test("Borrar elemento == NULL",lista_iter_borrar(iter)==NULL);
print_test("Iter al final", lista_iter_al_final(iter)== true);
lista_iter_destruir(iter);
iter=lista_iter_crear(lista);
printf("creacion de iter apuntando a primer elemento\n");
print_test("Actual = 1", lista_iter_ver_actual(iter)== &a);
print_test("Borrar elemento == 1",lista_iter_borrar(iter)== &a);
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
print_test("Tamaño Lista = 0", lista_largo(lista)==0);
}
//destrucción
lista_destruir(lista, NULL);
lista_iter_destruir(iter);
}
void prueba_elementos_iter(){
printf("~~~ PRUEBA VARIOS ELEMENTOS CON ITER ~~~\n");
printf("En stack \n");
//variables
int a=1,b=2,c=3;
lista_t* lista = lista_crear();
lista_iter_t* iter= lista_iter_crear(lista);
if (lista != NULL && iter!= NULL){
print_test("Lista esta vacia", lista_esta_vacia(lista) == true );
print_test("Inserción de elemento 1",lista_iter_insertar(iter,&a)==true);
print_test("Inserción de elemento 2",lista_iter_insertar(iter,&b)==true);
print_test("Inserción de elemento 3",lista_iter_insertar(iter,&c)==true);
print_test("Tamaño Lista = 3", lista_largo(lista)==3);
print_test("Primero = 3", lista_ver_primero(lista)== &c);
print_test("Iter avanzar",lista_iter_avanzar(iter)==true);
print_test("Actual = 2", lista_iter_ver_actual(iter)== &b);
print_test("Iter avanzar",lista_iter_avanzar(iter)==true);
print_test("Actual = 1", lista_iter_ver_actual(iter)== &a);
print_test("Iter avanzar",lista_iter_avanzar(iter)==true);
print_test("Iter al final",lista_iter_al_final(iter)==true);
//destrucción
lista_destruir(lista, NULL);
lista_iter_destruir(iter);
}
}
void prueba_volumen_iter(){
printf("~~~ PRUEBA VOLUMEN CON ITER ~~~\n");
printf("En stack \n");
//variables
lista_t* lista = lista_crear();
lista_iter_t* iter= lista_iter_crear(lista);
if (lista != NULL && iter!= NULL){
for(int i=0; i<1000; i++){
lista_iter_insertar(iter,&i);
}
//destrucción
lista_destruir(lista, NULL);
lista_iter_destruir(iter);
}
printf("En heap \n");
lista= lista_crear();
iter=lista_iter_crear(lista);
if (lista != NULL && iter!= NULL){
for (int i=0; i<1000; i++){
int*p =malloc(sizeof(int));
*p=i;
lista_iter_insertar(iter, p);
}
while( !lista_iter_al_final(iter) ){
void* p= lista_iter_borrar(iter);
free(p);
}
//destrucción
lista_destruir(lista, NULL);
lista_iter_destruir(iter);
}
}
bool multiplicar(void* dato, void* extra){
int* elemento= dato;
int* operacion=extra;
*elemento= *operacion*(*elemento);
return true;
}
bool borrar(void* dato, void*extra){
int*contador=extra;
free(dato);
++(*contador);
if (*contador == 2 )return false;
return true;
}
void prueba_interno(){
printf("~~~ PRUEBA ITERADOR INTERNO ~~~\n");
//variables
lista_t* lista = lista_crear();
int a=1,b=2,c=3;
int operando=2,contador=0;
if (lista != NULL){
printf("Duplicado:\n");
lista_insertar_ultimo(lista,&a);
lista_insertar_ultimo(lista,&b);
lista_insertar_ultimo(lista,&c);
lista_iterar(lista, multiplicar, &operando);
int* p= lista_borrar_primero(lista);
print_test("Elemento 1 duplicado",*p == 2);
int* p1= lista_borrar_primero(lista);
print_test("Elemento 2 duplicado",*p1 == 4);
int* p2= lista_borrar_primero(lista);
print_test("Elemento 3 duplicado",*p2 == 6);
printf("free de datos\n");
for (int i=0; i<3; i++){
int*p4 =malloc(sizeof(int));
*p4=i;
lista_insertar_ultimo(lista, p4);
}
printf("Se insertaron 3 punteros\n");
lista_iterar(lista, borrar, &contador);
printf("Se liberaron 2 punteros\n");
lista_borrar_primero(lista);
lista_borrar_primero(lista);
}
//destrucción
lista_destruir(lista, free);
}
void pruebas_lista_alumno() {
lista_t* ejemplo = NULL;
print_test("Puntero inicializado a NULL", ejemplo == NULL);
//pruebas sin iterador
prueba_null();
prueba_un_elemento();
prueba_elementos();
prueba_destruccion();
prueba_volumen();
//pruebas con iterador externo
prueba_un_elemento_iter();
prueba_elementos_iter();
prueba_volumen_iter();
//prueba con iterador interno
prueba_interno();
}
| 511b1ab7a794250a0217496d4cca79d3115821e6 | [
"Markdown",
"C"
] | 4 | C | kevinspasiuk/lista | da3448c4d8efaa2ffbaaed60cab495e9509a5594 | 91732e39baa86531283f42b2430b08551a7c8806 |
refs/heads/master | <repo_name>somebin/gopher-lua<file_sep>/gas.go
package lua
const (
OP_MOVE_GAS int = 1
OP_MOVEN_GAS int = 1
OP_LOADK_GAS int = 1
OP_LOADBOOL_GAS int = 1
OP_LOADNIL_GAS int = 1
OP_GETUPVAL_GAS int = 1
OP_GETGLOBAL_GAS int = 1
OP_GETTABLE_GAS int = 1
OP_GETTABLEKS_GAS int = 1
OP_SETGLOBAL_GAS int = 1
OP_SETUPVAL_GAS int = 1
OP_SETTABLE_GAS int = 1
OP_SETTABLEKS_GAS int = 1
OP_NEWTABLE_GAS int = 1
OP_SELF_GAS int = 1
OP_ADD_GAS int = 1
OP_SUB_GAS int = 1
OP_MUL_GAS int = 1
OP_DIV_GAS int = 1
OP_MOD_GAS int = 1
OP_POW_GAS int = 1
OP_UNM_GAS int = 1
OP_NOT_GAS int = 1
OP_LEN_GAS int = 1
OP_CONCAT_GAS int = 1
OP_JMP_GAS int = 1
OP_EQ_GAS int = 1
OP_LT_GAS int = 1
OP_LE_GAS int = 1
OP_TEST_GAS int = 1
OP_TESTSET_GAS int = 1
OP_CALL_GAS int = 1
OP_TAILCALL_GAS int = 1
OP_RETURN_GAS int = 1
OP_FORLOOP_GAS int = 1
OP_FORPREP_GAS int = 1
OP_TFORLOOP_GAS int = 1
OP_SETLIST_GAS int = 1
OP_CLOSE_GAS int = 1
OP_CLOSURE_GAS int = 1
OP_VARARG_GAS int = 1
OP_NOP_GAS int = 1
) | 775707ae1f41f43deb9aa36e49d81944cb06fcd9 | [
"Go"
] | 1 | Go | somebin/gopher-lua | 0691d2bac59bb0abebd1738c9c1083d91b6bba58 | 3270195b0d9505aea2d9c90bdfe96acb56c700eb |
refs/heads/master | <repo_name>Joshrlear/NPS-API<file_sep>/script.js
'use strict'
const apiKey = '<KEY>';
const baseUrl = 'https://developer.nps.gov/api/v1/parks';
function formatQueryParams(params) {
const queryItems = Object.keys(params).map(key =>
`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
function displayResults(responseJson) {
console.log('displaying...');
$('#results-container').empty();
$('#error').empty();
const data = responseJson.data;
for (let i = 0; i < data.length; i++) {
$('#results-container').append(`
<li class="park-name">${responseJson.data[i].fullName}</li>
<p class="park-description">${responseJson.data[i].description}</p>
<a href="${responseJson.data[i].url}"><button role="button type="button" class="park-button">More Info</button></a>
`)
}
console.log(responseJson.data);
}
function getParks(resultQty, search) {
console.log('getting parks');
const params = {
api_key: apiKey,
stateCode: search,
limit: resultQty - 1
};
console.log(params);
const queryString = formatQueryParams(params);
const url = baseUrl + '?' + queryString;
console.log(url);
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err => {
console.log(err);
$('#error').text(`Uh oh! Something went wrong: ${err.message}`);
});
}
function handleSumbit() {
$('#form').submit(event => {
event.preventDefault();
const search = $('#search').val().replace(/[,\s]/g,',').split(',');
const resultQty = $('#result-quantity').val();
getParks(resultQty, search);
})
}
$(function onLoad() {
handleSumbit();
}) | 9443a2cd1aa117cc58717e5c1b057fd58ca7ce13 | [
"JavaScript"
] | 1 | JavaScript | Joshrlear/NPS-API | f5f2febe70b7143faa3fa9b643fbb1d8ab1e9357 | 0d1a334f4256eb89989adbde95aa94d13db24b19 |
refs/heads/master | <file_sep># gmall
gmall-user用户服务为8080<file_sep>package com.itnan.gmall.user.controller;
import com.itnan.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author nan
* @date 2020/10/2020/10/1821:31
*/
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/index")
@ResponseBody
public String index(){
return "hello world";
}
}
<file_sep>package com.itnan.gmall.user.service.impl;
import com.itnan.gmall.user.mapper.UserMapper;
import com.itnan.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author nan
* @date 2020/10/2020/10/1821:34
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
}
<file_sep>package com.itnan.gmall.user.service;
/**
* @author nan
* @date 2020/10/2020/10/1821:33
*/
public interface UserService {
}
| 3639c5faa4e96bebaad5638d92f5a4aa817aecb9 | [
"Markdown",
"Java"
] | 4 | Markdown | nanjieying/gmall | eb8673c776dad7b0333176e697c95f4e1f17f93a | 70624f7f39f57e92a1238dc0d91acd1d52e897cc |
refs/heads/main | <file_sep>const schedule = require('node-schedule');
console.log('l')
let someDate = new Date('2021-08-06 20:31:30');
schedule.scheduleJob(someDate, () => {
console.log('Job ran @', new Date().toString())
});<file_sep>/* const express = require('express');
const app = express();
// const cors = require('cors');
const port = 3000;
// app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.sendFile(__dirname + "/index.html");
})
app.use(express.json());
const accountSid = '<KEY>';
const authToken = '<PASSWORD>';
const client = require('twilio')(accountSid, authToken);
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Headers', '*');
next();
});
app.post('/sms', (req, res) => {
// res.set('Access-Control-Allow-Origin', '*');
client.messages
.create({
body: req.body.message,
messagingServiceSid: 'MGda7af18591f0c237763fb5cf2be37db5',
to: `+1${req.body.number}`,
})
.then(message => console.log("Message Sent!"))
.done();
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
*/
//here
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
const port = process.env.PORT || 3000;
app.use(express.json());
const accountSid = '<KEY>';
const authToken = '<PASSWORD>';
const client = require('twilio')(accountSid, authToken);
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Headers', '*');
next();
});
app.get("/", (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', '*');
res.set('Access-Control-Allow-Headers', '*');
res.sendFile(__dirname + "/index.html");
})
const schedule = require('node-schedule');
app.get('/', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', '*');
res.set('Access-Control-Allow-Headers', '*');
})
app.post('/sms', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', '*');
res.set('Access-Control-Allow-Headers', '*');
let time = {
alarmTime: req.body.alarmTime
}
console.log(time.alarmTime)
let TIME = '2021-08-06 ' + time.alarmTime + ':00';
console.log(TIME)
let someDate = new Date(TIME);
let obj = {
body: req.body.message,
messagingServiceSid: 'MGda7af18591f0c237763fb5cf2be37db5',
to: `+1${req.body.number}`
};
schedule.scheduleJob(someDate, () => {
client.messages
.create({
body: obj.body,
messagingServiceSid: obj.messagingServiceSid,
to: obj.to,
})
.then(message => console.log("Message Sent!"))
.done();
});
});
/*
let dateObj = new Date();
console.log(dateObj.toTimeString());
// dateObj.toTimeString() = "17:05:29 GMT-0700 (Pacific Daylight Time)"
let i = 0;
let myFunction = () => {
let i = 0;
if (i = 0) {
console.log('it works')
client.messages
.create({
body: obj.body,
messagingServiceSid: obj.messagingServiceSid,
to: obj.to,
})
.then(message => console.log("Message Sent!"))
.done();
}
};
app.post('/sms', (req, res) => {
let obj = {
body: req.body.message,
messagingServiceSid: 'MGda7af18591f0c237763fb5cf2be37db5',
to: `+1${req.body.number}`
}
setInterval (
() => {
if (1 < 5) {
client.messages
.create({
body: obj.body,
messagingServiceSid: obj.messagingServiceSid,
to: obj.to,
})
.then(message => console.log("Message Sent!"))
.done();
break;
}
},
1000
);
});
.create({
body: obj.body,
messagingServiceSid: obj.messagingServiceSid,
to: obj.to,
})
.then(message => console.log("Message Sent!"))
.done();
*/
app.listen(port, () => {
console.log(`App is listening at http://localhost:${port}`);
}); | e419ff1e0b510ba181ce4e12424ed829c5cef3aa | [
"JavaScript"
] | 2 | JavaScript | CheesyPizzaBoi/2021-app-node-server | 7cd8cb1f943ea2e97ea6619c7391ec809652dd51 | ff105e62c95609891b4bd304c99f2a95972d7b1f |
refs/heads/master | <file_sep>import abc
from lafontaine.helpers.feature_types import FeatureType
class BaseFeatureResult(abc.ABC):
def __init__(self, result: bool, frames: int, feature: str, feature_type: FeatureType):
self.result = result
self.frames = frames
self.feature = feature
self.feature_type = feature_type
<file_sep>class Scene:
def __init__(self):
self.frames = []
def add_frame(self, frame):
self.frames.append(frame)
def add_frames(self, frames):
self.frames.extend(frames)
def start_ts(self):
return self.frames[0].timestamp
def end_ts(self):
return self.frames[-1].timestamp
<file_sep>from enum import Enum
class FeatureType(Enum):
SingleFrameFeature = 1
ContinuousFrameFeature = 2
<file_sep>from datetime import timedelta
from typing import Optional
from lafontaine.feature_director.feature.base_feature import BaseFeature
class FeatureDirector:
def __init__(self, genre, max_length: timedelta, all_features):
self.genre = genre
self.max_length = max_length
self.all_features = all_features
def check_for_all_features(self, frame) -> Optional[BaseFeature]:
return self._check_for_features(frame)
def _check_for_features(self, frame):
for f in self.all_features:
result = f.check_feature(frame)
if result.result:
return result
return None
<file_sep>from typing import Optional
import pysrt
from moviepy.editor import VideoFileClip
from pysrt import SubRipFile
from lafontaine.helpers.feature_types import FeatureType
from lafontaine.feature_director.feature_director import FeatureDirector
from lafontaine.helpers.frame import Frame
from lafontaine.helpers.scene import Scene
from lafontaine.helpers.video_stats import VideoStats
class VideoParser:
def __init__(self, video_path, srt_path, downscale):
self.video = VideoFileClip(video_path)
if downscale:
self.video = self.video.resize(height=int(downscale))
self.audio = self.video.audio
self.duration = self.video.duration
if srt_path:
self.subs: Optional[SubRipFile] = pysrt.open(srt_path, encoding='iso-8859-1')
else:
self.subs = None
self.video_stats = VideoStats(self.video.fps, self.video.w, self.video.h)
def get_scenes(self, feature_director: FeatureDirector, spoiler: bool):
scenes = []
current_scene = None
countdown = None
recording = False
for t, raw_img in self.video.iter_frames(with_times=True):
audio_frame = self.audio.get_frame(t)
if spoiler:
percent = (100 / (self.duration / 2)) * t
if percent >= 100:
break
else:
percent = (100 / self.duration) * t
if self.subs:
sub = self.subs.at(seconds=t)
frame = Frame(raw_img, audio_frame, t, sub)
else:
frame = Frame(raw_img, audio_frame, t)
result = feature_director.check_for_all_features(frame)
if result and result.result and result.feature_type == FeatureType.ContinuousFrameFeature and result.candidate_frames:
scene = Scene()
scene.add_frames(result.candidate_frames)
scenes.append(scene)
recording = False
current_scene = None
countdown = None
else:
if countdown and countdown < 0:
recording = False
scenes.append(current_scene)
current_scene = None
countdown = None
if recording:
current_scene.add_frame(frame)
countdown -= 1
else:
if result and result.result is True:
print(f'Activating {result.feature} for {result.frames} frames.')
if current_scene is None:
current_scene = Scene()
recording = True
countdown = result.frames
current_scene.add_frame(frame)
info = f'Processed frame at {t:.2f}. {percent:.2f}%'
print(info)
if current_scene is not None:
scenes.append(current_scene)
return scenes
<file_sep>from lafontaine.feature_director.features.sound.sound_util import SoundUtil
from lafontaine.feature_director.feature.single_frame_feature import SingleFrameFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
from lafontaine.helpers.frame import Frame
class SoundPeakDetector(SingleFrameFeature):
def __init__(self, audio_threshold, frames):
self.audio_threshold = audio_threshold
super().__init__('SoundPeakDetector', frames)
def check_feature(self, frame: Frame):
frame_volume = SoundUtil.get_volume_of_frame(frame)
# We have to do this because numpy bool_ is True will return false
if frame_volume >= self.audio_threshold:
return SingleFrameFeatureResult(True, self.frames, self.feature_id)
else:
return SingleFrameFeatureResult(False, self.frames, self.feature_id)
<file_sep>import face_recognition
from lafontaine.feature_director.feature.single_frame_feature import SingleFrameFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
class FaceRecognizer(SingleFrameFeature):
def __init__(self, face_count, frames, cuda: bool):
self.face_count = face_count
self.cuda = cuda
super().__init__('FaceRecognizer', frames)
def check_feature(self, frame):
if self.cuda:
face_locations = face_recognition.face_locations(frame.image, model="cnn")
else:
face_locations = face_recognition.face_locations(frame.image)
return SingleFrameFeatureResult(len(face_locations) >= self.face_count, self.frames, self.feature_id)
<file_sep>class VideoStats:
def __init__(self, fps, width, height):
self.fps = fps
self.width = width
self.height = height
<file_sep>from lafontaine.feature_director.feature.single_frame_feature import SingleFrameFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
from lafontaine.helpers.frame import Frame
class SubtitleConversationCount(SingleFrameFeature):
def __init__(self, conversation_count, frames):
self.conversation_count = conversation_count
super().__init__('SubtitleConversationCount', frames)
def check_feature(self, frame: Frame):
if frame.sub:
sub_text = frame.sub.text
how_many = sub_text.count("-")
return SingleFrameFeatureResult(how_many >= self.conversation_count, self.frames, self.feature_id)
return SingleFrameFeatureResult(False, self.frames, self.feature_id)
<file_sep>from pysrt import SubRipItem
class Frame:
def __init__(self, image, audio, timestamp, sub: SubRipItem = None):
self.image = image
self.audio = audio
self.timestamp = timestamp
self.sub = sub
<file_sep>from lafontaine.feature_director.features.sound.sound_util import SoundUtil
from lafontaine.feature_director.feature.continuous_feature import ContinuousFeature
from lafontaine.feature_director.feature_result.continuous_frame_result import ContinuousFrameResult
class HighVolumeDetector(ContinuousFeature):
def __init__(self, volume, frame_limit, frames):
self.volume_limit = volume
self.counting = False
self.candidate_frames = []
self.frame_limit = frame_limit
self.count = frame_limit
super().__init__('HighVolumeDetector', frames)
def check_feature(self, frame) -> ContinuousFrameResult:
frame_volume = SoundUtil.get_volume_of_frame(frame)
if self.counting:
if frame_volume >= self.volume_limit:
if self.count <= 0:
self.counting = False
frames = self.candidate_frames
self.candidate_frames = []
return ContinuousFrameResult(True, self.frames, self.feature_id, frames)
self.candidate_frames.append(frame)
self.count -= 1
else:
self.counting = False
self.candidate_frames = []
self.count = self.frame_limit
return ContinuousFrameResult(False, self.frames, self.feature_id, self.candidate_frames)
if frame_volume >= self.volume_limit:
self.candidate_frames.append(frame)
self.counting = True
self.count = self.frame_limit
return ContinuousFrameResult(False, self.frames, self.feature_id, self.candidate_frames)
<file_sep>import argparse
import os
import pathlib
import time
from pathlib import Path
from lafontaine.generator.video_generator import VideoGenerator
from lafontaine.parser.config_parser import ConfigParser
from lafontaine.parser.video_parser import VideoParser
def main():
parser = argparse.ArgumentParser(description='LaFontaine is an automatic movie trailer generator.')
parser.add_argument('-f', '--file', help='Path for the video.', required=True)
parser.add_argument('-c', '--config', help='Path for the configuration file.', required=True)
parser.add_argument('-o', '--output', help='Path for the output.', required=False)
parser.add_argument('-s', '--sub', help='Path for the subtitle file.', required=False)
parser.add_argument('-d', '--downscale', help='Which width to downscale the video to.', required=False)
parser.add_argument('-t', '--title', help='Title screen to put in the end of the trailer.', required=False)
parser.add_argument('-cd', '--cuda', help='Enable CUDA support.', action='store_true')
parser.add_argument('-sp', '--spoiler', help='Do not spoil the movie.', action='store_true')
args = vars(parser.parse_args())
path_to_video = args['file']
path_to_config = args['config']
output_path = args['output']
path_to_sub = args['sub']
optimize = args['downscale']
title = args['title']
cuda = args['cuda']
spoiler = args['spoiler']
# Parsers
config_contents = Path(path_to_config).read_text()
director = ConfigParser.get_director_from_config(config_contents, cuda)
video_parser = VideoParser(path_to_video, path_to_sub, optimize)
video_stats = video_parser.video_stats
print(f'Loaded {video_stats.width}x{video_stats.height} video with {video_stats.fps} FPS.')
start = time.time()
print('Started processing..')
# Process scenes
scenes = video_parser.get_scenes(director, spoiler)
end = time.time()
print(f'Finished processing. Took {end - start} seconds.')
print(f'Found {len(scenes)} scenes.')
# Generator
if output_path:
save_path = output_path
else:
video_name = os.path.basename(path_to_video)
base_path = f'out/'
pathlib.Path(base_path).mkdir(exist_ok=True)
save_path = f'{base_path}/trailer_{video_name}'
video_generator = VideoGenerator(path_to_video, director.max_length, f'{save_path}', title)
video_generator.generate_from_scenes(scenes, video_stats.fps)
if __name__ == '__main__':
main()
<file_sep>import abc
from lafontaine.feature_director.feature.base_feature import BaseFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
class SingleFrameFeature(BaseFeature):
@abc.abstractmethod
def check_feature(self, frame) -> SingleFrameFeatureResult:
pass
<file_sep>import os
from datetime import timedelta
from typing import List
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.editor import concatenate_videoclips
from moviepy.video.VideoClip import TextClip
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
from lafontaine.helpers.frame import Frame
from lafontaine.helpers.scene import Scene
class VideoGenerator:
def __init__(self, path_to_video, max_length: timedelta, out_path, title):
self.audio = AudioFileClip(path_to_video)
self.max_length = max_length
self.out_path = out_path
self.title = title
def generate_from_scenes(self, scenes: List[Scene], fps):
clips = []
total_duration = 0
for scene in scenes:
clip = self._generate_from_scene(scene, fps)
total_duration += clip.duration
if total_duration > self.max_length.seconds:
break
clips.append(clip)
if clips:
if self.title:
title_clip = TextClip(self.title, color='white', bg_color='black', fontsize=60,
size=(clips[0].w, clips[0].h)).set_duration(5)
clips.append(title_clip)
trailer = concatenate_videoclips(clips)
if os.path.exists(self.out_path):
os.remove(self.out_path)
trailer.write_videofile(self.out_path)
def _generate_from_scene(self, scene, fps) -> ImageSequenceClip:
return self._generate_from_frames(scene.frames, fps)
def _generate_from_frames(self, frames: List[Frame], fps):
images = []
for f in frames:
images.append(f.image)
clip = ImageSequenceClip(images, fps=fps)
audio_clip = self.audio.subclip(frames[0].timestamp, frames[-1].timestamp)
new_clip = clip.set_audio(audio_clip)
return new_clip
<file_sep>import abc
from lafontaine.feature_director.feature.base_feature import BaseFeature
from lafontaine.feature_director.feature_result.continuous_frame_result import ContinuousFrameResult
class ContinuousFeature(BaseFeature):
@abc.abstractmethod
def check_feature(self, frame) -> ContinuousFrameResult:
pass
<file_sep>astroid==2.1.0
atomicwrites==1.2.1
attrs==18.2.0
certifi==2018.11.29
chardet==3.0.4
Click==7.0
decorator==4.3.0
dlib==19.16.0
face-recognition==1.2.3
face-recognition-models==0.3.0
ffmpeg-python==0.1.17
future==0.17.1
idna==2.7
imageio==2.4.1
isort==4.3.4
lazy-object-proxy==1.3.1
mccabe==0.6.1
more-itertools==4.3.0
moviepy==0.2.3.5
multiprocess==0.70.6.1
mypy==0.641
mypy-extensions==0.4.1
numpy==1.15.4
Pillow==5.3.0
pluggy==0.8.0
pox==0.2.4
ppft==1.6.4.8
py==1.7.0
pycodestyle==2.4.0
pydub==0.23.0
pyflakes==2.0.0
pylint==2.2.2
pysrt==1.1.1
pytest==4.0.1
requests==2.20.1
six==1.11.0
tqdm==4.28.1
typed-ast==1.1.0
urllib3==1.24.1
wrapt==1.10.11
<file_sep># LaFontaine [](https://travis-ci.org/umutseven92/LaFontaine) [](https://app.codacy.com/app/umutseven92/LaFontaine?utm_source=github.com&utm_medium=referral&utm_content=umutseven92/LaFontaine&utm_campaign=Badge_Grade_Dashboard)
LaFontaine is an automatic movie trailer generator.
## Description
LaFontaine creates movie trailers for any genre using pre-defined features, like number of faces on screen, and loudness of volume.
Scenes are extracted using these features and combined to create the final trailer.
There are three features for frame, three features for sound and three features for subtitles. Features are read from configurations and are fully configurable.
## Etymology
LaFontaine is named after the legendary [Don LaFontaine](https://en.wikipedia.org/wiki/Don_LaFontaine), who was the voice of more than 5000 movie trailers.
He is the voice in the classic phrase "In a world...".
## All Features
### Image Features
#### Face Recognizer
```json
{
"id": "FaceRecognizer",
"face_count": 3,
"frames": 100
}
```
Records for *frames* amount of frames if the amount of faces in the screen is greater than *face_count*.
#### Frame Delta Detector
```json
{
"id": "FrameDeltaDetector",
"delta": 0.95,
"frame_limit": 50,
"scene_change_limit": 3,
"frames": 75
}
```
Records for *frames* amount of frames if frame difference percentage is greater than *delta* at least *scene_change_limit* times continuously for at least *frame_limit* frames.
#### Frame Color Counter
```json
{
"id": "ColorCounter",
"color_count": 50000,
"frames": 100
}
```
Records for *frames* amount of frames if the amount of unique colors is greater than *color_count*.
### Sound Features
#### Sound Peak Detector
```json
{
"id": "SoundPeakDetector",
"audio_threshold": 0.30,
"frames": 50
}
```
Records for *frames* amount of frames if the volume is higher than *audio_threshold*.
#### High Volume Detector
```json
{
"id": "HighVolumeDetector",
"volume": 0.60,
"frame_limit": 50,
"frames": 70
}
```
Records for *frames* amount of frames if the volume is continuously higher than *volume* for *frame_limit* amount of frames.
#### Sound Delta Detector
```json
{
"id": "SoundDeltaDetector",
"delta": 3,
"frame_limit": 50,
"scene_change_limit": 3,
"frames": 75
}
```
Records for *frames* amount of frames if audio difference percentage is greater than *delta* at least *scene_change_limit* times continuously for at least *frame_limit* frames.
### Subtitle Features
#### Subtitle Density Detector
```json
{
"id": "SubtitleDensityDetector",
"char_count": 60,
"frames": 100
}
```
Records for *frames* amount of frames if the subtitle has more than *char_count* characters.
#### Subtitle Intensity Detector
```json
{
"id": "SubtitleIntensityDetector",
"intensity_char": "!",
"char_count": 3,
"frames": 100
}
```
Records for *frames* amount of frames if the subtitle has more than *char_count* *intensity_char* characters.
#### Subtitle Conversation Counter
```json
{
"id": "SubtitleConversationCount",
"conversation_count": 2,
"frames": 100
}
```
Records for *frames* amount of frames if the subtitle has more than *conversation_count* characters speaking.
## Dependencies
* Python 3+.
* ImageMagick is required to create end titles.
* If CUDA is going to be enabled for better performance, *dlib* needs to be compiled with CUDA support.
## Configuration
Configuration files contain list of features and some other metadata. Each genre has its own configuration file. To create an action movie trailer, you use the *action.lf* file, to create a comedy movie trailer you use *comedy.lf* and vice versa.
Example configuration files are given in the *res/config/* folder, however you can create your own custom configurations.
*res/config/action.lf*:
```json
{
"genre": "action",
"max_length": "120",
"features": [
{
"id": "SoundPeakDetector",
"audio_threshold": 0.30,
"frames": 50
},
{
"id": "FrameDeltaDetector",
"delta": 0.95,
"frame_limit": 50,
"scene_change_limit": 3,
"frames": 75
},
{
"id": "HighVolumeDetector",
"volume": 0.60,
"frame_limit": 50,
"frames": 70
},
{
"id": "FaceRecognizer",
"face_count": 3,
"frames": 100
},
{
"id": "SubtitleIntensityDetector",
"intensity_char": "!",
"char_count": 3,
"frames": 100
}
]
}
```
Parameter|Description|Required
--- | ---| ---
genre | Name of the genre | True
max_length | Max length of the trailer in seconds | True
features | List of features, listed in order of importance | True
## Usage
```bash
python lafontaine.py -f res/videos/northbynorthwest.mp4 -s res/subtitles/northbynorthwest.srt -c res/config/action.lf -t "North by Northwest" -d 480 -cd
```
Parameter|Description|Required
--- | ---| ---
-f, --file | Path to the video file | True
-s, --sub | Path to the subtitle file<sup>1</sup> | False
-o, --output | Path to the output file<sup>2</sup> | False
-c, --config | Path to the feature configuration file | True
-t, --title | What to put on the title card in the end of the trailer | False
-d, --downscale | Which width to downscale the resolution to<sup>3</sup>| False
-cd, --cuda | Enable CUDA support | False
-sp, --spoiler | Parse only the first half of the movie to avoid spoilers | False
<sup>1</sup>: If this option is not given, subtitle features will be disabled.
<sup>2</sup>: If this option is not given, the output will be saved to lafontaine/out/.
<sup>3</sup>: Aspect ration will be preserved.
## Example Trailer
<file_sep>from lafontaine.helpers.feature_types import FeatureType
from lafontaine.feature_director.feature_result.base_feature_result import BaseFeatureResult
class SingleFrameFeatureResult(BaseFeatureResult):
def __init__(self, result: bool, frames: int, feature: str):
super().__init__(result, frames, feature, FeatureType.SingleFrameFeature)
<file_sep>from lafontaine.feature_director.feature.single_frame_feature import SingleFrameFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
from lafontaine.helpers.frame import Frame
class SubtitleDensityDetector(SingleFrameFeature):
def __init__(self, char_count, frames):
self.char_count = char_count
super().__init__('SubtitleDensityDetector', frames)
def check_feature(self, frame: Frame):
if frame.sub:
sub_length = len(frame.sub.text)
return SingleFrameFeatureResult(sub_length >= self.char_count, self.frames, self.feature_id)
return SingleFrameFeatureResult(False, self.frames, self.feature_id)
<file_sep>from typing import List
from lafontaine.helpers.feature_types import FeatureType
from lafontaine.feature_director.feature_result.base_feature_result import BaseFeatureResult
from lafontaine.helpers.frame import Frame
class ContinuousFrameResult(BaseFeatureResult):
def __init__(self, result: bool, frames: int, feature: str, candidate_frames: List[Frame]):
super().__init__(result, frames, feature, FeatureType.ContinuousFrameFeature)
self.candidate_frames = candidate_frames
<file_sep>import abc
class BaseFeature(abc.ABC):
def __init__(self, feature_id, frames):
self.feature_id = feature_id
self.frames = frames
<file_sep>import json
from datetime import timedelta
from lafontaine.feature_director.features.sound.sound_delta_detector import SoundDeltaDetector
from lafontaine.feature_director.feature_director import FeatureDirector
from lafontaine.feature_director.features.image.color_counter import ColorCounter
from lafontaine.feature_director.features.image.face_recognizer import FaceRecognizer
from lafontaine.feature_director.features.image.frame_delta_detector import FrameDeltaDetector
from lafontaine.feature_director.features.sound.high_volume_detector import HighVolumeDetector
from lafontaine.feature_director.features.sound.sound_peak_detector import SoundPeakDetector
from lafontaine.feature_director.features.subtitle.subtitle_conversation_count import SubtitleConversationCount
from lafontaine.feature_director.features.subtitle.subtitle_density_detector import SubtitleDensityDetector
from lafontaine.feature_director.features.subtitle.subtitle_intensity_detector import SubtitleIntensityDetector
class ConfigParser:
@staticmethod
def get_director_from_config(config: str, cuda: bool) -> FeatureDirector:
all_features = []
loaded = json.loads(config)
features = loaded['features']
genre = loaded['genre']
max_length = int(loaded['max_length'])
for feature in features:
feature_id = feature['id']
frames = feature['frames']
# Image Features
if feature_id == 'FaceRecognizer':
face_count = feature['face_count']
all_features.append(FaceRecognizer(face_count, frames, cuda))
elif feature_id == 'ColorCounter':
color_count = feature['color_count']
all_features.append(ColorCounter(color_count, frames))
elif feature_id == 'FrameDeltaDetector':
delta = feature['delta']
frame_limit = feature['frame_limit']
change_limit = feature['scene_change_limit']
all_features.append(FrameDeltaDetector(delta, change_limit, frame_limit, frames))
# Sound Features
elif feature_id == 'SoundPeakDetector':
audio_threshold = feature['audio_threshold']
all_features.append(SoundPeakDetector(audio_threshold, frames))
elif feature_id == 'HighVolumeDetector':
volume = feature['volume']
frame_limit = feature['frame_limit']
all_features.append(HighVolumeDetector(volume, frame_limit, frames))
elif feature_id == 'SoundDeltaDetector':
delta = feature['delta']
frame_limit = feature['frame_limit']
change_limit = feature['scene_change_limit']
all_features.append(SoundDeltaDetector(delta, change_limit, frame_limit, frames))
# Subtitle Features
elif feature_id == 'SubtitleDensityDetector':
char_count = feature['char_count']
all_features.append(SubtitleDensityDetector(char_count, frames))
elif feature_id == 'SubtitleIntensityDetector':
char_count = feature['char_count']
intensity_char = feature['intensity_char']
all_features.append(SubtitleIntensityDetector(intensity_char, char_count, frames))
elif feature_id == 'SubtitleConversationCount':
conversation_count = feature['conversation_count']
all_features.append(SubtitleConversationCount(conversation_count, frames))
director = FeatureDirector(genre, timedelta(seconds=max_length), all_features)
return director
<file_sep>import numpy as np
class SoundUtil:
@staticmethod
def get_volume_of_frame(frame) -> bool:
return np.sqrt((frame.audio * 1.0) ** 2).mean()
<file_sep>from unittest import TestCase, mock
import numpy as np
from lafontaine.feature_director.features.image.frame_delta_detector import FrameDeltaDetector
from lafontaine.feature_director.features.image.color_counter import ColorCounter
class TestFeatureDirector(TestCase):
def test_can_get_unique_colors(self):
with mock.patch('lafontaine.helpers.frame.Frame') as mock_frame:
mock_frame.image = np.array(
[[[2, 4, 2], [5, 5, 1], [9, 2, 1]],
[[2, 4, 2], [5, 5, 1], [9, 2, 2]]]
)
unique_colors = ColorCounter.get_unique_colors(mock_frame)
self.assertEqual(len(unique_colors), 4)
def test_can_calculate_frame_image_delta(self):
with mock.patch('lafontaine.helpers.frame.Frame') as mock_frame1, mock.patch('lafontaine.helpers.frame.Frame') as mock_frame2:
mock_frame1.image = np.array(
[[[2, 4, 2], [5, 5, 1], [9, 2, 1]],
[[2, 4, 2], [5, 5, 1], [9, 2, 2]]]
)
mock_frame2.image = np.array(
[[[2, 4, 2], [5, 5, 1], [10, 2, 1]],
[[2, 4, 2], [5, 5, 1], [9, 2, 2]]]
)
delta = FrameDeltaDetector.calculate_delta(mock_frame1, mock_frame2)
self.assertEqual(delta, 0.05555555555555555)
<file_sep>import numpy as np
from lafontaine.feature_director.feature.single_frame_feature import SingleFrameFeature
from lafontaine.feature_director.feature_result.single_frame_feature_result import SingleFrameFeatureResult
from lafontaine.helpers.frame import Frame
class ColorCounter(SingleFrameFeature):
def __init__(self, color_count, frames):
self.color_count = color_count
super().__init__('ColorCounter', frames)
@staticmethod
def get_unique_colors(frame):
return np.unique(frame.image.reshape(-1, frame.image.shape[2]), axis=0)
def check_feature(self, frame: Frame):
unique_colors = self.get_unique_colors(frame)
frame_color_count = len(unique_colors)
return SingleFrameFeatureResult(frame_color_count >= self.color_count, self.frames, self.feature_id)
<file_sep>import numpy as np
from lafontaine.helpers.frame import Frame
from lafontaine.feature_director.feature.continuous_feature import ContinuousFeature
from lafontaine.feature_director.feature_result.continuous_frame_result import ContinuousFrameResult
class SoundDeltaDetector(ContinuousFeature):
def __init__(self, delta, frame_change_limit, frame_limit, frames):
self.delta = delta
self.previous_frame = None
self.counting = False
self.candidate_frames = []
self.frame_limit = frame_limit
self.count = frame_limit
self.frame_change_limit = frame_change_limit
self.frame_change_amount = frame_change_limit
super().__init__('SoundDeltaDetector', frames)
@staticmethod
def calculate_delta(frame1: Frame, frame2: Frame):
return np.mean(frame1.audio != frame2.audio)
def check_feature(self, frame):
if self.previous_frame is None:
self.previous_frame = frame
return ContinuousFrameResult(False, self.frames, self.feature_id, self.candidate_frames)
if self.counting:
self.candidate_frames.append(frame)
delta = self.calculate_delta(self.previous_frame, frame)
if delta >= self.delta:
self.frame_change_amount -= 1
if self.frame_change_amount <= 0:
self.frame_change_amount = self.frame_change_limit
self.counting = False
frames = self.candidate_frames
self.candidate_frames = []
return ContinuousFrameResult(True, self.frames, self.feature_id, frames)
self.count -= 1
if self.count <= 0:
self.counting = False
self.candidate_frames = []
self.previous_frame = frame
return ContinuousFrameResult(False, self.frames, self.feature_id, self.candidate_frames)
delta = self.calculate_delta(self.previous_frame, frame)
if delta >= self.delta:
self.candidate_frames.append(frame)
self.counting = True
self.count = self.frame_limit
self.previous_frame = frame
return ContinuousFrameResult(False, self.frames, self.feature_id, self.candidate_frames)
| f7488ac65333d6c485aff67b66aede1e45eccd84 | [
"Markdown",
"Python",
"Text"
] | 26 | Python | havingfun/LaFontaine | b554df9bcec1bc23ff2fcb6c315351d0fa9c23a1 | 60fc35693a7095d7da51ccdbbc11ab3c9e636467 |
refs/heads/master | <repo_name>cloudfelipe/ExampleCI<file_sep>/example/simple.js
/*
* AppempresarialesExampleCI
* https://github.com/cloudfelipe/appempresarialesexampleci
*
* Copyright (c) 2015 Felipeco & <NAME>
* Licensed under the MIT license.
*/
'use strict';
var appempresarialesexampleci = require('../');
console.log(appempresarialesexampleci()); // "awesome"
<file_sep>/test/appempresarialesexampleci_test.js
'use strict';
var appempresarialesexampleci = require('../');
var assert = require('should');
describe('appempresarialesexampleci', function () {
it('should be awesome', function () {
appempresarialesexampleci().should.equal('awesome');
});
});
<file_sep>/lib/appempresarialesexampleci.js
/*
* AppempresarialesExampleCI
* https://github.com/cloudfelipe/appempresarialesexampleci
*
* Copyright (c) 2015 Felipeco & <NAME>
* Licensed under the MIT license.
*/
'use strict';
module.exports = function() {
return 'awesome';
};
| 81aeb9d9e4aec52f5d4d0aba67ebb5d51893295f | [
"JavaScript"
] | 3 | JavaScript | cloudfelipe/ExampleCI | 561f6fe9e3ba75c476878e06fc865c7a92cca136 | 126bb6aec997155e8df0c82663d308af4264127b |
refs/heads/master | <repo_name>jonasrains/SMOB3_Python<file_sep>/cappy.py
import pygame
import collision
import json
json_data = open('hitboxes.json').read()
hitboxes = json.loads(json_data)
print(hitboxes)
image = pygame.image.load(r'./images/game elements/cappy/1.png')
images = {'mario':[], 'luigi':[]}
thrown = False
def load_images():
global images
for i in range(8):
images['mario'] += [pygame.image.load(r'./images/game elements/mario/' + str(i+1) + '.png').convert_alpha()]
def throw(player='mario'):
global thrown
if thrown:
print('')
def update(player='mario'):
global thrown
<file_sep>/mario.py
import pygame
import math
import collision
import json
import cappy
json_data = open('hitboxes.json').read()
hitboxes = json.loads(json_data)
print(hitboxes)
direction = 90
ground_hitbox = []
xpos = 0
ypos = 0
yoffset = 0
frame = 1
running = False
walk_anim = 1
max_speed = 3
velocity = 0
image = pygame.image.load(r'./images/game elements/mario/1.png')
images = []
jumping = False
jump_rep = 0
jump_height = 20
up_released = False
falling = False
crouching = False
world = 0
level = 0
def load_images():
global images
for i in range(54):
images += [pygame.image.load(r'./images/game elements/mario/' + str(i+1) + '.png').convert_alpha()]
def enter_level(w, l):
global running, xpos, ypos, ground_hitbox, world, level
world = w
level = l
load_images()
cappy.load_images()
running = True
ground_hitbox = hitboxes['ground'][str(world) + '-' + str(level)]
print(ground_hitbox)
if world == 1 and level == 1:
xpos = 16
ypos = 0 # 280
def touch_ground():
return collision.collision([[xpos - 16, xpos + 16], [ypos - 32, ypos + 22]], hitboxes['ground'][str(world) + '-' + str(level)])
def touch_semisolid():
for i in hitboxes['semisolid'][str(world) + '-' + str(level)]:
collide = collision.collision([[xpos - 16, xpos + 16], [ypos + 20, ypos + 22]], i)
if collide[0]:
return collide
return [False, []]
def touch_ceiling():
return collision.collision([[xpos - 16, xpos + 16], [ypos - 32, ypos - 30]], hitboxes['ground'][str(world) + '-' + str(level)])
def crouch(down_pressed):
global crouching
if down_pressed and on_ground():
crouching = True
elif not down_pressed:
if on_ground():
crouching = False
def on_ground():
return(touch_ground()[1] or touch_semisolid()[0])
def jump(up_pressed):
global ypos, jumping, jump_rep, jump_height, up_released
ypos += 1
jump_rep += 1
if (up_pressed and not jumping) and on_ground():
jumping = True
jump_rep = 0
jump_height = 20
up_released = False
ypos -= 1
if jumping and jump_rep < jump_height + 3:
if not up_pressed and not up_released:
jump_height = jump_rep
up_released = True
if jump_rep < jump_height:
for i in range(3 + round(jump_rep / 2)):
if not touch_ceiling()[0]:
ypos -= 1
else:
if not touch_ceiling()[0]:
ypos -= (jump_rep - jump_height - 1)
if touch_ceiling()[0]:
ypos += 1
jumping = False
else:
jumping = False
def update(left_pressed, right_pressed, up_pressed, down_pressed):
global image, frame, walk_anim, velocity, frame, direction, xpos, ypos, falling, yoffset
falling = False
crouch(down_pressed)
while (touch_ground()[0] and 2 not in touch_ground()[1]) or (touch_semisolid()[0] and 2 not in touch_semisolid()[1]) and not jumping:
ypos -= 1
ypos += 1
if not (right_pressed and left_pressed) and (not crouching or (crouching and not on_ground())):
if right_pressed or left_pressed:
if on_ground():
if walk_anim > 24:
walk_anim = 1
else:
walk_anim += 1
else:
falling = True
walk_anim = 18
else:
if not math.ceil(walk_anim) / 6 == 1:
if on_ground():
if walk_anim > 24:
walk_anim = 1
else:
walk_anim += 1
if not on_ground():
falling = True
walk_anim = 18
if right_pressed:
direction = 90
if velocity < max_speed:
velocity += .2
else:
velocity = max_speed
elif left_pressed:
direction = -90
if velocity > - max_speed:
velocity -= .2
else:
velocity = - max_speed
else:
velocity = velocity * .8
else:
if not math.ceil(walk_anim) / 6 == 1:
if on_ground():
if walk_anim > 24:
walk_anim = 1
else:
walk_anim += 1
if not on_ground():
falling = True
walk_anim = 18
velocity = velocity * .8
if abs(velocity) < .02:
velocity = 0
ypos -= 2
if 2 not in touch_ground()[1]:
xpos += velocity
if 2 in touch_ground()[1]:
while 2 in touch_ground()[1]:
if velocity != 0:
xpos = xpos - (abs(velocity)/velocity)
velocity = 0
ypos += 1
jump(up_pressed)
if not jumping:
for i in range(6):
if not on_ground():
ypos += 1
if crouching:
yoffset = 20
frame = 5
else:
yoffset = 0
if jumping:
frame = 4
elif falling:
frame = 3
elif ((velocity < 0 and right_pressed) or (velocity > 0 and left_pressed)) and not(left_pressed and right_pressed):
frame = 6
else:
if math.ceil(walk_anim / 6) == 1:
frame = 1
elif math.ceil(walk_anim / 6) == 2 or math.ceil(walk_anim / 6) == 4:
frame = 2
elif math.ceil(walk_anim / 6) == 3:
frame = 3
image = images[frame - 1]<file_sep>/collision_v2.py
def collision():
# [left, right, top, bottom]
col_type = [False, False, False, False]
# hb2 must be split into multiple parts that get loaded at different times to decrease running speed
# first entry in each area is the start x and end x. used to determine which areas need to be loaded
hb2 = [[[0, 704], [0, 0], [0, 339], [704, 339], [704, 243]], [[704, 1246], [704, 243], [768, 243], [768, 339],[1246, 339]], [[1246, 2048], [1246, 307], [2048, 307], [2048, 0], [2048, 500], [0, 500]]]
# hb1 is in [[start x, end x], [start y, end y], [center x, center y]]
hb1 = [[0, 32], [0, 64], [16, 32]]
# go through hb2, find out which area to test for then go through all the lines in that area
i = 0
for area in hb2:
# tests if line goes through the hit-box area
if area[0][0] - 5 <= hb1[2][0] <= area[0][1]:
ii = 0
for point in area:
next_point = area[i+1]
# the first point in each area is the min and max x, so it gets skipped here
if i == 0:
continue
# tests if any lines are with in the range of the hit-box, and sets the corresponding index in col_type to true if it is
if point[0]-5 <= hb1[0][0] <= next_point[0]+5 and point[0]-5 <= hb1[2][0] <= next_point[0]+5:
col_type[0] = True
if point[0]-5 <= hb1[0][1] <= next_point[0]+5 and point[0]-5 <= hb1[2][0] <= next_point[0]+5:
col_type[1] = True
if point[1]-5 <= hb1[1][0] <= next_point[1]+5 and point[0]-5 <= hb1[2][1] <= next_point[0]+5:
col_type[2] = True
if point[1]-5 <= hb1[1][1] <= next_point[1]+5 and point[0]-5 <= hb1[2][1] <= next_point[0]+5:
col_type[3] = True
ii += 1
# continues if player is not in the area's range
else:
continue
i += 1
# return value of col_type
return col_type
# collisions: if both sides and/or the bottom are colliding with something, it is solid ground, if one side and bottom collide then it is a slope. both sides and top are colliding then it is a ceiling hit
<file_sep>/README.md
# SMOB3_Python
This is an attempt to port my game to python
Nintendo owns the copyright to Super Mario Bros. 3 and Super Mario Odyssey. This is just a fan game that I am working on that combines the two
[](https://repl.it/@juliarains/SMOB3Python#README.md)
This requires pygame to run, https://www.pygame.org/
<file_sep>/main.py
import pygame
import mario
pygame.init()
display = pygame.display.set_mode((512, 480))
pygame.display.set_caption('Super Mario Odyssey Bros. 3')
pygame.display.set_icon(pygame.image.load(r'./images/icon.png'))
clock = pygame.time.Clock()
pygame.font.init()
areas = 4
running = True
camx = 0
camx_min = 256
camx_max = 256 + (areas - 1) * 512
camy = 0
camy_min = 186
camy_max = -(186 + 2 * 372)
screen = 'title'
world = 1
level = 1
right_pressed = False
left_pressed = False
up_pressed = False
down_pressed = False
area_imgs = []
border = pygame.image.load(r'./images/game elements/bottom border.png')
def load_background():
global area_imgs
area_imgs = []
for area in range(areas):
area_imgs += [pygame.image.load(r'./images/game elements/ground/world ' + str(world) + '/level ' + str(level) + '/' + str(area + 1) + '.png').convert_alpha()]
def center_camera():
global camx, camy, camx_min, camx_max, camy_min, camy_min
marx = (round(mario.xpos / 2) - 8) * 2
mary = (round(mario.ypos / 2) - 16) * 2
if marx < camx_min:
camx = camx_min
elif marx > camx_max:
camx = camx_max
else:
camx = marx
if mary > camy_min:
camy = camy_min
elif mary < camy_max:
camy = camy_max
else:
camy = mary
mario.enter_level(world, level)
load_background()
while running:
display.fill((182, 229, 235))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_RIGHT:
right_pressed = True
if event.key == pygame.K_LEFT:
left_pressed = True
if event.key == pygame.K_UP:
up_pressed = True
if event.key == pygame.K_DOWN:
down_pressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
right_pressed = False
if event.key == pygame.K_LEFT:
left_pressed = False
if event.key == pygame.K_UP:
up_pressed = False
if event.key == pygame.K_DOWN:
down_pressed = False
if event.type == pygame.MOUSEMOTION:
mouse_position = pygame.mouse.get_pos()
print(str(-(-mouse_position[0] - camx + 256)) + ', ' + str(-(-mouse_position[1] - camy + 186)))
mario.update(left_pressed, right_pressed, up_pressed, down_pressed)
center_camera()
for area in range(areas):
image = area_imgs[area]
display.blit(image, ((area * 512)-camx + 256, -camy + 186))
marx = (round(mario.xpos / 2) - 8) * 2
mary = (round(mario.ypos / 2) - 16) * 2
if mario.direction == 90:
display.blit(mario.image, (marx - camx + 256, mary - camy + 186 + mario.yoffset))
else:
display.blit(pygame.transform.flip(mario.image, True, False), (marx - camx + 256, mary - camy + 186 + mario.yoffset))
display.blit(border, (0, 0))
display.blit(border, (0, -1))
pygame.display.update()
clock.tick(60)
pygame.quit()
<file_sep>/collision.py
def collision(hitbox1_points, hitbox2_points):
boollist1 = []
collision_type = []
for point in range(len(hitbox2_points)):
point1 = hitbox2_points[point]
if point == len(hitbox2_points) -1:
point2 = hitbox2_points[0]
else:
point2 = hitbox2_points[point + 1]
if (((point1[0] > sum(hitbox1_points[0]) / 2 - 768) and (point1[0] < sum(hitbox1_points[0]) / 2 + 768)) or (point2[0] > sum(hitbox1_points[0]) / 2 - 768) and (point2[0] < sum(hitbox1_points[0]) / 2 + 768)) and (((point1[1] > sum(hitbox1_points[1]) / 2 - 720) and (point1[1] < sum(hitbox1_points[1]) / 2 + 720)) or ((point2[1] > sum(hitbox1_points[1]) / 2 - 720) and (point2[1] < sum(hitbox1_points[1]) / 2 + 720))):
if point1[0] != point2[0]:
m = (point2[1] - point1[1]) / (point2[0] - point1[0])
else:
m = 'undefined'
if m != 'undefined':
b = point1[1] - (m * point1[0])
else:
b = 'undefined'
boollist2 = []
if m != 'undefined':
if m != 0:
if (point1[0] < hitbox1_points[0][0] < point2[0] or point1[0] < hitbox1_points[0][1] < point2[0]) and (point1[1] > hitbox1_points[1][0] > point2[1] or point1[1] > hitbox1_points[1][1] > point2[1]):
for i in range(round(abs(point2[0] - point1[0]))):
x = point1[0] + (abs((point2[0] - point1[0])) / (point2[0] - point1[0])) * i
y = m * x + b
boollist2.append((hitbox1_points[0][0] < x < hitbox1_points[0][1]) and (hitbox1_points[1][0] < y < hitbox1_points[1][1]))
if(hitbox1_points[0][0] < x < hitbox1_points[0][1]) and (hitbox1_points[1][0] < y < hitbox1_points[1][1]):
if 1 not in collision_type:
collision_type += [1]
if m == 0:
boollist2.append((point1[0] < hitbox1_points[0][0] < point2[0] or point1[0] < hitbox1_points[0][1] < point2[0]) and (hitbox1_points[1][0] < point1[1] < hitbox1_points[1][1]))
if(point1[0] < hitbox1_points[0][0] < point2[0] or point1[0] < hitbox1_points[0][1] < point2[0]) and (hitbox1_points[1][0] < point1[1] < hitbox1_points[1][1]):
if 1 not in collision_type:
collision_type += [1]
else:
boollist2.append(hitbox1_points[0][0] < point1[0] < hitbox1_points[0][1]
and (((point1[1] < hitbox1_points[1][0] < point2[1]) or (point1[1] < hitbox1_points[1][1] < point2[1]))
or ((point1[1] > hitbox1_points[1][0] > point2[1]) or (point1[1] > hitbox1_points[1][1] > point2[1]))))
if(hitbox1_points[0][0] < point1[0] < hitbox1_points[0][1]
and (((point1[1] < hitbox1_points[1][0] < point2[1]) or (point1[1] < hitbox1_points[1][1] < point2[1]))
or ((point1[1] > hitbox1_points[1][0] > point2[1]) or (point1[1] > hitbox1_points[1][1] > point2[1])))):
if 2 not in collision_type:
collision_type += [2]
boollist1.append(True in boollist2)
return [True in boollist1, collision_type]
| 7882b5c4dd5aed70e64156d4e6a6037e87b6044a | [
"Markdown",
"Python"
] | 6 | Python | jonasrains/SMOB3_Python | 280f9d8857c4fe551646a1c2de7b5c2f6eee67ce | 8bca5d5b0cab8c672d300a5f5854abd4f17db9c0 |
refs/heads/master | <repo_name>dp88/go-sdl2<file_sep>/sdl/error.go
package sdl
// #include "sdl_wrapper.h"
import "C"
import "errors"
const (
ENOMEM = C.SDL_ENOMEM
EFREAD = C.SDL_EFREAD
EFWRITE = C.SDL_EFWRITE
EFSEEK = C.SDL_EFSEEK
UNSUPPORTED = C.SDL_UNSUPPORTED
LASTERROR = C.SDL_LASTERROR
)
type ErrorCode uint
func (ec ErrorCode) c() C.SDL_errorcode {
return C.SDL_errorcode(ec)
}
// GetError (https://wiki.libsdl.org/SDL_GetError)
func GetError() error {
_err := C.SDL_GetError()
if *_err == 0 {
return nil
}
return errors.New(C.GoString(_err))
}
// ClearError (https://wiki.libsdl.org/SDL_ClearError)
func ClearError() {
C.SDL_ClearError()
}
func Error(code ErrorCode) {
C.SDL_Error(code.c())
}
func OutOfMemory() {
Error(ENOMEM)
}
func Unsupported() {
Error(UNSUPPORTED)
}
<file_sep>/sdl/version.go
package sdl
// #include "sdl_wrapper.h"
import "C"
import "unsafe"
const (
MAJOR_VERSION = C.SDL_MAJOR_VERSION
MINOR_VERSION = C.SDL_MINOR_VERSION
PATCHLEVEL = C.SDL_PATCHLEVEL
)
// Version (https://wiki.libsdl.org/SDL_Version)
type Version struct {
Major uint8
Minor uint8
Patch uint8
}
func (v *Version) cptr() *C.SDL_version {
return (*C.SDL_version)(unsafe.Pointer(v))
}
// VERSION (https://wiki.libsdl.org/SDL_VERSION)
func VERSION(version *Version) {
version.Major = MAJOR_VERSION
version.Minor = MINOR_VERSION
version.Patch = PATCHLEVEL
}
// VERSIONNUM (https://wiki.libsdl.org/SDL_VERSIONNUM)
func VERSIONNUM(x, y, z int) int {
return (x*1000 + y*100 + z)
}
// COMPILEDVERSION (https://wiki.libsdl.org/SDL_COMPILEDVERSION)
func COMPILEDVERSION() int {
return VERSIONNUM(MAJOR_VERSION, MINOR_VERSION, PATCHLEVEL)
}
// VERSION_ATLEAST (https://wiki.libsdl.org/SDL_VERSION_ATLEAST)
func VERSION_ATLEAST(x, y, z int) bool {
return COMPILEDVERSION() >= VERSIONNUM(x, y, z)
}
// GetVersion (https://wiki.libsdl.org/SDL_GetVersion)
func GetVersion(v *Version) {
C.SDL_GetVersion(v.cptr())
}
// GetRevision (https://wiki.libsdl.org/SDL_GetRevision)
func GetRevision() string {
return (string)(C.GoString(C.SDL_GetRevision()))
}
// GetRevisionNumber (https://wiki.libsdl.org/SDL_GetRevisionNumber)
func GetRevisionNumber() int {
return (int)(C.SDL_GetRevisionNumber())
}
<file_sep>/sdl/surface.go
package sdl
/*
#include "sdl_wrapper.h"
*/
import "C"
import "unsafe"
import "reflect"
const (
SWSURFACE = C.SDL_SWSURFACE
PREALLOC = C.SDL_PREALLOC
RLEACCEL = C.SDL_RLEACCEL
DONTFREE = C.SDL_DONTFREE
)
// Surface (https://wiki.libsdl.org/SDL_Surface)
type Surface struct {
Flags uint32
Format *PixelFormat
W int32
H int32
Pitch int
pixels unsafe.Pointer // use Pixels() for access
UserData unsafe.Pointer
Locked int
LockData unsafe.Pointer
ClipRect Rect
_map *[0]byte
RefCount int
}
type blit C.SDL_blit
func (surface *Surface) cptr() *C.SDL_Surface {
return (*C.SDL_Surface)(unsafe.Pointer(surface))
}
// Surface (https://wiki.libsdl.org/SDL_MustLock)
func (surface *Surface) MustLock() bool {
return (surface.Flags & RLEACCEL) != 0
}
// CreateRGBSurface (https://wiki.libsdl.org/SDL_CreateRGBSurface)
func CreateRGBSurface(flags uint32, width, height, depth int32, Rmask, Gmask, Bmask, Amask uint32) *Surface {
return (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurface(C.Uint32(flags),
C.int(width),
C.int(height),
C.int(depth),
C.Uint32(Rmask),
C.Uint32(Gmask),
C.Uint32(Bmask),
C.Uint32(Amask))))
}
// CreateRGBSurfaceFrom (https://wiki.libsdl.org/SDL_CreateRGBSurfaceFrom)
func CreateRGBSurfaceFrom(pixels unsafe.Pointer, width, height, depth, pitch int, Rmask, Gmask, Bmask, Amask uint32) *Surface {
return (*Surface)(unsafe.Pointer(C.SDL_CreateRGBSurfaceFrom(pixels,
C.int(width),
C.int(height),
C.int(depth),
C.int(pitch),
C.Uint32(Rmask),
C.Uint32(Gmask),
C.Uint32(Bmask),
C.Uint32(Amask))))
}
// Surface (https://wiki.libsdl.org/SDL_FreeSurface)
func (surface *Surface) Free() {
C.SDL_FreeSurface(surface.cptr())
}
// Surface (https://wiki.libsdl.org/SDL_SetSurfacePalette)
func (surface *Surface) SetPalette(palette *Palette) int {
return int(C.SDL_SetSurfacePalette(surface.cptr(), palette.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_LockSurface)
func (surface *Surface) Lock() {
C.SDL_LockSurface(surface.cptr())
}
// Surface (https://wiki.libsdl.org/SDL_UnlockSurface)
func (surface *Surface) Unlock() {
C.SDL_UnlockSurface(surface.cptr())
}
// LoadBMP_RW (https://wiki.libsdl.org/SDL_LoadBMP_RW)
func LoadBMP_RW(src *RWops, freeSrc int) *Surface {
_surface := C.SDL_LoadBMP_RW(src.cptr(), C.int(freeSrc))
return (*Surface)(unsafe.Pointer(_surface))
}
// LoadBMP (https://wiki.libsdl.org/SDL_LoadBMP)
func LoadBMP(file string) *Surface {
return (*Surface)(LoadBMP_RW(RWFromFile(file, "rb"), 1))
}
// Surface (https://wiki.libsdl.org/SDL_SaveBMP_RW)
func (surface *Surface) SaveBMP_RW(dst *RWops, freeDst int) int {
return int(C.SDL_SaveBMP_RW(surface.cptr(), dst.cptr(), C.int(freeDst)))
}
// Surface (https://wiki.libsdl.org/SDL_SaveBMP)
func (surface *Surface) SaveBMP(file string) int {
return int(surface.SaveBMP_RW(RWFromFile(file, "wb"), 1))
}
// Surface (https://wiki.libsdl.org/SDL_SetSurfaceRLE)
func (surface *Surface) SetRLE(flag int) int {
return int(C.SDL_SetSurfaceRLE(surface.cptr(), C.int(flag)))
}
// Surface (https://wiki.libsdl.org/SDL_SetColorKey)
func (surface *Surface) SetColorKey(flag int, key uint32) int {
return int(C.SDL_SetColorKey(surface.cptr(), C.int(flag), C.Uint32(key)))
}
// Surface (https://wiki.libsdl.org/SDL_GetColorKey)
func (surface *Surface) GetColorKey() (key uint32, status int) {
_key := (*C.Uint32)(unsafe.Pointer(&key))
status = int(C.SDL_GetColorKey(surface.cptr(), _key))
return key, status
}
// Surface (https://wiki.libsdl.org/SDL_SetSurfaceColorMod)
func (surface *Surface) SetColorMod(r, g, b uint8) int {
return int(C.SDL_SetSurfaceColorMod(surface.cptr(), C.Uint8(r), C.Uint8(g), C.Uint8(b)))
}
// Surface (https://wiki.libsdl.org/SDL_GetSurfaceColorMod)
func (surface *Surface) GetColorMod() (r, g, b uint8, status int) {
_r := (*C.Uint8)(unsafe.Pointer(&r))
_g := (*C.Uint8)(unsafe.Pointer(&g))
_b := (*C.Uint8)(unsafe.Pointer(&b))
status = int(C.SDL_GetSurfaceColorMod(surface.cptr(), _r, _g, _b))
return r, g, b, status
}
// Surface (https://wiki.libsdl.org/SDL_SetSurfaceAlphaMod)
func (surface *Surface) SetAlphaMod(alpha uint8) int {
return int(C.SDL_SetSurfaceAlphaMod(surface.cptr(), C.Uint8(alpha)))
}
// Surface (https://wiki.libsdl.org/SDL_GetSurfaceAlphaMod)
func (surface *Surface) GetAlphaMod() (alpha uint8, status int) {
_alpha := (*C.Uint8)(unsafe.Pointer(&alpha))
status = int(C.SDL_GetSurfaceAlphaMod(surface.cptr(), _alpha))
return alpha, status
}
// Surface (https://wiki.libsdl.org/SDL_SetSurfaceBlendMode)
func (surface *Surface) SetBlendMode(bm BlendMode) int {
return int(C.SDL_SetSurfaceBlendMode(surface.cptr(), bm.c()))
}
// Surface (https://wiki.libsdl.org/SDL_GetSurfaceBlendMode)
func (surface *Surface) GetBlendMode() (bm BlendMode, status int) {
status = int(C.SDL_GetSurfaceBlendMode(surface.cptr(), bm.cptr()))
return bm, status
}
// Surface (https://wiki.libsdl.org/SDL_SetClipRect)
func (surface *Surface) SetClipRect(rect *Rect) bool {
return C.SDL_SetClipRect(surface.cptr(), rect.cptr()) > 0
}
// Surface (https://wiki.libsdl.org/SDL_GetClipRect)
func (surface *Surface) GetClipRect(rect *Rect) {
C.SDL_GetClipRect(surface.cptr(), rect.cptr())
}
// Surface (https://wiki.libsdl.org/SDL_ConvertSurface)
func (surface *Surface) Convert(fmt *PixelFormat, flags uint32) *Surface {
_surface := C.SDL_ConvertSurface(surface.cptr(), fmt.cptr(), C.Uint32(flags))
return (*Surface)(unsafe.Pointer(_surface))
}
// Surface (https://wiki.libsdl.org/SDL_ConvertSurfaceFormat)
func (surface *Surface) ConvertFormat(pixelFormat uint32, flags uint32) *Surface {
return (*Surface)(unsafe.Pointer(C.SDL_ConvertSurfaceFormat(surface.cptr(), C.Uint32(pixelFormat), C.Uint32(flags))))
}
// ConvertPixels (https://wiki.libsdl.org/SDL_ConvertPixels)
func ConvertPixels(width, height int, srcFormat uint32, src unsafe.Pointer, srcPitch int,
dstFormat uint32, dst unsafe.Pointer, dstPitch int) int {
return int(C.SDL_ConvertPixels(C.int(width), C.int(height), C.Uint32(srcFormat), src, C.int(srcPitch), C.Uint32(dstFormat), dst, C.int(dstPitch)))
}
// Surface (https://wiki.libsdl.org/SDL_FillRect)
func (surface *Surface) FillRect(rect *Rect, color uint32) int {
return int(C.SDL_FillRect(surface.cptr(), rect.cptr(), C.Uint32(color)))
}
// Surface (https://wiki.libsdl.org/SDL_FillRects)
func (surface *Surface) FillRects(rects []Rect, color uint32) int {
return int(C.SDL_FillRects(surface.cptr(), rects[0].cptr(), C.int(len(rects)), C.Uint32(color)))
}
// Surface (https://wiki.libsdl.org/SDL_BlitSurface)
func (src *Surface) Blit(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_BlitSurface(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_BlitScaled)
func (src *Surface) BlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_BlitScaled(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_UpperBlit)
func (src *Surface) UpperBlit(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_UpperBlit(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_LowerBlit)
func (src *Surface) LowerBlit(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_LowerBlit(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_SoftStretch)
func (src *Surface) SoftStretch(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_SoftStretch(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_UpperBlitScaled)
func (src *Surface) UpperBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_UpperBlitScaled(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
// Surface (https://wiki.libsdl.org/SDL_LowerBlitScaled)
func (src *Surface) LowerBlitScaled(srcRect *Rect, dst *Surface, dstRect *Rect) int {
return int(C.SDL_LowerBlitScaled(src.cptr(), srcRect.cptr(), dst.cptr(), dstRect.cptr()))
}
func (surface *Surface) PixelNum() int {
return int(surface.W * surface.H)
}
func (surface *Surface) BytesPerPixel() int {
return int(surface.Format.BytesPerPixel)
}
func (surface *Surface) Pixels() []byte {
var b []byte
length := int(surface.W*surface.H) * int(surface.Format.BytesPerPixel)
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sliceHeader.Cap = int(length)
sliceHeader.Len = int(length)
sliceHeader.Data = uintptr(surface.pixels)
return b
}
func (surface *Surface) Data() unsafe.Pointer {
return surface.pixels
}
| 773d122650d1d332c5c82e0382c297c56eca2c54 | [
"Go"
] | 3 | Go | dp88/go-sdl2 | ba04864cac0b3a3a4931fd9af4da17ead82ec56a | 81fb21caf90ae91954f378a44209ba809df01a4e |
refs/heads/master | <repo_name>Jarrott/Jian<file_sep>/jian/redprint.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
class Redprint:
def __init__(self, name, with_prefix=True):
self.name = name
self.with_prefix = with_prefix
self.mound = []
def route(self, rule, **options):
def decorator(f):
self.mound.append((f, rule, options))
return f
return decorator
def register(self, bp, url_prefix=None):
if url_prefix is None and self.with_prefix:
url_prefix = '/' + self.name
else:
url_prefix = ''
for f, rule, options in self.mound:
endpoint = self.name + '+' + options.pop("endpoint", f.__name__)
if rule:
url = url_prefix + rule
bp.add_url_rule(url, endpoint, f, **options)
else:
bp.add_url_rule(url_prefix, endpoint, f, **options)
<file_sep>/jian/jwt.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from functools import wraps
from flask_jwt_extended import JWTManager, verify_jwt_in_request, get_current_user, create_access_token, \
create_refresh_token
from .exception import AuthFailed, InvalidTokenException, ExpiredTokenException, NotFound
jwt = JWTManager()
def admin_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
verify_jwt_in_request()
current_user = get_current_user()
if not current_user.is_super:
raise AuthFailed(msg='只有超级管理员可操作')
return fn(*args, **kwargs)
return wrapper
def group_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
verify_jwt_in_request()
current_user = get_current_user()
# check current user is active or not
# 判断当前用户是否为激活状态
if not current_user.is_active:
raise AuthFailed(msg='您目前处于未激活状态,请联系超级管理员')
# not super
if not current_user.is_super:
group_id = current_user.group_id
if group_id is None:
raise AuthFailed(msg='您还不属于任何权限组,请联系超级管理员获得权限')
from .core import is_user_allowed
it = is_user_allowed(group_id)
if not it:
raise AuthFailed(msg='权限不够,请联系超级管理员获得权限')
else:
return fn(*args, **kwargs)
else:
return fn(*args, **kwargs)
return wrapper
def login_required(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
verify_jwt_in_request()
return fn(*args, **kwargs)
return wrapper
@jwt.user_loader_callback_loader
def user_loader_callback(identity):
from .core import find_user
# token is granted , user must be exit
# 如果token已经被颁发,则该用户一定存在
user = find_user(id=identity)
if user is None:
raise NotFound(msg='用户不存在')
return user
@jwt.expired_token_loader
def expired_loader_callback():
return ExpiredTokenException()
@jwt.invalid_token_loader
def invalid_loader_callback(e):
return InvalidTokenException()
@jwt.unauthorized_loader
def unauthorized_loader_callback(e):
return AuthFailed(msg='认证失败,请检查请求头或者重新登陆')
def get_tokens(user):
access_token = create_access_token(identity=user.id)
refresh_token = create_refresh_token(identity=user.id)
return access_token, refresh_token<file_sep>/jian/loader.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from importlib import import_module
from .redprint import Redprint
from .db import db
from .plugin import Plugin
from .core import gigi_config
class Loader(object):
plugin_path: dict = None
def __init__(self, plugin_path):
self.plugins = {}
assert type(plugin_path) is dict, 'plugin_path must be a dict'
self.plugin_path = plugin_path
self.load_plugins_config()
self.load_plugins()
def load_plugins(self):
for name, conf in self.plugin_path.items():
enable = conf.get('enable', None)
if enable:
path = conf.get('path')
# load plugin
path and self._load_plugin(f'{path}.app.__init__', name)
def load_plugins_config(self):
for name, conf in self.plugin_path.items():
path = conf.get('path', None)
# load config
self._load_config(f'{path}.config', name, conf)
def _load_plugin(self, path, name):
mod = import_module(path)
plugin = Plugin(name=name)
dic = mod.__dict__
for key in dic.keys():
if not key.startswith('_'):
attr = dic[key]
if isinstance(attr, Redprint):
plugin.add_controller(attr.name, attr)
elif issubclass(attr, db.Model):
plugin.add_model(attr.__name__, attr)
# 暂时废弃加载service,用处不大
# elif issubclass(attr, ServiceInterface):
# plugin.add_service(attr.__name__, attr)
self.plugins[plugin.name] = plugin
def _load_config(self, config_path, name, conf):
default_conf = {**conf} if conf else {}
try:
if config_path:
mod = import_module(config_path)
dic = mod.__dict__
for key in dic.keys():
if not key.startswith('_'):
default_conf[key] = dic[key]
except ModuleNotFoundError as e:
pass
gigi_config.add_plugin_config(plugin_name=name, obj=default_conf)
<file_sep>/jian/notify.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from functools import wraps
import re
from datetime import datetime
from flask import Response, request
from flask_jwt_extended import get_current_user
from .sse import sser
REG_XP = r'[{](.*?)[}]'
OBJECTS = ['user', 'response', 'request']
SUCCESS_STATUS = [200, 201]
MESSAGE_EVENTS = set()
class Notify(object):
def __init__(self, template=None, event=None, **kwargs):
"""
Notify a message or create a log
:param template: message template
{user.nickname}查看自己是否为激活状态 ,状态码为{response.status_code} -> pedro查看自己是否为激活状态 ,状态码为200
:param write: write to db or not
:param push: push to front_end or not
"""
if event:
self.event = event
elif self.event is None:
raise Exception('event must not be None!')
if template:
self.template: str = template
elif self.template is None:
raise Exception('template must not be None!')
# 加入所有types中
MESSAGE_EVENTS.add(event)
self.message = ''
self.response = None
self.user = None
self.extra = kwargs
def __call__(self, func):
@wraps(func)
def wrap(*args, **kwargs):
response: Response = func(*args, **kwargs)
self.response = response
self.user = get_current_user()
self.message = self._parse_template()
self.push_message()
return response
return wrap
def push_message(self):
# status = '操作成功' if self.response.status_code in SUCCESS_STATUS else '操作失败'
sser.add_message(self.event,
{'message': self.message,
'time': int(datetime.now().timestamp()),
**self.extra
})
# 解析自定义消息的模板
def _parse_template(self):
message = self.template
total = re.findall(REG_XP, message)
for it in total:
assert '.' in it, '%s中必须包含 . ,且为一个' % it
i = it.rindex('.')
obj = it[:i]
assert obj in OBJECTS, '%s只能为user,response,request中的一个' % obj
prop = it[i + 1:]
if obj == 'user':
item = getattr(self.user, prop, '')
elif obj == 'response':
item = getattr(self.response, prop, '')
else:
item = getattr(request, prop, '')
message = message.replace('{%s}' % it, str(item))
return message
def _check_can_push(self):
# 超级管理员不可push,暂时测试可push
if self.user.is_super:
return False
return True
<file_sep>/jian/__init__.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from .core import Jian, route_meta, manager
from .db import db
from .jwt import login_required, group_required, admin_required
<file_sep>/jian/config.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from collections import defaultdict
class Config(defaultdict):
def add_plugin_config(self, plugin_name, obj):
if type(obj) is dict:
if self.get(plugin_name, None) is None:
self[plugin_name] = {}
for k, v in obj.items():
self[plugin_name][k] = v
def add_plugin_config_item(self, plugin_name, key, value):
if self.get(plugin_name, None) is None:
self[plugin_name] = {}
self[plugin_name][key] = value
def get_plugin_config(self, plugin_name, default=None):
return self.get(plugin_name, default)
def get_plugin_config_item(self, plugin_name, key, default=None):
plugin_conf = self.get(plugin_name)
if plugin_conf is None:
return default
return plugin_conf.get(key, default)
def get_config(self, key: str, default=None):
""" plugin_name.key """
if '.' not in key:
return self.get(key, default)
index = key.rindex('.')
plugin_name = key[:index]
plugin_key = key[index + 1:]
plugin_conf = self.get(plugin_name)
if plugin_conf is None:
return default
return plugin_conf.get(plugin_key, default)
<file_sep>/jian/db.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy, BaseQuery
from sqlalchemy import inspect, orm, func
from contextlib import contextmanager
from .exception import NotFound
class SQLAlchemy(_SQLAlchemy):
@contextmanager
def auto_commit(self):
try:
yield
self.session.commit()
except Exception as e:
self.session.rollback()
raise e
class Query(BaseQuery):
def filter_by(self, soft=True, **kwargs):
# soft 应用软删除
soft = kwargs.get('soft')
if soft:
kwargs['delete_time'] = None
if soft is not None:
kwargs.pop('soft')
return super(Query, self).filter_by(**kwargs)
def get_or_404(self, ident):
rv = self.get(ident)
if not rv:
raise NotFound()
return rv
def first_or_404(self):
rv = self.first()
if not rv:
raise NotFound()
return rv
db = SQLAlchemy(query_class=Query)
def get_total_nums(cls, is_soft=False, **kwargs):
nums = db.session.query(func.count(cls.id))
nums = nums.filter(cls.delete_time == None).filter_by(**kwargs).scalar() if is_soft else nums.filter().scalar()
if nums:
return nums
else:
return 0
class MixinJSONSerializer:
@orm.reconstructor
def init_on_load(self):
self._fields = []
self._exclude = []
self._set_fields()
self.__prune_fields()
def _set_fields(self):
pass
def __prune_fields(self):
columns = inspect(self.__class__).columns
if not self._fields:
all_columns = set([column.name for column in columns])
self._fields = list(all_columns - set(self._exclude))
def hide(self, *args):
for key in args:
self._fields.remove(key)
return self
def keys(self):
return self._fields
def __getitem__(self, key):
return getattr(self, key)
<file_sep>/jian/forma.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/07/03 <https://7yue.in>
"""
from flask import request
from wtforms import Form as WTForm, IntegerField
from wtforms.validators import StopValidation
from .exception import ParameterException
class Form(WTForm):
def __init__(self):
data = request.get_json(silent=True)
args = request.args.to_dict()
super(Form, self).__init__(data=data, **args)
def validate_for_api(self):
valid = super(Form, self).validate()
if not valid:
raise ParameterException(msg=self.errors)
return self
def integer_check(form, field):
if field.data is None:
raise StopValidation('输入字段不可为空')
try:
field.data = int(field.data)
except ValueError:
raise StopValidation('不是一个有效整数')
class JianIntegerField(IntegerField):
"""
校验一个字段是否为正整数
"""
def __init__(self, label=None, validators=None, **kwargs):
if validators is not None and type(validators) == list:
validators.insert(0, integer_check)
else:
validators = [integer_check]
super(JianIntegerField, self).__init__(label, validators, **kwargs)<file_sep>/README.md
<h4 align="center">Jian (简单)</h4>
<p align="center">
<a href="http://flask.pocoo.org/docs/1.0/" rel="nofollow">
<img src="https://img.shields.io/badge/Flask-1.0.2-green.svg" alt="flask version" data-canonical-src="https://img.shields.io/badge/Flask-1.0.2-green.svg" style="max-width:100%;"></a>
<a href="https://www.python.org" rel="nofollow"><img src="https://img.shields.io/badge/Python-%3E3.5-yellowgreen.svg" alt="Python version" data-canonical-src="https://img.shields.io/badge/Python-%3E3.5-yellowgreen.svg" style="max-width:100%;"></a>
</p>
<p align="center">
<a href="#Jian">简介</a> | <a href="#更新计划">更新计划</a>
</p>
# Jian
对Flask项目中一些常用第三方进行封装.
例如:
- SQLalchemy
- WTF-forms
- JWT
- Blueprint
- Route_meta
- Exception
- Log
对这些优秀的第三方库进行二次开发,使更贴合我们项目中的使用.
# 安装 install
> pipenv or pip
```bash
pipenv install jian
```
`or`
```bash
pip install jian
```
## 使用
> 初始化项目,并且注册Jian
```python
from jian import Jian
def create_apps():
app = Flask(__name__)
app.config.from_object('app.config.setting')
Jian(app)
```
> 数据层操作
```python
from sqlalchemy import Column, String, Integer
from jian.interface import InfoCrud as Base
class Friend(Base):
id = Column(Integer, primary_key=True, autoincrement=True)
url = Column(String(32), unique=True)
doc = Column(String(50))
image = Column(String(50))
```
> 表单验证
```python
from wtforms import PasswordFiled
from wtforms.validators import DataRequired
from jian.forms import Form
# 注册校验
class RegisterForm(Form):
password = PasswordField('新密码', validators=[
DataRequired(message='新密码不可为空'),
Regexp(r'^[A-Za-z0-9_*&$#@]{6,22}$', message='密码长度必须在6~22位之间,包含字符、数字和 _ '),
EqualTo('confirm_password', message='两次输入的密码不一致,请输入相同的密码')])
confirm_password = PasswordField('<PASSWORD>', validators=[DataRequired(message='请确认密码')])
nickname = StringField(validators=[DataRequired(message='昵称不可为空'),
length(min=2, max=10, message='昵称长度必须在2~10之间')])
```
> 获取JWT登录令牌
```python
from jian.jwt import get_tokens
# Forms , Exception, Model 等要自己引入,这里只介绍jwt的用法
# 登录逻辑只是展示,并不是这样直接用,登录逻辑已经封装到jian.core中
@login.route('/login', methods=['POST'])
def login():
form = LoginForm().validate_for_api()
user = User.query.filter_by(nickname=nickname).first()
if user is None or user.delete_time is not None:
raise NotFound(msg='用户不存在')
if not user.check_password(password):
raise ParameterException(msg='密码错误,请输入正确密码')
if not user.is_active:
raise AuthFailed(msg='您目前处于未激活状态,请联系超级管理员')
access_token, refresh_token = get_tokens(user)
return jsonify({
'access_token': access_token,
'refresh_token': refresh_token
})
```
> 记录日志模块
```python
from jian.log import Logger
# 第一种方法
@Logger(template='新注册了一个用户')
def register_user():
pass
# 第二种方法主要是复杂的结构
def register_user():
Log.create_log(
message=f'{user.nickname}登陆成功获取了令牌',
user_id=user.id, user_name=user.nickname,
status_code=200, method='post',path='/cms/user/login',
authority='无', commit=True
)
...
```
## 更新计划
- [ ] 加入Swagger文档.
- [ ] 文件上传模块.<file_sep>/jian/log.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from functools import wraps
import re
from flask import Response, request
from flask_jwt_extended import get_current_user
from .core import find_info_by_ep, Log
REG_XP = r'[{](.*?)[}]'
OBJECTS = ['user', 'response', 'request']
class Logger(object):
# message template
template = None
def __init__(self, template=None):
if template:
self.template: str = template
elif self.template is None:
raise Exception('template must not be None!')
self.message = ''
self.response = None
self.user = None
def __call__(self, func):
@wraps(func)
def wrap(*args, **kwargs):
response: Response = func(*args, **kwargs)
self.response = response
self.user = get_current_user()
self.message = self._parse_template()
self.write_log()
return response
return wrap
def write_log(self):
info = find_info_by_ep(request.endpoint)
authority = info.auth if info is not None else ''
status_code = getattr(self.response, 'status_code', None)
if status_code is None:
status_code = getattr(self.response, 'code', None)
if status_code is None:
status_code = 0
Log.create_log(message=self.message, user_id=self.user.id, user_name=self.user.nickname,
status_code=status_code, method=request.method,
path=request.path, authority=authority, commit=True)
# 解析自定义模板
def _parse_template(self):
message = self.template
total = re.findall(REG_XP, message)
for it in total:
assert '.' in it, '%s中必须包含 . ,且为一个' % it
i = it.rindex('.')
obj = it[:i]
assert obj in OBJECTS, '%s只能为user,response,request中的一个' % obj
prop = it[i + 1:]
if obj == 'user':
item = getattr(self.user, prop, '')
elif obj == 'response':
item = getattr(self.response, prop, '')
else:
item = getattr(request, prop, '')
message = message.replace('{%s}' % it, str(item))
return message
<file_sep>/jian/enums.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from enum import Enum
# status for user is super
# 是否为超级管理员的枚举
class UserSuper(Enum):
COMMON = 1
SUPER = 2
# : status for user is active
# : 当前用户是否为激活状态的枚举
class UserActive(Enum):
ACTIVE = 1
NOT_ACTIVE = 2
<file_sep>/jian/plugin.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
class Plugin(object):
def __init__(self, name=None):
"""
:param name: plugin的名称
"""
# container of plugin's controllers
# 控制器容器
self.controllers = {}
# container of plugin's models
# 模型层容器
self.models = {}
# plugin's services
self.services = {}
self.name = name
def add_model(self, name, model):
self.models[name] = model
def get_model(self, name):
return self.models.get(name)
def add_controller(self, name, controller):
self.controllers[name] = controller
def add_service(self, name, service):
self.services[name] = service
def get_service(self, name):
return self.services.get(name)
<file_sep>/jian/core.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from collections import namedtuple
from datetime import datetime, date
from flask import Flask, current_app, request, Blueprint
from flask.json import JSONEncoder as _JSONEncoder
from werkzeug.exceptions import HTTPException
from werkzeug.local import LocalProxy
from .db import db
from .jwt import jwt
from .exception import APIException, UnknownException
from .interface import UserInterface, GroupInterface, AuthInterface, LogInterface, EventInterface
from .exception import NotFound, AuthFailed
from .config import Config
__version__ = 0.1
# 路由函数的权限和模块信息(meta信息)
Meta = namedtuple('meta', ['auth', 'module'])
# -> endpoint -> func
# auth -> module
# -> endpoint -> func
# 记录路由函数的权限和模块信息
route_meta_infos = {}
gigi_config = Config()
def route_meta(auth, module='common', mount=True):
"""
记录路由函数的信息
记录路由函数访问的推送信息模板
注:只有使用了 route_meta 装饰器的函数才会被记录到权限管理的map中
:param auth: 权限
:param module: 所属模块
:param mount: 是否挂在到权限中(一些视图函数需要说明,或暂时决定不挂在到权限中,则设置为False)
:return:
"""
def wrapper(func):
if mount:
name = func.__name__
exit = route_meta_infos.get(name, None)
if exit:
raise Exception("func's name cant't be repeat")
else:
route_meta_infos.setdefault(name, Meta(auth, module))
return func
return wrapper
def find_user(**kwargs):
return manager.find_user(**kwargs)
def find_group(**kwargs):
return manager.find_group(**kwargs)
def get_ep_infos():
""" 返回权限管理中的所有视图函数的信息,包含它所属module """
infos = {}
for ep, meta in manager.ep_meta.items():
mod = infos.get(meta.module, None)
if mod:
sub = mod.get(meta.auth, None)
if sub:
sub.append(ep)
else:
mod[meta.auth] = [ep]
else:
infos.setdefault(meta.module, {meta.auth: [ep]})
return infos
def find_info_by_ep(ep):
""" 通过请求的endpoint寻找路由函数的meta信息"""
return manager.ep_meta.get(ep)
def is_user_allowed(group_id):
"""查看当前user有无权限访问该路由函数"""
ep = request.endpoint
# 根据 endpoint 查找 authority
meta = manager.ep_meta.get(ep)
return manager.verity_user_in_group(group_id, meta.auth, meta.module)
def find_auth_module(auth):
""" 通过权限寻找meta信息"""
for _, meta in manager.ep_meta.items():
if meta.auth == auth:
return meta
return None
class Jian(object):
def __init__(self,
app: Flask = None, # flask app , default None
group_model=None, # group model, default None
user_model=None, # user model, default None
auth_model=None, # authority model, default None
create_all=False, # 是否创建所有数据库表, default false
mount=True, # 是否挂载默认的蓝图, default True
handle=True, # 是否使用全局异常处理 , default True
json_encoder=True, # 是否使用自定义的json_encoder , default True
):
self.app = app
self.manager = None
if app is not None:
self.init_app(app, group_model, user_model, auth_model, create_all, mount, handle, json_encoder)
def init_app(self,
app: Flask,
group_model=None,
user_model=None,
auth_model=None,
create_all=False,
mount=True,
handle=True,
json_encoder=True,
):
# default config
app.config.setdefault('PLUGIN_PATH', {})
# 默认蓝图的前缀
app.config.setdefault('BP_URL_PREFIX', '')
json_encoder and self._enable_json_encoder(app)
self.app = app
# 初始化 manager
self.manager = Manager(app.config.get('PLUGIN_PATH'),
group_model,
user_model,
auth_model)
self.app.extensions['manager'] = self.manager
db.init_app(app)
create_all and self._enable_create_all(app)
jwt.init_app(app)
mount and self.mount(app)
handle and self.handle_error(app)
def mount(self, app):
# 加载默认插件路由
bp = Blueprint('plugin', __name__)
# 加载插件的路由
for plugin in self.manager.plugins.values():
for controller in plugin.controllers.values():
controller.register(bp)
app.register_blueprint(bp, url_prefix=app.config.get('BP_URL_PREFIX'))
for ep, func in app.view_functions.items():
info = route_meta_infos.get(func.__name__, None)
if info:
self.manager.ep_meta.setdefault(ep, info)
def handle_error(self, app):
@app.errorhandler(Exception)
def handler(e):
if isinstance(e, APIException):
return e
if isinstance(e, HTTPException):
code = e.code
msg = e.description
error_code = 20000
return APIException(msg, code, error_code)
else:
if not app.config['DEBUG']:
return UnknownException()
else:
raise e
def _enable_json_encoder(self, app):
app.json_encoder = JSONEncoder
def _enable_create_all(self, app):
with app.app_context():
db.create_all()
class Manager(object):
""" manager for Jian """
# 路由函数的meta信息的容器
ep_meta = {}
def __init__(self, plugin_path, group_model=None, user_model=None, auth_model=None):
if not group_model:
self.group_model = Group
else:
self.group_model = group_model
if not user_model:
self.user_model = User
else:
self.user_model = user_model
if not auth_model:
self.auth_model = Auth
else:
self.auth_model = auth_model
from .loader import Loader
self.loader: Loader = Loader(plugin_path)
def find_user(self, **kwargs):
return self.user_model.query.filter_by(**kwargs).first()
def verify_user(self, nickname, password):
return self.user_model.verify(nickname, password)
def find_group(self, **kwargs):
return self.group_model.query.filter_by(**kwargs).first()
def verity_user_in_group(self, group_id, auth, module):
return self.auth_model.query.filter_by(group_id=group_id, auth=auth, module=module).first()
@property
def plugins(self):
return self.loader.plugins
def get_plugin(self, name):
return self.loader.plugins.get(name)
def get_model(self, name):
# attention!!! if models have the same name,will return the first one
# 注意!!! 如果容器内有相同的model,则默认返回第一个
for plugin in self.plugins.values():
return plugin.models.get(name)
def get_service(self, name):
# attention!!! if services have the same name,will return the first one
# 注意!!! 如果容器内有相同的service,则默认返回第一个
for plugin in self.plugins.values():
return plugin.services.get(name)
# a proxy for manager instance
# attention, only used when context in stack
# 获得manager实例
# 注意,仅仅在flask的上下文栈中才可获得
manager: Manager = LocalProxy(lambda: get_manager())
def get_manager():
_manager = current_app.extensions['manager']
if _manager:
return _manager
else:
app = current_app._get_current_object()
with app.app_context():
return app.extensions['manager']
class User(UserInterface, db.Model):
@classmethod
def verify(cls, nickname, password):
user = cls.query.filter_by(nickname=nickname).first()
if user is None:
raise NotFound(msg='用户不存在')
if not user.check_password(password):
raise AuthFailed(msg='密码错误,请输入正确密码')
return user
def reset_password(self, new_password):
#: attention,remember to commit
#: 注意,修改密码后记得提交至数据库
self.password = <PASSWORD>
def change_password(self, old_password, new_password):
#: attention,remember to commit
#: 注意,修改密码后记得提交至数据库
if self.check_password(old_password):
self.password = <PASSWORD>
return True
return False
class Group(GroupInterface):
pass
class Auth(AuthInterface):
pass
# log model
class Log(LogInterface):
@staticmethod
def create_log(**kwargs):
log = Log()
for key in kwargs.keys():
if hasattr(log, key):
setattr(log, key, kwargs[key])
db.session.add(log)
if kwargs.get('commit') is True:
db.session.commit()
return log
# event model
class Event(EventInterface):
pass
class JSONEncoder(_JSONEncoder):
def default(self, o):
if hasattr(o, 'keys') and hasattr(o, '__getitem__'):
return dict(o)
if isinstance(o, datetime):
return o.strftime('%Y-%m-%dT%H:%M:%SZ')
if isinstance(o, date):
return o.strftime('%Y-%m-%d')
return JSONEncoder.default(self, o)
<file_sep>/jian/sse.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
import json
from collections import deque
class Sse(object):
messages = deque()
_retry = None
def __init__(self, default_retry=2000):
self._buffer = []
self._default_id = 1
self.set_retry(default_retry)
def set_retry(self, num):
self._retry = num
self._buffer.append("retry: {0}\n".format(self._retry))
def set_event_id(self, event_id=None):
if event_id:
self._default_id = event_id
self._buffer.append("id: {0}\n".format(event_id))
else:
self._buffer.append("id: {0}\n".format(self._default_id))
def reset_event_id(self):
self.set_event_id(1)
def increase_id(self):
self._default_id += 1
def add_message(self, event, obj, flush=True):
self.set_event_id()
self._buffer.append("event: {0}\n".format(event))
line = json.dumps(obj, ensure_ascii=False)
self._buffer.append("data: {0}\n".format(line))
self._buffer.append("\n")
if flush:
self.flush()
def flush(self):
self.messages.append(self.join_buffer())
self._buffer.clear()
self.increase_id()
def pop(self):
return self.messages.popleft()
def heartbeat(self, comment=None):
# 发送注释 : this is a test stream\n\n 告诉客户端,服务器还活着
if comment and type(comment) == 'str':
self._buffer.append(comment)
else:
self._buffer.append(': sse sever is still alive \n\n')
tmp = self.join_buffer()
self._buffer.clear()
return tmp
def join_buffer(self):
string = ''
for it in self._buffer:
string += it
return string
def exit_message(self):
return len(self.messages) > 0
sser = Sse()
<file_sep>/jian/util.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
import time
import re
import errno
import random
import types
from importlib import import_module
import os
import importlib.util
from flask import request, current_app
from .exception import ParameterException
def get_timestamp(fmt='%Y-%m-%d %H:%M:%S'):
return time.strftime(fmt, time.localtime(time.time()))
def get_pyfile(path, module_name, silent=False):
"""
get all properties of a pyfile
获得一个.py文件的所有属性
:param path: path of pytfile
:param module_name: name
:param silent: show the error or not
:return: all properties of a pyfile
"""
d = types.ModuleType(module_name)
d.__file__ = path
try:
with open(path, mode='rb') as config_file:
exec(compile(config_file.read(), path, 'exec'), d.__dict__)
except IOError as e:
if silent and e.errno in (
errno.ENOENT, errno.EISDIR, errno.ENOTDIR
):
return False
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
return d.__dict__
def load_object(path):
"""
获得一个模块中的某个属性
:param path: module path
:return: the obj of module which you want get.
"""
try:
dot = path.rindex('.')
except ValueError:
raise ValueError("Error loading object '%s': not a full path" % path)
module, name = path[:dot], path[dot + 1:]
mod = import_module(module)
try:
obj = getattr(mod, name)
except AttributeError:
raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name))
return obj
def import_module_abs(name, path):
"""
绝对路径导入模块
:param name: name of module
:param path: absolute path of module
:return: the module
"""
spec = importlib.util.spec_from_file_location(name, path)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
def get_pwd():
"""
:return: absolute current work path
"""
return os.path.abspath(os.getcwd())
def paginate():
count = int(request.args.get('count', current_app.config.get('COUNT_DEFAULT') if current_app.config.get(
'COUNT_DEFAULT') else 5))
start = int(request.args.get('page', current_app.config.get('PAGE_DEFAULT') if current_app.config.get(
'PAGE_DEFAULT') else 0))
count = 15 if count >= 15 else count
start = start * count
if start < 0 or count < 0:
raise ParameterException()
return start, count
def camel2line(camel: str):
p = re.compile(r'([a-z]|\d)([A-Z])')
line = re.sub(p, r'\1_\2', camel).lower()
return line
def get_random_str(length):
seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
sa = []
for i in range(length):
sa.append(random.choice(seed))
salt = ''.join(sa)
return salt
<file_sep>/jian/interface.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from datetime import datetime
from sqlalchemy import Column, Integer, String, FetchedValue, SmallInteger, TIMESTAMP
from werkzeug.security import generate_password_hash, check_password_hash
from .enums import UserSuper, UserActive
from .db import MixinJSONSerializer, db
from .util import camel2line
# 基础的crud model
class BaseCrud(db.Model, MixinJSONSerializer):
__abstract__ = True
def __init__(self):
name: str = self.__class__.__name__
if not hasattr(self, '__tablename__'):
self.__tablename__ = camel2line(name)
def _set_fields(self):
self._exclude = []
def set_attrs(self, attrs_dict):
for key, value in attrs_dict.items():
if hasattr(self, key) and key != 'id':
setattr(self, key, value)
# 硬删除
def delete(self, commit=False):
db.session.delete(self)
if commit:
db.session.commit()
# 查
@classmethod
def get(cls, start=None, count=None, one=True, **kwargs):
if one:
return cls.query.filter().filter_by(**kwargs).first()
return cls.query.filter().filter_by(**kwargs).offset(start).limit(count).all()
# 增
@classmethod
def create(cls, **kwargs):
one = cls()
for key in kwargs.keys():
if hasattr(one, key):
setattr(one, key, kwargs[key])
db.session.add(one)
if kwargs.get('commit') is True:
db.session.commit()
return one
def update(self, **kwargs):
for key in kwargs.keys():
if hasattr(self, key):
setattr(self, key, kwargs[key])
db.session.add(self)
if kwargs.get('commit') is True:
db.session.commit()
return self
# 提供软删除,及创建时间,更新时间信息的crud model
class InfoCrud(db.Model, MixinJSONSerializer):
__abstract__ = True
_create_time = Column('create_time', TIMESTAMP(True), default=datetime.now)
update_time = Column(TIMESTAMP(True), default=datetime.now, onupdate=datetime.now)
delete_time = Column(TIMESTAMP(True))
def __init__(self):
name: str = self.__class__.__name__
if not hasattr(self, '__tablename__'):
self.__tablename__ = camel2line(name)
def _set_fields(self):
self._exclude = ['update_time', 'delete_time']
@property
def create_time(self):
if self._create_time is None:
return None
return int(round(self._create_time.timestamp() * 1000))
# @property
# def update_time(self):
# if self._update_time is None:
# return None
# return int(round(self._update_time.timestamp() * 1000))
# @property
# def delete_time(self):
# if self._delete_time is None:
# return None
# return int(round(self._delete_time.timestamp() * 1000))
def set_attrs(self, attrs_dict):
for key, value in attrs_dict.items():
if hasattr(self, key) and key != 'id':
setattr(self, key, value)
# 软删除
def delete(self, commit=False):
self.delete_time = datetime.now()
db.session.add(self)
# 记得提交会话
if commit:
db.session.commit()
# 硬删除
def hard_delete(self, commit=False):
db.session.delete(self)
if commit:
db.session.commit()
# 查
@classmethod
def get(cls, start=None, count=None, one=True, **kwargs):
# 应用软删除,必须带有delete_time
if kwargs.get('delete_time') is None:
kwargs['delete_time'] = None
if one:
return cls.query.filter().filter_by(**kwargs).first()
return cls.query.filter().filter_by(**kwargs).offset(start).limit(count).all()
# 增
@classmethod
def create(cls, **kwargs):
one = cls()
for key in kwargs.keys():
# if key == 'from':
# setattr(one, '_from', kwargs[key])
# if key == 'parts':
# setattr(one, '_parts', kwargs[key])
if hasattr(one, key):
setattr(one, key, kwargs[key])
db.session.add(one)
if kwargs.get('commit') is True:
db.session.commit()
return one
def update(self, **kwargs):
for key in kwargs.keys():
# if key == 'from':
# setattr(self, '_from', kwargs[key])
if hasattr(self, key):
setattr(self, key, kwargs[key])
db.session.add(self)
if kwargs.get('commit') is True:
db.session.commit()
return self
class UserInterface(InfoCrud):
__tablename__ = 'jian_user'
id = Column(Integer, primary_key=True)
nickname = Column(String(24), nullable=False, unique=True)
# : super express the user is super(super admin) ; 1 -> common | 2 -> super
# : super 代表是否为超级管理员 ; 1 -> 普通用户 | 2 -> 超级管理员
super = Column(SmallInteger, nullable=False, default=1, server_default=FetchedValue())
# : active express the user can manage the authorities or not ; 1 -> active | 2 -> not
# : active 代表当前用户是否为激活状态,非激活状态默认失去用户权限 ; 1 -> 激活 | 2 -> 非激活
active = Column(SmallInteger, nullable=False, default=1, server_default=FetchedValue())
# : used to send email in the future
# : 预留字段,方便以后扩展
email = Column(String(100), unique=True)
# : which group the user belongs,nullable is true
# : 用户所属的权限组id
group_id = Column(Integer)
_password = Column('password', String(100))
def _set_fields(self):
self._exclude = ['password']
@property
def password(self):
return self._password
@password.setter
def password(self, raw):
self._password = generate_password_hash(raw)
@property
def is_super(self):
return self.super == UserSuper.SUPER.value
@property
def is_active(self):
return self.active == UserActive.ACTIVE.value
@classmethod
def verify(cls, nickname, password):
raise Exception('must implement this method')
def check_password(self, raw):
if not self._password:
return False
return check_password_hash(self._password, raw)
def reset_password(self, new_password):
raise Exception('must implement this method')
def change_password(self, old_password, new_password):
raise Exception('must implement this method')
class AuthInterface(BaseCrud):
__tablename__ = 'jian_auth'
id = Column(Integer, primary_key=True)
# : belongs to which group
# : 所属权限组id
group_id = Column(Integer, nullable=False)
# : authority field
# : 权限字段
auth = Column(String(60))
# : authority module, default common , which can sort authorities
# : 权限的模块
module = Column(String(50))
class GroupInterface(BaseCrud):
__tablename__ = 'jian_group'
id = Column(Integer, primary_key=True)
# : name of group
# : 权限组名称
name = Column(String(60))
# a description of a group
# 权限组描述
info = Column(String(255))
class LogInterface(BaseCrud):
__tablename__ = 'jian_log'
id = Column(Integer, primary_key=True)
# : log message
# : 日志信息
message = Column(String(450))
# : create time
# : 日志创建时间
_time = Column('time', TIMESTAMP(True), default=datetime.now)
# : user id
# : 用户id
user_id = Column(Integer, nullable=False)
# user_name at that moment
# 用户当时的昵称
user_name = Column(String(20))
# : status_code check request is success or not
# : 请求的http返回码
status_code = Column(Integer)
# request method
# 请求方法
method = Column(String(20))
# request path
# 请求路径
path = Column(String(50))
# which authority is accessed
# 访问那个权限
authority = Column(String(100))
@property
def time(self):
if self._time is None:
return None
return int(round(self._time.timestamp() * 1000))
class EventInterface(BaseCrud):
__tablename__ = 'jian_event'
id = Column(Integer, primary_key=True)
# : belongs to which group
group_id = Column(Integer, nullable=False)
# message type ['订单','修改密码']
message_events = Column(String(250))
# service暂时不用
class ServiceInterface(object):
pass
<file_sep>/jian/exception.py
# -*- encoding:utf-8 -*-
"""
@ Created by Seven on 2019/01/19 <https://7yue.in>
"""
from flask import json, request
from werkzeug.exceptions import HTTPException
from werkzeug._compat import text_type
class APIException(HTTPException):
code = 500
msg = '抱歉,服务器未知错误'
error_code = 999
def __init__(self, msg=None, code=None, error_code=None,
headers=None):
if code:
self.code = code
if error_code:
self.error_code = error_code
if msg:
self.msg = msg
if headers is not None:
headers_merged = headers.copy()
headers_merged.update(self.headers)
self.headers = headers_merged
super(APIException, self).__init__(msg, None)
def get_body(self, environ=None):
body = dict(
msg=self.msg,
error_code=self.error_code,
request=request.method + ' ' + self.get_url_no_param()
)
text = json.dumps(body)
return text_type(text)
@staticmethod
def get_url_no_param():
full_path = str(request.full_path)
main_path = full_path.split('?')
return main_path[0]
def get_headers(self, environ=None):
return [('Content-Type', 'application/json')]
class Success(APIException):
code = 201
msg = '成功'
error_code = 0
class Failed(APIException):
code = 400
msg = '失败'
error_code = 9999
class AuthFailed(APIException):
code = 401
msg = '认证失败'
error_code = 10000
class NotFound(APIException):
code = 404
msg = '资源不存在'
error_code = 10020
class ParameterException(APIException):
code = 400
msg = '参数错误'
error_code = 10030
class InvalidTokenException(APIException):
code = 401
msg = '令牌失效'
error_code = 10040
class ExpiredTokenException(APIException):
code = 422
msg = '令牌过期'
error_code = 10050
class UnknownException(APIException):
code = 400
msg = '服务器未知错误'
error_code = 999
class RepeatException(APIException):
code = 400
msg = '字段重复'
error_code = 10060
class Forbidden(APIException):
code = 401
msg = '不可操作'
error_code = 10070
| ebfd5daf472451f4d82d400f72334d027af5bd57 | [
"Markdown",
"Python"
] | 17 | Python | Jarrott/Jian | bf4330589a23280e6bb7674c54086288a72ed048 | 2c278f80970514822ef3465561fd863c241d7ab0 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphVisualisationTool
{
interface FileHandlerInterface
{
List<List<T>> ParseFile<T>(string filename);
}
}
| 32bfe063a17a8700021abcac8e126ac582f6196e | [
"C#"
] | 1 | C# | galbenyosef/GraphVisualisationTool | 86f3dddfc27ec5674a96934eac9d4b8cc61344fc | de2f9034fb6f75d80ad004e804aeaa0748874895 |
refs/heads/master | <repo_name>ecrmnn/spaceholder-go<file_sep>/providers/providers.go
package providers
import (
"strings"
)
var (
m = map[string]func(string) string{
"loremPixel": loremPixel,
"unsplash": unsplash,
"dummyImage": dummyImage,
"fakeImg": fakeImg,
"placeImg": placeImg,
"placeholdIt": placeholdIt,
}
)
func GetImageFromProvider(provider, size string) string {
if (provider == "random") {
provider = randomProvider()
}
return m[provider](size)
}
func randomProvider() string {
randomProvider := ""
for key := range m {
randomProvider = key
}
return randomProvider
}
func loremPixel(size string) string {
pieces := strings.Split(size, "x")
return "http://lorempixel.com/" + pieces[0] + "/" + pieces[1] + "/"
}
func unsplash(size string) string {
pieces := strings.Split(size, "x")
return "https://unsplash.it/" + pieces[0] + "/" + pieces[1];
}
func dummyImage(size string) string {
return "https://dummyimage.com/" + size + "/000/fff"
}
func fakeImg(size string) string {
return "https://fakeimg.pl/" + size + "/384f66/ecf0f1/?text=Spaceholder&font=lobster"
}
func placeImg(size string) string {
pieces := strings.Split(size, "x")
return "http://placeimg.com/" + pieces[0] + "/" + pieces[1] + "/any"
}
func placeholdIt(size string) string {
pieces := strings.Split(size, "x")
return "http://placeholdit.imgix.net/~text?txtsize=40&txt=Spaceholder&w=" + pieces[0] + "&h=" + pieces[1]
}<file_sep>/README.md
# spaceholder-go
> Go implementation of [spaceholder](https://github.com/ecrmnn/spaceholder)
## Work in progress
This project is experimental and under development. If you want to use it's functionality I recommend you install the [original project](https://github.com/ecrmnn/spaceholder)
### What is it?
Spaceholder makes it easy to download placeholder images when you need them.
Images are downloaded from LoremPixel.com, Placehold.it, PlaceIMG.com, Dummyimage.com, Unsplash.it.
### Installation
Clone, build ``go build -o spaceholder github.com/ecrmnn/spaceholder-go`` and move to ``/usr/local/bin``
### Usage
```bash
spaceholder
# Downloads 1 image (1024x768px) into current directory
spaceholder -number 100
# Downloads 100 images into current directory
spaceholder -size 800x600
# Downloads 1 image (800x600px) into current directory
spaceholder -number 50 -size 800x600 -provider loremPixel
# Downloads 50 images (800x600px) from LoremPixel into current directory
# If no --provider is specified, each image is downloaded from a random provider
```
### Providers / Sources
- [Dummy Image](http://dummyimage.com)
- [FakeImg](fakeimg.pl)
- [Lorem Pixel](http://lorempixel.com)
- [PlaceholdIt](https://placehold.it)
- [PlaceImg](http://placeimg.com)
- [UnsplashIt](https://unsplash.it)
### License
MIT © [<NAME>](http://danieleckermann.com)<file_sep>/spaceholder.go
package main
import (
"flag"
"github.com/ecrmnn/spaceholder-go/providers"
"log"
"os"
"net/http"
"io"
"math/rand"
"time"
"fmt"
"sync"
"strconv"
)
func main() {
// Get flags and parse
provider := flag.String("provider", "random", "Set the image provider")
number := flag.Int("number", 1, "Number of images to download")
size := flag.String("size", "1024x768", "Set the image size")
flag.Parse()
var wg sync.WaitGroup
wg.Add(*number)
downloaded := 0
for i := 1; i <= *number; i++ {
go func() {
defer wg.Done()
time.Sleep(2 * time.Second)
// Get image URL
url := providers.GetImageFromProvider(*provider, *size)
// Download image
response, e := http.Get(url)
if e != nil {
log.Fatal(e)
}
defer response.Body.Close()
// Open file for writing
file, err := os.Create(currentDirectory() + "/" + generateFilename(*size))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(file, response.Body)
if err != nil {
log.Fatal(err)
}
file.Close()
downloaded++
fmt.Println("Downloaded " + strconv.Itoa(downloaded) + " of " + strconv.Itoa(*number))
}()
}
fmt.Println("Downloading image(s) ...")
wg.Wait()
}
func currentDirectory() string {
directory, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return directory;
}
func generateFilename(size string) string {
return "spaceholder_" + size + "_" + randomString() + ".jpg"
}
func randomString() string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, 6)
for i := 0; i < 6; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
| 9527b785d4570cd900c53f98213c7697a1e39821 | [
"Markdown",
"Go"
] | 3 | Go | ecrmnn/spaceholder-go | 50bd135fbd780a112b6706dc91c00f16687da4b4 | f8593fe6705f2d8cf60861bd53e46ad264bf3b45 |
refs/heads/main | <file_sep># store1
items sale store
| 934729e0683691ecc71691987c86b5e60c421ab2 | [
"Markdown"
] | 1 | Markdown | hovo99/store | 75af03b9b5245adf994104bfccbc903dc7453968 | edc1ad3cee1f38827545305977ad40219e883f1b |
refs/heads/master | <file_sep>import save_performance_to_database
import json
import requests
#Method to get data from url link with hackerrank_id and return a json string
def get_hackerrank_data(hackerrank_id):
#getting data from hackerrank url which returns a byte type data
try:
hackerrank_response_type_byte = requests.get("https://www.hackerrank.com/rest/hackers/%s/submission_histories" %hackerrank_id)
hackerrank_data_type_dict = json.loads(hackerrank_response_type_byte.content)
hackerrank_data_type_json_string = json.dumps(hackerrank_data_type_dict)
return hackerrank_data_type_json_string
except Exception as exc:
return "No Data Available"
def hackerrank_url_call(hackerrank_id,cursor=''):
try:
data = requests.get("https://www.hackerrank.com/rest/hackers/%s/recent_challenges?limit=20&response_version=v2&cursor=%s"%(hackerrank_id, cursor))
return json.loads(data.content)
except Exception as exc:
return 0
#print(hackerrank_url_call('sivagembali','MTA1NTQ2N3x8MTUxMTI4Njc2My4wfHwxXzEzNTAy'))
#Method to get data from url link with hackerrank id and returns number of problems solved with problem statements
def get_hackerrank_problems(hackerrank_id):
try:
result = {}
cursor=''
last_page = False
list_of_problems=[]
status = True
st_for_question = True
result_from_data_base = save_performance_to_database.get_hackerrank_problems_and_latest_qtn(hackerrank_id)
data_from_database= json.loads(result_from_data_base)
qtn_from_database = data_from_database['recent_problem']
problems_list = data_from_database['problems_list']
while(last_page!=True):
data = hackerrank_url_call(hackerrank_id,cursor)
if(st_for_question == True):
st_for_question = False
result['recent_problem']= data['models'][0]['name']
#print(len(data['models']))
for item in data['models']:
if(item['name']!= qtn_from_database):
problems_list.append(item['name'])
else:
status = False
break
last_page= data['last_page']
cursor= data['cursor']
if(status == False):
break
#print("List of problems",problems_list)
result['problems_list'] = problems_list
result['problems_count'] = len(problems_list)
#print(result)
return json.dumps(result)
except Exception as exc:
#print("Exception",exc)
return json.dumps({'problems_list':[],'problems_count':0,'recent_problem':''})
#print(get_hackerrank_problems('udayasriap'))
#method to get hackerrank data from database
def get_hackerrank_data_from_database(hackerrank_id):
result = save_performance_to_database.get_hack_data_from_db(hackerrank_id)
return result['hackerrank_status']
#get_hackerrank_data_from_database('sivagembali')
#method currently not working uncomment the url call
#print(get_hackerrank_data("kittusairam"))
#method to get data from url link with github_id and returns a json string
def get_github_data(github_id):
#getting data from github using url and github_id
#print(github_id)
try:
github_data = {}
github_response_type_byte = requests.get("https://api.github.com/users/%s/repos"%github_id)
github_response_data = json.loads(github_response_type_byte.content)
#print(github_response_data)
for repository_data in range(len(github_response_data)):
repo_id = github_response_data[repository_data]['id']
repo_data = {}
repo_data['name'] = github_response_data[repository_data]['name']
repo_data['created_at']= github_response_data[repository_data]['created_at']
repo_data['pushed_at'] = github_response_data[repository_data]['pushed_at']
github_data[repo_id]= repo_data
repo_count = len(list(github_data.keys()))
total_github_data = {'git_data':github_data,'repo_count':repo_count}
github_data_type_json_string = json.dumps(total_github_data)
#print(repo_count)
#print("git dataa:",github_data_type_json_string)
return github_data_type_json_string
except Exception as exc:
return json.dumps({'git_data':"No Data Available",'repo_count':0,'problem':'Error in getting data'})
#print(get_github_data('rajeunoia'))
#Method to get hackerrank and github data
def get_data(user_id,hackerrank_id,github_id):
hackerrank_and_github_data = {}
hackerrank_and_github_data ['hackerrank_problems'] = get_hackerrank_problems(hackerrank_id)
hackerrank_and_github_data ['userid']= user_id
hackerrank_and_github_data ['hackerrank_data'] = get_hackerrank_data(hackerrank_id)
hackerrank_and_github_data ['github_data'] = get_github_data(github_id)
try:
sum_data = 0
dict_data =json.loads(hackerrank_and_github_data ['hackerrank_data'])
if(type(dict_data) is dict):
for key in dict_data.keys():
sum_data = sum_data + int(dict_data[key])
#print(type(int(dict_data['2016-07-22'])))
hackerrank_and_github_data ['hackerrank_submissions']= sum_data
except Exception as exc:
hackerrank_and_github_data ['hackerrank_submissions']= 0
return hackerrank_and_github_data
#print(get_data(1,'sivagembali','sivagembali'))
#result = get_data(1,'sivagembali','sivagembali')
#update_performance.update_hackerrank_github_data(result)
def update_user_performance_data(userid):
user_details = save_performance_to_database.get_ids_studentperformance(userid)
user_id = user_details['userid']
hackerrank_id = user_details['hackerrankid']
github_id = user_details['githubid']
data = get_data(user_id,hackerrank_id,github_id)
save_performance_to_database.save_u_p_data(data)
return "Successfuly updated"
#update_user_performance_data(2)
#Method to update all users status retuns success message
def update_all_users_status():
snumbers = save_performance_to_database.get_snumber_from_studentperformance_table()
for data in snumbers:
update_user_performance_data(data[0])
return "Successfuly updated"
#Method to update all ids and retutns message status
def update_all_ids(ids):
email = ids['email_id']
#print("inside update_all_ids--",ids)
student_info_dict = save_performance_to_database.check_email_exist_or_not(email)
if(len(student_info_dict)):
user_details={}
user_details['userid'] = student_info_dict['userid']
user_details['hackerrankid'] = ids['hackerrank_id']
user_details['github_id'] = ids['github_id']
status = save_performance_to_database.update_ids_to_database(user_details)
return status
else:
return "Email not registred"
#Method return studentinfo to get hackerrank status and github status
def check_mail(email):
result = save_performance_to_database.check_email_exist_or_not(email)
return result
#print(check_mail('<EMAIL>'))
#{'studentinfo':1}
#Method to get status data from datbase and returns json string
def get_status_data(userid):
result_from_database = save_performance_to_database.get_student_github_hackerrank_status(userid)
json_string = json.dumps(result_from_database)
return json_string
#modified on 25th feb
def get_id_for_email(email):
result = save_performance_to_database.check_email_exist_or_not(email)
#print(type(result))
if isEmpty(result):
return result['userid']
else:
return 0
#get_id_for_email('<EMAIL>')
#Method to get studetn details
def get_students_data():
result = save_performance_to_database.get_all_students_data()
return result
def isEmpty(dictionary):
for element in dictionary:
if element:
return True
return False
#method to store csv data to database
def store_data_to_database():
file_access = open('FebWorkshops.csv','r')
file_data = file_access.read()
file_data_lines = file_data.split('\n')
for line_nu in range(1,len(file_data_lines)-1):
line_data = file_data_lines[line_nu].split(',')
name = line_data[1]
password = <PASSWORD>[2]
email = line_data[3]
mobile = line_data[4]
college = line_data[5]
gender = line_data[6]
batch = line_data[12]
location = line_data[11]
hackerrankid = line_data[7]
githubid = line_data[8]
linkedinid = line_data[9]
save_performance_to_database.insert_data(name,password,email,mobile,college,gender,batch,location,hackerrankid,githubid,linkedinid)
#print(email)
file_access.close()
return "success"
#print(file_data_lines[37])
#store_data_to_database()
'''#Method to verify and store data to database from the registration page
def verify_and_store_data_to_database(user_form_details):
user_email = user_form_details['email']
'''
<file_sep>import sqlite3
import json
#Method to save students hackerrank and github status
def save_u_p_data(hackerrank_github_data):
database_connection = sqlite3.connect('userdatabase.db')
user_id = hackerrank_github_data['userid']
hackerrank_info = hackerrank_github_data['hackerrank_data']
github_info = hackerrank_github_data['github_data']
hackerrank_problems = hackerrank_github_data['hackerrank_problems']
hackerrank_submissions = hackerrank_github_data['hackerrank_submissions']
database_connection.execute("UPDATE STUDENTPERFORMANCE SET HACKERRANK_STATUS=?,GITHUB_STATUS=?,HACKERRANK_PROBLEMS=?,HACKERRANK_SUBMISSIONS=? WHERE USERID = ?",(hackerrank_info,github_info,hackerrank_problems,hackerrank_submissions,user_id))
database_connection.commit()
database_connection.close()
#print("Successfully Updated")
#Method to get previous hackerrank problems and latest question
def get_hackerrank_problems_and_latest_qtn(hackerrank_id):
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
result_cursor = data_cursor.execute("SELECT HACKERRANK_PROBLEMS FROM STUDENTPERFORMANCE WHERE HACKERRANKID = '%s' "% hackerrank_id)
result_data = result_cursor.fetchall()
for row in result_data:
result = row[0]
if(result == None):
result = json.dumps({'problems_list':[],'problems_count':0,'recent_problem':''})
return result
#print(get_hackerrank_problems_and_latest_qtn('sivagembali'))
#Method to insert data into tables
def insert_data(name,password,email,mobile,college,gender,batch,location,hackerrankid,githubid,linkedinid):
print(name,password,email,mobile,college,gender,batch,location,hackerrankid,githubid,linkedinid)
database_connection = sqlite3.connect('userdatabase.db')
if(table_exists(database_connection,'STUDENTREGISTRATION')):
user_details = (name,password,email,mobile,college,gender,batch,location)
insertion_query = '''INSERT INTO STUDENTREGISTRATION(NAME,PASSWORD,EMAIL,MOBILE,COLLEGENAME,GENDER,BATCH,LOCATION) VALUES(?,?,?,?,?,?,?,?)'''
database_connection.execute(insertion_query,user_details)
database_connection.commit()
else:
database_connection.execute('''CREATE TABLE STUDENTREGISTRATION (USERID INTEGER PRIMARY KEY,NAME TEXT NOT NULL,PASSWORD TEXT NOT NULL,EMAIL TEXT UNIQUE,MOBILE TEXT NOT NULL,COLLEGENAME TEXT NOT NULL,GENDER TEXT NOT NULL,BATCH TEXT NOT NULL,LOCATION TEXT NOT NULL);''')
user_details = (1,name,password,email,mobile,college,gender,batch,location)
insertion_query = '''INSERT INTO STUDENTREGISTRATION(USERID,NAME,PASSWORD,EMAIL,MOBILE,COLLEGENAME,GENDER,BATCH,LOCATION) VALUES(?,?,?,?,?,?,?,?,?)'''
database_connection.execute(insertion_query,user_details)
database_connection.commit()
if(table_exists(database_connection,'STUDENTPERFORMANCE')):
student_info = check_email_exist_or_not(email)
#print(student_info['studentinfo'])
value = student_info['userid']
hackerrank_problems = json.dumps({'problems_list':[],'problems_count':0,'recent_problem':''})
user_details = (hackerrankid,githubid,hackerrank_problems,linkedinid,value)
insertion_query='''INSERT INTO STUDENTPERFORMANCE (HACKERRANKID,GITHUBID,HACKERRANK_PROBLEMS,LINKEDINID,USERID) VALUES(?,?,?,?,?)'''
database_connection.execute(insertion_query,user_details)
database_connection.commit()
else:
database_connection.execute('''CREATE TABLE STUDENTPERFORMANCE(S_NUMBER INTEGER PRIMARY KEY ,HACKERRANKID TEXT,GITHUBID TEXT,HACKERRANK_STATUS TEXT,HACKERRANK_SUBMISSIONS TEXT,HACKERRANK_PROBLEMS INTEGER,GITHUB_STATUS TEXT,LINKEDINID TEXT,STACKOVERFLOWID TEXT,USERID INTEGER,FOREIGN KEY (USERID) REFERENCES STUDENTREGISTRATION(USERID) )''')
student_info = check_email_exist_or_not(email)
#print(student_info['studentinfo'])
value = student_info['userid']
hackerrank_problems = json.dumps({'problems_list':[],'problems_count':0,'recent_problem':''})
user_details = (1,hackerrankid,githubid,hackerrank_problems,linkedinid,value)
insertion_query='''INSERT INTO STUDENTPERFORMANCE (S_NUMBER,HACKERRANKID,GITHUBID,HACKERRANK_PROBLEMS,LINKEDINID,USERID) VALUES(?,?,?,?,?,?)'''
database_connection.execute(insertion_query,user_details)
database_connection.commit()
database_connection.close()
#insert_data('<NAME>','pavani','<EMAIL>','9133610848','Gayatri Vidya Parishad college of engineering(A)','female','Feb-18','vizag','pavanilakkimset1','lakkimsettypavani','')
#Method to retrive data from database returns a json
def get_ids_studentperformance(userid):
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
result_cursor = data_cursor.execute("SELECT HACKERRANKID,GITHUBID FROM STUDENTPERFORMANCE WHERE USERID = %s "% userid)
result_data_set={}
result_data_set['userid']=userid
result_data = result_cursor.fetchall()
for row in result_data:
result_data_set['hackerrankid']=row[0]
result_data_set['githubid']=row[1]
data_cursor.close()
database_connection.close()
return result_data_set
#Method to retrive s_numbers from student performance table returns all students s_nubers
def get_snumber_from_studentperformance_table():
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
data_cursor = database_connection.execute("SELECT USERID FROM STUDENTPERFORMANCE")
resultant_data = data_cursor.fetchall()
data_cursor.close()
database_connection.close()
return resultant_data
#Method to check email exist in the database or not if exist returns student info(foreign key value) of type dictionary
def check_email_exist_or_not(email):
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
data_cursor = database_connection.execute("SELECT USERID FROM STUDENTREGISTRATION WHERE EMAIL=? OR MOBILE=? ",(email,email))
resultant_data = data_cursor.fetchall()
result = {}
for row in resultant_data:
result['userid']=row[0]
data_cursor.close()
database_connection.close()
return result
#print(check_email_exist_or_not('<EMAIL>'))
#Method to update hackerrankid and githubid and returns status message
def update_ids_to_database(user_details):
database_connection = sqlite3.connect('userdatabase.db')
student_info = user_details['userid']
hackerrank_id = user_details['hackerrankid']
github_id=user_details['github_id']
#print(hackerrank_id,github_id,student_info)
database_connection.execute("UPDATE STUDENTPERFORMANCE SET HACKERRANKID = ?,GITHUBID = ? WHERE USERID = ?",(hackerrank_id,github_id,student_info))
#database_connection.execute("INSERT INTO STUDENTPERFORMANCE(HACKERRANKID,GITHUBID,STUDENTINFO) VALUES(?,?,?)",(hackerrank_id,github_id,student_info))
#print("changes",database_connection.total_changes)
database_connection.commit()
database_connection.close()
return "Successfully Updated"
#Method to retrive data from database returns a json with github and hackerrank status
def get_student_github_hackerrank_status(student_info):
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
data_cursor = database_connection.execute("SELECT HACKERRANK_STATUS,GITHUB_STATUS FROM STUDENTPERFORMANCE WHERE USERID='%s'" % student_info)
data = data_cursor.fetchall()
result_status = {}
for row in data:
result_status['hackerrank_status']=row[0]
result_status['github_status']=row[1]
return result_status
def get_hack_data_from_db(hackerrank_id):
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
try:
data_cursor = database_connection.execute("SELECT HACKERRANK_STATUS FROM STUDENTPERFORMANCE WHERE HACKERRANKID='%s'" % hackerrank_id)
data = data_cursor.fetchall()
result_status = {}
for row in data:
result_status['hackerrank_status']=row[0]
return result_status
except Exception as exp:
return "Data Not Available"
def get_all_students_data():
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
data_cursor = database_connection.execute("SELECT * FROM STUDENTREGISTRATION")
data = data_cursor.fetchall()
result_status = {}
for row in data:
s_id = row[0]
result_status[s_id] = {}
result_status[s_id]['name:']=row[1]
result_status[s_id]['password']=row[2]
result_status[s_id]['email'] = row[3]
result_status[s_id]['mobile'] = row[4]
result_status[s_id]['college']= row[5]
result_status[s_id]['gender']=row[6]
result_status[s_id]['batch']=row[7]
result_status[s_id]['location']=row[8]
return result_status
#print(result_status)
#get_all_students_data()
#method to check table exist or not
def table_exists(conn,table_name):
result = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='"+table_name+"'")
result_data = result.fetchall()
if len(result_data)>0 and result_data[0][0] == table_name:
return True
else:
return False
"""#Method to store the data coming from the user registration
def save_user_registration_data(user_details):
database_connection = sqlite3.connect('userdatabase.db')
username = user_details['username']
password = user_details['<PASSWORD>']
collegename = user_details['collegename']
email = user_details['email']
mobile = user_details['mobile']
gender = user_details['gender']
user_data = (username,password,email,mobile,collegename,gender)
insertion_query = '''INSERT INTO STUDENTREGISTRATION(NAME,PASSWORD,EMAIL,MOBILE,COLLEGENAME,GENDER) VALUES(?,?,?,?,?,?)'''
database_connection.execute(insertion_query,user_data)
database_connection.commit()
database_connection.close()
#save_user_registration_data({'username':'siva','password':'<PASSWORD>','email':'<EMAIL>','mobile':'8978098722','collegename':'gvp','gender':'male'})
"""<file_sep><?php
include_once("sendmail.php");
$from=$_POST["from"] ;
$mailto = $_POST["mail"];
if($from == "subscribe") {
$m= new Mail; // create the mail
#$m->From( $mailto );
$m->To( "<EMAIL>" );
$m->Subject( "Subscription for PythonWorkshops" );
$message= $mailto;
$m->Body( $message); // set the body
$m->Cc( "<EMAIL>");
$m->Bcc( "<EMAIL>");
$m->Priority(4) ; // set the priority to Low
#$m->Attach( "/home/leo/toto.gif", "image/gif" ) ; // attach a file of type image/gif
//alternatively u can get the attachment uploaded from a form
//and retreive the filename and filetype and pass it to attach methos
$m->Send(); // send the mail
echo "Thanks for the subscription with email:<br><pre>", $mailto, "</pre>";
}
?><file_sep>import sqlite3
import json
import datetime
import hackerrank_and_github_response
from flask import Flask, redirect, url_for, request,current_app
from flask_cors import CORS
app = Flask(__name__)
CORS(app,resources=r'/students_status_display')
CORS(app,resources=r'/get_details')
@app.route('/')
def root():
return current_app.send_static_file('register.html')
@app.route('/login',methods = ['POST'])
def login():
conn = sqlite3.connect('userdatabase.db')
emailnumber = request.form['emailormobile']
pswd = request.form['password']
details = (pswd,emailnumber,emailnumber)
cursor = conn.execute("SELECT PASSWORD,EMAIL,MOBILE FROM STUDENTREGISTRATION WHERE PASSWORD= ? AND (EMAIL = ? OR MOBILE= ?) ",details)
data = cursor.fetchall()
cursor.close()
conn.close()
#print(len(data))
if(len(data)):
return "Successfully Loggedin"
else:
return "Invalid Credentials"
#redirect("/static/updation_page.html")
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
#This module is to store data from the registration form.
@app.route('/register',methods = ['POST'])
def register():
database_connection = sqlite3.connect('userdatabase.db')
batch = request.form['batch']
location = request.form['location']
gender = request.form['gender']
username = request.form['name']
password = request.form['password']
collegename = request.form['collegename']
email = request.form['email']
mobile = request.form['mobile']
if(username =='' or password =='' or collegename=='' or email=='' or mobile=='' or gender=='' or gender=='select' or batch =='' or location==''):
return "All Fields are Mandatory"
else:
email_validation = hackerrank_and_github_response.check_mail(email)
if(len(email_validation)):
database_connection.close()
return "Email already exist"
else:
user_details = (username,<PASSWORD>,email,mobile,collegename,gender,batch,location)
insertion_query = '''INSERT INTO STUDENTREGISTRATION(NAME,PASSWORD,EMAIL,MOBILE,COLLEGENAME,GENDER,BATCH,LOCATION) VALUES(?,?,?,?,?,?,?,?)'''
database_connection.execute(insertion_query,user_details)
database_connection.commit()
student_info = hackerrank_and_github_response.check_mail(email)
#print(student_info['studentinfo'])
value = student_info['userid']
database_connection.execute("INSERT INTO STUDENTPERFORMANCE(USERID) VALUES (%s)"% value)
database_connection.commit()
database_connection.close()
return "Successfully Registred"
@app.route('/updateuserperformance/<userid>')
def update_user_performance(userid):
result = hackerrank_and_github_response.update_user_performance_data(userid)
json_string = json.dumps(result)
return json_string
@app.route('/updateall')
def update_all_status():
result = hackerrank_and_github_response.update_all_users_status()
return result
@app.route('/update_ids',methods = ['POST'])
def update_ids():
email = request.form['email']
hackerrankid=request.form['hackerrankid']
githubid=request.form['githubid']
if(hackerrankid=='' or githubid==''):
return "All Fields are Mandatory"
else:
ids = {}
ids['email_id']=email
ids['hackerrank_id']=hackerrankid
ids['github_id']=githubid
result = hackerrank_and_github_response.update_all_ids(ids)
#to update all students status
#hackerrank_and_github_response.update_all_users_status()
return result
@app.route('/dashboard')
def dashboard():
mail = request.args.get('email')
user_id = hackerrank_and_github_response.get_id_for_email(mail)
#print("In side dashboard--",user_id)
result = hackerrank_and_github_response.get_status_data(user_id)
#print("In side Dashboard result--",result)
return result
#method to display students data
@app.route('/students_data')
def students_data():
result = hackerrank_and_github_response.get_students_data()
return json.dumps(result)
#method to get single user total performance in hackerrank
@app.route('/get_hack_data/<hackerrank_id>')
def get_hack_data(hackerrank_id):
sum_data = 0
data=hackerrank_and_github_response.get_hackerrank_data(hackerrank_id)
#print(type(data))
try:
dict_data =json.loads(data)
if(type(dict_data) is dict):
for key in dict_data.keys():
sum_data = sum_data + int(dict_data[key])
#print(type(int(dict_data['2016-07-22'])))
return str(sum_data)
except Exception as exc:
return "no data"
#print(get_hack_data('yandanagamani52'))
#method to get single user weekly performance in hackerrank except final day
#@app.route('/get_weekly_hack_data/<hackerrank_id>')
def get_weekly_hack_data(hackerrank_id):
sum_data = 0
data=hackerrank_and_github_response.get_hackerrank_data_from_database(hackerrank_id)
try:
dict_data =json.loads(data)
if(type(dict_data) is dict):
result ={}
weekly_count = 0
for i in range(7):
day = str(datetime.date.today()-datetime.timedelta(days=i))
if(day in dict_data.keys()):
weekly_count = weekly_count + int(dict_data[day])
#print(weekly_count)
result['weekly_count'] = weekly_count
if(str(datetime.date.today()) == list(dict_data.keys())[-1]):
result['tday_count'] = dict_data[list(dict_data.keys())[-1]]
else:
result['tday_count'] = 0
return result
except Exception as exc:
#print(hackerrank_id)
return "no data"
#print(get_weekly_hack_data('sivagembali'))
#method to get single user performance in github
@app.route('/get_git_data/<git_id>')
def get_git_data(git_id):
result = hackerrank_and_github_response.get_github_data(git_id)
#print(result)
try:
dict_data = json.loads(result)
if(type(dict_data) is dict):
return str(dict_data)
except Exception as exp:
return "no data"
#method to generate dynamic student details
#result will be in this format{1:{'student_name':'<NAME>','gender':'male','hackerrankid':'sivagembali','githubid':'sivagembali','linkedinid':'sivagembali','problems_count':157,'repo_count':8}}
@app.route('/get_details')
def get_details():
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
result_cursor = data_cursor.execute('select studentregistration.userid,studentregistration.name,studentregistration.gender,studentperformance.hackerrankid,studentperformance.githubid,studentperformance.linkedinid,studentperformance.hackerrank_problems,studentregistration.batch,studentperformance.github_status,studentregistration.job_status from studentregistration INNER JOIN studentperformance ON studentregistration.userid=studentperformance.userid')
result_data_set={}
result_data = result_cursor.fetchall()
for row in result_data:
hack_data = json.loads(row[6])
git_data = json.loads(row[8])
job_data = json.loads(row[9])
# and row[5]!='null' and row[5]!=None and row[7]!='Sept2017'
if(hack_data['problems_count']>=66):
row_id = row[0]
result_data_set[row_id]={}
result_data_set[row_id]['student_name']= row[1].title()
result_data_set[row_id]['gender']= row[2]
result_data_set[row_id]['hackerrankid']= row[3]
result_data_set[row_id]['githubid']= row[4]
result_data_set[row_id]['linkedinid']= row[5]
result_data_set[row_id]['problems_count'] = hack_data['problems_count']
result_data_set[row_id]['repo_count'] = git_data['repo_count']
result_data_set[row_id]['job_status'] = job_data['job_status']
result_data_set[row_id]['batch'] = row[7]
#print(result_data_set)
return json.dumps(result_data_set)
#print(get_details())
#method to read data from csv and store it in a database
@app.route('/store_students_data')
def store_csv_data_to_database():
result = hackerrank_and_github_response.store_data_to_database()
return result
#method to show students current status
@app.route('/students_status_display')
def students_status_display():
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
result_cursor = data_cursor.execute('select studentregistration.userid,studentregistration.name,studentregistration.batch,studentregistration.location,studentperformance.hackerrank_submissions,studentperformance.hackerrankid,studentperformance.hackerrank_status,studentperformance.github_status,studentperformance.hackerrank_problems,studentperformance.linkedinid from studentregistration INNER JOIN studentperformance ON studentregistration.userid=studentperformance.userid')
result_data_set={}
result_data = result_cursor.fetchall()
for row in result_data:
row_id = row[0]
result_data_set[row_id]={}
result_data_set[row_id]['name'] = row[1].lower()
result_data_set[row_id]['batch'] = row[2]
result_data_set[row_id]['location'] = row[3]
result_data_set[row_id]['hackerrank_submissions'] = row[4]
result_from_weekly_hack_data = get_weekly_hack_data(row[5])
if(result_from_weekly_hack_data!="no data"):
result_data_set[row_id]['weekly_count'] = result_from_weekly_hack_data['weekly_count']
result_data_set[row_id]['tday_count'] = result_from_weekly_hack_data['tday_count']
else:
result_data_set[row_id]['weekly_count'] =0
result_data_set[row_id]['tday_count'] = 0
hackerank_problems_data = json.loads(row[8])
result_data_set[row_id]['hackerrank_problems'] = hackerank_problems_data['problems_count']
#print(result_data_set)
return json.dumps(result_data_set)
#method to store student data into csv
@app.route('/create_csv')
def create_csv():
file_name = str(datetime.date.today())+".csv"
file_access = open(file_name,'a')
file_write = file_access.write("Name,Number of Problems\n")
database_connection = sqlite3.connect('userdatabase.db')
data_cursor = database_connection.cursor()
result_cursor = data_cursor.execute('select studentregistration.userid,studentregistration.name,studentregistration.batch,studentregistration.location,studentperformance.hackerrank_submissions,studentperformance.hackerrankid,studentperformance.hackerrank_status,studentperformance.github_status,studentperformance.hackerrank_problems,studentperformance.linkedinid from studentregistration INNER JOIN studentperformance ON studentregistration.userid=studentperformance.userid')
result_data_set={}
result_data = result_cursor.fetchall()
for row in result_data:
row_id = row[0]
result_data_set[row_id]={}
result_data_set[row_id]['name'] = row[1].lower()
result_data_set[row_id]['batch'] = row[2]
result_data_set[row_id]['location'] = row[3]
result_data_set[row_id]['hackerrank_submissions'] = row[4]
result_from_weekly_hack_data = get_weekly_hack_data(row[5])
if(result_from_weekly_hack_data!="no data"):
result_data_set[row_id]['weekly_count'] = result_from_weekly_hack_data['weekly_count']
result_data_set[row_id]['tday_count'] = result_from_weekly_hack_data['tday_count']
else:
result_data_set[row_id]['weekly_count'] =0
result_data_set[row_id]['tday_count'] = 0
hackerank_problems_data = json.loads(row[8])
result_data_set[row_id]['hackerrank_problems'] = hackerank_problems_data['problems_count']
if(hackerank_problems_data['problems_count'] < 66):
file_access.write(row[1]+","+str(hackerank_problems_data['problems_count'])+"\n")
file_access.close()
return "success"
if __name__ == '__main__':
app.run(debug=True) | 761cb983698ea292366b01434fc9ba211ed3e51c | [
"Python",
"PHP"
] | 4 | Python | sivagembali/user_registration | 3e507efd0e5aac9fef846b4377e584238e67f4ac | 8f9d0a7d1b6b3fc4c026b6ab2c38233dc64d52eb |
refs/heads/master | <file_sep>apply plugin: 'java'
apply plugin: 'application'
//apply plugin: 'distribution'
repositories {
mavenCentral()
}
compileJava.sourceCompatibility = 1.5
compileJava.targetCompatibility = 1.5
// println "${System.properties['java.home']}/../lib/tools.jar"
mainClassName = "org.github.sprofile.ui.Main"
dependencies {
compile files("${System.properties['java.home']}/../lib/tools.jar")
compile files('lib/jbzip2-0.9.1.jar')
compile 'junit:junit:4.11'
compile 'org.mortbay.jetty:servlet-api-2.5:6.1H.14.1'
compile 'org.swinglabs:swingx:1.6.1'
}
jar {
manifest {
attributes 'Main-Class': "org.github.sprofile.AttachToJvm", "Agent-Class": "org.github.sprofile.AgentMain"
}
}
/*
distributions {
main {
}
}
*/<file_sep>package org.github.sprofile.ui;
import org.github.sprofile.ui.timeline.TimelinePane;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/23/12
* Time: 11:35 AM
* To change this template use File | Settings | File Templates.
*/
public class MainUI {
private JPanel panel1;
private JTextPane textPane2;
private TimelinePane timelinePane1;
private void createUIComponents() {
// TODO: place custom component creation code here
}
}
<file_sep>package org.github.sprofile.servlet;
import org.github.sprofile.Details;
import org.github.sprofile.Profiler;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/29/12
* Time: 4:29 PM
* To change this template use File | Settings | File Templates.
*/
public class RequestFilter implements Filter {
Profiler profiler;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.profiler = ProfilerFactory.getInstance();
}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
String uri = "unknown";
String remoteAddr = "unknown";
if (servletRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
uri = request.getRequestURI();
remoteAddr = request.getRemoteAddr();
}
Details context = new Details("uri", uri, "remoteAddr", remoteAddr);
try {
this.profiler.callWithContext(context, new Runnable() {
@Override
public void run() {
try {
filterChain.doFilter(servletRequest, servletResponse);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
} catch (RuntimeException ex) {
if (ex.getCause() instanceof IOException) {
throw (IOException) ex.getCause();
} else if (ex.getCause() instanceof ServletException) {
throw (ServletException) ex.getCause();
}
}
}
@Override
public void destroy() {
ProfilerFactory.release(profiler);
}
}
<file_sep>package org.github.sprofile.transform;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/26/12
* Time: 8:29 AM
* To change this template use File | Settings | File Templates.
*/
public interface Transform {
public StackTraceElement[] transform(StackTraceElement[] trace);
}
<file_sep>package org.github.sprofile.ui.timeline;
import org.github.sprofile.Context;
import java.util.Arrays;
/**
* A timeline for a single thread
*/
public class Timeline {
final long[] timestamps;
final StackTraceElement[][] traces;
final Context[] contexts;
final int maxContextDepth;
final int maxTraceDepth;
public Timeline(long[] timestamps, StackTraceElement[][] traces, Context[] contexts) {
this.timestamps = timestamps;
this.traces = traces;
this.contexts = contexts;
int maxTraceDepth = 0;
int maxContextDepth = 0;
for (int i = 0; i < getSampleCount(); i++) {
maxTraceDepth = Math.max(getTraceDepth(i), maxTraceDepth);
maxContextDepth = Math.max(getContextDepth(i), maxContextDepth);
}
this.maxTraceDepth = maxTraceDepth;
this.maxContextDepth = maxContextDepth;
}
public int getIndexOf(long time) {
int i = Arrays.binarySearch(timestamps, time);
if (i < 0) {
i = -(i + 1);
}
return i;
}
public int getSampleCount() {
return timestamps.length;
}
public long getElapsedTime() {
return timestamps[timestamps.length - 1] - timestamps[0];
}
public long getTime(int index) {
return timestamps[index];
}
public int getMaxTraceDepth() {
return maxTraceDepth;
}
public int getMaxContextDepth() {
return maxContextDepth;
}
public Context getContext(int index) {
return contexts[index];
}
public StackTraceElement[] getTrace(int index) {
return traces[index];
}
public int getContextDepth(int index) {
if (contexts[index] != null)
return contexts[index].getDepth();
return 0;
}
public int getTraceDepth(int index) {
if (traces[index] != null) {
return traces[index].length;
}
return 0;
}
}
<file_sep>package org.github.sprofile.io;
import org.github.sprofile.Context;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import static org.github.sprofile.io.Constants.*;
public class SnapshotStreamWriter implements Writer {
final DataOutputStream out;
static class HashableElement {
String className;
String methodName;
String filename;
int lineNumber;
HashableElement(StackTraceElement element) {
this.className = element.getClassName();
this.methodName = element.getMethodName();
this.filename = element.getFileName();
this.lineNumber = element.getLineNumber();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
HashableElement that = (HashableElement) o;
if (lineNumber != that.lineNumber) return false;
if (className != null ? !className.equals(that.className) : that.className != null) return false;
if (filename != null ? !filename.equals(that.filename) : that.filename != null) return false;
if (methodName != null ? !methodName.equals(that.methodName) : that.methodName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = className != null ? className.hashCode() : 0;
result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
result = 31 * result + (filename != null ? filename.hashCode() : 0);
result = 31 * result + lineNumber;
return result;
}
}
private Map<HashableElement, Integer> stackTraceElements = new HashMap();
private Map<IdList, Integer> traces = new HashMap();
private Map<Long, String> threadInfo = new HashMap();
private Map<String, Integer> atoms = new HashMap();
{
atoms.put(null, 0);
}
// use a weak hashmap for contexts because we have the potential to accumulate a large number of these as parameter
// values are not from a small possible set of values. (Unlike file and method names)
private Map<Context, Integer> contextIds = new WeakHashMap<Context, Integer>();
{
contextIds.put(null, 0);
}
private List<String> unwrittenAtoms = new ArrayList();
private List<StackTraceElement> unwrittenStackTraceElements = new ArrayList();
private List<IdList> unwrittenTraces = new ArrayList();
private List<Context> unwrittenContexts = new ArrayList();
public SnapshotStreamWriter(String processDescription, OutputStream os) {
out = new DataOutputStream(os);
try {
out.writeByte(NEW_PROCESS);
out.writeUTF(processDescription);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void flush() {
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close() {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void writeCollectionFinished(int time) {
try {
out.writeByte(COLLECTION_TIME);
out.writeInt(time);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void write(long timestamp, Map<Thread, StackTraceElement[]> dump, Map<Thread, Context> contexts) throws IOException {
out.writeByte(TIMESTAMP);
out.writeLong(timestamp);
for (Thread thread : dump.keySet()) {
StackTraceElement trace[] = dump.get(thread);
Context context = contexts.get(thread);
// write everything to a temporary buffer so we can collect all the
// unwritten atoms first
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
writeThreadState(new DataOutputStream(buffer), thread, trace, context);
for (Context c : unwrittenContexts) {
int prevContextId = getContextId(c.getPrevious());
out.writeByte(NEW_CONTEXT);
out.writeInt(c.getInstance());
out.writeInt(prevContextId);
String[] keyValues = c.getKeyValues();
out.writeInt(keyValues.length / 2);
for (int i = 0; i < keyValues.length / 2; i++) {
String key = keyValues[i * 2];
String value = keyValues[i * 2];
out.writeInt(getAtomId(key));
out.writeInt(getAtomId(value));
}
}
unwrittenContexts.clear();
for (String atom : unwrittenAtoms) {
out.writeByte(NEW_ATOM);
out.writeUTF(atom);
}
unwrittenAtoms.clear();
out.write(buffer.toByteArray());
}
}
private void writeThreadState(DataOutputStream out, Thread thread2,
StackTraceElement[] trace, Context context) throws IOException {
String name = threadInfo.get(thread2.getId());
if (name == null || !name.equals(thread2.getName())) {
out.writeByte(THREAD_NAME);
out.writeLong(thread2.getId());
out.writeInt(getAtomId(thread2.getName()));
}
int traceId = getTraceId(trace);
int contextId = getContextId(context);
writeSample(out, thread2.getId(), thread2.getState(), traceId, contextId);
}
private int getAtomId(String str) {
Integer id = atoms.get(str);
if (id == null) {
id = atoms.size();
atoms.put(str, id);
unwrittenAtoms.add(str);
}
return id;
}
private void writeSample(DataOutputStream out, long threadId, Thread.State state, int traceId, int contextId)
throws IOException {
for (StackTraceElement e : unwrittenStackTraceElements) {
out.writeByte(NEW_TRACE_ELEMENT);
out.writeInt(getAtomId(e.getClassName()));
out.writeInt(getAtomId(e.getFileName()));
out.writeInt(getAtomId(e.getMethodName()));
out.writeInt(e.getLineNumber());
}
unwrittenStackTraceElements.clear();
for (IdList ids : unwrittenTraces) {
out.writeByte(NEW_TRACE);
out.writeShort(ids.ids.length);
for (int id : ids.ids) {
out.writeInt(id);
}
}
unwrittenTraces.clear();
out.writeByte(OBSERVED_TRACE);
out.writeLong(threadId);
out.writeByte(state.ordinal());
out.writeInt(traceId);
out.writeInt(contextId);
}
protected int getContextId(Context context) {
Integer id = contextIds.get(context);
if (id == null) {
id = contextIds.size();
contextIds.put(context, id);
unwrittenContexts.add(context);
}
return id;
}
private int getTraceId(StackTraceElement[] trace) {
int[] ids = new int[trace.length];
for (int i = 0; i < trace.length; i++) {
ids[i] = getTraceElementId(trace[i]);
}
IdList idList = new IdList(ids);
Integer traceId = traces.get(idList);
if (traceId == null) {
traceId = traces.size();
traces.put(idList, traceId);
unwrittenTraces.add(idList);
}
return traceId;
}
private int getTraceElementId(StackTraceElement stackTraceElement) {
HashableElement e = new HashableElement(stackTraceElement);
Integer id = stackTraceElements.get(e);
if (id == null) {
id = stackTraceElements.size();
stackTraceElements.put(e, id);
unwrittenStackTraceElements.add(stackTraceElement);
}
return id;
}
}
<file_sep>package org.github.sprofile.ui.timeline;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/26/12
* Time: 9:09 PM
* To change this template use File | Settings | File Templates.
*/
public class SelectionModel {
int selectionStart;
int selectionStop;
List<SelectionListener> selectionListenerList = new ArrayList();
public int getSelectionStart() {
return this.selectionStart;
}
public int getSelectionStop() {
return selectionStop;
}
public void setSelection(int selectionStart, int selectionStop) {
this.selectionStart = selectionStart;
this.selectionStop = selectionStop;
fireSelectionChanged();
}
protected void fireSelectionChanged() {
for (SelectionListener l : selectionListenerList) {
l.selectionChanged();
}
}
public void addSelectionListener(SelectionListener listener) {
this.selectionListenerList.add(listener);
}
public void removeSelectionListener(SelectionListener listener) {
this.selectionListenerList.remove(listener);
}
}
<file_sep>package org.github.sprofile.ui.timeline;
import org.github.sprofile.Context;
import org.github.sprofile.io.SampleListener;
import org.github.sprofile.ui.summary.SummaryTableRow;
import java.util.*;
public class TimelineBuilder implements SampleListener {
static class PointInTime {
final long timestamp;
final StackTraceElement[] trace;
final Context context;
PointInTime(long timestamp, StackTraceElement[] trace, Context context) {
this.timestamp = timestamp;
this.trace = trace;
this.context = context;
}
}
static class ThreadDetails {
String process;
long threadId;
Date start;
long lastTimestamp;
int samples;
List<PointInTime> points = new ArrayList();
}
Map<Long, ThreadDetails> threadDetailsMap = new HashMap();
Map<Long, String> threadNamesMap = new HashMap();
String currentProcess;
@Override
public void processDescription(String name) {
this.currentProcess = name;
}
@Override
public void sample(long timestamp, long threadId, Thread.State threadState, StackTraceElement[] trace, Context context) {
ThreadDetails threadDetails = threadDetailsMap.get(threadId);
if (threadDetails == null) {
threadDetails = new ThreadDetails();
threadDetails.threadId = threadId;
threadDetails.process = currentProcess;
threadDetails.start = new Date(timestamp);
threadDetailsMap.put(threadId, threadDetails);
}
threadDetails.lastTimestamp = timestamp;
threadDetails.samples++;
threadDetails.points.add(new PointInTime(timestamp, trace, context));
}
@Override
public void collectionTime(int milliseconds) {
}
@Override
public void threadName(long threadId, String name) {
threadNamesMap.put(threadId, name);
}
public List<SummaryTableRow> getThreads() {
List<SummaryTableRow> threads = new ArrayList();
for (ThreadDetails details : threadDetailsMap.values()) {
threads.add(new SummaryTableRow(details.process, details.threadId, threadNamesMap.get(details.threadId), details.samples, details.start, new Date(details.lastTimestamp), makeTimeline(details.points)));
}
return threads;
}
protected Timeline makeTimeline(List<PointInTime> pit) {
long[] timestamps = new long[pit.size()];
StackTraceElement[][] traces = new StackTraceElement[pit.size()][];
Context[] contexts = new Context[pit.size()];
for (int i = 0; i < pit.size(); i++) {
PointInTime p = pit.get(i);
timestamps[i] = p.timestamp;
traces[i] = p.trace;
contexts[i] = p.context;
}
return new Timeline(timestamps, traces, contexts);
}
}
<file_sep># SProfile - A toolkit for creating sampling profiles
## Background
Sprofile (still looking for a better name) is a library for embedding a
sampling profiler in a JVM process and visualizing/exploring the
results.
In the past I'd used YourKit which provided an excellent, rich ui, but I was
disappointed that it was not as flexible as I'd like. It's been a while,
but I remember being disappointed that while I could programatically capture
profiles, I didn't see a way to parse those generated profiles to mine
information that wasn't readily availible in the UI.
More recently, I've used jvisualvm which now has a sampling profiler, which
I've found, while less sleek, is very adequate. However, the software I was
building at the time were fair sized distributed Map/Reduce style jobs.
This made profiling more challenging because the processes I wanted to
collect information from were distributed across multiple machines.
Around that time I came across the Dapper paper (http://research.google.com/pubs/pub36356.html)
which I thought was very interesting. (I'm always a bit envous when I read about the
infrastructure that google has built and has at their disposal) While
Dapper is really about collecting traces distributed across
processes/servers and therefore different then the sampling profilers that
I'd been using, it got me thinking.
Looking at the source to jvisualvm and thinking about Dapper (and some
element of the intellectual exploration) eventually me to creating sprofile.
## Unique characteristics of Sprofile
(Maybe these traits exist elsewhere, but I hadn't encountered them)
* Samples are written as a sequential log. The idea being that you could
write multiple logs for different processes and then aggregate them together
in the UI to look at cross-server profiles. Also, this means that you can parse
an incomplete file and you should still get a valid profile up until a certain
point in time.
* There is the ability to save "context" information associated with a stack trace.
This can be used to embed some contextual information that will help explain
why it is spending so much time in the given routine. (For example, it
could be the filename that was passed into a parse call) If no sample is
taken while still in the call, then the context information is not written
and only adds very minimal overhead.
Sprofile is intended to be run with a very low sampling frequency. For these
large map/reduce jobs that took hours, even infrequent samples provide a
meaningful statistical sample. Also, sampling infrequently, the overhead
would be low enought that it would be part of the normal logging of the
process and used in production. When a performance question arose, we
could mine the already generated logs.
## Future work
I've considered adding:
* log memory usage along with each sample.
* add request handle for aggregating across threads. (This would allow
Dapper like cross-thread/process call trees to be constructed)
* Add thread state to timeline plot
* Add compression. There's already some amount of frugality in the
profile format, but a generic compressor would probably help greatly because
there still is a lot of repetition. There appear to be several fast
compressors availible, so I may try to incorporate one to further reduce the
size of the sample log.
<file_sep>package org.github.sprofile.io;
import org.github.sprofile.Context;
public interface SampleListener {
public void processDescription(String name);
public void threadName(long threadId, String name);
public void sample(long timestamp, long threadId,
Thread.State threadState, StackTraceElement[] trace, Context context);
public void collectionTime(int milliseconds);
}
<file_sep>package org.github.sprofile.ui.profile;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/26/12
* Time: 11:32 AM
* To change this template use File | Settings | File Templates.
*/
public class StackTreeNode {
final StackTraceElement element;
final float samplePercentage;
final int samples;
final List<StackTreeNode> children;
public StackTreeNode(StackTraceElement element, int samples, float samplePercentage, List<StackTreeNode> children) {
this.element = element;
this.samplePercentage = samplePercentage;
this.samples = samples;
this.children = children;
}
public float getSamplePercentage() {
return samplePercentage;
}
public int getSamples() {
return samples;
}
public List<StackTreeNode> getChildren() {
return children;
}
public StackTraceElement getElement() {
return element;
}
public String toString() {
if (element == null)
return "null";
return element.getMethodName();
}
}
<file_sep>package org.github.sprofile.servlet;
import org.github.sprofile.Profiler;
import org.github.sprofile.io.RollingFileWriter;
import org.github.sprofile.io.Writer;
import java.io.IOException;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/29/12
* Time: 4:46 PM
* To change this template use File | Settings | File Templates.
*/
public class ProfilerFactory {
public static final String CONFIG_PATH = "sprofile.properties";
public static final String PROCESS_DESCRIPTION = "processDescription";
public static final String LOG_FILE_PREFIX = "logPrefix";
public static final String LOG_LENGTH_THRESHOLD = "logLengthThreshold";
public static final String SLEEP_TIME = "sleepTime";
static Profiler profiler;
static int refCount;
private static String safeGet(Properties properties, String key) {
String value = (String) properties.get(key);
if (value == null) {
throw new RuntimeException("Could not find property key: " + key);
}
return value;
}
protected static Profiler createProfiler() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try {
props.load(classLoader.getResourceAsStream(CONFIG_PATH));
} catch (IOException ex) {
throw new RuntimeException("Got exception trying to load " + CONFIG_PATH + " from class loader");
}
long sleepTime = Long.parseLong(safeGet(props, SLEEP_TIME));
String processDescription = safeGet(props, PROCESS_DESCRIPTION);
int fileLengthThreshold = Integer.parseInt(safeGet(props, LOG_LENGTH_THRESHOLD));
String filenamePrefix = safeGet(props, LOG_FILE_PREFIX);
Writer writer = new RollingFileWriter(processDescription, fileLengthThreshold, 0, filenamePrefix);
return new Profiler(sleepTime, writer);
}
public synchronized static Profiler getInstance() {
if (profiler == null) {
refCount = 0;
profiler = createProfiler();
profiler.start();
}
refCount++;
return profiler;
}
public synchronized static void release(Profiler profiler) {
if (profiler != ProfilerFactory.profiler) {
throw new IllegalArgumentException("Tried to release an invalid instance of the profiler");
}
refCount--;
if (refCount < 0) {
throw new IllegalArgumentException("Profiler was released more times then it was obtained");
} else if (refCount == 0) {
profiler.stop();
ProfilerFactory.profiler = null;
}
}
}
<file_sep>package org.github.sprofile;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/22/12
* Time: 6:46 PM
* To change this template use File | Settings | File Templates.
*/
public class Details {
private final String[] names;
private final String[] values;
public Details(String... keyValues) {
names = new String[keyValues.length / 2];
values = new String[keyValues.length / 2];
for (int i = 0; i < keyValues.length; i += 2) {
names[i / 2] = keyValues[i];
values[i / 2] = keyValues[i + 1];
}
}
}
<file_sep>package org.github.sprofile.ui.profile;
import org.jdesktop.swingx.JXTreeTable;
import javax.swing.*;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.util.Arrays;
import java.util.Collections;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/26/12
* Time: 9:28 AM
* To change this template use File | Settings | File Templates.
*/
public class ProfileView {
public static JFrame createProfileWindow(StackTreeNode root) {
ProfileModel treeModel = new ProfileModel(root);
DefaultTreeCellRenderer treeCellRenderer = new DefaultTreeCellRenderer();
treeCellRenderer.setLeafIcon(null);
treeCellRenderer.setOpenIcon(null);
treeCellRenderer.setClosedIcon(null);
JXTreeTable tree = new JXTreeTable();
tree.setShowsRootHandles(true);
tree.setTreeCellRenderer(treeCellRenderer);
tree.setTreeTableModel(treeModel);
DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
TableColumn methodColumn = new TableColumn(0, 300, tree.getDefaultRenderer(String.class), tree.getDefaultEditor(String.class));
methodColumn.setHeaderValue(treeModel.getColumnName(0));
TableColumn packageColumn = new TableColumn(1, 50, tree.getDefaultRenderer(String.class), tree.getDefaultEditor(String.class));
packageColumn.setHeaderValue(treeModel.getColumnName(1));
TableColumn samplesColumn = new TableColumn(2, 50, tree.getDefaultRenderer(Integer.class), tree.getDefaultEditor(Integer.class));
samplesColumn.setHeaderValue(treeModel.getColumnName(2));
TableColumn percentColumn = new TableColumn(3, 100, new BarComponent(), tree.getDefaultEditor(Float.class));
percentColumn.setHeaderValue(treeModel.getColumnName(3));
columnModel.addColumn(methodColumn);
columnModel.addColumn(packageColumn);
columnModel.addColumn(samplesColumn);
columnModel.addColumn(percentColumn);
tree.setColumnModel(columnModel);
//tree.set
JFrame frame = new JFrame("Aggregated Profile");
frame.setSize(600, 400);
frame.getContentPane().add(new JScrollPane(tree));
// frame.pack();
return frame;
}
public static void main(String[] args) throws Exception {
StackTreeNode child1 = new StackTreeNode(new StackTraceElement("class", "method1", "file", 100), 30, 0.5f, Collections.EMPTY_LIST);
StackTreeNode child3 = new StackTreeNode(new StackTraceElement("class", "method2", "file", 100), 30, 0.2f, Collections.EMPTY_LIST);
StackTreeNode child2 = new StackTreeNode(new StackTraceElement("class", "method3", "file", 100), 30, 0.5f, Arrays.asList(child3));
StackTreeNode root = new StackTreeNode(null, 100, 0.5f, Arrays.asList(child1, child2));
JFrame frame = createProfileWindow(root);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
<file_sep>package org.github.sprofile.ui.timeline;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
public class TimelinePane extends JComponent {
Timeline model;
SelectionModel selectionModel;
public TimelinePane(SelectionModel selectionModel, Timeline model) {
super();
this.model = model;
this.selectionModel = selectionModel;
MouseInputAdapter listener = new MouseInputAdapter() {
int mouseDownIndex;
int mouseIndex;
@Override
public void mousePressed(MouseEvent mouseEvent) {
mouseDownIndex = mapClientXToIndex(mouseEvent.getX());
mouseIndex = mapClientXToIndex(mouseEvent.getX());
updateSelection(mouseDownIndex, mouseIndex);
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
mouseIndex = mapClientXToIndex(mouseEvent.getX());
updateSelection(mouseDownIndex, mouseIndex);
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
mouseIndex = mapClientXToIndex(mouseEvent.getX());
updateSelection(mouseDownIndex, mouseIndex);
}
};
this.addMouseListener(listener);
this.addMouseMotionListener(listener);
}
protected int mapClientXToIndex(int x) {
long elapsed = model.getElapsedTime();
long start = model.getTime(0);
long time = start + x * elapsed / getWidth();
return model.getIndexOf(time);
}
protected void updateSelection(int down, int up) {
selectionModel.setSelection(Math.min(up, down), Math.max(up, down) + 1);
repaint();
}
@Override
protected void paintComponent(Graphics graphics) {
int height = getHeight();
int width = getWidth();
graphics.setColor(Color.BLACK);
graphics.drawLine(0, height / 2, width, height / 2);
long elapsed = model.getElapsedTime();
long start = model.getTime(0);
int maxTraceDepth = model.getMaxTraceDepth() + 1;
int maxContextDepth = model.getMaxContextDepth() + 1;
int selectionStart = selectionModel.getSelectionStart();
int selectionStop = selectionModel.getSelectionStop();
// scale = elapsed / width
Rectangle clip = graphics.getClipBounds();
int lastX = clip.x - 1;
long startingTime = (lastX * elapsed / width) + start;
int firstIndex = model.getIndexOf(startingTime);
for (int i = firstIndex; i < model.getSampleCount(); i++) {
long time = model.getTime(i);
int x = (int) ((time - start) * width / elapsed);
// don't bother with overdraw. If we've already draw values for this column of pixels, move on
if (x <= lastX)
continue;
Color bg = Color.WHITE;
Color fg = Color.BLACK;
if (i >= selectionStart && i < selectionStop) {
fg = Color.BLUE;
bg = Color.YELLOW;
}
int traceDepth = model.getTraceDepth(i);
paintBar(graphics, fg, bg, lastX, 0, x - lastX, traceDepth * height / 2 / maxTraceDepth, height / 2);
int contextDepth = model.getContextDepth(i);
paintBar(graphics, fg, bg, lastX, height / 2, x - lastX, contextDepth * height / 2 / maxContextDepth, height / 2);
// don't bother drawing past the edge of the clip region
if (x > clip.x + clip.width)
break;
lastX = x;
}
}
private void paintBar(Graphics g, Color fg, Color bg, int x, int y, int w, int h, int full_h) {
g.setColor(fg);
g.fillRect(x, y, w, h);
g.setColor(bg);
g.fillRect(x, y + h, w, full_h - h);
}
public Timeline getModel() {
return model;
}
}
<file_sep>package org.github.sprofile;
import org.github.sprofile.io.SampleListener;
import org.github.sprofile.io.SamplesParser;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SummarizeProfiles {
static class Counts {
String name;
int self;
int children;
Map<String, Counts> childCounts;
}
public static final class SummarizeObservations implements
SampleListener {
@Override
public void processDescription(String name) {
throw new RuntimeException("unimplemented");
}
@Override
public void sample(long timestamp, long threadId, Thread.State threadState, StackTraceElement[] trace, Context context) {
if (filter != null) {
boolean foundMatch = false;
for (StackTraceElement element : trace) {
Matcher m = filter.matcher(element.getClassName());
if (m.matches()) {
foundMatch = true;
break;
}
}
if (!foundMatch)
return;
}
Counts tree = callTree;
for (StackTraceElement element : trace) {
get(element).children++;
String methodName = element.getClassName() + "."
+ element.getMethodName();
Counts node = tree.childCounts.get(methodName);
if (node == null) {
node = new Counts();
node.name = methodName;
node.childCounts = new HashMap();
tree.childCounts.put(methodName, node);
}
node.children++;
tree = node;
}
tree.self++;
if (trace.length > 0) {
StackTraceElement element = trace[trace.length - 1];
get(element).self++;
}
}
final static Comparator<Counts> COMPARE_BY_CHILD_COUNT = new Comparator<Counts>() {
public int compare(Counts o1, Counts o2) {
return -(o1.children - o2.children);
}
};
Pattern filter;
public SummarizeObservations(Pattern filter) {
this.filter = filter;
this.callTree.childCounts = new HashMap();
this.callTree.name = "[root]";
}
Map<String, Counts> counts = new HashMap();
Counts callTree = new Counts();
@Override
public void threadName(long threadId, String name) {
}
private Counts get(StackTraceElement element) {
String methodName = element.getClassName() + "."
+ element.getMethodName();
Counts c = counts.get(methodName);
if (c == null) {
c = new Counts();
c.name = methodName;
counts.put(methodName, c);
}
return c;
}
public void collectionTime(int milliseconds) {
}
public void printCollectionSummary() {
List<Counts> sorted = new ArrayList(counts.values());
Collections.sort(sorted, COMPARE_BY_CHILD_COUNT);
for (Counts c : sorted) {
System.out.println("" + c.children + "\t" + c.self + "\t"
+ c.name);
}
System.out.println("\nCall tree:");
printTree(System.out, 0, callTree);
}
public void printTree(PrintStream out, int indentLevel, Counts tree) {
out.print("" + tree.children + "\t" + tree.self + "\t");
for (int i = 0; i < indentLevel; i++) {
out.print('\t');
}
out.println(tree.name);
List<Counts> children = new ArrayList(tree.childCounts.values());
Collections.sort(children, COMPARE_BY_CHILD_COUNT);
for (Counts child : children) {
// prune any nodes that only have a single sample
if (child.children > 1)
printTree(out, indentLevel + 1, child);
}
}
}
public static void main(String[] args) throws IOException {
Pattern filter = null;
if (args.length > 1) {
filter = Pattern.compile(args[1]);
}
SummarizeObservations listener = new SummarizeObservations(filter);
recursivelyParse(new File(args[0]), listener);
listener.printCollectionSummary();
}
private static void recursivelyParse(File path,
SummarizeObservations listener) throws IOException {
for (File child : path.listFiles()) {
if (child.isDirectory()) {
recursivelyParse(child, listener);
} else if (child.getName().startsWith("samples")
&& child.getName().endsWith(".dat")) {
System.out.println("reading " + child.getPath());
SamplesParser pp = new SamplesParser(child.getAbsolutePath(),
listener);
pp.read();
}
}
}
}
<file_sep>package org.github.sprofile.io;
import org.github.sprofile.Context;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/27/12
* Time: 11:43 PM
* To change this template use File | Settings | File Templates.
*/
public class SamplesParser extends ProfileParser {
static class Adapter implements ProfileVisitor {
final SampleListener listener;
long timestamp;
Adapter(SampleListener listener) {
this.listener = listener;
}
@Override
public void handleTimestamp(long timestamp) {
this.timestamp = timestamp;
}
@Override
public void handleTraceElement(int id, String className, String filename, String methodName, int lineNumber) {
}
@Override
public void handleTrace(int id, StackTraceElement[] elements) {
}
@Override
public void handleSampledTrace(long threadId, Thread.State state, StackTraceElement[] trace, Context context) {
listener.sample(timestamp, threadId, state,
trace, context);
}
@Override
public void handleThreadName(long threadId, String threadName) {
listener.threadName(threadId, threadName);
}
@Override
public void handleAtom(int id, String value) {
}
@Override
public void handleCollectionTime(int elapsed) {
}
@Override
public void handleProcessInfo(String name) {
listener.processDescription(name);
}
@Override
public void handleContext(int prevContextId, Context context) {
}
}
public SamplesParser(String filename, SampleListener listener) throws IOException {
super(filename, new Adapter(listener));
}
}
<file_sep>package org.github.sprofile;
import org.github.sprofile.io.SnapshotStreamWriter;
import org.itadaki.bzip2.BZip2OutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Profiler2Test {
static void call1(int count) throws Exception {
Thread.sleep(100);
call2(count);
Thread.sleep(50);
call3();
Thread.sleep(100);
}
static void call2(int count) throws Exception {
Thread.sleep(100);
for (int i = 0; i < count; i++) {
call4();
}
Thread.sleep(100);
}
static void call3() throws Exception {
Thread.sleep(100);
}
static void call4() throws Exception {
Thread.sleep(30);
}
static public void main(String args[]) throws Exception {
System.out.println(new File(".").getAbsolutePath());
FileOutputStream out = new FileOutputStream("profile2");
SnapshotStreamWriter writer = new SnapshotStreamWriter("sample proc", out);
Profiler p = new Profiler(50, writer);
p.start();
runCpuIntensiveTask();
p.stop();
out.close();
}
public static void runCpuIntensiveTask() throws Exception {
for (int i = 0; i < 3; i++) {
FileInputStream in = new FileInputStream("/Users/pgm/search_results.FASTA");
byte[] buffer = new byte[5000];
BZip2OutputStream dest = new BZip2OutputStream(new FileOutputStream("/tmp/dump"));
while (true) {
int read = in.read(buffer);
if (read < 0) {
break;
}
dest.write(buffer, 0, read);
}
in.close();
dest.close();
System.out.println("" + i);
}
}
}
<file_sep>package org.github.sprofile.ui.summary;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class SummaryForm {
private JTextField elementFilterTextField;
private JButton viewTimelineButton;
private JTable table;
private JButton viewAggregateTimesButton;
private JTextField traceFilterTextField;
public JPanel rootPanel;
private final List<SummaryTableRow> rows;
private final Controller controller;
public SummaryForm(Controller controller, List<SummaryTableRow> rows) {
if(controller == null) {
throw new NullPointerException();
}
if(rows == null) {
throw new NullPointerException();
}
SummaryTableModel model = new SummaryTableModel(rows);
table.setModel(model);
this.controller = controller;
this.rows = rows;
viewAggregateTimesButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
SummaryForm.this.controller.showAggregate(getSelectedRows(), elementFilterTextField.getText(), traceFilterTextField.getText());
}
});
viewTimelineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
SummaryForm.this.controller.showTimeline(SummaryForm.this.rows.get(table.getSelectedRow()), elementFilterTextField.getText(), traceFilterTextField.getText());
}
});
updateButtonState();
}
private List<SummaryTableRow> getSelectedRows() {
List<SummaryTableRow> rows = new ArrayList();
for (int rowIndex : table.getSelectedRows()) {
rows.add(this.rows.get(rowIndex));
}
return rows;
}
protected void updateButtonState() {
int rowCount = table.getSelectedRows().length;
viewTimelineButton.setEnabled(rowCount == 1);
viewAggregateTimesButton.setEnabled(rowCount >= 1);
}
private void createUIComponents() {
SummaryTableModel model = new SummaryTableModel(new ArrayList<SummaryTableRow>());
table = new JTable();
table.setModel(model);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent listSelectionEvent) {
updateButtonState();
}
});
}
}
<file_sep>package org.github.sprofile.io;
import org.github.sprofile.Context;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/27/12
* Time: 11:43 PM
* To change this template use File | Settings | File Templates.
*/
public interface ProfileVisitor {
public void handleTimestamp(long timestamp);
public void handleTraceElement(int id, String className, String filename, String methodName, int lineNumber);
public void handleTrace(int id, StackTraceElement[] elements);
public void handleSampledTrace(long threadId, Thread.State state, StackTraceElement[] trace, Context context);
public void handleThreadName(long threadId, String threadName);
public void handleAtom(int id, String value);
public void handleCollectionTime(int elapsed);
public void handleProcessInfo(String name);
public void handleContext(int id, Context context);
}
<file_sep>package org.github.sprofile.io;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: pgm
* Date: 12/22/12
* Time: 5:46 PM
* To change this template use File | Settings | File Templates.
*/
class IdList {
final int ids[];
public IdList(int ids[]) {
this.ids = ids;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(ids);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IdList other = (IdList) obj;
if (!Arrays.equals(ids, other.ids))
return false;
return true;
}
}
| 607f6ad5358ec8533c96d6f7484880efba32121c | [
"Markdown",
"Java",
"Gradle"
] | 21 | Gradle | pgm/sprofile | c03a27a9d95cc32593fabb14b62083ced6632b86 | 39cfd4d5c1abbf377eab22928f90dbfbc8b6ff11 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
public class PlateConfigDTO
{
private double[,] mPlateConfig = null;
private List<int> mPreferAddressIndexList = new List<int>();
private List<int> mPreferWorkShopIndexList = new List<int>();
public string Name { get; set; }
public DateTime InitialImportDate { get; set; } // 최초 투입 예정일
public DateTime InitialExportDate { get; set; } // 최초 종료 예정일
public DateTime ActualImportDate { get; set; } // 실제 투입일
public DateTime ActualExportDate { get; set; } // 실제 종료일
public DateTime PlanImportDate { get; set; } //(알고리즘 내에서) 현재 예정된 투입일
public DateTime PlanExportDate { get; set; } //(알고리즘 내에서) 현재 예정된 종료일
public bool IsDelayed { get; set; }
public bool IsLocated { get; set; }
public bool IsFinished { get; set; }
public double DelayedDays { get; set; }
public double LeadTime { get; set; }
//Period 추가
public int Period { get; set; }
public int RowCount { get; set; }
public int ColCount { get; set; }
public int CurrentLocatedWorkshopIndex { get; set; }
public int ActualLocatedWorkshopIndex { get; set; }
public int CurrentLocatedAddressIndex { get; set; }
public int LocatedRow { get; set; }
public int LocateCol { get; set; }
public double[,] PlateConfig //비어있는곳은 0, 차있으면 1
{
get
{
double[,] _getter = null;
if (mPlateConfig != null)
{
_getter = (double[,])mPlateConfig.Clone();
}
return _getter;
}
set
{
if (value != null)
{
double[,] _setter = (double[,])value.Clone();
mPlateConfig = _setter;
}
}
}
public List<int> PreferWorkShopIndexList
{
get
{
List<int> _getter = null;
if (mPreferWorkShopIndexList != null)
{
_getter = new List<int>();
for (int i = 0; i < mPreferWorkShopIndexList.Count; i++) _getter.Add(mPreferWorkShopIndexList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mPreferWorkShopIndexList = new List<int>();
for (int i = 0; i < value.Count; i++) mPreferWorkShopIndexList.Add(value[i]);
}
}
}
public List<int> PreferAddressIndexList
{
get
{
List<int> _getter = null;
if (mPreferAddressIndexList != null)
{
_getter = new List<int>();
for (int i = 0; i < mPreferAddressIndexList.Count; i++) _getter.Add(mPreferAddressIndexList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mPreferAddressIndexList = new List<int>();
for (int i = 0; i < value.Count; i++) mPreferAddressIndexList.Add(value[i]);
}
}
}
public PlateConfigDTO()
{
Name = "";
InitialImportDate = DateTime.MaxValue;
InitialExportDate = DateTime.MaxValue;
ActualImportDate = DateTime.MaxValue;
ActualExportDate = DateTime.MaxValue;
PlanImportDate = DateTime.MaxValue;
PlanExportDate = DateTime.MaxValue;
IsDelayed = false;
IsLocated = false;
IsFinished = false;
DelayedDays = 0;
LeadTime = 0;
RowCount = 0;
ColCount = 0;
mPreferAddressIndexList = new List<int>();
mPreferWorkShopIndexList = new List<int>();
}
public PlateConfigDTO(string PlateName, int ConfigRow, int ConfigCol)
{
Name = PlateName;
RowCount = ConfigRow;
ColCount = ConfigCol;
InitialImportDate = DateTime.MaxValue;
InitialExportDate = DateTime.MaxValue;
ActualImportDate = DateTime.MaxValue;
ActualExportDate = DateTime.MaxValue;
PlanImportDate = DateTime.MaxValue;
PlanExportDate = DateTime.MaxValue;
IsFinished = false;
IsDelayed = false;
IsLocated = false;
DelayedDays = 0;
LeadTime = 0;
mPreferAddressIndexList = new List<int>();
mPreferWorkShopIndexList = new List<int>();
}
public PlateConfigDTO Clone()
{
PlateConfigDTO ResultDTO = new PlateConfigDTO();
ResultDTO.Name = this.Name;
ResultDTO.RowCount = this.RowCount;
ResultDTO.ColCount = this.ColCount;
ResultDTO.IsDelayed = this.IsDelayed;
ResultDTO.IsLocated = this.IsLocated;
ResultDTO.IsFinished = this.IsFinished;
ResultDTO.DelayedDays = this.DelayedDays;
ResultDTO.LeadTime = this.LeadTime;
//Period 추가
ResultDTO.Period = this.Period;
ResultDTO.CurrentLocatedWorkshopIndex = this.CurrentLocatedWorkshopIndex;
ResultDTO.ActualLocatedWorkshopIndex = this.ActualLocatedWorkshopIndex;
ResultDTO.InitialImportDate = this.InitialImportDate;
ResultDTO.InitialExportDate = this.InitialExportDate;
ResultDTO.ActualImportDate = this.ActualImportDate;
ResultDTO.ActualExportDate = this.ActualExportDate;
ResultDTO.PlanImportDate = this.PlanImportDate;
ResultDTO.PlanExportDate = this.PlanExportDate;
ResultDTO.PlateConfig = this.PlateConfig;
for (int i = 0; i < this.PreferWorkShopIndexList.Count; i++) ResultDTO.PreferWorkShopIndexList.Add(this.PreferWorkShopIndexList[i]);
for (int i = 0; i < this.PreferAddressIndexList.Count; i++) ResultDTO.PreferAddressIndexList.Add(this.PreferAddressIndexList[i]);
return ResultDTO;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using System.Drawing;
using System.Windows.Forms;
using System.CodeDom.Compiler;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Implementation
{
public class BlockArrangementMgr : IBlockArrangement
{
#region 지번 자동할당
/// <summary>
/// 지번 자동 할당 (지번 갯수 만큼 작업장을 열방향으로 등분함)
/// </summary>
/// <param name="WorkShopList">작업장 정보 리스트</param>
/// <returns>지번 정보가 입력되어 있는 UnitcellDTO 배열 목록</returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
List<UnitcellDTO[,]> IBlockArrangement.InitializeArrangementMatrixWithAddress(List<WorkshopDTO> WorkShopList)
{
List<UnitcellDTO[,]> ResultWorkShopList = new List<UnitcellDTO[,]>();
for (int WorkShopCount = 0; WorkShopCount < WorkShopList.Count; WorkShopCount++)
{
UnitcellDTO[,] tempWorkShop = new UnitcellDTO[Convert.ToInt16(Math.Ceiling(WorkShopList[WorkShopCount].RowCount)), Convert.ToInt16(Math.Ceiling(WorkShopList[WorkShopCount].ColumnCount))];
int NumOfAddress = WorkShopList[WorkShopCount].NumOfAddress;
int addressStartColumn = 0;
for (int CurrentAddress = 0; CurrentAddress < NumOfAddress; CurrentAddress++)
{
int rowOfAddress = 0;
if (CurrentAddress != (NumOfAddress - 1)) rowOfAddress = Convert.ToInt16(Math.Ceiling(Convert.ToDouble(WorkShopList[WorkShopCount].ColumnCount) / Convert.ToDouble(NumOfAddress)));
else rowOfAddress = Convert.ToInt16(Math.Ceiling(WorkShopList[WorkShopCount].ColumnCount)) - Convert.ToInt16(Math.Ceiling(WorkShopList[WorkShopCount].ColumnCount / NumOfAddress)) * (NumOfAddress - 1);
for (int row = 0; row < WorkShopList[WorkShopCount].RowCount; row++)
{
for (int column = addressStartColumn; column < addressStartColumn + rowOfAddress; column++)
{
tempWorkShop[row, column] = new UnitcellDTO(-1, false, CurrentAddress);
}
}
addressStartColumn = addressStartColumn + rowOfAddress;
}
ResultWorkShopList.Add(tempWorkShop);
}
return ResultWorkShopList;
}
/// <summary>
/// 배치 매트릭스 생성, 배치 불가구역 설정
/// </summary>
/// <param name="WorkShopList">작업장 정보 리스트</param>
/// <returns>배치 불가구역이 설정되어 있는 배치 매트릭스 리스트</returns>
/// <remarks>
/// 최초 작성 : 유상현, 2020년 05월 12일
/// </remarks>
List<Int32[,]> IBlockArrangement.InitializeArrangementMatrix(List<WorkshopDTO> WorkShopList)
{
List<Int32[,]> ArrangementMatrixList = new List<int[,]>();
for (int WorkShopCount = 0; WorkShopCount < WorkShopList.Count; WorkShopCount++)
{
// 모든 칸이 0으로 초기화된 작업장 크기만큼의 배치 매트릭스 생성
// 작업장 타입이 -1인 경우는 모두 1로 초기화
int tempWorkshopRowCount = Convert.ToInt32(Math.Ceiling(WorkShopList[WorkShopCount].RowCount));
int tempWorkshopColumnCount = Convert.ToInt32(Math.Ceiling(WorkShopList[WorkShopCount].ColumnCount));
Int32[,] tempArrangementMatrix = new Int32[tempWorkshopRowCount, tempWorkshopColumnCount];
if (WorkShopList[WorkShopCount].Type != -1)
{
for (int i = 0; i < tempWorkshopRowCount; i++)
{
for (int j = 0; j < tempWorkshopColumnCount; j++)
{
tempArrangementMatrix[i, j] = 0;
}
}
}
else
{
for (int i = 0; i < tempWorkshopRowCount; i++)
{
for (int j = 0; j < tempWorkshopColumnCount; j++)
{
tempArrangementMatrix[i, j] = 1;
}
}
}
// 해당 배치 매트릭스에 배치 불가구역이 있는 경우 배치
foreach (ArrangementMatrixInfoDTO arrangementMatrixInfo in WorkShopList[WorkShopCount].ArrangementMatrixInfoList)
{
int tempRowLocation = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.RowLocation));
int tempColumnLocation = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.ColumnLocation));
int tempRowCount = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.RowCount));
int tempColumnCount = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.ColumnCount));
tempArrangementMatrix = PutBlockOnMatrix(tempArrangementMatrix, tempRowLocation, tempColumnLocation, tempRowCount, tempColumnCount, 0);
}
ArrangementMatrixList.Add(tempArrangementMatrix);
}
return ArrangementMatrixList;
}
/// <summary>
/// 배치 매트릭스 생성, 배치 불가구역 설정
/// </summary>
/// <param name="WorkShopList">작업장 정보 리스트</param>
/// <returns>배치 불가구역이 설정되어 있는 배치 매트릭스 리스트</returns>
/// <remarks>
/// 최초 작성 : 유상현, 2020년 05월 12일
/// </remarks>
public List<Int32[,]> InitializeArrangementMatrixWithSlack(List<WorkshopDTO> WorkShopList, int Slack)
{
List<Int32[,]> ArrangementMatrixList = new List<int[,]>();
for (int WorkShopCount = 0; WorkShopCount < WorkShopList.Count; WorkShopCount++)
{
// 모든 칸이 0으로 초기화된 작업장 크기만큼의 배치 매트릭스 생성
int tempWorkshopRowCount = Convert.ToInt32(Math.Ceiling(WorkShopList[WorkShopCount].RowCount));
int tempWorkshopColumnCount = Convert.ToInt32(Math.Ceiling(WorkShopList[WorkShopCount].ColumnCount));
// 양측 여유공간 더해줌
tempWorkshopRowCount += Slack * 2;
tempWorkshopColumnCount += Slack * 2;
Int32[,] tempArrangementMatrix = new Int32[tempWorkshopRowCount, tempWorkshopColumnCount];
if (WorkShopList[WorkShopCount].Type != -1)
{
for (int i = 0; i < tempWorkshopRowCount; i++)
{
for (int j = 0; j < tempWorkshopColumnCount; j++)
{
tempArrangementMatrix[i, j] = 0;
}
}
}
else
{
for (int i = 0; i < tempWorkshopRowCount; i++)
{
for (int j = 0; j < tempWorkshopColumnCount; j++)
{
tempArrangementMatrix[i, j] = 1;
}
}
}
// 해당 배치 매트릭스에 배치 불가구역이 있는 경우 배치
foreach (ArrangementMatrixInfoDTO arrangementMatrixInfo in WorkShopList[WorkShopCount].ArrangementMatrixInfoList)
{
int tempRowLocation = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.RowLocation));
int tempColumnLocation = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.ColumnLocation));
int tempRowCount = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.RowCount));
int tempColumnCount = Convert.ToInt32(Math.Ceiling(arrangementMatrixInfo.ColumnCount));
// 여유공간만큼 이격해서 배치
tempRowLocation += Slack;
tempColumnLocation += Slack;
tempArrangementMatrix = PutBlockOnMatrix(tempArrangementMatrix, tempRowLocation, tempColumnLocation, tempRowCount, tempColumnCount, 0);
}
ArrangementMatrixList.Add(tempArrangementMatrix);
}
return ArrangementMatrixList;
}
#endregion 지번 자동할당
#region BLF, Greedy 알고리즘
/// <summary>
/// 투입일, 반출일, 지번을 고려한 BLF 알고리즘
/// </summary>
/// <param name="inputBlockList">입력 블록 정보</param>
/// <param name="ArrangementMatrix">배치할 작업장에 대한 정보(그리드)</param>
/// <param name="WorkShopInfo">배치할 작업장에 대한 정보</param>
/// <param name="ArrangementStartDate">배치 시작일</param>
/// <param name="ArrangementFinishDate">배치 종료일</param>
/// <returns>블록 배치 결과</returns>
/// 최초 작성 : 주수헌, 2015년 9월 20일
/// 수정 일자 : 유상현, 2020년 5월 15일
ArrangementResultWithDateDTO IBlockArrangement.RunBLFAlgorithm(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArrangementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel)
{
ArrangementResultWithDateDTO ResultInfo;
List<List<WorkshopDTO>> TotalWorkshopResultList = new List<List<WorkshopDTO>>();
List<Int32[,]> CurrentArrangementMatrix = ArrangementMatrixList;
List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
List<BlockDTO> BlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalDailyDelayedBlockList = new List<List<BlockDTO>>();
DateTime CurrentArrangementDate = new DateTime();
// 배치 시작일을 현재 배치일로 지정
CurrentArrangementDate = ArrangementStartDate;
// 입력 블록 리스트를 함수 내부에서 사용할 리스트로 복사
for (int i = 0; i < inputBlockList.Count; i++)
{
BlockList.Add(inputBlockList[i].Clone());
}
List<BlockDTO> TodayCandidateBlockList;
List<BlockDTO> TodayImportBlock;
List<BlockDTO> TodayExportBlock;
List<BlockDTO> TodayDelayedBlockList;
TimeSpan ts = ArrangementFinishDate - ArrangementStartDate;
int differenceInDays = ts.Days;
ProgressBar.Maximum = differenceInDays;
int count = 0;
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, 0);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가
if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 원래 배치 일이 오늘인 것 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate) TodayCandidateBlockList.Add(Block);
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
BlockLocation = DetermineBlockLocation(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0);
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // 작업장 순회 for loop 종료
if (!IsLocated)
{
TodayDelayedBlockList.Add(Block);
Block.IsDelayed = true;
Block.DelayedTime += 1;
Block.ImportDate = Block.ImportDate.AddDays(1);
Block.ExportDate = Block.ExportDate.AddDays(1);
}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
List<List<int>> tempBlockIndexList = new List<List<int>>();
double[] SumBlockArea = new double[WorkShopInfo.Count];
for (int n = 0; n < WorkShopInfo.Count; n++)
{
tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
tempBlockIndexList.Add(new List<int>());
SumBlockArea[n] = 0;
}
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
}
foreach (WorkshopDTO Workshop in tempWorkshopInfo)
{
Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
}
//날짜별 변수를 리스트에 저장
TotalBlockImportLogList.Add(TodayImportBlock);
TotalBlockExportLogList.Add(TodayExportBlock);
TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
TotalWorkshopResultList.Add(tempWorkshopInfo);
List<BlockDTO> tempBlockList = new List<BlockDTO>();
for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
{
BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow;
temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn;
temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
tempBlockList.Add(temp);
}
TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}//while 종료
ProgressLabel.Text = "Completed!";
ProgressBar.GetCurrentParent().Refresh();
//결과 전달을 위한 DTO 생성
ResultInfo = new ArrangementResultWithDateDTO(TotalWorkshopResultList, BlockList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDailyDelayedBlockList);
return ResultInfo;
}
/// <summary>
/// 투입일, 반출일, 지번을 고려한 BLF 알고리즘
/// </summary>
/// <param name="inputBlockList">입력 블록 정보</param>
/// <param name="ArrangementMatrix">배치할 작업장에 대한 정보(그리드)</param>
/// <param name="WorkShopInfo">배치할 작업장에 대한 정보</param>
/// <param name="ArrangementStartDate">배치 시작일</param>
/// <param name="ArrangementFinishDate">배치 종료일</param>
/// <returns>블록 배치 결과</returns>
/// 최초 작성 : 주수헌, 2015년 9월 20일
/// 수정 일자 : 유상현, 2020년 5월 15일
ArrangementResultWithDateDTO IBlockArrangement.RunBLFAlgorithmWithAddress(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArrangementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel)
{
ArrangementResultWithDateDTO ResultInfo;
List<List<WorkshopDTO>> TotalWorkshopResultList = new List<List<WorkshopDTO>>();
List<Int32[,]> CurrentArrangementMatrix = ArrangementMatrixList;
List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
List<BlockDTO> BlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalDailyDelayedBlockList = new List<List<BlockDTO>>();
DateTime CurrentArrangementDate = new DateTime();
// 배치 시작일을 현재 배치일로 지정
CurrentArrangementDate = ArrangementStartDate;
// 입력 블록 리스트를 함수 내부에서 사용할 리스트로 복사
for (int i = 0; i < inputBlockList.Count; i++)
{
BlockList.Add(inputBlockList[i].Clone());
}
List<BlockDTO> TodayCandidateBlockList;
List<BlockDTO> TodayImportBlock;
List<BlockDTO> TodayExportBlock;
List<BlockDTO> TodayDelayedBlockList;
TimeSpan ts = ArrangementFinishDate - ArrangementStartDate;
int differenceInDays = ts.Days;
ProgressBar.Maximum = differenceInDays;
int count = 0;
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가
if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 원래 배치 일이 오늘인 것 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate) TodayCandidateBlockList.Add(Block);
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
#region 첫 작업장에서 선호 지번 고려한 배치
// PreferWorkShopCount = 0이면 선호 지번 고려한 배치. if (PreferWorkshopCount == 0) for (int PreferAddressCount = 0; PreferAddressCount < Block.PreferAddressIndexList.Count; PreferAddressCount++) 선호지번 고려한 배치가능구역 탐색 함수
if (PreferWorkShopCount == 0)
{
for (int PreferAddressCount = 0; PreferAddressCount < Block.PreferAddressIndexList.Count; PreferAddressCount++)
{
// 선호지번의 좌우측 경계 열 번호 가져오기
double AddressLeftPoint = WorkShopInfo[CurrentWorkShopNumber].AddressColumnLocation[Block.PreferAddressIndexList[PreferAddressCount]];
double AddressRightPoint;
try
{
AddressRightPoint = WorkShopInfo[CurrentWorkShopNumber].AddressColumnLocation[Block.PreferAddressIndexList[PreferAddressCount] + 1];
}
catch (Exception)
{
AddressRightPoint = WorkShopInfo[CurrentWorkShopNumber].ColumnCount;
}
// 해당 선호지번 구역 내에서 배치 가능 유무 파악
int[] tempBlockLocation = new int[3];
tempBlockLocation = DetermineBlockLocationWithAddress(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, AddressLeftPoint, AddressRightPoint, 1);
if (tempBlockLocation[0] == -1) tempBlockLocation = DetermineBlockLocationWithAddress(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, AddressLeftPoint, AddressRightPoint, 0);
// 배치 가능한 경우 배치
if (tempBlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], tempBlockLocation[0], tempBlockLocation[1], Block.RowCount, Block.ColumnCount, tempBlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = tempBlockLocation[0];
Block.LocatedColumn = tempBlockLocation[1];
Block.Orientation = tempBlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.IsConditionSatisfied = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break;
}
}
}
if (IsLocated) break; // 작업장 순회 for loop 탈출
#endregion 첫 작업장에서 선호 지번 고려한 배치
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
BlockLocation = DetermineBlockLocation(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocation(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0);
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // 작업장 순회 for loop 종료
if (!IsLocated)
{
TodayDelayedBlockList.Add(Block);
Block.IsDelayed = true;
Block.DelayedTime += 1;
Block.ImportDate = Block.ImportDate.AddDays(1);
Block.ExportDate = Block.ExportDate.AddDays(1);
}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
List<List<int>> tempBlockIndexList = new List<List<int>>();
double[] SumBlockArea = new double[WorkShopInfo.Count];
for (int n = 0; n < WorkShopInfo.Count; n++)
{
tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
tempBlockIndexList.Add(new List<int>());
SumBlockArea[n] = 0;
}
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
}
foreach (WorkshopDTO Workshop in tempWorkshopInfo)
{
Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
}
//날짜별 변수를 리스트에 저장
TotalBlockImportLogList.Add(TodayImportBlock);
TotalBlockExportLogList.Add(TodayExportBlock);
TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
TotalWorkshopResultList.Add(tempWorkshopInfo);
List<BlockDTO> tempBlockList = new List<BlockDTO>();
for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
{
BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow;
temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn;
temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
temp.DelayedTime = CurrentArrangementedBlockList[i].DelayedTime;
tempBlockList.Add(temp);
}
TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}//while 종료
ProgressLabel.Text = "Completed!";
ProgressBar.GetCurrentParent().Refresh();
//결과 전달을 위한 DTO 생성
ResultInfo = new ArrangementResultWithDateDTO(TotalWorkshopResultList, BlockList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDailyDelayedBlockList);
return ResultInfo;
}
/// <summary>
/// 투입일, 반출일을 고려한 BLF 알고리즘 + 여유공간
/// </summary>
/// <param name="inputBlockList">입력 블록 정보</param>
/// <param name="ArrangementMatrix">배치할 작업장에 대한 정보(그리드)</param>
/// <param name="WorkShopInfo">배치할 작업장에 대한 정보</param>
/// <param name="ArrangementStartDate">배치 시작일</param>
/// <param name="ArrangementFinishDate">배치 종료일</param>
/// <returns>블록 배치 결과</returns>
/// 최초 작성 : 주수헌, 2015년 9월 20일
/// 수정 일자 : 유상현, 2020년 5월 15일
ArrangementResultWithDateDTO IBlockArrangement.RunBLFAlgorithmWithSlack(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArrangementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack)
{
ArrangementResultWithDateDTO ResultInfo;
List<List<WorkshopDTO>> TotalWorkshopResultList = new List<List<WorkshopDTO>>();
List<Int32[,]> CurrentArrangementMatrix = ArrangementMatrixList;
List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
List<BlockDTO> BlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalDailyDelayedBlockList = new List<List<BlockDTO>>();
DateTime CurrentArrangementDate = new DateTime();
// 배치 시작일을 현재 배치일로 지정
CurrentArrangementDate = ArrangementStartDate;
// 입력 블록 리스트를 함수 내부에서 사용할 리스트로 복사 + 양측 여유공간 더해줌
for (int i = 0; i < inputBlockList.Count; i++)
{
BlockList.Add(inputBlockList[i].Clone());
BlockList[i].RowCount += Slack * 2 + BlockList[i].UpperSideCount + BlockList[i].BottomSideCount;
BlockList[i].ColumnCount += Slack * 2 + BlockList[i].LeftSideCount + BlockList[i].RightSideCount;
}
List<BlockDTO> TodayCandidateBlockList;
List<BlockDTO> TodayImportBlock;
List<BlockDTO> TodayExportBlock;
List<BlockDTO> TodayDelayedBlockList;
TimeSpan ts = ArrangementFinishDate - ArrangementStartDate;
int differenceInDays = ts.Days;
ProgressBar.Maximum = differenceInDays;
int count = 0;
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가
if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 원래 배치 일이 오늘인 것 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate) TodayCandidateBlockList.Add(Block);
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // 작업장 순회 for loop 종료
if (!IsLocated)
{
TodayDelayedBlockList.Add(Block);
Block.IsDelayed = true;
Block.DelayedTime += 1;
Block.ImportDate = Block.ImportDate.AddDays(1);
Block.ExportDate = Block.ExportDate.AddDays(1);
}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
List<List<int>> tempBlockIndexList = new List<List<int>>();
double[] SumBlockArea = new double[WorkShopInfo.Count];
for (int n = 0; n < WorkShopInfo.Count; n++)
{
tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
tempBlockIndexList.Add(new List<int>());
SumBlockArea[n] = 0;
}
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
}
foreach (WorkshopDTO Workshop in tempWorkshopInfo)
{
Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
}
//날짜별 변수를 리스트에 저장
TotalBlockImportLogList.Add(TodayImportBlock);
TotalBlockExportLogList.Add(TodayExportBlock);
TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
TotalWorkshopResultList.Add(tempWorkshopInfo);
List<BlockDTO> tempBlockList = new List<BlockDTO>();
for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
{
BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow + temp.UpperSideCount;
temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn + temp.LeftSideCount;
temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
temp.DelayedTime = CurrentArrangementedBlockList[i].DelayedTime;
//여유공간 다시 빼줌
temp.RowCount -= Slack * 2 + temp.UpperSideCount + temp.BottomSideCount;
temp.ColumnCount -= Slack * 2 + temp.LeftSideCount + temp.RightSideCount;
tempBlockList.Add(temp);
}
TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}//while 종료
ProgressLabel.Text = "Completed!";
ProgressBar.GetCurrentParent().Refresh();
//결과 전달을 위한 DTO 생성
ResultInfo = new ArrangementResultWithDateDTO(TotalWorkshopResultList, BlockList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDailyDelayedBlockList);
return ResultInfo;
}
/// <summary>
/// 투입일, 반출일, 지번을 고려한 BLF 알고리즘 + 여유공간 + 우선배치
/// </summary>
/// <param name="inputBlockList">입력 블록 정보</param>
/// <param name="ArrangementMatrix">배치할 작업장에 대한 정보(그리드)</param>
/// <param name="WorkShopInfo">배치할 작업장에 대한 정보</param>
/// <param name="ArrangementStartDate">배치 시작일</param>
/// <param name="ArrangementFinishDate">배치 종료일</param>
/// <returns>블록 배치 결과</returns>
/// 최초 작성 : 주수헌, 2015년 9월 20일
/// 수정 일자 : 유상현, 2020년 6월 27일
ArrangementResultWithDateDTO IBlockArrangement.RunBLFAlgorithmWithSlackWithPriority(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArrangementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack)
{
ArrangementResultWithDateDTO ResultInfo;
List<List<WorkshopDTO>> TotalWorkshopResultList = new List<List<WorkshopDTO>>();
List<Int32[,]> CurrentArrangementMatrix = ArrangementMatrixList;
List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
List<BlockDTO> BlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalDailyDelayedBlockList = new List<List<BlockDTO>>();
List<List<Int32[,]>> PriorityMatrixList = new List<List<int[,]>>();
DateTime CurrentArrangementDate = new DateTime();
// 배치 시작일을 현재 배치일로 지정
CurrentArrangementDate = ArrangementStartDate;
// 입력 블록 리스트를 함수 내부에서 사용할 리스트로 복사 + 양측 여유공간 더해줌
for (int i = 0; i < inputBlockList.Count; i++)
{
BlockList.Add(inputBlockList[i].Clone());
BlockList[i].RowCount += Slack * 2 + BlockList[i].UpperSideCount + BlockList[i].BottomSideCount;
BlockList[i].ColumnCount += Slack * 2 + BlockList[i].LeftSideCount + BlockList[i].RightSideCount;
}
List<BlockDTO> TodayCandidateBlockList;
List<BlockDTO> TodayImportBlock;
List<BlockDTO> TodayExportBlock;
List<BlockDTO> TodayDelayedBlockList;
TimeSpan ts = ArrangementFinishDate - ArrangementStartDate;
int differenceInDays = ts.Days;
ProgressBar.Maximum = differenceInDays;
int count = 0;
//우선순위 블록 먼저 배치
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = "우선 배치 블록 : " + CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가 - 우선배치 블록은 지연 없음
// if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 원래 배치 일이 오늘인 것 추가
// 우선순위 블록만 배치 리스트에 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate & Block.IsPrior == true) TodayCandidateBlockList.Add(Block);
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가 -> 일반 블록 배치하고 나서 같이 하기
CurrentArrangementedBlockList.Add(Block);
//TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // 작업장 순회 for loop 종료
//if (!IsLocated)
//{
// TodayDelayedBlockList.Add(Block);
// Block.IsDelayed = true;
// Block.DelayedTime += 1;
// Block.ImportDate = Block.ImportDate.AddDays(1);
// Block.ExportDate = Block.ExportDate.AddDays(1);
//}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//이건 일반 배치 블록 다 끝나고 할 수 있도록. 그러려면 CurrentArrangementedBlockList가 보존되어야 함. 문제 -> 우선순위 블록 배치하는 과정에서, 제거하게 되는 블록은 CurrentArrangementedBlockList에서도 제거하게 됨. -> TotalDailyArrangementedBlockList를 활용해야 할 듯 싶은데??
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
//List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
//List<List<int>> tempBlockIndexList = new List<List<int>>();
//double[] SumBlockArea = new double[WorkShopInfo.Count];
//for (int n = 0; n < WorkShopInfo.Count; n++)
//{
// tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
// tempBlockIndexList.Add(new List<int>());
// SumBlockArea[n] = 0;
//}
//foreach (BlockDTO Block in CurrentArrangementedBlockList)
//{
// tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
// SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
//}
//foreach (WorkshopDTO Workshop in tempWorkshopInfo)
//{
// Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
// Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
// Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
//}
// 일반배치 블록에서는 여기서 리스트를 더하는게 아니라. TotalBlockImportLogList[count].Add(Block) 이렇게 블록단위로해야 할 듯. 아니면 tempList에 저장해놨다가 여기서 한번에 하던가.
// 아니면 우선순위 블록배치할 때는 진짜 위치, 날짜 등만 정하고 끝나고, 각종 리스트에 더하는건 일반 블록 배치할 때 우선순위 블록 예외처리해서 위치 결정과정만 건너뛰고 리스트에는 그 때 추가하는 걸로 하던가. 내일 뭐가 더 좋을지 생각해보자!
// 일단 후자가 더 좋아보임 ㅎ
//날짜별 변수를 리스트에 저장
//TotalBlockImportLogList.Add(TodayImportBlock);
//TotalBlockExportLogList.Add(TodayExportBlock);
//TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
//TotalWorkshopResultList.Add(tempWorkshopInfo);
//List<BlockDTO> tempBlockList = new List<BlockDTO>();
//for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
//{
// BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
// temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow + temp.UpperSideCount;
// temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn + temp.LeftSideCount;
// temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
// temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
// temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
// temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
// temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
// temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
// temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
// temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
// //여유공간 다시 빼줌
// temp.RowCount -= Slack * 2 + temp.UpperSideCount + temp.BottomSideCount;
// temp.ColumnCount -= Slack * 2 + temp.LeftSideCount + temp.RightSideCount;
// tempBlockList.Add(temp);
//}
//TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
List<Int32[,]> tempMatrixList = new List<Int32[,]>();
foreach(int[,] Matrix in CurrentArrangementMatrix)
{
int[,] tempMatrix = CloneMatrix(Matrix);
tempMatrixList.Add(tempMatrix);
}
PriorityMatrixList.Add(tempMatrixList);
count++;
}//while 종료
// 현재 배치일 초기화
CurrentArrangementDate = ArrangementStartDate;
count = 0;
//일반 배치 블록에 대해서 배치 진행
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = "일반 배치 블록 : " + CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
// 일반 블록인 경우 그대로 진행
if (Block.IsPrior == false)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
// 우선 배치 블록인 경우 리스트에만 추가
else TodayExportBlock.Add(Block);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가
if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 일반 블록 중 원래 배치 일이 오늘인 것 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate & Block.IsPrior == false) TodayCandidateBlockList.Add(Block);
// 우선순위 블록 중 오늘 배치해야할 블록은 결과 리스트에만 추가
foreach (BlockDTO Block in BlockList)
{
if (Block.ImportDate == CurrentArrangementDate & Block.IsPrior == true)
{
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
}
}
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 우선 배치 블록과 충돌하는지 체크
if (BlockLocation[0] != -1)
{
for (int dayCount = 0; dayCount < Block.Leadtime; dayCount++)
{
if (CheckInterference(PriorityMatrixList[count + dayCount][CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]) == false)
{
BlockLocation[0] = -1;
break;
}
}
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // 작업장 순회 for loop 종료
if (!IsLocated)
{
TodayDelayedBlockList.Add(Block);
Block.IsDelayed = true;
Block.DelayedTime += 1;
Block.ImportDate = Block.ImportDate.AddDays(1);
Block.ExportDate = Block.ExportDate.AddDays(1);
}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
List<List<int>> tempBlockIndexList = new List<List<int>>();
double[] SumBlockArea = new double[WorkShopInfo.Count];
for (int n = 0; n < WorkShopInfo.Count; n++)
{
tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
tempBlockIndexList.Add(new List<int>());
SumBlockArea[n] = 0;
}
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
}
foreach (WorkshopDTO Workshop in tempWorkshopInfo)
{
Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
}
//날짜별 변수를 리스트에 저장
TotalBlockImportLogList.Add(TodayImportBlock);
TotalBlockExportLogList.Add(TodayExportBlock);
TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
TotalWorkshopResultList.Add(tempWorkshopInfo);
List<BlockDTO> tempBlockList = new List<BlockDTO>();
for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
{
BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow + temp.UpperSideCount;
temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn + temp.LeftSideCount;
temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
temp.DelayedTime = CurrentArrangementedBlockList[i].DelayedTime;
//여유공간 다시 빼줌
temp.RowCount -= Slack * 2 + temp.UpperSideCount + temp.BottomSideCount;
temp.ColumnCount -= Slack * 2 + temp.LeftSideCount + temp.RightSideCount;
tempBlockList.Add(temp);
}
TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}//while 종료
ProgressLabel.Text = "Completed!";
ProgressBar.GetCurrentParent().Refresh();
//결과 전달을 위한 DTO 생성
ResultInfo = new ArrangementResultWithDateDTO(TotalWorkshopResultList, BlockList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDailyDelayedBlockList);
return ResultInfo;
}
/// <summary>
/// 투입일, 반출일, 지번을 고려한 BLF 알고리즘 + 여유공간 + 우선배치 + 해상크레인 출고장 개념 도입
/// </summary>
/// <param name="inputBlockList">입력 블록 정보</param>
/// <param name="ArrangementMatrix">배치할 작업장에 대한 정보(그리드)</param>
/// <param name="WorkShopInfo">배치할 작업장에 대한 정보</param>
/// <param name="ArrangementStartDate">배치 시작일</param>
/// <param name="ArrangementFinishDate">배치 종료일</param>
/// <returns>블록 배치 결과</returns>
/// 최초 작성 : 주수헌, 2015년 9월 20일
/// 수정 일자 : 유상현, 2020년 6월 27일
ArrangementResultWithDateDTO IBlockArrangement.RunBLFAlgorithmWithFloatingCrane(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArrangementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack, int ExportWorkshopIndex)
{
ArrangementResultWithDateDTO ResultInfo;
List<List<WorkshopDTO>> TotalWorkshopResultList = new List<List<WorkshopDTO>>();
List<Int32[,]> CurrentArrangementMatrix = ArrangementMatrixList;
List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
List<BlockDTO> BlockList = new List<BlockDTO>();
List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
List<List<BlockDTO>> TotalDailyDelayedBlockList = new List<List<BlockDTO>>();
List<List<Int32[,]>> PriorityMatrixList = new List<List<int[,]>>();
DateTime CurrentArrangementDate = new DateTime();
// 배치 시작일을 현재 배치일로 지정
CurrentArrangementDate = ArrangementStartDate;
// 입력 블록 리스트를 함수 내부에서 사용할 리스트로 복사 + 양측 여유공간 더해줌
for (int i = 0; i < inputBlockList.Count; i++)
{
BlockList.Add(inputBlockList[i].Clone());
BlockList[i].RowCount += Slack * 2 + BlockList[i].UpperSideCount + BlockList[i].BottomSideCount;
BlockList[i].ColumnCount += Slack * 2 + BlockList[i].LeftSideCount + BlockList[i].RightSideCount;
}
List<BlockDTO> TodayCandidateBlockList;
List<BlockDTO> TodayImportBlock;
List<BlockDTO> TodayExportBlock;
List<BlockDTO> TodayDelayedBlockList;
TimeSpan ts = ArrangementFinishDate - ArrangementStartDate;
int differenceInDays = ts.Days;
ProgressBar.Maximum = differenceInDays;
int count = 0;
//출고장 스케줄 먼저 확정
// 우선순위 블록의 출고일에 해당하는 BlockDTO List 생성
// 해당 리스트의 블록들 가시화 할 수 있게 하기
List<BlockDTO> FloatingCraneExportBlockList = new List<BlockDTO>();
foreach (BlockDTO Block in BlockList)
{
if (Block.IsPrior == true)
{
BlockDTO tempBlock = Block.Clone();
tempBlock.ImportDate = Block.ExportDate;
tempBlock.ExportDate = Block.ExportDate;
tempBlock.ArrangementDirection = Block.ArrangementDirection;
tempBlock.IsFloatingCraneExportBlock = true;
FloatingCraneExportBlockList.Add(tempBlock);
Block.ExportDate = Block.ExportDate.AddDays(-1);
}
}
// 해당 리스트의 블록들 매트릭스에 배치
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = "주기조립장 출고 스케줄 : " + CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
List<Int32[,]> tempMatrixList = new List<Int32[,]>();
foreach (int[,] Matrix in CurrentArrangementMatrix)
{
int[,] tempMatrix = CloneMatrix(Matrix);
tempMatrixList.Add(tempMatrix);
}
foreach (BlockDTO Block in FloatingCraneExportBlockList)
{
if (Block.ImportDate == CurrentArrangementDate)
{
if (CurrentArrangementDate == new DateTime(2020,3,5))
{
int testtest = 1;
}
if (Block.Index == 271)
{
int testttt = 1;
}
int[] BlockLocation = new int[3];
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(tempMatrixList[ExportWorkshopIndex], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(tempMatrixList[ExportWorkshopIndex], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(tempMatrixList[ExportWorkshopIndex], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
// 배치 매트릭스 점유정보 업데이트
if (BlockLocation[0] != -1)
{
tempMatrixList[ExportWorkshopIndex] = PutBlockOnMatrix(tempMatrixList[ExportWorkshopIndex], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
Block.LocatedRow = BlockLocation[0] + Block.UpperSideCount;
Block.LocatedColumn = BlockLocation[1] + Block.LeftSideCount;
Block.Orientation = BlockLocation[2];
Block.CurrentLocatedWorkshopIndex = ExportWorkshopIndex;
//여유공간 다시 빼줌
Block.RowCount -= Slack * 2 + Block.UpperSideCount + Block.BottomSideCount;
Block.ColumnCount -= Slack * 2 + Block.LeftSideCount + Block.RightSideCount;
}
// 배치 불가능할 경우 다음날로 미룸
else Block.ImportDate = Block.ImportDate.AddDays(1); Block.ExportDate = Block.ExportDate.AddDays(1);
}
}
PriorityMatrixList.Add(tempMatrixList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}// while 종료
// 현재 배치일 초기화
CurrentArrangementDate = ArrangementStartDate;
count = 0;
//우선순위 블록 먼저 배치
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = "우선 배치 블록 : " + CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가 - 우선배치 블록은 지연 없음
// if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 원래 배치 일이 오늘인 것 추가
// 우선순위 블록만 배치 리스트에 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate & Block.IsPrior == true) TodayCandidateBlockList.Add(Block);
if (CurrentArrangementDate == new DateTime(2020, 7,10))
{
foreach (BlockDTO Block in BlockList)
{
if (Block.Index == 332)
{
int aaaaaa = 1;
}
}
}
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
if (Block.Index == 332)
{
int fff = 1;
}
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 출고장 배치 가능 여부 파악
#region 출고장 배치 가능 여부 파악
CurrentWorkShopNumber = ExportWorkshopIndex;
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 출고장 스케줄과 충돌하는지 체크
if (BlockLocation[0] != -1)
{
for (int dayCount = 0; dayCount < Block.Leadtime; dayCount++)
{
if (CheckInterference(PriorityMatrixList[count + dayCount][CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]) == false)
{
BlockLocation[0] = -1;
break;
}
}
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가 -> 일반 블록 배치하고 나서 같이 하기
CurrentArrangementedBlockList.Add(Block);
//TodayImportBlock.Add(Block);
IsLocated = true;
//break; // 작업장 순회 for loop 탈출 -> 작업장 순회 for loop 따위 없으니까 필요 없음
}
#endregion
// 작업장 순회 for loop, 출고장에 배치되지 않았을 때만, 출고장은 빼고 탐색
if (Block.IsLocated == false)
{
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
if (CurrentWorkShopNumber != ExportWorkshopIndex)
{
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
//int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가 -> 일반 블록 배치하고 나서 같이 하기
CurrentArrangementedBlockList.Add(Block);
//TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
}
} // 작업장 순회 for loop 종료
} // 작업장 순회 for loop를 돌지 결정하는 if문 종료
//if (!IsLocated)
//{
// TodayDelayedBlockList.Add(Block);
// Block.IsDelayed = true;
// Block.DelayedTime += 1;
// Block.ImportDate = Block.ImportDate.AddDays(1);
// Block.ExportDate = Block.ExportDate.AddDays(1);
//}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//이건 일반 배치 블록 다 끝나고 할 수 있도록. 그러려면 CurrentArrangementedBlockList가 보존되어야 함. 문제 -> 우선순위 블록 배치하는 과정에서, 제거하게 되는 블록은 CurrentArrangementedBlockList에서도 제거하게 됨. -> TotalDailyArrangementedBlockList를 활용해야 할 듯 싶은데??
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
//List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
//List<List<int>> tempBlockIndexList = new List<List<int>>();
//double[] SumBlockArea = new double[WorkShopInfo.Count];
//for (int n = 0; n < WorkShopInfo.Count; n++)
//{
// tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
// tempBlockIndexList.Add(new List<int>());
// SumBlockArea[n] = 0;
//}
//foreach (BlockDTO Block in CurrentArrangementedBlockList)
//{
// tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
// SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
//}
//foreach (WorkshopDTO Workshop in tempWorkshopInfo)
//{
// Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
// Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
// Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
//}
// 일반배치 블록에서는 여기서 리스트를 더하는게 아니라. TotalBlockImportLogList[count].Add(Block) 이렇게 블록단위로해야 할 듯. 아니면 tempList에 저장해놨다가 여기서 한번에 하던가.
// 아니면 우선순위 블록배치할 때는 진짜 위치, 날짜 등만 정하고 끝나고, 각종 리스트에 더하는건 일반 블록 배치할 때 우선순위 블록 예외처리해서 위치 결정과정만 건너뛰고 리스트에는 그 때 추가하는 걸로 하던가. 내일 뭐가 더 좋을지 생각해보자!
// 일단 후자가 더 좋아보임 ㅎ
//날짜별 변수를 리스트에 저장
//TotalBlockImportLogList.Add(TodayImportBlock);
//TotalBlockExportLogList.Add(TodayExportBlock);
//TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
//TotalWorkshopResultList.Add(tempWorkshopInfo);
//List<BlockDTO> tempBlockList = new List<BlockDTO>();
//for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
//{
// BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
// temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow + temp.UpperSideCount;
// temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn + temp.LeftSideCount;
// temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
// temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
// temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
// temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
// temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
// temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
// temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
// temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
// //여유공간 다시 빼줌
// temp.RowCount -= Slack * 2 + temp.UpperSideCount + temp.BottomSideCount;
// temp.ColumnCount -= Slack * 2 + temp.LeftSideCount + temp.RightSideCount;
// tempBlockList.Add(temp);
//}
//TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
List<Int32[,]> tempMatrixList = new List<Int32[,]>();
foreach (int[,] Matrix in CurrentArrangementMatrix)
{
int[,] tempMatrix = CloneMatrix(Matrix);
tempMatrixList.Add(tempMatrix);
}
// 우선배치 매트릭스의 현재 날짜에 해당하는 매트릭스 업데이트
PriorityMatrixList[count] = tempMatrixList;
count++;
}//while 종료
// 현재 배치일 초기화
CurrentArrangementDate = ArrangementStartDate;
count = 0;
//일반 배치 블록에 대해서 배치 진행
//시작일과 종료일 사이에서 하루씩 시간을 진행하면서 배치를 진행
while (DateTime.Compare(CurrentArrangementDate, ArrangementFinishDate) < 0)
{
ProgressBar.Value = count;
ProgressLabel.Text = "일반 배치 블록 : " + CurrentArrangementDate.ToString("yyyy-MM-dd") + " (" + (Math.Round(((double)count / (double)differenceInDays) * 100.0, 2)).ToString() + "%)";
ProgressBar.GetCurrentParent().Refresh();
TodayCandidateBlockList = new List<BlockDTO>();
TodayImportBlock = new List<BlockDTO>();
TodayExportBlock = new List<BlockDTO>();
TodayDelayedBlockList = new List<BlockDTO>();
//현재의 작업장 배치 정보 중, 반출일에 해당하는 블록을 제거
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.ExportDate.AddDays(1) == CurrentArrangementDate)
{
// 일반 블록인 경우 그대로 진행
if (Block.IsPrior == false)
{
//블록의 배치 상태 및 완료 상태, 실제 반출 날짜 기록
Block.IsLocated = false;
Block.IsFinished = true;
Block.ActualExportDate = CurrentArrangementDate;
//당일 반출 블록 목록에 추가
TodayExportBlock.Add(Block);
// 배치 매트릭스에서 반출 블록 점유 정보 제거
CurrentArrangementMatrix[Block.LocatedWorkshopIndex] = RemoveBlockFromMatrix(CurrentArrangementMatrix[Block.LocatedWorkshopIndex], Block.LocatedRow, Block.LocatedColumn, Block.RowCount, Block.ColumnCount, Block.Orientation);
}
// 우선 배치 블록인 경우 리스트에만 추가
else TodayExportBlock.Add(Block);
}
}
// 현재 작업장에 배치중인 블록 리스트에서 반출 블록을 제거
foreach (BlockDTO Block in TodayExportBlock) CurrentArrangementedBlockList.Remove(Block);
// 오늘 배치해야 할 BlockList 생성
// Delay 된 것 먼저 추가
if (TotalDailyDelayedBlockList.Count != 0) foreach (BlockDTO Block in TotalDailyDelayedBlockList[TotalDailyDelayedBlockList.Count - 1]) TodayCandidateBlockList.Add(Block);
// 일반 블록 중 원래 배치 일이 오늘인 것 추가
foreach (BlockDTO Block in BlockList) if (Block.IsDelayed == false & Block.IsFinished == false & Block.IsLocated == false & Block.ImportDate == CurrentArrangementDate & Block.IsPrior == false) TodayCandidateBlockList.Add(Block);
// 우선순위 블록 중 오늘 배치해야할 블록은 결과 리스트에만 추가
foreach (BlockDTO Block in BlockList)
{
if (Block.ImportDate == CurrentArrangementDate & Block.IsPrior == true)
{
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
}
}
// 오늘 배치해야 할 BlockList에서 차례로 배치
foreach (BlockDTO Block in TodayCandidateBlockList)
{
bool IsLocated = false;
int CurrentWorkShopNumber = 0;
// 작업장 순회 for loop
for (int PreferWorkShopCount = 0; PreferWorkShopCount < Block.PreferWorkShopIndexList.Count; PreferWorkShopCount++)
{
CurrentWorkShopNumber = Block.PreferWorkShopIndexList[PreferWorkShopCount];
// 출고장은 빼고 배치
if (CurrentWorkShopNumber != ExportWorkshopIndex)
{
// 지번 신경 안쓰고 그냥 배치
// 배치 가능 위치 탐색
int[] BlockLocation = new int[3];
// 도로 주변에 배치해야하는 경우
if (Block.IsRoadSide == true)
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, WorkShopInfo[CurrentWorkShopNumber]);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, WorkShopInfo[CurrentWorkShopNumber]);
}
else BlockLocation = DetermineBlockLocationOnRoadSide(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, WorkShopInfo[CurrentWorkShopNumber]);
}
else
{
if (Block.ArrangementDirection == -1)
{
BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 0, Block.SearchDirection);
if (BlockLocation[0] == -1) BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, 1, Block.SearchDirection);
}
else BlockLocation = DetermineBlockLocationWithSearchDirection(CurrentArrangementMatrix[CurrentWorkShopNumber], Block.RowCount, Block.ColumnCount, Block.ArrangementDirection, Block.SearchDirection);
}
// 우선 배치 블록과 충돌하는지 체크
if (BlockLocation[0] != -1)
{
for (int dayCount = 0; dayCount < Block.Leadtime; dayCount++)
{
if (CheckInterference(PriorityMatrixList[count + dayCount][CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]) == false)
{
BlockLocation[0] = -1;
break;
}
}
}
// 배치 가능한 경우 배치
if (BlockLocation[0] != -1)
{
// 배치 매트릭스 점유정보 업데이트
CurrentArrangementMatrix[CurrentWorkShopNumber] = PutBlockOnMatrix(CurrentArrangementMatrix[CurrentWorkShopNumber], BlockLocation[0], BlockLocation[1], Block.RowCount, Block.ColumnCount, BlockLocation[2]);
// 블록 정보 업데이트
Block.LocatedRow = BlockLocation[0];
Block.LocatedColumn = BlockLocation[1];
Block.Orientation = BlockLocation[2];
Block.LocatedWorkshopIndex = CurrentWorkShopNumber;
Block.CurrentLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.ActualLocatedWorkshopIndex = CurrentWorkShopNumber;
Block.IsLocated = true;
Block.ActualImportDate = CurrentArrangementDate;
// 기타 블록 리스트에 블록 추가
CurrentArrangementedBlockList.Add(Block);
TodayImportBlock.Add(Block);
IsLocated = true;
break; // 작업장 순회 for loop 탈출
}
} // if
} // 작업장 순회 for loop 종료
if (!IsLocated)
{
TodayDelayedBlockList.Add(Block);
Block.IsDelayed = true;
Block.DelayedTime += 1;
Block.ImportDate = Block.ImportDate.AddDays(1);
Block.ExportDate = Block.ExportDate.AddDays(1);
}
//if 종료
} // 오늘 배치해야 할 블록들 배치 완료
//날짜별 배치 결과를 바탕으로 날짜별 작업장의 블록 배치 개수와 공간 점유율 계산
List<WorkshopDTO> tempWorkshopInfo = new List<WorkshopDTO>();
List<List<int>> tempBlockIndexList = new List<List<int>>();
double[] SumBlockArea = new double[WorkShopInfo.Count];
for (int n = 0; n < WorkShopInfo.Count; n++)
{
tempWorkshopInfo.Add(WorkShopInfo[n].Clone());
tempBlockIndexList.Add(new List<int>());
SumBlockArea[n] = 0;
}
foreach (BlockDTO Block in CurrentArrangementedBlockList)
{
if (Block.CurrentLocatedWorkshopIndex == -1)
{
int testtestttt = 1;
}
tempBlockIndexList[Block.CurrentLocatedWorkshopIndex].Add(Block.Index);
SumBlockArea[Block.CurrentLocatedWorkshopIndex] += Block.RowCount * Block.ColumnCount;
}
foreach (WorkshopDTO Workshop in tempWorkshopInfo)
{
Workshop.LocatedBlockIndexList = tempBlockIndexList[Workshop.Index];
Workshop.NumOfLocatedBlocks = Workshop.LocatedBlockIndexList.Count;
Workshop.AreaUtilization = SumBlockArea[Workshop.Index] / (Workshop.RowCount * Workshop.ColumnCount);
}
//날짜별 변수를 리스트에 저장
TotalBlockImportLogList.Add(TodayImportBlock);
TotalBlockExportLogList.Add(TodayExportBlock);
TotalDailyDelayedBlockList.Add(TodayDelayedBlockList);
TotalWorkshopResultList.Add(tempWorkshopInfo);
List<BlockDTO> tempBlockList = new List<BlockDTO>();
for (int i = 0; i < CurrentArrangementedBlockList.Count; i++)
{
BlockDTO temp = CurrentArrangementedBlockList[i].Clone();
temp.LocatedRow = CurrentArrangementedBlockList[i].LocatedRow + temp.UpperSideCount;
temp.LocatedColumn = CurrentArrangementedBlockList[i].LocatedColumn + temp.LeftSideCount;
temp.Orientation = CurrentArrangementedBlockList[i].Orientation;
temp.CurrentLocatedWorkshopIndex = CurrentArrangementedBlockList[i].CurrentLocatedWorkshopIndex;
temp.CurrentLocatedAddressIndex = CurrentArrangementedBlockList[i].CurrentLocatedAddressIndex;
temp.IsLocated = CurrentArrangementedBlockList[i].IsLocated;
temp.IsFinished = CurrentArrangementedBlockList[i].IsFinished;
temp.IsRoadSide = CurrentArrangementedBlockList[i].IsRoadSide;
temp.IsConditionSatisfied = CurrentArrangementedBlockList[i].IsConditionSatisfied;
temp.IsDelayed = CurrentArrangementedBlockList[i].IsDelayed;
temp.DelayedTime = CurrentArrangementedBlockList[i].DelayedTime;
//여유공간 다시 빼줌
temp.RowCount -= Slack * 2 + temp.UpperSideCount + temp.BottomSideCount;
temp.ColumnCount -= Slack * 2 + temp.LeftSideCount + temp.RightSideCount;
tempBlockList.Add(temp);
}
TotalDailyArragnementedBlockList.Add(tempBlockList);
CurrentArrangementDate = CurrentArrangementDate.AddDays(1);
count++;
}//while 종료
// 해상크레인 출고장 블록 가시화를 위해 TotalDailyArrangementedBlockList에 추가
foreach (BlockDTO Block in FloatingCraneExportBlockList)
{
int tempDayCount = (Block.ImportDate - ArrangementStartDate).Days;
TotalDailyArragnementedBlockList[tempDayCount].Add(Block);
}
ProgressLabel.Text = "Completed!";
ProgressBar.GetCurrentParent().Refresh();
//결과 전달을 위한 DTO 생성
ResultInfo = new ArrangementResultWithDateDTO(TotalWorkshopResultList, BlockList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDailyDelayedBlockList);
return ResultInfo;
}
#endregion
#region 기타 메서드(최소,최대 입출고일 계산, 면적활용률 계산, 리스트 중복제거 등등)
/// <summary>
/// 현재 입력되어 있는 블록 정보 중 가장 빠른 입고일과 가장 늦은 출고일을 계산하는 함수
/// </summary>
/// <param name="_blockInfoList">블록 정보</param>
/// <returns>
/// [0]: 가장 빠른 입고일
/// [1]: 가장 늦은 출고일
/// </returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// 수정 작성 : 이동건, 2016년 03월 30일
/// </remarks>
DateTime[] IBlockArrangement.CalcEarliestAndLatestDates(List<BlockDTO> _blockInfoList)
{
DateTime[] returnDates = new DateTime[2];
List<DateTime> importDateList = new List<DateTime>();
List<DateTime> exportDateList = new List<DateTime>();
for (int i = 0; i < _blockInfoList.Count; i++)
{
importDateList.Add(_blockInfoList[i].ImportDate);
exportDateList.Add(_blockInfoList[i].ExportDate);
}
//가장 빠른 입고일, 가장 늦은 입고일 찾기
DateTime earliestDate = FindEarliestDate(importDateList);
DateTime latestDate = FindLatestDate(exportDateList);
latestDate = latestDate.AddMonths(2);
returnDates[0] = earliestDate;
returnDates[1] = latestDate;
return returnDates;
}
/// <summary>
/// 입력된 날짜 리스트 중 가장 빠른 날짜를 반환하는 함수
/// </summary>
/// <param name="inputList">날짜 리스트</param>
/// <returns>가장 빠른 날짜</returns>
/// <remarks>
/// 최초 구현: 정용국, 2015년 10월 23일
/// 최종 수정: 정용국, 2015년 10월 23일
/// </remarks>
DateTime FindEarliestDate(List<DateTime> inputList)
{
DateTime returnDate = new DateTime();
returnDate = inputList[0];
for (int i = 1; i < inputList.Count; i++)
{
if (DateTime.Compare(inputList[i], returnDate) < 0) returnDate = inputList[i];
}
return returnDate;
}
/// <summary>
/// 입력된 날짜 리스트 중 가장 느린 날짜를 반환하는 함수
/// </summary>
/// <param name="inputList">날짜 리스트</param>
/// <returns>가장 느린 날짜</returns>
/// <remarks>
/// 최초 구현: 정용국, 2015년 10월 23일
/// 최종 수정: 정용국, 2015년 10월 23일
/// </remarks>
DateTime FindLatestDate(List<DateTime> inputList)
{
DateTime returnDate = new DateTime();
returnDate = inputList[0];
for (int i = 1; i < inputList.Count; i++)
{
if (DateTime.Compare(inputList[i], returnDate) > 0) returnDate = inputList[i];
}
return returnDate;
}
/// <summary>
/// 현재 작업장에 배치된 블록의 index를 검색하는 함수
/// </summary>
/// <param name="CurrentArrangementMatrix">검색하고자 하는 작업장의 배치정보</param>
/// <param name="WorkShopInfo">작업장 정보</param>
/// <param name="workshopIndex">작업장의 번호</param>
/// <returns>현재 작업장에 배치된 블록의 일련번호 목록</returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
List<int> FindMyLocatedBlockIndex(List<UnitcellDTO[,]> CurrentArrangementMatrix, List<WorkshopDTO> WorkShopInfo, int workshopIndex)
{
List<int> returnBlockIndexList = new List<int>();
List<int> _locatedWorkshopIndex = new List<int>();
for (int i = 0; i < CurrentArrangementMatrix[workshopIndex].GetLength(0); i++)
{
for (int j = 0; j < CurrentArrangementMatrix[workshopIndex].GetLength(1); j++)
{
if (CurrentArrangementMatrix[workshopIndex][i, j].BlockIndex != -1)
{
bool isduplicated = false;
for (int k = 0; k < returnBlockIndexList.Count; k++)
{
if (CurrentArrangementMatrix[workshopIndex][i, j].BlockIndex == returnBlockIndexList[k])
{
isduplicated = true;
}
}
if (isduplicated == false)
{
returnBlockIndexList.Add(CurrentArrangementMatrix[workshopIndex][i, j].BlockIndex);
}
}
}
}
return returnBlockIndexList;
}
/// <summary>
/// 선택된 작업장의 면적활용률을 계산하는 함수
/// </summary>
/// <param name="CurrentArrangementMatrix">현재 배치상황을 저장하고 있는 목록</param>
/// <param name="WorkShopInfo">작업장 정보</param>
/// <param name="workshopIndex">선택된 작업장 일련번호</param>
/// <returns>면적활용률</returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
double CalcMyAreaUtilization(List<UnitcellDTO[,]> CurrentArrangementMatrix, List<WorkshopDTO> WorkShopInfo, int workshopIndex)
{
int occupiedAreaCount = 0;
int totalAreaCount = 0;
for (int row = 0; row < CurrentArrangementMatrix[workshopIndex].GetLength(0); row++)
{
for (int column = 0; column < CurrentArrangementMatrix[workshopIndex].GetLength(1); column++)
{
totalAreaCount++;
if (CurrentArrangementMatrix[workshopIndex][row, column].IsOccupied == true) occupiedAreaCount++;
}
}
return (double)(occupiedAreaCount) / (double)(totalAreaCount);
}
/// <summary>
/// 정수 리스트에서 최소값을 반환하는 함수
/// </summary>
/// <param name="inputList">정수 리스트</param>
/// <returns>최소값</returns>
/// <remarks>
/// 최초 작성: 주수헌
/// 최종 수정: 정용국, 2016년 05월 08일
/// </remarks>
int CalcLowestValue(List<int> inputList)
{
int tempValue = 100000;
int returnIndex = 0;
for (int i = 0; i < inputList.Count; i++)
{
if (inputList[i] < tempValue)
{
tempValue = inputList[i];
returnIndex = i;
}
}
return tempValue;
}
/// <summary>
/// 후보점 리스트에서 중복된 점을 확인하여 제거하는 함수
/// </summary>
/// <param name="ListofCandidateLocations">후보점 리스트</param>
/// <returns>중복된 점이 제거된 리스트</returns>
List<Point> RemoveDuplicatedLocations(List<Point> ListofCandidateLocations)
{
List<Point> candidateLocations = new List<Point>();
Dictionary<string, Point> DictionaryForCheck = new Dictionary<string, Point>();
for (int i = 0; i < ListofCandidateLocations.Count; i++)
{
string sKeyforCheck = "X" + Convert.ToString(ListofCandidateLocations[i].X) + "Y" + Convert.ToString(ListofCandidateLocations[i].Y);
if (!DictionaryForCheck.ContainsKey(sKeyforCheck))
{
DictionaryForCheck.Add(sKeyforCheck, ListofCandidateLocations[i]);
candidateLocations.Add(ListofCandidateLocations[i]);
}
}
return candidateLocations;
}
/// <summary>
/// 사각형 블록의 꼭지점을 반환하는 함수
/// </summary>
/// <param name="currentLocatedBlock">블록 정보</param>
/// <returns>꼭지점 4개</returns>
Point[] FindMyVertices(BlockDTO currentLocatedBlock)
{
int tempLocatedX = System.Convert.ToInt32(currentLocatedBlock.LocatedColumn);
int tempLocatedY = System.Convert.ToInt32(currentLocatedBlock.LocatedRow);
int tempRowCount = System.Convert.ToInt32(Math.Ceiling(currentLocatedBlock.RowCount));
int tempColumnCount = System.Convert.ToInt32(Math.Ceiling(currentLocatedBlock.ColumnCount));
Point temp1 = new Point(tempLocatedX, tempLocatedY);
Point temp2 = new Point(tempLocatedX + tempColumnCount - 1, tempLocatedY);
Point temp3 = new Point(tempLocatedX, tempLocatedY + tempRowCount - 1);
Point temp4 = new Point(tempLocatedX + tempColumnCount - 1, tempLocatedY + tempRowCount - 1);
Point[] ArrayofVertex = new Point[4] { temp1, temp2, temp3, temp4 };
return ArrayofVertex;
}
/// <summary>
/// 대상 날짜에 대해 Block,workshop 정보를 바탕으로 해당 RepresentingBlockInfoAtGrid날짜의 배치 형상을 만드는 함수
/// </summary>
/// <param name="inputBlockList"></param>
/// <param name="ArrangementMatrix"></param>
/// <param name="WorkShopInfo"></param>
/// <param name="TargetDate"></param>
/// <returns></returns>
List<UnitcellDTO[,]> RepresentingBlockInfoAtGrid(List<BlockDTO> inputBlockList, List<WorkshopDTO> WorkShopInfo, DateTime TargetDate)
{
List<UnitcellDTO[,]> ResultArrangementedWorkShop = new List<UnitcellDTO[,]>();
//지번자동할당(배치 Grid 정보 생성)
ResultArrangementedWorkShop = ((IBlockArrangement)this).InitializeArrangementMatrixWithAddress(WorkShopInfo);
List<BlockDTO> LocatedBlockList = new List<BlockDTO>();
//배치된 블록 선정
for (int i = 0; i < inputBlockList.Count; i++)
{
if (DateTime.Compare(TargetDate, inputBlockList[i].ActualImportDate) >= 0 & DateTime.Compare(inputBlockList[i].ActualExportDate, TargetDate) >= 0)
{
BlockDTO tempBlockDTO = inputBlockList[i].Clone();
tempBlockDTO.ActualLocatedWorkshopIndex = inputBlockList[i].ActualLocatedWorkshopIndex;
tempBlockDTO.IsFinished = inputBlockList[i].IsFinished;
tempBlockDTO.IsLocated = inputBlockList[i].IsLocated;
tempBlockDTO.LocatedRow = inputBlockList[i].LocatedRow;
tempBlockDTO.LocatedColumn = inputBlockList[i].LocatedColumn;
LocatedBlockList.Add(tempBlockDTO);
}
}
//배치된 블록에 대해 작업장 grid로 배치현황을 표현
for (int i = 0; i < LocatedBlockList.Count; i++)
{
if (LocatedBlockList[i].IsLocated == true || LocatedBlockList[i].IsFinished == true)
{
int Locatedworkshop = LocatedBlockList[i].ActualLocatedWorkshopIndex;
for (int j = 0; j < Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].RowCount)); j++)
{
for (int k = 0; k < Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].ColumnCount)); k++)
{
ResultArrangementedWorkShop[Locatedworkshop][Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].LocatedRow)) + j, Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].LocatedColumn)) + k].BlockIndex = i;
ResultArrangementedWorkShop[Locatedworkshop][Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].LocatedRow)) + j, Convert.ToInt16(Math.Ceiling(LocatedBlockList[i].LocatedColumn)) + k].IsOccupied = true;
}
}
}
}
return ResultArrangementedWorkShop;
}
/// <summary>
/// 특정 2차원 배열을 오른쪽으로 90도 회전시키는 함수
/// </summary>
/// <param name="inputMartix"></param>
/// <returns></returns>
double[,] MatrixRightRotate(double[,] inputMartix)
{
int LengthX = inputMartix.GetLength(1);
int LengthY = inputMartix.GetLength(0);
double[,] ResultMaritx = new double[LengthX, LengthY];
for (int y = 0; y < LengthY; y++)
{
for (int x = 0; x < LengthX; x++)
{
ResultMaritx[x, y] = inputMartix[LengthY - 1 - y, x];
}
}
return ResultMaritx;
}
/// <summary>
/// 특정 2차원 배열을 오른쪽으로 N회 회전시키는 함수
/// </summary>
/// <param name="inputMatrix"></param>
/// <param name="RotateCount"></param>
/// <returns></returns>
double[,] MatrixRightRotate(double[,] inputMatrix, int RotateCount)
{
double[,] ResultMatrix = new double[inputMatrix.GetLength(0), inputMatrix.GetLength(1)];
ResultMatrix = inputMatrix;
for (int i = 0; i < RotateCount; i++)
{
ResultMatrix = this.MatrixRightRotate(ResultMatrix);
}
return ResultMatrix;
}
/// <summary>
/// 현재 작업장 배치 현황에서 주판의 형상을 고려한 BLF 배치 위치를 찾는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <param name="TargetPlateConfig"></param>
/// <returns>배치될 주판의 바운딩박스 시작 위치 (행,렬), 둘다 -1, -1 이면 배치 불가능</returns>
int[] DeterminePlateLocationWithConfig(UnitcellDTO[,] CurrentWorkShopMatrix, double[,] TargetPlateConfig)
{
int[] ResultRowCol = new int[2];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
int WorkshopRow = CurrentWorkShopMatrix.GetLength(0);
int WorkshopCol = CurrentWorkShopMatrix.GetLength(1);
//배치 대상 주판의 가로 세로 바운딩 박스의 길이/
int rowCount = TargetPlateConfig.GetLength(0);
int colCount = TargetPlateConfig.GetLength(1);
bool IsLocated = false; //주판의 배치 유무
for (int column = 0; column < WorkshopCol; column++)
{
for (int row = 0; row < WorkshopRow; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
for (int PlateColumn = 0; PlateColumn < colCount; PlateColumn++)
{
for (int PlateRow = 0; PlateRow < rowCount; PlateRow++)
{
//config 형상이 존재하는 위치에 대해서만, 점유 정보를 확인함
if (TargetPlateConfig[PlateRow, PlateColumn] == 1) // 사각형 안에 포함되지만 형상이 존재하는 부분은 점유함
{
if (row + PlateRow < WorkshopRow && column + PlateColumn < WorkshopCol)
{
IsOccupied = IsOccupied || CurrentWorkShopMatrix[row + PlateRow, column + PlateColumn].IsOccupied;
if (IsOccupied) break;
}
else
{
IsOccupied = true;
if (IsOccupied) break;
}
}
}
if (IsOccupied) break;
}
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
return ResultRowCol;
}
/// <summary>
/// "Roller 용" 현재 작업장 배치 현황에서 주판의 형상을 고려한 BLF 배치 위치를 찾는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <param name="TargetPlateConfig"></param>
/// <returns>배치될 주판의 바운딩박스 시작 위치 (행,렬), 둘다 -1, -1 이면 배치 불가능</returns>
int[] Roller_DeterminePlateLocationWithConfig(UnitcellDTO[,] CurrentWorkShopMatrix, double[,] TargetPlateConfig, int WidthOfAddress)
{
int[] ResultRowCol = new int[2];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
int WorkshopRow = CurrentWorkShopMatrix.GetLength(0);
int WorkshopCol = WidthOfAddress;
//배치 대상 주판의 가로 세로 바운딩 박스의 길이/
int rowCount = TargetPlateConfig.GetLength(0);
int colCount = TargetPlateConfig.GetLength(1);
bool IsLocated = false; //주판의 배치 유무
for (int column = 0; column < WorkshopCol; column++)
{
for (int row = 0; row < WorkshopRow; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
for (int PlateColumn = 0; PlateColumn < colCount; PlateColumn++)
{
for (int PlateRow = 0; PlateRow < rowCount; PlateRow++)
{
//config 형상이 존재하는 위치에 대해서만, 점유 정보를 확인함
if (TargetPlateConfig[PlateRow, PlateColumn] == 1) // 사각형 안에 포함되지만 형상이 존재하는 부분은 점유함
{
if (row + PlateRow < WorkshopRow && column + PlateColumn < WorkshopCol)
{
IsOccupied = IsOccupied || CurrentWorkShopMatrix[row + PlateRow, column + PlateColumn].IsOccupied;
if (IsOccupied) break;
}
else
{
IsOccupied = true;
if (IsOccupied) break;
}
}
}
if (IsOccupied) break;
}
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
return ResultRowCol;
}
#endregion
#region 탐색, 배치 실행 기능 함수
/// <summary>
/// 현재 작업장 배치 현황에서 BLF 배치 위치를 찾는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <returns>배치될 블록의 바운딩박스 시작 위치 (행,열), 둘다 -1, -1 이면 배치 불가능</returns>
int[] DetermineBlockLocation(Int32[,] CurrentArrangementMatrix, double _BlockRowCount, double _BlockColumnCount, int Orientation)
{
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
// Orientation == -1 일 때, 회전시켜서 비교 후 좋은 점 반환하는 코드 작성해야함
int[] ResultRowCol = new int[3];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
ResultRowCol[2] = Orientation;
int WorkshopRow = CurrentArrangementMatrix.GetLength(0);
int WorkshopCol = CurrentArrangementMatrix.GetLength(1);
bool IsLocated = false; //블록의 배치 유무
for (int column = 0; column < WorkshopCol - BlockColumnCount; column++)
{
for (int row = 0; row < WorkshopRow - BlockRowCount; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
// 네 꼭짓점 먼저 탐색
if (CurrentArrangementMatrix[row, column] == 0 & CurrentArrangementMatrix[row + BlockRowCount - 1, column] == 0 & CurrentArrangementMatrix[row, column + BlockColumnCount - 1] == 0 & CurrentArrangementMatrix[row + BlockRowCount, column + BlockColumnCount] == 0)
{
// 네 꼭짓점 모두 비어있다면, 내부 탐색
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
} // 네 꼭짓점 중 비어있지 않은 곳이 있다면
else IsOccupied = true;
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
return ResultRowCol;
}
/// <summary>
/// 현재 작업장 배치 현황 중 선호지번 구역에서 BLF 배치 위치를 찾는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <returns>배치될 블록의 바운딩박스 시작 위치 (행,열), 둘다 -1, -1 이면 배치 불가능</returns>
int[] DetermineBlockLocationWithAddress(Int32[,] CurrentArrangementMatrix, double _BlockRowCount, double _BlockColumnCount, double _AddressLeftPoint, double _AddressRightPoint, int Orientation)
{
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
// Orientation == -1 일 때, 회전시켜서 비교 후 좋은 점 반환하는 코드 작성해야함
int AddressLeftPoint = Convert.ToInt32(Math.Ceiling(_AddressLeftPoint));
int AddressRightPoint = Convert.ToInt32(Math.Ceiling(_AddressRightPoint));
int[] ResultRowCol = new int[3];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
ResultRowCol[2] = Orientation;
int WorkshopRow = CurrentArrangementMatrix.GetLength(0);
int WorkshopCol = CurrentArrangementMatrix.GetLength(1);
bool IsLocated = false; //블록의 배치 유무
for (int column = AddressLeftPoint; column < AddressRightPoint - BlockColumnCount; column++)
{
for (int row = 0; row < WorkshopRow - BlockRowCount; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
// 네 꼭짓점 먼저 탐색
if (CurrentArrangementMatrix[row, column] == 0 & CurrentArrangementMatrix[row + BlockRowCount - 1, column] == 0 & CurrentArrangementMatrix[row, column + BlockColumnCount - 1] == 0 & CurrentArrangementMatrix[row + BlockRowCount, column + BlockColumnCount] == 0)
{
// 네 꼭짓점 모두 비어있다면, 내부 탐색
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
} // 네 꼭짓점 중 비어있지 않은 곳이 있다면
else IsOccupied = true;
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
return ResultRowCol;
}
/// <summary>
/// 현재 작업장 배치 현황에서 도로변에 BLF 배치 위치를 찾는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <returns>배치될 블록의 바운딩박스 시작 위치 (행,열), 둘다 -1, -1 이면 배치 불가능</returns>
int[] DetermineBlockLocationOnRoadSide(Int32[,] CurrentArrangementMatrix, double _BlockRowCount, double _BlockColumnCount, int Orientation, WorkshopDTO _WorkshopInfo)
{
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
// Orientation == -1 일 때, 회전시켜서 비교 후 좋은 점 반환하는 코드 작성해야함
int[] ResultRowCol = new int[3];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
ResultRowCol[2] = Orientation;
int WorkshopRow = CurrentArrangementMatrix.GetLength(0);
int WorkshopCol = CurrentArrangementMatrix.GetLength(1);
bool IsLocated = false; //블록의 배치 유무
// 모서리를 돌아가면서 탐색, 방향은 좌측 -> 하단 -> 우측 -> 상단
// Left side 탐색
if (_WorkshopInfo.LeftRoadside != null)
{
for (int row = Convert.ToInt32(Math.Ceiling(_WorkshopInfo.LeftRoadside[0])); row < Convert.ToInt32(Math.Ceiling(_WorkshopInfo.LeftRoadside[1])) - BlockRowCount ; row++)
{
int column = 0;
if (column < 0) break;
bool IsOccupied = false; // 작업장 셀의 점유유무
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) return ResultRowCol;
}
}
// Bottom side 탐색
if (_WorkshopInfo.BottomRoadside != null)
{
for (int column = Convert.ToInt32(Math.Ceiling(_WorkshopInfo.BottomRoadside[0])); column < Convert.ToInt32(Math.Ceiling(_WorkshopInfo.BottomRoadside[1])) - BlockColumnCount; column++)
{
int row = WorkshopRow - BlockRowCount;
if (row < 0) break;
bool IsOccupied = false; // 작업장 셀의 점유유무
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) return ResultRowCol;
}
}
// Right side 탐색
if (_WorkshopInfo.RightRoadside != null)
{
for (int row = Convert.ToInt32(Math.Ceiling(_WorkshopInfo.RightRoadside[0])); row < Convert.ToInt32(Math.Ceiling(_WorkshopInfo.RightRoadside[1])) - BlockRowCount; row++)
{
int column = WorkshopCol - BlockColumnCount;
if (column < 0) break;
bool IsOccupied = false; // 작업장 셀의 점유유무
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) return ResultRowCol;
}
}
// Upper side 탐색
if (_WorkshopInfo.UpperRoadside != null)
{
for (int column = Convert.ToInt32(Math.Ceiling(_WorkshopInfo.UpperRoadside[0])); column < Convert.ToInt32(Math.Ceiling(_WorkshopInfo.UpperRoadside[1])) - BlockColumnCount; column++)
{
int row = 0;
bool IsOccupied = false; // 작업장 셀의 점유유무
// 네 꼭짓점 먼저 탐색
if (CurrentArrangementMatrix[row, column] == 0 & CurrentArrangementMatrix[row + BlockRowCount - 1, column] == 0 & CurrentArrangementMatrix[row, column + BlockColumnCount - 1] == 0 & CurrentArrangementMatrix[row + BlockRowCount, column + BlockColumnCount] == 0)
{
// 네 꼭짓점 모두 비어있다면, 내부 탐색
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
} // 네 꼭짓점 중 비어있지 않은 곳이 있다면
else IsOccupied = true;
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) return ResultRowCol;
}
}
// 어느 곳도 배치를 못했다면
return ResultRowCol;
}
/// <summary>
/// 현재 작업장 배치 현황에서 BLF 배치 위치를 찾는 함수, 탐색 방향 명시 기능 추가
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <returns>배치될 블록의 바운딩박스 시작 위치 (행,열), 둘다 -1, -1 이면 배치 불가능</returns>
int[] DetermineBlockLocationWithSearchDirection(Int32[,] CurrentArrangementMatrix, double _BlockRowCount, double _BlockColumnCount, int Orientation, int SearchDirection)
{
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
// Orientation == -1 일 때, 회전시켜서 비교 후 좋은 점 반환하는 코드 작성해야함
int[] ResultRowCol = new int[3];
ResultRowCol[0] = -1;
ResultRowCol[1] = -1;
ResultRowCol[2] = Orientation;
int WorkshopRow = CurrentArrangementMatrix.GetLength(0);
int WorkshopCol = CurrentArrangementMatrix.GetLength(1);
bool IsLocated = false; //블록의 배치 유무
//좌->우 탐색
if (SearchDirection == 1)
{
for (int column = 0; column < WorkshopCol - BlockColumnCount; column++)
{
for (int row = 0; row < WorkshopRow - BlockRowCount; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
// 네 꼭짓점 먼저 탐색
if (CurrentArrangementMatrix[row, column] == 0 & CurrentArrangementMatrix[row + BlockRowCount - 1, column] == 0 & CurrentArrangementMatrix[row, column + BlockColumnCount - 1] == 0 & CurrentArrangementMatrix[row + BlockRowCount, column + BlockColumnCount] == 0)
{
// 네 꼭짓점 모두 비어있다면, 내부 탐색
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
} // 네 꼭짓점 중 비어있지 않은 곳이 있다면
else IsOccupied = true;
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
}
//우->좌 탐색
else
{
for (int column = WorkshopCol - BlockColumnCount-1; column >=0 ; column--)
{
for (int row = 0; row < WorkshopRow - BlockRowCount; row++)
{
bool IsOccupied = false; // 작업장 셀의 점유유무
// 네 꼭짓점 먼저 탐색
if (CurrentArrangementMatrix[row, column] == 0 & CurrentArrangementMatrix[row + BlockRowCount - 1, column] == 0 & CurrentArrangementMatrix[row, column + BlockColumnCount - 1] == 0 & CurrentArrangementMatrix[row + BlockRowCount, column + BlockColumnCount] == 0)
{
// 네 꼭짓점 모두 비어있다면, 내부 탐색
for (int BlockColumn = 0; BlockColumn < BlockColumnCount; BlockColumn++)
{
for (int BlockRow = 0; BlockRow < BlockRowCount; BlockRow++)
{
if (CurrentArrangementMatrix[row + BlockRow, column + BlockColumn] != 0)
{
IsOccupied = true;
}
if (IsOccupied) break;
}
if (IsOccupied) break;
}
} // 네 꼭짓점 중 비어있지 않은 곳이 있다면
else IsOccupied = true;
//만약에 IsOccupied가 false라서 배치가 가능하다면,
if (!IsOccupied)
{
IsLocated = true;
ResultRowCol[0] = row;
ResultRowCol[1] = column;
}
if (IsLocated) break;
}
if (IsLocated) break;
}
}
return ResultRowCol;
}
/// <summary>
/// 배치 매트릭스, 블록 위치, 가로 및 세로 길이, 방향을 입력받고 배치 매트릭스에 배치 정보를 반영하는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <param name="TargetPlateConfig"></param>
/// <returns>입력 블록이 배치된 배치 매트릭스 - 0이면 빈 그리드, 1이면 배치된 그리드</returns>
Int32[,] PutBlockOnMatrix(Int32[,] CurrentArrangementMatrix, double _RowLocation, double _ColumnLocation, double _BlockRowCount, double _BlockColumnCount, int Orientation)
{
int RowLocation = Convert.ToInt32(Math.Ceiling(_RowLocation));
int ColumnLocation = Convert.ToInt32(Math.Ceiling(_ColumnLocation));
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
for (int i = 0; i < BlockRowCount; i++)
{
for (int j = 0; j < BlockColumnCount; j++)
{
CurrentArrangementMatrix[RowLocation + i, ColumnLocation + j] = 1;
}
}
return CurrentArrangementMatrix;
}
/// <summary>
/// 제거 대상 매트릭스, 블록 위치, 가로 및 세로 길이, 방향을 입력받고 배치 매트릭스에서 블록 배치 정보를 제거하는 함수
/// </summary>
/// <param name="CurrentWorkShopMatrix"></param>
/// <param name="TargetPlateConfig"></param>
/// <returns>입력 블록이 배치된 배치 매트릭스 - 0이면 빈 그리드, 1이면 배치된 그리드</returns>
Int32[,] RemoveBlockFromMatrix(Int32[,] CurrentArrangementMatrix, double _RowLocation, double _ColumnLocation, double _BlockRowCount, double _BlockColumnCount, int Orientation)
{
int RowLocation = Convert.ToInt32(Math.Ceiling(_RowLocation));
int ColumnLocation = Convert.ToInt32(Math.Ceiling(_ColumnLocation));
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
for (int i = 0; i < BlockRowCount; i++)
{
for (int j = 0; j < BlockColumnCount; j++)
{
CurrentArrangementMatrix[RowLocation + i, ColumnLocation + j] = 0;
}
}
return CurrentArrangementMatrix;
}
// 매트릭스 복사
Int32[,] CloneMatrix(Int32[,] ArrangementMatrix)
{
Int32[,] tempMatrix = new Int32[ArrangementMatrix.GetLength(0), ArrangementMatrix.GetLength(1)];
for (int i=0; i < ArrangementMatrix.GetLength(0); i++)
{
for (int j=0; j < ArrangementMatrix.GetLength(1); j++)
{
tempMatrix[i, j] = ArrangementMatrix[i, j];
}
}
return tempMatrix;
}
// 매트릭스와 블록 위치, 크기, 방향을 입력받았을 때 간섭하는지 체크하는 함수
// 간섭 안하면 true, 간섭하면 false 반환
bool CheckInterference(Int32[,] CurrentArrangementMatrix, double _RowLocation, double _ColumnLocation, double _BlockRowCount, double _BlockColumnCount, int Orientation)
{
int RowLocation = Convert.ToInt32(Math.Ceiling(_RowLocation));
int ColumnLocation = Convert.ToInt32(Math.Ceiling(_ColumnLocation));
int BlockRowCount = 0;
int BlockColumnCount = 0;
if (Orientation == 0)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
}
else if (Orientation == 1)
{
BlockRowCount = Convert.ToInt32(Math.Ceiling(_BlockColumnCount));
BlockColumnCount = Convert.ToInt32(Math.Ceiling(_BlockRowCount));
}
for (int i = 0; i < BlockRowCount; i++)
{
for (int j = 0; j < BlockColumnCount; j++)
{
if(CurrentArrangementMatrix[RowLocation + i, ColumnLocation + j] != 0)
{
return false;
}
}
}
return true;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
public class ArrangementResultWithDateDTO
{
//날짜별 작업장 정보의 저장을 위한 변수 (ex. 면적점유율)
public List<List<WorkshopDTO>> ResultWorkShopInfo { get; set; }
//블록정보 또는 주판정보을 위한 리스트
public List<BlockDTO> BlockResultList { get; set; }
//시작일 및 종료일을 나타내는 변수
public DateTime ArrangementStartDate { get; set; }
public DateTime ArrangementFinishDate { get; set; }
//날짜별 투입 블록, 반출 블록, 미배치 블록 등 블록 목록을 위한 변수
public List<List<BlockDTO>> TotalDailyArragnementedBlockList { get; set; }
public List<List<BlockDTO>> TotalBlockImportLogList { get; set; }
public List<List<BlockDTO>> TotalBlockExportLogList { get; set; }
public List<List<BlockDTO>> TotalDelayedBlockList { get; set; }
public ArrangementResultWithDateDTO(List<List<WorkshopDTO>> _resultWorkShopInfo, List<BlockDTO> _blockResultList, DateTime _arrangementStartDate, DateTime _arrangementFinishDate, List<List<BlockDTO>> _totalDailyArragnementedBlockList, List<List<BlockDTO>> _totalBlockImportLogList, List<List<BlockDTO>> _totalBlockExportLogList, List<List<BlockDTO>> _totalDelayedBlockList)
{
ResultWorkShopInfo = _resultWorkShopInfo;
BlockResultList = _blockResultList;
TotalDailyArragnementedBlockList = _totalDailyArragnementedBlockList;
TotalBlockImportLogList = _totalBlockImportLogList;
TotalBlockExportLogList = _totalBlockExportLogList;
TotalDelayedBlockList = _totalDelayedBlockList;
ArrangementStartDate = _arrangementStartDate;
ArrangementFinishDate = _arrangementFinishDate;
}
public ArrangementResultWithDateDTO Clone()
{
return new ArrangementResultWithDateDTO(ResultWorkShopInfo, BlockResultList, ArrangementStartDate, ArrangementFinishDate, TotalDailyArragnementedBlockList, TotalBlockImportLogList, TotalBlockExportLogList, TotalDelayedBlockList);
}
public ArrangementResultWithDateDTO()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;
using System.Diagnostics;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface
{
public interface IBlockArrangement
{
//지번 자동 할당
List<UnitcellDTO[,]> InitializeArrangementMatrixWithAddress(List<WorkshopDTO> WorkShopList);
List<Int32[,]> InitializeArrangementMatrix(List<WorkshopDTO> WorkShopList);
List<Int32[,]> InitializeArrangementMatrixWithSlack(List<WorkshopDTO> WorkShopList, int Slack);
//BLF 알고리즘 수행
DateTime[] CalcEarliestAndLatestDates(List<BlockDTO> _blockInfoList);
ArrangementResultWithDateDTO RunBLFAlgorithm(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArranegementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel);
ArrangementResultWithDateDTO RunBLFAlgorithmWithAddress(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArranegementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel);
ArrangementResultWithDateDTO RunBLFAlgorithmWithSlack(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArranegementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack);
ArrangementResultWithDateDTO RunBLFAlgorithmWithSlackWithPriority(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArranegementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack);
ArrangementResultWithDateDTO RunBLFAlgorithmWithFloatingCrane(List<BlockDTO> inputBlockList, List<Int32[,]> ArrangementMatrixList, List<WorkshopDTO> WorkShopInfo, DateTime ArranegementStartDate, DateTime ArrangementFinishDate, ToolStripProgressBar ProgressBar, ToolStripStatusLabel ProgressLabel, int Slack, int ExportWorkshopIndex);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eoba.Shipyard.ArrangementSimulator.MainUI
{
public partial class frmGreedyObjectParameterSetting : Form
{
public double CoefficientOfTwistNum { get; set; }
public double CoefficientOfAdjacentNum { get; set; }
public double CoefficientOfAdjacentLength { get; set; }
public double CoefficientOfDistanceofCentroid { get; set; }
public frmGreedyObjectParameterSetting()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
CoefficientOfTwistNum = Convert.ToDouble(tboxNumofTwist.Text);
CoefficientOfAdjacentNum = Convert.ToDouble(tboxNumofAdjacentNum.Text);
CoefficientOfAdjacentLength = Convert.ToDouble(tboxAdjacentLength.Text);
CoefficientOfDistanceofCentroid = Convert.ToDouble(tboxDistanceofCentroid.Text);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
namespace Eoba.Shipyard.ArrangementSimulator.MainUI
{
public partial class frmResultsViewer : Form
{
public frmResultsViewer()
{
InitializeComponent();
}
public frmResultsViewer(ArrangementResultWithDateDTO _resultsInfo, List<WorkshopDTO> _workshopInfoList)
{
InitializeComponent(_resultsInfo, _workshopInfoList);
}
public frmResultsViewer(List<BlockDTO> _blockInfoList, List<WorkshopDTO> _workshopInfoList, List<UnitcellDTO[,]> _arrangementMatrixList)
{
InitializeComponent(_blockInfoList, _workshopInfoList, _arrangementMatrixList);
}
private void elementHost1_ChildChanged(object sender, System.Windows.Forms.Integration.ChildChangedEventArgs e)
{
}
private void elementHost1_ChildChanged_1(object sender, System.Windows.Forms.Integration.ChildChangedEventArgs e)
{
}
private void elementHost1_ChildChanged_2(object sender, System.Windows.Forms.Integration.ChildChangedEventArgs e)
{
}
private void elementHost1_ChildChanged_3(object sender, System.Windows.Forms.Integration.ChildChangedEventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Drawing;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Implementation
{
public class ResultsManagement: IResultsManagement
{
/// <summary>
/// 각 작업장의 배치 결과를 요약하여 출력할 차트를 초기화 하는 함수
/// </summary>
/// <param name="_workshopInfoList">작업장 정보 리스트</param>
/// <param name="_chartList">가시화 할 차트 리스트</param>
/// <param name="_chart">이미 생성되어 있는 0번째 작업장 차트</param>
/// <param name="_tabPage">가시화 할 탭 페이지</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
void IResultsManagement.InitializeIndividualWorkshopChart(List<WorkshopDTO> _workshopInfoList, List<Chart> _chartList, Chart _chart, TabControl _tabPage)
{
_chartList.Add(_chart);
for (int i = 1; i < _workshopInfoList.Count; i++)
{
ChartArea tempChartArea = new ChartArea();
tempChartArea.CursorX.IsUserEnabled = true;
tempChartArea.CursorX.IsUserSelectionEnabled = true;
tempChartArea.CursorX.SelectionColor = System.Drawing.Color.Transparent;
tempChartArea.Name = "ChartArea" + Convert.ToInt16(i + 1);
Chart tempChart = new Chart();
tempChart.ChartAreas.Add(tempChartArea);
tempChart.Dock = System.Windows.Forms.DockStyle.Fill;
tempChart.Location = new System.Drawing.Point(3, 3);
tempChart.Name = "ChartWorkshop1";
tempChart.Size = new System.Drawing.Size(948, 238);
tempChart.TabIndex = 0;
tempChart.Text = "chart1";
_chartList.Add(tempChart);
}
//tabpage 생성
for (int i = 1; i < _workshopInfoList.Count; i++)
{
TabPage tempTabpages = new TabPage();
tempTabpages.Controls.Add(_chartList[i]);
tempTabpages.Location = new System.Drawing.Point(4, 22);
tempTabpages.Name = "tpgWorkstage" + Convert.ToString(i + 1);
tempTabpages.Padding = new System.Windows.Forms.Padding(3);
tempTabpages.Size = new System.Drawing.Size(954, 244);
tempTabpages.TabIndex = 0;
tempTabpages.Text = "Workshop" + Convert.ToString(i + 1);
tempTabpages.UseVisualStyleBackColor = true;
_tabPage.TabPages.Add(tempTabpages);
}
// 각 차트를 차트 리스트에 입력
//4개의 작업장 갯수 만큼 시리즈를 생성하여 각 차트에 설정
Series IndividualLineSerise; //면적활용률
Series IndividualBarSerise; //배치블록 갯수
for (int i = 0; i < _chartList.Count; i++)
{
IndividualLineSerise = new Series();
IndividualLineSerise.ChartType = SeriesChartType.Line;
IndividualLineSerise.XValueType = ChartValueType.Time;
IndividualLineSerise.Name = "면적 활용률";
IndividualBarSerise = new Series();
IndividualBarSerise.ChartType = SeriesChartType.Column;
IndividualBarSerise.XValueType = ChartValueType.Time;
IndividualBarSerise.Name = "배치블록 갯수";
_chartList[i].Series.Add(IndividualBarSerise);
_chartList[i].Series.Add(IndividualLineSerise);
_chartList[i].ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;
_chartList[i].ChartAreas[0].AxisX.LabelStyle.Format = "yy-MM-dd";
}
for (int i = 0; i < _chartList.Count; i++)
{
_chartList[i].Series[0].Points.Clear();
_chartList[i].Series[1].Points.Clear();
}
}
/// <summary>
/// 전체 작업장 배치 결과를 종합하여 출력할 차트를 초기화 하는 함수
/// </summary>
/// <param name="_chart">전체 작업장 정보를 출력할 차트</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
void IResultsManagement.InitializeTotalWorkshopChart(Chart _chart)
{
Series TotalLineSeries = new Series();
Series TotalBarSeries = new Series();
Series TotalDelaySeries = new Series();
TotalLineSeries.ChartType = SeriesChartType.Line;
TotalLineSeries.XValueType = ChartValueType.Time;
TotalLineSeries.Name = "평균 면적 활용률";
TotalBarSeries.ChartType = SeriesChartType.Column;
TotalBarSeries.XValueType = ChartValueType.Time;
TotalBarSeries.Name = "평균 배치블록 갯수";
TotalDelaySeries.ChartType = SeriesChartType.Column;
TotalDelaySeries.XValueType = ChartValueType.Time;
TotalDelaySeries.Name = "일별 지연블록 갯수";
TotalDelaySeries.Color = Color.Red;
_chart.Series.Add(TotalBarSeries);
_chart.Series.Add(TotalLineSeries);
_chart.Series.Add(TotalDelaySeries);
_chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;
_chart.ChartAreas[0].AxisX.LabelStyle.Format = "yy-MM-dd";
_chart.Series[0].Points.Clear();
_chart.Series[1].Points.Clear();
_chart.Series[2].Points.Clear();
}
/// <summary>
/// 블록 배치 결과 입력 받아 차트에 출력하는 함수
/// </summary>
/// <param name="_resultInfo">블록 배치 결과</param>
/// <param name="_chartList">블록 정보가 출력 될 차트 리스트</param>
/// <param name="_chart">전체 작업장 정보를 출력할 차트</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
void IResultsManagement.DrawChart(ArrangementResultWithDateDTO _resultInfo, List<Chart> _chartList, Chart _chart)
{
for (int i = 0; i < _resultInfo.TotalBlockImportLogList.Count; i++)
{
double SumofAreaUtilization = 0;
double SumofLocatedBlock = 0;
//작업장 별 결과
for (int j = 0; j < _resultInfo.ResultWorkShopInfo[i].Count; j++)
{
_chartList[j].Series[0].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), _resultInfo.ResultWorkShopInfo[i][j].AreaUtilization * 100);
_chartList[j].Series[1].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), _resultInfo.ResultWorkShopInfo[i][j].NumOfLocatedBlocks);
SumofAreaUtilization = SumofAreaUtilization + _resultInfo.ResultWorkShopInfo[i][j].AreaUtilization * 100;
SumofLocatedBlock = SumofLocatedBlock + _resultInfo.ResultWorkShopInfo[i][j].NumOfLocatedBlocks;
}
//종합 결과
_chart.Series[0].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), SumofAreaUtilization);
_chart.Series[1].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), SumofLocatedBlock / Convert.ToDouble(_resultInfo.ResultWorkShopInfo[i].Count));
_chart.Series[2].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), _resultInfo.TotalDelayedBlockList[i].Count);
}
}
/// <summary>
/// 배치 결과를 그래프에 나타내는 함수, 주판 배치용 오버라이드를 위해 bool 변수 추가함
/// </summary>
/// <param name="_resultInfo">블록 배치 결과</param>
/// <param name="_chartList">블록 정보가 출력 될 차트 리스트</param>
/// <param name="_chart">전체 작업장 정보를 출력할 차트</param>
/// <param name="IsPlateArrangement">주판배치를 나타내는 오버라이드용 변수, 주판일 시 true</param>
void IResultsManagement.DrawChart(ArrangementResultWithDateDTO _resultInfo, List<Chart> _chartList, Chart _chart, bool IsPlateArrangement)
{
for (int i = 0; i < _resultInfo.TotalBlockImportLogList.Count; i++)
{
double SumofAreaUtilization = 0;
double SumofLocatedBlock = 0;
//작업장 별 결과
for (int j = 0; j < _resultInfo.ResultWorkShopInfo[i].Count; j++)
{
_chartList[j].Series[0].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), _resultInfo.ResultWorkShopInfo[i][j].AreaUtilization * 100);
_chartList[j].Series[1].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), _resultInfo.ResultWorkShopInfo[i][j].NumOfLocatedBlocks);
SumofAreaUtilization = SumofAreaUtilization + _resultInfo.ResultWorkShopInfo[i][j].AreaUtilization * 100;
SumofLocatedBlock = SumofLocatedBlock + _resultInfo.ResultWorkShopInfo[i][j].NumOfLocatedBlocks;
}
//종합 결과
_chart.Series[0].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), SumofAreaUtilization / Convert.ToDouble(_resultInfo.ResultWorkShopInfo[i].Count));
_chart.Series[1].Points.AddXY(_resultInfo.ArrangementStartDate.AddDays(i).ToShortDateString(), SumofLocatedBlock / Convert.ToDouble(_resultInfo.ResultWorkShopInfo[i].Count));
}
}
/// <summary>
/// 배치가 완료된 블록 정보를 바탕으로 블록 배치 정보가 입력되어 있는 UnitcellDTO 배열 목록을 생성하는 함수(배치 완료 후 결과 가시화에 사용됨)
/// </summary>
/// <param name="InpuBlockList">배치가 완료된 블록 리스트</param>
/// <param name="WorkShopArrangementInfo">지번 정보가 입력되어 있는 UnitCellDTO 목록(블록 배치 정보는 입력되지 않음)</param>
/// <returns>각 격자에 배치된 블록의 정보가 입력되어 있는 UnitCellDTO 목록</returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
List<UnitcellDTO[,]> IResultsManagement.GenterateArrangementMatrixFromBlockinfo(List<BlockDTO> InpuBlockList, List<UnitcellDTO[,]> WorkShopArrangementInfo)
{
for (int BlockIndex = 0; BlockIndex < InpuBlockList.Count; BlockIndex++)
{
for (int row = 0; row < Convert.ToInt16(Math.Ceiling(InpuBlockList[BlockIndex].RowCount)); row++)
{
for (int column = 0; column < Convert.ToInt16(Math.Ceiling(InpuBlockList[BlockIndex].ColumnCount)); column++)
{
WorkShopArrangementInfo[InpuBlockList[BlockIndex].CurrentLocatedWorkshopIndex][Convert.ToInt16(InpuBlockList[BlockIndex].LocatedRow) + row, Convert.ToInt16(InpuBlockList[BlockIndex].LocatedColumn) + column].BlockIndex = InpuBlockList[BlockIndex].Index;
WorkShopArrangementInfo[InpuBlockList[BlockIndex].CurrentLocatedWorkshopIndex][Convert.ToInt16(InpuBlockList[BlockIndex].LocatedRow) + row, Convert.ToInt16(InpuBlockList[BlockIndex].LocatedColumn) + column].IsOccupied = true;
}
}
}
return WorkShopArrangementInfo;
}
/// <summary>
/// 배치가 완료된 주판 정보를 바탕으로 주판 배치 정보가 입력되어 있는 UnitcellDTO 배열 목록을 생성하는 함수(배치 완료 후 결과 가시화에 사용됨)
/// </summary>
/// <param name="InpuBlockList">배치가 완료된 주판 리스트</param>
/// <param name="WorkShopArrangementInfo">지번 정보가 입력되어 있는 UnitCellDTO 목록(블록 배치 정보는 입력되지 않음)</param>
/// <returns>각 격자에 배치된 블록의 정보가 입력되어 있는 UnitCellDTO 목록</returns>
List<UnitcellDTO[,]> IResultsManagement.GenterateArrangementMatrixFromPlateinfo(List<PlateConfigDTO> InpuPlateList, List<UnitcellDTO[,]> WorkShopArrangementInfo)
{
for (int PlateIndex = 0; PlateIndex < InpuPlateList.Count; PlateIndex++)
{
for (int row = 0; row < InpuPlateList[PlateIndex].RowCount; row++)
{
for (int column = 0; column < InpuPlateList[PlateIndex].ColCount; column++)
{
WorkShopArrangementInfo[InpuPlateList[PlateIndex].CurrentLocatedWorkshopIndex][InpuPlateList[PlateIndex].LocatedRow + row, InpuPlateList[PlateIndex].LocateCol + column].BlockIndex = PlateIndex;
//실제 주판의 형상에 따라 실제 점유표기를 다르게 함
if (InpuPlateList[PlateIndex].PlateConfig[row, column] == 0)
{
WorkShopArrangementInfo[InpuPlateList[PlateIndex].CurrentLocatedWorkshopIndex][InpuPlateList[PlateIndex].LocatedRow + row, InpuPlateList[PlateIndex].LocateCol + column].IsOccupied = false;
}
else
{
WorkShopArrangementInfo[InpuPlateList[PlateIndex].CurrentLocatedWorkshopIndex][InpuPlateList[PlateIndex].LocatedRow + row, InpuPlateList[PlateIndex].LocateCol + column].IsOccupied = true;
}
}
}
}
return WorkShopArrangementInfo;
}
/// <summary>
/// 각 작업장의 날짜별 배치 블록 현황을 출력하는 함수(csv 파일 생성)
/// 2020 수정 -> 각 블록 별 확정된 배치 좌표 및 실제 입출고 일자를 출력하는 함수
/// </summary>
/// <param name="_resultInfo">블록 배치 결과</param>
/// <param name="_fileName">생성할 파일 경로 및 이름</param>
/// <remarks>
/// 최초 구현 : 주수헌, 2015년 9월 16일
/// 최종 수정 : 유상현, 2020년 07월 05일
/// </remarks>
void IResultsManagement.PrintArrangementResult(ArrangementResultWithDateDTO _resultInfo, string _fileName)
{
FileStream fs = new FileStream(_fileName + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
//열 이름 설정
string FirstRow = "PROJECTNO,Block No.,Initial Import Date,Initial Export Date,Actual Import Date,Actual Export Date,Delayed Days,Workshop Index,Located Row,Located Column";
sw.WriteLine(FirstRow);
foreach (BlockDTO Block in _resultInfo.BlockResultList)
{
string tempRowstring = "";
tempRowstring += Block.Project;
tempRowstring += "," + Block.Name;
tempRowstring += "," + Block.InitialImportDate.ToShortDateString();
tempRowstring += "," + Block.InitialExportDate.ToShortDateString();
tempRowstring += "," + Block.ActualImportDate.ToShortDateString();
tempRowstring += "," + Block.ActualExportDate.ToShortDateString();
if (Block.InitialImportDate == Block.ActualImportDate) tempRowstring += "," + "0";
else tempRowstring += "," + Convert.ToString((Block.ActualImportDate - Block.InitialImportDate).Days);
tempRowstring += "," + Convert.ToString(Block.CurrentLocatedWorkshopIndex);
tempRowstring += "," + Convert.ToString(Block.LocatedRow);
tempRowstring += "," + Convert.ToString(Block.LocatedColumn);
sw.WriteLine(tempRowstring);
}
sw.Close();
fs.Close();
#region 이전 버전
//작업장 갯수 만큼 반복하여 파일 생성
//for (int workshopindex = 0; workshopindex < _resultInfo.ResultWorkShopInfo[0].Count; workshopindex++)
//{
// FileStream fs = new FileStream(_fileName + "_" + _resultInfo.ResultWorkShopInfo[0][workshopindex].Name + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write);
// StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
// //열 이름 설정
// string FirstRow = "Date,Area Utilization,# of Blocks,Block name";
// sw.WriteLine(FirstRow);
// //날짜별 배치 정보에서 해당 작업장에 배치된 블록 검색
// List<List<BlockDTO>> tempTotalDailyBlockList = new List<List<BlockDTO>>();
// for (int i = 0; i < _resultInfo.TotalDailyArragnementedBlockList.Count; i++)
// {
// List<BlockDTO> tempTodayBlockList = new List<BlockDTO>();
// for (int j = 0; j < _resultInfo.TotalDailyArragnementedBlockList[i].Count; j++)
// {
// if (_resultInfo.ResultWorkShopInfo[0][workshopindex].Index == _resultInfo.TotalDailyArragnementedBlockList[i][j].CurrentLocatedWorkshopIndex)
// {
// tempTodayBlockList.Add(_resultInfo.TotalDailyArragnementedBlockList[i][j]);
// }
// }
// tempTotalDailyBlockList.Add(tempTodayBlockList);
// }
// //날짜별 점유 블록 정보 입력
// DateTime CurrentDate = _resultInfo.ArrangementStartDate;
// for (int i = 0; i < _resultInfo.TotalDailyArragnementedBlockList.Count; i++)
// {
// string tempRowstring = "";
// tempRowstring = CurrentDate.ToShortDateString();
// tempRowstring = tempRowstring + "," + _resultInfo.ResultWorkShopInfo[i][workshopindex].AreaUtilization;
// tempRowstring = tempRowstring + "," + _resultInfo.ResultWorkShopInfo[i][workshopindex].NumOfLocatedBlocks;
// string LocatedBlockName = "";
// for (int j = 0; j < tempTotalDailyBlockList[i].Count; j++)
// {
// if (j == 0)
// {
// LocatedBlockName = "(" + tempTotalDailyBlockList[i][j].Project + ")" + tempTotalDailyBlockList[i][j].Name;
// }
// else
// {
// LocatedBlockName = LocatedBlockName + "," + "(" + tempTotalDailyBlockList[i][j].Project + ")" + tempTotalDailyBlockList[i][j].Name;
// }
// }
// tempRowstring = tempRowstring + "," + LocatedBlockName;
// sw.WriteLine(tempRowstring);
// CurrentDate = CurrentDate.AddDays(1);
// }
// sw.Close();
// fs.Close();
//}
#endregion
}
/// <summary>
/// 특정 날짜의 작업장 별 배치 형상을 텍스트로 출력하는 함수(csv 파일 생성)
/// </summary>
/// <param name="ArrangementMatrix">작업장 별 블록 배치 현황</param>
/// <param name="_workshopFileName">현재 선택된 작업장 정보 파일 이름</param>
/// <param name="_blockFileName">현재 선택된 블록 정보 파일 이름</param>
/// <param name="_resultInfo">블록 배치 결과</param>
/// <param name="_selectedDate">확인하고자 하는 날짜의 일련번호</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
void IResultsManagement.PrintArrangementMatrixListResultWithDate(List<UnitcellDTO[,]> ArrangementMatrix, string _workshopFileName, string _blockFileName, ArrangementResultWithDateDTO _resultInfo, int _selectedDate)
{
if (ArrangementMatrix != null)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string selected = dialog.SelectedPath;
string FileName = selected + "\\" + _workshopFileName + "_" + _blockFileName + "_Matrix";
for (int workshopindex = 0; workshopindex < ArrangementMatrix.Count; workshopindex++)
{
FileStream fs = new FileStream(FileName + "_" + _resultInfo.ResultWorkShopInfo[_selectedDate][workshopindex].Name + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
for (int i = 0; i < ArrangementMatrix[workshopindex].GetLength(0); i++)
{
string row = "";
for (int j = 0; j < ArrangementMatrix[workshopindex].GetLength(1); j++)
{
row = row + ArrangementMatrix[workshopindex][i, j].BlockIndex + ",";
}
sw.WriteLine(row);
}
sw.Close();
fs.Close();
}
MessageBox.Show(selected + "에 " + _resultInfo.ResultWorkShopInfo[_selectedDate].Count.ToString() + "개의 파일이 생성되었습니다.");
}
}
else MessageBox.Show("결과 정보가 없습니다.");
}
/// <summary>
/// Greedy 알고리즘으로 생성된 특정 작업장의 배치 결과를 출력하는 함수(csv 파일 생성)
/// </summary>
/// <param name="ArrangementMatrix">특정 작업장 배치 현황</param>
/// <param name="_workshopFileName">작업장 파일 이름</param>
/// <param name="_blockFileName">블록 정보 파일 이름</param>
void IResultsManagement.PrintArrangementMatrixResult(UnitcellDTO[,] ArrangementMatrix, string _workshopFileName, string _blockFileName)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string FilePath = dialog.SelectedPath;
string FileName = FilePath + "\\" + _workshopFileName + "_" + _blockFileName;
FileStream fs = new FileStream(FileName + Environment.TickCount.ToString() + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
//각 격자에 배치된 블록의 Index 출력
int row = ArrangementMatrix.GetLength(0);
int col = ArrangementMatrix.GetLength(1);
for (int i = 0; i < row; i++)
{
string temp = ArrangementMatrix[i, 0].BlockIndex.ToString();
for (int j = 1; j < col; j++)
{
temp = temp + "," + ArrangementMatrix[i, j].BlockIndex.ToString();
}
sw.WriteLine(temp);
}
sw.Close();
fs.Close();
}
MessageBox.Show("결과 출력 파일이 생성되었습니다.");
}
/// <summary>
/// Greedy 알고리즘으로 생성된 특정 작업장의 누적 점유 정보 결과를 출력하는 함수(csv 파일 생성)
/// </summary>
/// <param name="ArrangementMatrix">특정 작업장 배치 현황</param>
/// <param name="_workshopFileName">작업장 파일 이름</param>
/// <param name="_blockFileName">블록 정보 파일 이름</param>
void IResultsManagement.PrintArrangementMatrixResult(double[,] ArrangementMatrix, string _workshopFileName, string _blockFileName, int workshopNum)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string FilePath = dialog.SelectedPath;
string FileName = FilePath + "\\" + _workshopFileName + "_" + _blockFileName;
FileStream fs = new FileStream(FileName + "_" +workshopNum.ToString() + Environment.TickCount.ToString() + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
//각 격자에 배치된 블록의 Index 출력
int row = ArrangementMatrix.GetLength(0);
int col = ArrangementMatrix.GetLength(1);
for (int i = 0; i < row; i++)
{
string temp = ArrangementMatrix[i, 0].ToString();
for (int j = 1; j < col; j++)
{
temp = temp + "," + ArrangementMatrix[i, j].ToString();
}
sw.WriteLine(temp);
}
sw.Close();
fs.Close();
}
MessageBox.Show("결과 출력 파일이 생성되었습니다.");
}
/// <summary>
/// BLF 알고리즘 결과 요약 출력
/// </summary>
/// <param name="_resultInfo">배치결과</param>
/// <param name="_sw">초시계</param>
void IResultsManagement.PrintBLFAlgorithmResultsSummary(ArrangementResultWithDateDTO _resultInfo, Stopwatch _sw)
{
int LocatedBlockNo = 0;
int FinishedBlockNo = 0;
int DelayedBlockNo = 0;
int UnarrangementedBlockNo = 0;
int TotalDelayedTime = 0;
for (int i = 0; i < _resultInfo.BlockResultList.Count; i++)
{
if (_resultInfo.BlockResultList[i].IsLocated == true)
LocatedBlockNo++;
if (_resultInfo.BlockResultList[i].IsFinished == true)
FinishedBlockNo++;
if (_resultInfo.BlockResultList[i].IsDelayed == true && _resultInfo.BlockResultList[i].IsFinished == true)
{
DelayedBlockNo++;
TotalDelayedTime += _resultInfo.BlockResultList[i].DelayedTime;
}
if (_resultInfo.BlockResultList[i].IsFinished == false && _resultInfo.BlockResultList[i].IsLocated == false)
{
UnarrangementedBlockNo++;
}
}
double AverageDelayedTime = Math.Round((double)TotalDelayedTime / (double)DelayedBlockNo, 2);
//배치결과 요약 출력
if (_sw.ElapsedMilliseconds < 5000)
{
string strTS = _sw.ElapsedMilliseconds.ToString();
MessageBox.Show("블록 배치가 완료되었습니다.\r처리시간 : " + strTS + "ms \r전체 대상블록 개수 :" + _resultInfo.BlockResultList.Count.ToString() + "개\r완료된 블록 개수(배치중 블록 개수) : " + FinishedBlockNo.ToString() + "(" + LocatedBlockNo.ToString() + ")" + "개\r미배치 블록 개수 : " + UnarrangementedBlockNo.ToString() + "개 \r지연된 블록 개수 : " + DelayedBlockNo.ToString() + "개\n평균 지연 일수 : " + AverageDelayedTime.ToString() + "일");
//MessageBox.Show("블록 배치가 완료되었습니다.\r처리시간 : " + strTS + "ms \r전체 대상블록 개수 :" + mResultInfo.BlockResultList.Count.ToString() + "개\r완료된 블록 개수(배치중 블록 개수) : " + FinishedBlockNo.ToString() + "(" + LocatedBlockNo.ToString() + ")" + "개\r미배치 블록 개수 : " + UnarrangementedBlockNo.ToString() + "개 \r지연된 블록 개수 : " + DelayedBlockNo.ToString() + "개 \r총 지연 일수 : " + DelayedDays.ToString() + "일");
}
if (_sw.ElapsedMilliseconds > 5000)
{
string strTS = (_sw.ElapsedMilliseconds / 1000).ToString();
MessageBox.Show("블록 배치가 완료되었습니다.\r처리시간 : " + strTS + "s \r전체 대상블록 개수 :" + _resultInfo.BlockResultList.Count.ToString() + "개\r완료된 블록 개수(배치중 블록 개수) : " + FinishedBlockNo.ToString() + "(" + LocatedBlockNo.ToString() + ")" + "개\r미배치 블록 개수 : " + UnarrangementedBlockNo.ToString() + "개 \r지연된 블록 개수 : " + DelayedBlockNo.ToString() +"개\n평균 일수 : " + AverageDelayedTime.ToString() + "일");
//MessageBox.Show("블록 배치가 완료되었습니다.\r처리시간 : " + strTS + "s \r전체 대상블록 개수 :" + mResultInfo.BlockResultList.Count.ToString() + "개\r완료된 블록 개수(배치중 블록 개수) : " + FinishedBlockNo.ToString() + "(" + LocatedBlockNo.ToString() + ")" + "개\r미배치 블록 개수 : " + UnarrangementedBlockNo.ToString() + "개 \r지연된 블록 개수 : " + DelayedBlockNo.ToString() + "개 \r총 지연 일수 : " + DelayedDays.ToString() + "일");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface;
using System.Windows.Forms;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Implementation
{
public class DataManagement : IDataManagement
{
/// <summary>
/// 작업장 정보를 불러와 그리드에 출력하는 함수
/// </summary>
/// <param name="_datagrid">작업장 정보를 출력할 대상 그리드</param>
/// <param name="_workshopList">작업장 정보</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
///
void IDataManagement.PrintWorkshopDataOnGrid(DataGridView _datagrid, List<WorkshopDTO> _workshopList)
{
_datagrid.Rows.Clear();
for (int row = 0; row < _workshopList.Count; row++)
{
string[] temprow = { Convert.ToString(_workshopList[row].Index),
_workshopList[row].Name,
Convert.ToString(_workshopList[row].RowCount),
Convert.ToString(_workshopList[row].ColumnCount),
Convert.ToString(_workshopList[row].NumOfAddress) };
_datagrid.Rows.Add(temprow);
}
}
/// <summary>
/// 작업장 그리드 정보가 갱신되면 이를 불러와 작업장 정보에 저장하는 함수
/// </summary>
/// <param name="_datagrid">작업장 정보가 변경된 그리드</param>
/// <param name="_workshopList">갱신할 작업장 정보</param>
/// <remarks>
/// 최초 작성 : 이동건, 2016년 02월 25일
/// </remarks>
void IDataManagement.UpdateWorkshopDataOfGrid(DataGridView _datagrid, List<WorkshopDTO> _workshopList)
{
WorkshopDTO tempWorkshopDTO;
_workshopList.Clear();
foreach (DataGridViewRow row in _datagrid.Rows)
{
//for(int i=0; i < row.Cells.Count; i++)
//{
// if (row.IsNewRow || row.Cells[i].Value == null)
// break;
// }
if (row.Cells[0].Value != null)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
string value3 = row.Cells[2].Value.ToString();
string value4 = row.Cells[3].Value.ToString();
string value5 = row.Cells[4].Value.ToString();
tempWorkshopDTO = new WorkshopDTO(Convert.ToInt16(value1), value2, Convert.ToDouble(value3), Convert.ToDouble(value4), Convert.ToInt32(value5));
_workshopList.Add(tempWorkshopDTO);
}
}
}
/// <summary>
/// 블록 정보를 불러와 그리드에 출력하는 함수
/// </summary>
/// <param name="_datagrid">블록 정보를 출력할 대상 그리드</param>
/// <param name="_blockList">블록 정보</param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// 수정 작성 : 이동건, 2016년 02월 19일
/// </remarks>
void IDataManagement.PrintBlockDataOnGrid(DataGridView _datagrid, List<BlockDTO> _blockList)
{
_datagrid.Rows.Clear();
_datagrid.Columns.Clear();
_datagrid.ColumnCount = 14;
_datagrid.Columns[0].Name = "Index";
_datagrid.Columns[1].Name = "프로젝트번호";
_datagrid.Columns[2].Name = "블록번호";
_datagrid.Columns[3].Name = "세로";
_datagrid.Columns[4].Name = "가로";
_datagrid.Columns[5].Name = "상향작업공간";
_datagrid.Columns[6].Name = "하향작업공간";
_datagrid.Columns[7].Name = "좌측작업공간";
_datagrid.Columns[8].Name = "우측작업공간";
_datagrid.Columns[9].Name = "리드타임";
_datagrid.Columns[10].Name = "투입날짜";
_datagrid.Columns[11].Name = "반출날짜";
_datagrid.Columns[12].Name = "선호 작업장";
_datagrid.Columns[13].Name = "선호 지번";
for (int row = 0; row < _blockList.Count; row++)
{
string strPreferedWorkShop = "";
string strPreferedAddress = "";
for (int i = 0; i < _blockList[row].PreferWorkShopIndexList.Count; i++)
{
if (i != _blockList[row].PreferWorkShopIndexList.Count - 1)
strPreferedWorkShop = strPreferedWorkShop + Convert.ToString(_blockList[row].PreferWorkShopIndexList[i]) + ",";
else
strPreferedWorkShop = strPreferedWorkShop + Convert.ToString(_blockList[row].PreferWorkShopIndexList[i]);
}
for (int i = 0; i < _blockList[row].PreferAddressIndexList.Count; i++)
{
if (i != _blockList[row].PreferAddressIndexList.Count - 1)
strPreferedAddress = strPreferedAddress + Convert.ToString(_blockList[row].PreferAddressIndexList[i]) + ",";
else
strPreferedAddress = strPreferedAddress + Convert.ToString(_blockList[row].PreferAddressIndexList[i]);
}
string[] temprow = { Convert.ToString(_blockList[row].Index),
_blockList[row].Project,
_blockList[row].Name,
Convert.ToString(_blockList[row].RowCount),
Convert.ToString(_blockList[row].ColumnCount),
Convert.ToString(_blockList[row].UpperSideCount),
Convert.ToString(_blockList[row].BottomSideCount),
Convert.ToString(_blockList[row].LeftSideCount),
Convert.ToString(_blockList[row].RightSideCount),
Convert.ToString(_blockList[row].Leadtime),
_blockList[row].ImportDate.ToShortDateString(),
_blockList[row].ExportDate.ToShortDateString(),
strPreferedWorkShop,
strPreferedAddress
};
_datagrid.Rows.Add(temprow);
}
}
/// <summary>
/// 주판 정보를 불러와 그리드에 출력하는 함수
/// </summary>
/// <param name="_datagrid">주판 정보를 출력할 대상 그리드</param>
/// <param name="_blockList">주판 정보</param>
/// 최종수정 : 2019-09-28 (주수헌)
void IDataManagement.PrintPlateDataOnFrid(DataGridView _datagrid, List<PlateConfigDTO> _plateList)
{
_datagrid.Rows.Clear();
// 주판의 정보 입력을 위한 그리드 컬럼 변경
_datagrid.Columns.Clear();
_datagrid.ColumnCount = 8;
_datagrid.Columns[0].Name = "주판번호";
_datagrid.Columns[1].Name = "세로";
_datagrid.Columns[2].Name = "가로";
_datagrid.Columns[3].Name = "리드타임";
_datagrid.Columns[4].Name = "투입날짜";
_datagrid.Columns[5].Name = "반출날짜";
_datagrid.Columns[6].Name = "선호 작업장";
_datagrid.Columns[7].Name = "선호 지번";
for (int row = 0; row < _plateList.Count; row++)
{
string strPreferedWorkShop = "";
string strPreferedAddress = "";
for (int i = 0; i < _plateList[row].PreferWorkShopIndexList.Count; i++)
{
if (i != _plateList[row].PreferWorkShopIndexList.Count - 1)
strPreferedWorkShop = strPreferedWorkShop + Convert.ToString(_plateList[row].PreferWorkShopIndexList[i]) + ",";
else
strPreferedWorkShop = strPreferedWorkShop + Convert.ToString(_plateList[row].PreferWorkShopIndexList[i]);
}
for (int i = 0; i < _plateList[row].PreferAddressIndexList.Count; i++)
{
if (i != _plateList[row].PreferAddressIndexList.Count - 1)
strPreferedAddress = strPreferedAddress + Convert.ToString(_plateList[row].PreferAddressIndexList[i]) + ",";
else
strPreferedAddress = strPreferedAddress + Convert.ToString(_plateList[row].PreferAddressIndexList[i]);
}
string[] temprow = { _plateList[row].Name,
Convert.ToString(_plateList[row].RowCount),
Convert.ToString(_plateList[row].ColCount),
Convert.ToString(_plateList[row].LeadTime),
_plateList[row].PlanImportDate.ToShortDateString(),
_plateList[row].PlanExportDate.ToShortDateString(),
strPreferedWorkShop,
strPreferedAddress
};
_datagrid.Rows.Add(temprow);
}
}
/// <summary>
/// 블록 그리드 정보가 갱신되면 이를 불러와 블록 정보에 저장하는 함수
/// </summary>
/// <param name="_datagrid">블록 정보가 변경된 그리드</param>
/// <param name="_workshopList">갱신할 블록 정보</param>
/// <remarks>
/// 최초 작성 : 이동건, 2016년 02월 25일
/// </remarks>
void IDataManagement.UpdateBlockDataOfGrid(DataGridView _datagrid, List<BlockDTO> _blockList)
{
BlockDTO tempBlockDTO;
_blockList.Clear();
foreach (DataGridViewRow row in _datagrid.Rows)
{
//for (int i = 0; i < row.Cells.Count; i++)
//{
// if (row.IsNewRow || row.Cells[i].Value == null)
// continue;
//}
if (row.Cells[0].Value != null)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
string value3 = row.Cells[2].Value.ToString();
string value4 = row.Cells[3].Value.ToString();
string value5 = row.Cells[4].Value.ToString();
string value6 = row.Cells[5].Value.ToString();
string value7 = row.Cells[6].Value.ToString();
string value8 = row.Cells[7].Value.ToString();
string value9 = row.Cells[8].Value.ToString();
string value10 = row.Cells[9].Value.ToString();
string value11 = row.Cells[10].Value.ToString();
string value12 = row.Cells[11].Value.ToString();
string value13 = row.Cells[12].Value.ToString();
string value14 = row.Cells[13].Value.ToString();
List<int> tempPreferWorkShop = new List<int>();
List<int> tempPreferAddress = new List<int>();
string[] PreferWorkshoptemp = value13.Split(',');
for (int j = 0; j < PreferWorkshoptemp.Length; j++) tempPreferWorkShop.Add(Convert.ToInt32(PreferWorkshoptemp[j]));
if (value14 != "")
{
string[] PreferAddresstemp = value14.Split(',');
for (int j = 0; j < PreferAddresstemp.Length; j++) tempPreferAddress.Add(Convert.ToInt32(PreferAddresstemp[j]));
}
tempBlockDTO = new BlockDTO(Convert.ToInt16(value1),
value2,
value3,
Convert.ToDouble(value4),
Convert.ToDouble(value5),
Convert.ToDouble(value6),
Convert.ToDouble(value7),
Convert.ToDouble(value8),
Convert.ToDouble(value9),
tempPreferWorkShop,
tempPreferAddress,
Convert.ToDouble(value10),
DateTime.Parse(value11),
DateTime.Parse(value12),
DateTime.MinValue,
DateTime.MinValue);
_blockList.Add(tempBlockDTO);
}
}
}
/// <summary>
/// 입력한 블록 정보를 정제하는 함수
/// </summary>
/// <param name="_inputStringList">csv 파일로부터 읽어온 블록 정보 raw 데이터</param>
/// <param name="_workshopList">작업장 정보</param>
/// <returns>정제된 블록 정보</returns>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// 수정 작성 : 유상현, 2020년 05월 13일
/// </remarks>
List<BlockDTO> IDataManagement.RefineInputBlockData(List<string[]> _inputStringList, List<WorkshopDTO> _workshopList, double _UnitGridLength)
{
List<BlockDTO> returnList = new List<BlockDTO>();
//작업영역 고려 여부 변수 추가
//bool IsWorkAreaInfoConsidered = false;
for (int i = 1; i < _inputStringList.Count; i++)
{
double tempUpperCount;
double tempBotCount;
double tempLeftCount;
double tempRightCount;
double tempLeadTime;
double tempLength;
double tempBreadth;
DateTime tempImportDate;
DateTime tempExportDate;
List<int> tempPreferWorkShop = new List<int>();
List<int> tempPreferAddress = new List<int>();
bool PreferWorkShop = true;
bool PreferAddress = true;
bool IsRoadSide = false;
int tempSearchDirection;
int tempArrangementDirection;
BlockDTO tempBlockDTO;
//블록 크기 입력
//if (Convert.ToDouble(_inputStringList[i][3]) >= Convert.ToDouble(_inputStringList[i][4])) tempLength = Convert.ToDouble(_inputStringList[i][4]);
tempLength = Convert.ToDouble(_inputStringList[i][3]);
//if (Convert.ToDouble(_inputStringList[i][4]) < Convert.ToDouble(_inputStringList[i][3])) tempBreadth = Convert.ToDouble(_inputStringList[i][3]);
tempBreadth = Convert.ToDouble(_inputStringList[i][4]);
tempLength /= _UnitGridLength;
tempBreadth /= _UnitGridLength;
//상하좌우 작업공간 입력
if (_inputStringList[i][11] == "") tempUpperCount = 0.0;
else tempUpperCount = Convert.ToDouble(_inputStringList[i][11]);
if (_inputStringList[i][12] == "") tempBotCount = 0.0;
else tempBotCount = Convert.ToDouble(_inputStringList[i][12]);
if (_inputStringList[i][13] == "") tempLeftCount = 0.0;
else tempLeftCount = Convert.ToDouble(_inputStringList[i][13]);
if (_inputStringList[i][14] == "") tempRightCount = 0.0;
else tempRightCount = Convert.ToDouble(_inputStringList[i][14]);
//tempLeadTime = 0.0;
//if (_inputStringList[i][9] == "") tempLeadTime = 0.0;
//else tempLeadTime = Convert.ToDouble(_inputStringList[i][9]);
//입출고일 입력
if (_inputStringList[i][6] == "") tempImportDate = DateTime.Parse("0001-01-01");
else tempImportDate = DateTime.Parse(_inputStringList[i][6]);
if (_inputStringList[i][7] == "") tempExportDate = DateTime.Parse("0001-01-01");
else tempExportDate = DateTime.Parse(_inputStringList[i][7]);
//리드타임 계산
TimeSpan ts = tempExportDate - tempImportDate;
tempLeadTime = ts.Days;
//입고일과 출고일이 같은 데이터가 입력된 경우에는 출고일 +1
//TimeSpan ts = tempExportDate - tempImportDate;
//int tempTS = ts.Days;
//if (tempTS == 0) tempExportDate = tempExportDate.AddDays(1);
//선호작업장, 도로인접 배치 여부 입력
if (_inputStringList[i][8] == "")
{
PreferWorkShop = false;
PreferAddress = false;
}
else if (_inputStringList[i][8] == "-1")
{
PreferWorkShop = false;
IsRoadSide = true;
}
if (PreferWorkShop == false) //선호작업장 값이 없는 경우
{
//모든 작업장을 선호작업장으로 가짐
int totalWorkShop = _workshopList.Count;
for (int j = 0; j < totalWorkShop; j++) tempPreferWorkShop.Add(j);
}
else//선호작업장 값이 있는 경우
{
string[] temp = _inputStringList[i][8].Split('-');
for (int j = 0; j < temp.Length; j++) tempPreferWorkShop.Add(Convert.ToInt32(temp[j]));
int totalWorkShop = _workshopList.Count;
for (int j = 0; j < totalWorkShop; j++) if(!tempPreferWorkShop.Contains(j)) tempPreferWorkShop.Add(j);
}
// 선호지번 잠시 안씀
//if (_inputStringList[i][9] == "") PreferAddress = false;
//if (PreferAddress == false) //선호지번 값이 없는 경우
//{
// //선호지번은 빈 리스트
//}
//else//선호지번 값이 있는 경우
//{
// string[] temp = _inputStringList[i][9].Split('-');
// for (int j = 0; j < temp.Length; j++) tempPreferAddress.Add(Convert.ToInt32(temp[j]));
//}
//탐색방향 입력
if (_inputStringList[i][9] == "") tempSearchDirection = 1;
else tempSearchDirection = Convert.ToInt32(_inputStringList[i][9]);
//배치방향 입력
if (_inputStringList[i][10] == "") tempArrangementDirection = 0;
else tempArrangementDirection = Convert.ToInt32(_inputStringList[i][10]);
tempBlockDTO = new BlockDTO(
Convert.ToInt16(_inputStringList[i][0]),
_inputStringList[i][1],
_inputStringList[i][2],
tempBreadth,
tempLength,
tempUpperCount,
tempBotCount,
tempLeftCount,
tempRightCount,
tempPreferWorkShop,
tempPreferAddress,
tempLeadTime,
tempImportDate,
tempExportDate,
DateTime.MinValue,
DateTime.MinValue,
IsRoadSide,
PreferWorkShop,
tempSearchDirection,
tempArrangementDirection);
returnList.Add(tempBlockDTO);
}
return returnList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Eoba.Shipyard.ArrangementSimulator.MainUI;
namespace Eoba.Shipyard.ArrangementSimulator.MainUI
{
public partial class frmSetParameter : Form
{
public string temp1 { get; set; }
public string temp2 { get; set; }
public frmSetParameter()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.temp1 = textBox1.Text;
this.temp2 = textBox2.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void frmSetParameter_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Implementation;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Security.Cryptography;
namespace Eoba.Shipyard.ArrangementSimulator.ResultsViewer
{
/// <summary>
/// UserControl1.xaml에 대한 상호 작용 논리
/// </summary>
public partial class Viewer : UserControl
{
public Viewer()
{
InitializeComponent();
}
IBlockArrangement mBlockArrangement;
IDataManagement mDataManagement;
IResultsManagement mResultsManagement;
ArrangementResultWithDateDTO mResultsInfo;
List<BlockDTO> mBlockInfoList;
List<WorkshopDTO> mWorkshopInfoList;
List<UnitcellDTO[,]> mArrangementMatrixList;
Model3DGroup main3DGroup = new Model3DGroup();
List<string> tempDateIndexList = new List<string>();
int seletedDateIndex;
int workshopIndex = 0;
/// <summary>
/// BLF 알고리즘 적용시 호출되는 생성자
/// </summary>
/// <param name="_resultsInfo"></param>
/// <param name="_workshopInfoList"></param>
public Viewer(ArrangementResultWithDateDTO _resultsInfo, List<WorkshopDTO> _workshopInfoList)
{
mResultsInfo = new ArrangementResultWithDateDTO();
mResultsInfo = _resultsInfo;
mBlockArrangement = new BlockArrangementMgr();
mDataManagement = new DataManagement();
mResultsManagement = new ResultsManagement();
mWorkshopInfoList = new List<WorkshopDTO>();
mWorkshopInfoList = _workshopInfoList;
mArrangementMatrixList = new List<UnitcellDTO[,]>();
int numOfDates;
numOfDates = mResultsInfo.TotalDailyArragnementedBlockList.Count;
for (int i = 0; i < numOfDates; i++)
{
DateTime tempDate = mResultsInfo.ArrangementStartDate;
tempDate = tempDate.AddDays(i);
string strtempDate = tempDate.ToShortDateString();
tempDateIndexList.Add(strtempDate);
}
InitializeComponent();
lstArrDateList.ItemsSource = tempDateIndexList;
}
/// <summary>
/// Greedy 알고리즘 적용시 호출되는 생성자
/// </summary>
/// <param name="_blockInfoList"></param>
/// <param name="_workshopInfoList"></param>
public Viewer(List<BlockDTO> _blockInfoList, List<WorkshopDTO> _workshopInfoList, List<UnitcellDTO[,]> _arrangementMatrixList)
{
mBlockArrangement = new BlockArrangementMgr();
mDataManagement = new DataManagement();
mResultsManagement = new ResultsManagement();
mBlockInfoList = new List<BlockDTO>();
mBlockInfoList = _blockInfoList;
mWorkshopInfoList = new List<WorkshopDTO>();
mWorkshopInfoList = _workshopInfoList;
mArrangementMatrixList = new List<UnitcellDTO[,]>();
mArrangementMatrixList = _arrangementMatrixList;
InitializeComponent();
//btnShow.IsEnabled = true;
}
/// <summary>
/// PlateConfig의 상세를 보여줄 수 있는 3D 형상을 출력하는 버튼
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnShow_Click(object sender, RoutedEventArgs e)
{
//이전 코드
#region
////3차원 가시화
//HelixResultViewer.Children.Clear();
//if (main3DGroup.Children.Count == 0)
//{
// //카메라 초기화
// PerspectiveCamera myCamera = (PerspectiveCamera)HelixResultViewer.Camera;
// myCamera = SetCameraPosition(myCamera, mWorkshopInfoList[workshopIndex]);
//}
//else main3DGroup.Children.Clear();
////조명 설정
//var lights = new DefaultLights();
//HelixResultViewer.Children.Add(lights);
////작업장 가시화
//int row = mArrangementMatrixList[workshopIndex].GetLength(0);
//int column = mArrangementMatrixList[workshopIndex].GetLength(1);
//main3DGroup.Children.Add(CreateRectModel(row, column, 1, new Point3D(0, 0, 0), Colors.LightGray));
////블록 가시화
//ModelVisual3D model1 = new ModelVisual3D();
//for (int i = 0; i < mBlockInfoList.Count; i++)
//{
// //일반 블록은 녹색
// Color blockColor = Colors.LightGreen;
// blockColor.A = 220;
// string[] arrprintedstring = { mBlockInfoList[i].Name, mBlockInfoList[i].Project, mBlockInfoList[i].InitialImportDate.ToShortDateString(), mBlockInfoList[i].InitialExportDate.ToShortDateString() };
// //블록 위에 출력되는 정보 확인을 위하여 minSize 계산
// double minSize = mBlockInfoList[i].RowCount;
// if (mBlockInfoList[i].RowCount > mBlockInfoList[i].ColumnCount) minSize = mBlockInfoList[i].ColumnCount;
// minSize = minSize / arrprintedstring[2].Length;
// if (minSize > 3.0) minSize = 3.0;
// main3DGroup.Children.Add(CreateRectModel(Math.Ceiling(mBlockInfoList[i].RowCount), Math.Ceiling(mBlockInfoList[i].ColumnCount), 10.0, new Point3D(Math.Ceiling(mBlockInfoList[i].LocatedRow), Math.Ceiling(mBlockInfoList[i].LocatedColumn), 1), blockColor, minSize, arrprintedstring));
//}
//model1.Content = main3DGroup;
//HelixResultViewer.Children.Add(model1);
#endregion
}
/// <summary>
/// 실제로 가시화를 수행하는 이벤트 (BLF 알고리즘에서 날짜 선택시)
/// 주수헌 수정,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstArrDateList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
seletedDateIndex = lstArrDateList.SelectedIndex;
//조회하고자 하는 특정 날짜 index
int target_date = seletedDateIndex;
List<BlockDTO> targetBlockList = new List<BlockDTO>();
//블록배치와 주판 배치에 따라 다른 대상 설정
//특정 날짜에 배치되어 있는 블록 호출
targetBlockList = mResultsInfo.TotalDailyArragnementedBlockList[seletedDateIndex];
// 배치 블록 가시화 창 밑의 배치 블록 리스트에 현재 블록 정보 입력하는 코드
//grdBlockDetails.ItemsSource = targetBlockList;
//작업장 원점 좌표
//List<double[]> ws = new List<double[]>();
//foreach (WorkshopDTO workshop in mWorkshopInfoList)
//{
// ws.Add(new double[2] { workshop.RowLocation, workshop.ColumnLocation });
//}
//카메라 초기화를 위한 임시 작업장 생성
WorkshopDTO tempWorkshopDTO = new WorkshopDTO();
tempWorkshopDTO.RowCount = 199;
tempWorkshopDTO.ColumnCount = 809;
//3차원 가시화
HelixResultViewer.Children.Clear();
if (main3DGroup.Children.Count == 0)
{
//카메라 초기화
PerspectiveCamera myCamera = (PerspectiveCamera)HelixResultViewer.Camera;
myCamera = SetCameraPosition(myCamera, tempWorkshopDTO);
}
else main3DGroup.Children.Clear();
//조명 설정
var lights = new DefaultLights();
HelixResultViewer.Children.Add(lights);
DateTime CurrentDate = mResultsInfo.ArrangementStartDate.AddDays(seletedDateIndex);
ModelVisual3D model1 = new ModelVisual3D();
//작업장 가시화
foreach (WorkshopDTO Workshop in mWorkshopInfoList)
{
if (Workshop.Type != -1) main3DGroup.Children.Add(CreateRectModel(Workshop.RowCount, Workshop.ColumnCount, 0, new Point3D(Workshop.RowLocation, Workshop.ColumnLocation, 0), Colors.White));
else main3DGroup.Children.Add(CreateRectModel(Workshop.RowCount, Workshop.ColumnCount, 0, new Point3D(Workshop.RowLocation, Workshop.ColumnLocation, 0), Colors.Gray, 10, new string[4] { Workshop.Name, "", "", "" }));
}
//main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[0].RowCount, mWorkshopInfoList[0].ColumnCount, 0, new Point3D(ws[0][0], ws[0][1], 0), Colors.White));
//main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[1].RowCount, mWorkshopInfoList[1].ColumnCount, 0, new Point3D(ws[1][0], ws[1][1], 0), Colors.White));
//main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[2].RowCount, mWorkshopInfoList[2].ColumnCount, 0, new Point3D(ws[2][0], ws[2][1], 0), Colors.White));
//main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[3].RowCount, mWorkshopInfoList[3].ColumnCount, 0, new Point3D(ws[3][0], ws[3][1], 0), Colors.White));
////도크 가시화
//main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[3].RowCount, ws[2][1] - mWorkshopInfoList[3].ColumnCount, 0.000000, new Point3D(0, mWorkshopInfoList[3].ColumnCount, 0), Colors.Gray, 10, new string[4] { "Main Dock", "", "", ""}));
////입고장(북) 가시화
////main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[0].RowCount, ws[1][1] - ws[0][1] - mWorkshopInfoList[0].ColumnCount, 1, new Point3D(ws[0][0], ws[0][1] + mWorkshopInfoList[0].ColumnCount, 0), Colors.Gray));
//배치불가구역 가시화
foreach (WorkshopDTO Workshop in mWorkshopInfoList)
{
foreach (ArrangementMatrixInfoDTO Object in Workshop.ArrangementMatrixInfoList)
{
main3DGroup.Children.Add(CreateRectModel(Math.Ceiling(Object.RowCount), Math.Ceiling(Object.ColumnCount), 0, new Point3D(Workshop.RowLocation + Math.Ceiling(Object.RowLocation), Workshop.ColumnLocation + Math.Ceiling(Object.ColumnLocation), 0), Colors.LightCyan, 3, new string[4] { "NA", "", "", "" }));
}
}
//블록 가시화
foreach (BlockDTO Block in targetBlockList)
{
//리드타임 계산 (출고일 - 입고일)
TimeSpan ts = Block.ExportDate - Block.ImportDate;
int Leadtime = ts.Days;
Leadtime++;
//실제 반출일 계산 (실제 입고일 + 리드타임)
DateTime ActualExportDate = Block.ActualImportDate.AddDays(Leadtime - 1);
//남아 있는 작업일 계산 (실제 반출일 - 현재 날짜)
TimeSpan ts1 = ActualExportDate - CurrentDate;
int ResidualTime = ts1.Days;
ResidualTime++;
//방향에 따른 가로세로 길이 조정
double tempRow = Math.Ceiling(Block.RowCount);
double tempCol = Math.Ceiling(Block.ColumnCount);
if (Block.Orientation == 1)
{
tempRow = Math.Ceiling(Block.ColumnCount);
tempCol = Math.Ceiling(Block.RowCount);
}
//일반 블록은 검정 테두리
Color blockColor = Colors.Black;
//blockColor.A = 220;
//당일 입고 블록은 초록색
if (CurrentDate == Block.ActualImportDate) { blockColor = Colors.LightGreen; }
//blockColor.A = 100;
//조건 만족 블록은 파란색
if (Block.IsRoadSide == true) { blockColor = Colors.Blue; }
//지연 블록은 빨간색
if (Block.IsDelayed == true) { blockColor = Colors.Red; }
//출고 블록은 노란색
if (ResidualTime == 1) { blockColor = Colors.Yellow; }
//blockColor.A = 100;
DateTime tempdate = Block.InitialExportDate.AddDays(2);
string[] arrprintedstring = { Block.Project, "-" + Block.Name, Block.ImportDate.ToShortDateString().Substring(5), Block.ExportDate.ToShortDateString().Substring(5) };
if (Block.IsPrior == true & Block.IsFloatingCraneExportBlock == false) arrprintedstring[3] = "aaa";
else if (Block.IsFloatingCraneExportBlock == true) arrprintedstring[2] = Block.InitialImportDate.ToShortDateString().Substring(5); arrprintedstring[3] = Block.InitialExportDate.ToShortDateString().Substring(5);
//블록 위에 출력되는 정보 확인을 위하여 minSize 계산
double minSize = Block.RowCount;
if (Block.RowCount > Block.ColumnCount) minSize = Block.ColumnCount;
minSize = minSize / arrprintedstring[0].Length;
if (minSize > 3.0) minSize = 3.0;
main3DGroup.Children.Add(CreateRectModel(tempRow, tempCol, 0, new Point3D(mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].RowLocation + Math.Ceiling(Block.LocatedRow), mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].ColumnLocation + Math.Ceiling(Block.LocatedColumn), 0), blockColor));
//우선순위 블록은 노란색으로 채우기
if(Block.IsPrior == true & Block.IsFloatingCraneExportBlock == false) main3DGroup.Children.Add(CreateRectModel(tempRow - 0.8, tempCol - 0.8, 0, new Point3D(mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].RowLocation + Math.Ceiling(Block.LocatedRow) + 0.4, mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].ColumnLocation + Math.Ceiling(Block.LocatedColumn) + 0.4, 0), Colors.Yellow, minSize, arrprintedstring));
//출고장용 블록
else if (Block.IsFloatingCraneExportBlock == true) main3DGroup.Children.Add(CreateRectModel(tempRow - 0.8, tempCol - 0.8, 0, new Point3D(mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].RowLocation + Math.Ceiling(Block.LocatedRow) + 0.4, mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].ColumnLocation + Math.Ceiling(Block.LocatedColumn) + 0.4, 0), Colors.Yellow, minSize, arrprintedstring));
else main3DGroup.Children.Add(CreateRectModel(tempRow-0.8, tempCol-0.8, 0, new Point3D(mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].RowLocation + Math.Ceiling(Block.LocatedRow)+0.4, mWorkshopInfoList[Block.CurrentLocatedWorkshopIndex].ColumnLocation + Math.Ceiling(Block.LocatedColumn)+0.4, 0), Colors.Silver, minSize, arrprintedstring));
}
model1.Content = main3DGroup;
HelixResultViewer.Children.Add(model1);
}
Model3DGroup CreateRectModel(double X_Size, double Y_Size, double Z_Size, Point3D moveDistance, Color color)
{
Model3DGroup group = new Model3DGroup();
Point3D p0 = new Point3D(0, 0, 0);
Point3D p1 = new Point3D(X_Size, 0, 0);
Point3D p2 = new Point3D(X_Size, 0, Z_Size);
Point3D p3 = new Point3D(0, 0, Z_Size);
Point3D p4 = new Point3D(0, Y_Size, 0);
Point3D p5 = new Point3D(X_Size, Y_Size, 0);
Point3D p6 = new Point3D(X_Size, Y_Size, Z_Size);
Point3D p7 = new Point3D(0, Y_Size, Z_Size);
Point3D p0_move = new Point3D(p0.X + moveDistance.X, p0.Y + moveDistance.Y, p0.Z + moveDistance.Z);
Point3D p1_move = new Point3D(p1.X + moveDistance.X, p1.Y + moveDistance.Y, p1.Z + moveDistance.Z);
Point3D p2_move = new Point3D(p2.X + moveDistance.X, p2.Y + moveDistance.Y, p2.Z + moveDistance.Z);
Point3D p3_move = new Point3D(p3.X + moveDistance.X, p3.Y + moveDistance.Y, p3.Z + moveDistance.Z);
Point3D p4_move = new Point3D(p4.X + moveDistance.X, p4.Y + moveDistance.Y, p4.Z + moveDistance.Z);
Point3D p5_move = new Point3D(p5.X + moveDistance.X, p5.Y + moveDistance.Y, p5.Z + moveDistance.Z);
Point3D p6_move = new Point3D(p6.X + moveDistance.X, p6.Y + moveDistance.Y, p6.Z + moveDistance.Z);
Point3D p7_move = new Point3D(p7.X + moveDistance.X, p7.Y + moveDistance.Y, p7.Z + moveDistance.Z);
group.Children.Add(CreateCubeModel(p0_move, p1_move, p2_move, p3_move, p4_move, p5_move, p6_move, p7_move, color));
return group;
}
Model3DGroup CreateRectModel(double X_Size, double Y_Size, double Z_Size, Point3D moveDistance, Color color, double textSize, string[] arrtext)
{
Model3DGroup group = new Model3DGroup();
Point3D p0 = new Point3D(0, 0, 0);
Point3D p1 = new Point3D(X_Size, 0, 0);
Point3D p2 = new Point3D(X_Size, 0, Z_Size);
Point3D p3 = new Point3D(0, 0, Z_Size);
Point3D p4 = new Point3D(0, Y_Size, 0);
Point3D p5 = new Point3D(X_Size, Y_Size, 0);
Point3D p6 = new Point3D(X_Size, Y_Size, Z_Size);
Point3D p7 = new Point3D(0, Y_Size, Z_Size);
Point3D p0_move = new Point3D(p0.X + moveDistance.X, p0.Y + moveDistance.Y, p0.Z + moveDistance.Z);
Point3D p1_move = new Point3D(p1.X + moveDistance.X, p1.Y + moveDistance.Y, p1.Z + moveDistance.Z);
Point3D p2_move = new Point3D(p2.X + moveDistance.X, p2.Y + moveDistance.Y, p2.Z + moveDistance.Z);
Point3D p3_move = new Point3D(p3.X + moveDistance.X, p3.Y + moveDistance.Y, p3.Z + moveDistance.Z);
Point3D p4_move = new Point3D(p4.X + moveDistance.X, p4.Y + moveDistance.Y, p4.Z + moveDistance.Z);
Point3D p5_move = new Point3D(p5.X + moveDistance.X, p5.Y + moveDistance.Y, p5.Z + moveDistance.Z);
Point3D p6_move = new Point3D(p6.X + moveDistance.X, p6.Y + moveDistance.Y, p6.Z + moveDistance.Z);
Point3D p7_move = new Point3D(p7.X + moveDistance.X, p7.Y + moveDistance.Y, p7.Z + moveDistance.Z);
Point3D upper_center0 = new Point3D((p0_move.X + p1_move.X) / 2.0 - textSize * 1.5, (p0_move.Y + p4_move.Y) / 2.0, p6_move.Z + 1.0);
Point3D upper_center1 = new Point3D((p0_move.X + p1_move.X) / 2.0 - textSize * 0.5 , (p0_move.Y + p4_move.Y) / 2.0, p6_move.Z + 1.0);
Point3D upper_center2 = new Point3D((p0_move.X + p1_move.X) / 2.0 + textSize * 0.5, (p0_move.Y + p4_move.Y) / 2.0, p6_move.Z + 1.0);
Point3D upper_center3 = new Point3D((p0_move.X + p1_move.X) / 2.0 + textSize * 1.5, (p0_move.Y + p4_move.Y) / 2.0, p6_move.Z + 1.0);
group.Children.Add(CreateCubeModel(p0_move, p1_move, p2_move, p3_move, p4_move, p5_move, p6_move, p7_move, color));
if (arrtext != null)
{
group.Children.Add(CreateTextLabelModel3D(arrtext[0], Brushes.Black, true, textSize, upper_center0, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
group.Children.Add(CreateTextLabelModel3D(arrtext[1], Brushes.Black, true, textSize, upper_center1, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
group.Children.Add(CreateTextLabelModel3D(arrtext[2], Brushes.Black, true, textSize, upper_center2, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
group.Children.Add(CreateTextLabelModel3D(arrtext[3], Brushes.Black, true, textSize, upper_center3, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
//if (arrtext[0].Length != 0) group.Children.Add(bitmapText(arrtext[0], Brushes.Black, true, textSize, upper_center0, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
//if (arrtext[1].Length != 0) group.Children.Add(bitmapText(arrtext[1], Brushes.Black, true, textSize, upper_center1, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
//if (arrtext[2].Length != 0) group.Children.Add(bitmapText(arrtext[2], Brushes.Black, true, textSize, upper_center2, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
//if (arrtext[3].Length != 0) group.Children.Add(bitmapText(arrtext[3], Brushes.Black, true, textSize, upper_center3, new Vector3D(0, 1, 0), new Vector3D(-1, 0, 0)));
}
return group;
}
public static GeometryModel3D CreateTextLabelModel3D(string text, Brush textColor, bool isDoubleSided, double height, Point3D center, Vector3D textDirection, Vector3D updirection)
{
// First we need a textblock containing the text of our label
var tb = new TextBlock(new Run(text)) { Foreground = textColor, FontFamily = new FontFamily("Arial") };
tb.FontWeight = FontWeights.Bold;
// Now use that TextBlock as the brush for a material
var mat = new DiffuseMaterial { Brush = new VisualBrush(tb) };
// We just assume the characters are square
double width = text.Length * height*0.6;
// tb.Measure(new Size(text.Length * height * 2, height * 2));
// width=tb.DesiredSize.Width;
// Since the parameter coming in was the center of the label,
// we need to find the four corners
// p0 is the lower left corner
// p1 is the upper left
// p2 is the lower right
// p3 is the upper right
var p0 = center - width / 2 * textDirection - height / 2 * updirection;
var p1 = p0 + updirection * 1 * height;
var p2 = p0 + textDirection * width;
var p3 = p0 + updirection * 1 * height + textDirection * width;
// Now build the geometry for the sign. It's just a
// rectangle made of two triangles, on each side.
var mg = new MeshGeometry3D { Positions = new Point3DCollection { p0, p1, p2, p3 } };
if (isDoubleSided)
{
mg.Positions.Add(p0); // 4
mg.Positions.Add(p1); // 5
mg.Positions.Add(p2); // 6
mg.Positions.Add(p3); // 7
}
mg.TriangleIndices.Add(0);
mg.TriangleIndices.Add(3);
mg.TriangleIndices.Add(1);
mg.TriangleIndices.Add(0);
mg.TriangleIndices.Add(2);
mg.TriangleIndices.Add(3);
if (isDoubleSided)
{
mg.TriangleIndices.Add(4);
mg.TriangleIndices.Add(5);
mg.TriangleIndices.Add(7);
mg.TriangleIndices.Add(4);
mg.TriangleIndices.Add(7);
mg.TriangleIndices.Add(6);
}
// These texture coordinates basically stretch the
// TextBox brush to cover the full side of the label.
mg.TextureCoordinates.Add(new Point(0, 1));
mg.TextureCoordinates.Add(new Point(0, 0));
mg.TextureCoordinates.Add(new Point(1, 1));
mg.TextureCoordinates.Add(new Point(1, 0));
if (isDoubleSided)
{
mg.TextureCoordinates.Add(new Point(1, 1));
mg.TextureCoordinates.Add(new Point(1, 0));
mg.TextureCoordinates.Add(new Point(0, 1));
mg.TextureCoordinates.Add(new Point(0, 0));
}
// And that's all. Return the result.
return new GeometryModel3D(mg, mat);
}
public static GeometryModel3D bitmapText(string _text, Brush textColor, bool isDoubleSided, double height, Point3D center, Vector3D textDirection, Vector3D updirection)
{
//Image myImage = new Image();
FormattedText text = new FormattedText(_text,
new CultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, new FontStretch()),
height,
textColor);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawText(text, new Point(0, 0));
drawingContext.Close();
// We just assume the characters are square
double width = _text.Length * height * 0.6;
int _height = Convert.ToInt32(Math.Floor(height));
int _width = Convert.ToInt32(Math.Floor(width));
if (_height == 0) _height = 1;
if (_width == 0) _width = 1;
RenderTargetBitmap bmp = new RenderTargetBitmap(_width, _height, 240, 192, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
//myImage.Source = bmp;
// Now use that TextBlock as the brush for a material
var mat = new DiffuseMaterial { Brush = new ImageBrush(bmp) { Viewport = new Rect(0,0,1,1), Stretch = Stretch.Fill } };
// tb.Measure(new Size(text.Length * height * 2, height * 2));
// width=tb.DesiredSize.Width;
// Since the parameter coming in was the center of the label,
// we need to find the four corners
// p0 is the lower left corner
// p1 is the upper left
// p2 is the lower right
// p3 is the upper right
var p0 = center - width / 2 * textDirection - height / 2 * updirection;
var p1 = p0 + updirection * 1 * height;
var p2 = p0 + textDirection * width;
var p3 = p0 + updirection * 1 * height + textDirection * width;
// Now build the geometry for the sign. It's just a
// rectangle made of two triangles, on each side.
var mg = new MeshGeometry3D { Positions = new Point3DCollection { p0, p1, p2, p3 } };
if (isDoubleSided)
{
mg.Positions.Add(p0); // 4
mg.Positions.Add(p1); // 5
mg.Positions.Add(p2); // 6
mg.Positions.Add(p3); // 7
}
mg.TriangleIndices.Add(0);
mg.TriangleIndices.Add(3);
mg.TriangleIndices.Add(1);
mg.TriangleIndices.Add(0);
mg.TriangleIndices.Add(2);
mg.TriangleIndices.Add(3);
if (isDoubleSided)
{
mg.TriangleIndices.Add(4);
mg.TriangleIndices.Add(5);
mg.TriangleIndices.Add(7);
mg.TriangleIndices.Add(4);
mg.TriangleIndices.Add(7);
mg.TriangleIndices.Add(6);
}
// These texture coordinates basically stretch the
// TextBox brush to cover the full side of the label.
mg.TextureCoordinates.Add(new Point(0, 1));
mg.TextureCoordinates.Add(new Point(0, 0));
mg.TextureCoordinates.Add(new Point(1, 1));
mg.TextureCoordinates.Add(new Point(1, 0));
if (isDoubleSided)
{
mg.TextureCoordinates.Add(new Point(1, 1));
mg.TextureCoordinates.Add(new Point(1, 0));
mg.TextureCoordinates.Add(new Point(0, 1));
mg.TextureCoordinates.Add(new Point(0, 0));
}
// And that's all. Return the result.
return new GeometryModel3D(mg, mat);
}
Model3DGroup CubeParallelMove(double CubeSize, Point3D moveDistance, Color color)
{
Model3DGroup group = new Model3DGroup();
Point3D p0 = new Point3D(0, 0, 0);
Point3D p1 = new Point3D(CubeSize, 0, 0);
Point3D p2 = new Point3D(CubeSize, 0, CubeSize);
Point3D p3 = new Point3D(0, 0, CubeSize);
Point3D p4 = new Point3D(0, CubeSize, 0);
Point3D p5 = new Point3D(CubeSize, CubeSize, 0);
Point3D p6 = new Point3D(CubeSize, CubeSize, CubeSize);
Point3D p7 = new Point3D(0, CubeSize, CubeSize);
Point3D p0_move = new Point3D(p0.X + moveDistance.X, p0.Y + moveDistance.Y, p0.Z + moveDistance.Z);
Point3D p1_move = new Point3D(p1.X + moveDistance.X, p1.Y + moveDistance.Y, p1.Z + moveDistance.Z);
Point3D p2_move = new Point3D(p2.X + moveDistance.X, p2.Y + moveDistance.Y, p2.Z + moveDistance.Z);
Point3D p3_move = new Point3D(p3.X + moveDistance.X, p3.Y + moveDistance.Y, p3.Z + moveDistance.Z);
Point3D p4_move = new Point3D(p4.X + moveDistance.X, p4.Y + moveDistance.Y, p4.Z + moveDistance.Z);
Point3D p5_move = new Point3D(p5.X + moveDistance.X, p5.Y + moveDistance.Y, p5.Z + moveDistance.Z);
Point3D p6_move = new Point3D(p6.X + moveDistance.X, p6.Y + moveDistance.Y, p6.Z + moveDistance.Z);
Point3D p7_move = new Point3D(p7.X + moveDistance.X, p7.Y + moveDistance.Y, p7.Z + moveDistance.Z);
group.Children.Add(CreateCubeModel(p0_move, p1_move, p2_move, p3_move, p4_move, p5_move, p6_move, p7_move, color));
return group;
}
Model3DGroup CreateCubeModel(Point3D p0, Point3D p1, Point3D p2, Point3D p3, Point3D p4, Point3D p5, Point3D p6, Point3D p7, Color color)
{
Model3DGroup group = new Model3DGroup();
//front side triangles
group.Children.Add(CreateTriangleModel(p3, p2, p6, color));
group.Children.Add(CreateTriangleModel(p3, p6, p7, color));
//right side triangles
group.Children.Add(CreateTriangleModel(p2, p1, p5, color));
group.Children.Add(CreateTriangleModel(p2, p5, p6, color));
//back side triangles
group.Children.Add(CreateTriangleModel(p1, p0, p4, color));
group.Children.Add(CreateTriangleModel(p1, p4, p5, color));
//left side triangles
group.Children.Add(CreateTriangleModel(p0, p3, p7, color));
group.Children.Add(CreateTriangleModel(p0, p7, p4, color));
//top side triangles
group.Children.Add(CreateTriangleModel(p7, p6, p5, color));
group.Children.Add(CreateTriangleModel(p7, p5, p4, color));
//bottom side triangles
group.Children.Add(CreateTriangleModel(p2, p3, p0, color));
group.Children.Add(CreateTriangleModel(p2, p0, p1, color));
return group;
}
Model3DGroup CreateTriangleModel(Point3D p0, Point3D p1, Point3D p2, Color color)
{
MeshGeometry3D mesh = new MeshGeometry3D();
mesh.Positions.Add(p0);
mesh.Positions.Add(p1);
mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);
Vector3D normal = CalculateNormal(p0, p1, p2);
mesh.Normals.Add(normal);
SolidColorBrush brush = new SolidColorBrush(color);
brush.Opacity = 100;
Material material = new DiffuseMaterial(brush);
GeometryModel3D model = new GeometryModel3D(mesh, material);
Model3DGroup group = new Model3DGroup();
group.Children.Add(model);
return group;
}
Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2)
{
Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3D v1 = new Vector3D(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
return Vector3D.CrossProduct(v0, v1);
}
private void btnChangeWorkshop_Click(object sender, RoutedEventArgs e)
{
workshopIndex = Convert.ToInt32(txtWorkshopIndex.Text);
if ((workshopIndex >= mWorkshopInfoList.Count) || (workshopIndex < 0))
{
MessageBox.Show("작업장 번호를 잘못 입력하였습니다.");
}
else
{
seletedDateIndex = lstArrDateList.SelectedIndex;
//조회하고자 하는 특정 날짜 index
int target_date = seletedDateIndex;
//Grid에 상세 정보 출력
List<BlockDTO> targetBlockList = new List<BlockDTO>();
for (int i = 0; i < mResultsInfo.TotalDailyArragnementedBlockList[seletedDateIndex].Count; i++)
{
if (mResultsInfo.TotalDailyArragnementedBlockList[seletedDateIndex][i].CurrentLocatedWorkshopIndex == workshopIndex) targetBlockList.Add(mResultsInfo.TotalDailyArragnementedBlockList[seletedDateIndex][i]);
}
//3차원 가시화
HelixResultViewer.Children.Clear();
main3DGroup.Children.Clear();
//카메라 초기화
PerspectiveCamera myCamera = (PerspectiveCamera)HelixResultViewer.Camera;
myCamera = SetCameraPosition(myCamera, mWorkshopInfoList[workshopIndex]);
//조명 설정
var lights = new DefaultLights();
HelixResultViewer.Children.Add(lights);
//작업장 가시화
main3DGroup.Children.Add(CreateRectModel(mWorkshopInfoList[workshopIndex].RowCount, mWorkshopInfoList[workshopIndex].ColumnCount, 0, new Point3D(0, 0, 0), Colors.White));
DateTime CurrentDate = mResultsInfo.ArrangementStartDate.AddDays(seletedDateIndex);
ModelVisual3D model1 = new ModelVisual3D();
//배치불가구역 가시화
foreach (ArrangementMatrixInfoDTO Object in mWorkshopInfoList[workshopIndex].ArrangementMatrixInfoList)
{
main3DGroup.Children.Add(CreateRectModel(Math.Ceiling(Object.RowCount), Math.Ceiling(Object.ColumnCount), 0, new Point3D(Math.Ceiling(Object.RowLocation), Math.Ceiling(Object.ColumnLocation), 0), Colors.LightCyan, 3, new string[4] { "NotAvailable", "", "", "" }));
}
//블록 가시화
foreach (BlockDTO Block in targetBlockList)
{
//리드타임 계산 (출고일 - 입고일)
TimeSpan ts = Block.ExportDate - Block.ImportDate;
int Leadtime = ts.Days;
Leadtime++;
//실제 반출일 계산 (실제 입고일 + 리드타임)
DateTime ActualExportDate = Block.ActualImportDate.AddDays(Leadtime - 1);
//남아 있는 작업일 계산 (실제 반출일 - 현재 날짜)
TimeSpan ts1 = ActualExportDate - CurrentDate;
int ResidualTime = ts1.Days;
ResidualTime++;
//방향에 따른 가로세로 길이 조정
double tempRow = Math.Ceiling(Block.RowCount);
double tempCol = Math.Ceiling(Block.ColumnCount);
if (Block.Orientation == 1)
{
tempRow = Math.Ceiling(Block.ColumnCount);
tempCol = Math.Ceiling(Block.RowCount);
}
//일반 블록은 검정 테두리
Color blockColor = Colors.Black;
//blockColor.A = 220;
//당일 입고 블록은 초록색
if (CurrentDate == Block.ActualImportDate) { blockColor = Colors.Green; }
//blockColor.A = 100;
//조건 만족 블록은 파란색
if (Block.IsRoadSide == true) { blockColor = Colors.Blue; }
//지연 블록은 빨간색
if (Block.IsDelayed == true) { blockColor = Colors.Red; }
//출고 블록은 노란색
if (ResidualTime == 1) { blockColor = Colors.Yellow; }
//blockColor.A = 100;
string[] arrprintedstring = { Block.Project, "-" + Block.Name, Block.ImportDate.ToShortDateString().Substring(5), Block.ExportDate.ToShortDateString().Substring(5) };
//블록 위에 출력되는 정보 확인을 위하여 minSize 계산
double minSize = Block.RowCount;
if (Block.RowCount > Block.ColumnCount) minSize = Block.ColumnCount;
minSize = minSize / arrprintedstring[0].Length;
if (minSize > 3.0) minSize = 3.0;
main3DGroup.Children.Add(CreateRectModel(tempRow, tempCol, 0, new Point3D(Math.Ceiling(Block.LocatedRow), Math.Ceiling(Block.LocatedColumn), 0), blockColor));
main3DGroup.Children.Add(CreateRectModel(tempRow - 0.8, tempCol - 0.8, 0, new Point3D(Math.Ceiling(Block.LocatedRow) + 0.4, Math.Ceiling(Block.LocatedColumn) + 0.4, 0), Colors.Silver, minSize, arrprintedstring));
}
model1.Content = main3DGroup;
HelixResultViewer.Children.Add(model1);
}
}
private void btnTest_Click(object sender, RoutedEventArgs e)
{
//카메라 초기화
PerspectiveCamera myCamera = (PerspectiveCamera)HelixResultViewer.Camera;
myCamera = SetCameraPosition(myCamera, mWorkshopInfoList[workshopIndex]);
}
PerspectiveCamera SetCameraPosition(PerspectiveCamera _camera, WorkshopDTO _workshop)
{
PerspectiveCamera returnCamera = _camera;
double pX = _workshop.RowCount / 2.0;
double pY = _workshop.ColumnCount / 2.0;
double pZ;
if ((pY / pX) < 2.0) //작업장 세로길이(pX)를 기준으로 카메라 맞춤
{
pZ = Math.Tan(Math.PI * 80.0 / 180.0) * pX;
}
else //작업장 가로길이(pY)를 기준으로 카메라 맞춤
{
pZ = Math.Tan(Math.PI * 70.0 / 180.0) * pY;
}
double dX = 0.0;
double dY = 0.0;
double dZ = -1.0;
double uX = -1.0;
double uY = 0.0;
double uZ = 0.0;
Point3D cameraPosition = new Point3D(pX, pY, pZ);
Vector3D cameraLookDirection = new Vector3D(dX, dY, dZ);
Vector3D cameraUpDirection = new Vector3D(uX, uY, uZ);
returnCamera.Position = cameraPosition;
returnCamera.LookDirection = cameraLookDirection;
returnCamera.UpDirection = cameraUpDirection;
return returnCamera;
}
private void txtWorkshopIndex_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eoba.Shipyard.ArrangementSimulator.MainUI
{
public partial class frmArrangementRangeSetting : Form
{
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
public frmArrangementRangeSetting(DateTime earliestDate, DateTime latestDate)
{
InitializeComponent();
monthCalendar1.SelectionStart = earliestDate;
monthCalendar2.SelectionStart = latestDate;
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
StartDate = monthCalendar1.SelectionStart;
textBox1.Text = monthCalendar1.SelectionStart.ToString("yyyy-MM-dd");
}
private void monthCalendar2_DateChanged(object sender, DateRangeEventArgs e)
{
if (DateTime.Compare(StartDate, monthCalendar2.SelectionStart) > 0)
{
MessageBox.Show("종료일이 시작일보다 빠릅니다.");
monthCalendar2.SelectionStart = StartDate;
}
else
{
FinishDate = monthCalendar2.SelectionStart;
textBox2.Text = monthCalendar2.SelectionStart.ToString("yyyy-MM-dd");
}
}
private void button1_Click(object sender, EventArgs e)
{
StartDate = monthCalendar1.SelectionStart;
FinishDate = monthCalendar2.SelectionStart;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms.DataVisualization.Charting;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Implementation;
using Eoba.Shipyard.ArrangementSimulator.BusinessComponent;
using Eoba.Shipyard.ArrangementSimulator.ResultsViewer;
using System.Diagnostics;
//using Excel = Microsoft.Office.Interop.Excel;
namespace Eoba.Shipyard.ArrangementSimulator.MainUI
{
public partial class frmMain : Form
{
List<BlockDTO> mBlockInfoList;
List<WorkshopDTO> mWorkshopInfoList;
ArrangementResultWithDateDTO mResultInfo;
List<Int32[,]> mArrangementMatrixList;
List<ArrangementMatrixInfoDTO> mArrangementMatrixInfoList;
List<PlateConfigDTO> mPlateConfigList = new List<PlateConfigDTO>();
List<ArrangementResultDTO> mArrangementResultList = new List<ArrangementResultDTO>();
List<Chart> mChartList = new List<Chart>();
string OpenedWorkshopFileName;
string OpenedArrangementMatrixFileName;
string OpenedBlockFileName;
IBlockArrangement mBlockArrangement;
IDataManagement mDataManagement;
IResultsManagement mResultsManagement;
bool IsWorkshopInfoReady;
bool IsBlockInfoReady;
bool IsPlateInfoReady = false;
int ArrangementAlgorithmMode = 0;//0:BLF, 1:Greedy
public double UnitGridLength = 1;
public double InputSlack = 2;
int ExportWorkshopIndex = -1;
OpenFileDialog myOpenFileDialog = new OpenFileDialog();
SaveFileDialog mySaveFileDialog = new SaveFileDialog();
public frmMain()
{
InitializeComponent();
IsWorkshopInfoReady = false;
IsBlockInfoReady = false;
mBlockArrangement = new BlockArrangementMgr();
mDataManagement = new DataManagement();
mResultsManagement = new ResultsManagement();
grdWorkshopInfo.ColumnCount = 5;
grdWorkshopInfo.Columns[0].Name = "Index";
grdWorkshopInfo.Columns[1].Name = "작업장이름";
grdWorkshopInfo.Columns[2].Name = "세로";
grdWorkshopInfo.Columns[3].Name = "가로";
grdWorkshopInfo.Columns[4].Name = "지번 갯수";
grdBlockInfo.ColumnCount = 14;
grdBlockInfo.Columns[0].Name = "Index";
grdBlockInfo.Columns[1].Name = "프로젝트번호";
grdBlockInfo.Columns[2].Name = "블록번호";
grdBlockInfo.Columns[3].Name = "세로";
grdBlockInfo.Columns[4].Name = "가로";
grdBlockInfo.Columns[5].Name = "상향작업공간";
grdBlockInfo.Columns[6].Name = "하향작업공간";
grdBlockInfo.Columns[7].Name = "좌측작업공간";
grdBlockInfo.Columns[8].Name = "우측작업공간";
grdBlockInfo.Columns[9].Name = "리드타임";
grdBlockInfo.Columns[10].Name = "투입날짜";
grdBlockInfo.Columns[11].Name = "반출날짜";
grdBlockInfo.Columns[12].Name = "선호 작업장";
grdBlockInfo.Columns[13].Name = "선호 지번";
}
/// <summary>
/// Workshop 정보 읽기 버튼 클릭 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// 최초 구현 : 주수헌, 2015년 9월 16일
/// 최종 수정 : 정용국, 2016년 02월 25일
/// </remarks>
private void openWorkshopInfomationWToolStripMenuItem_Click(object sender, EventArgs e)
{
ClearAllData();
try
{
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.Filter = "CSV Files|*.csv";
myOpenFileDialog.InitialDirectory = path;
List<string[]> input = new List<string[]>();
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFileName = myOpenFileDialog.FileName;
string tempFileName = selectedFileName.Substring(selectedFileName.LastIndexOf("\\") + 1);
tempFileName = tempFileName.Remove(tempFileName.Length - 4);
OpenedWorkshopFileName = tempFileName;
StreamReader sr = new StreamReader(selectedFileName, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
input.Add(temp);
}
IsWorkshopInfoReady = true;
}
//data 읽기 완료
mWorkshopInfoList = new List<WorkshopDTO>();
for (int i = 1; i < input.Count; i++)
{
mWorkshopInfoList.Add(new WorkshopDTO(Convert.ToInt16(input[i][0]), input[i][1], Convert.ToDouble(input[i][2]) / UnitGridLength, Convert.ToDouble(input[i][3]) / UnitGridLength, Convert.ToInt32(input[i][4])));
mWorkshopInfoList[mWorkshopInfoList.Count - 1].RowLocation = Convert.ToDouble(input[i][5]) / UnitGridLength;
mWorkshopInfoList[mWorkshopInfoList.Count - 1].ColumnLocation = Convert.ToDouble(input[i][6]) / UnitGridLength;
if (input[i][7] != "")
{
string[] temp = input[i][7].Split('-');
double[] tempDouble = new double[2];
for (int j = 0; j < temp.Length; j++) tempDouble[j] = Convert.ToDouble(temp[j]) / UnitGridLength;
mWorkshopInfoList[mWorkshopInfoList.Count - 1].UpperRoadside = tempDouble;
}
if (input[i][8] != "")
{
string[] temp = input[i][8].Split('-');
double[] tempDouble = new double[2];
for (int j = 0; j < temp.Length; j++) tempDouble[j] = Convert.ToDouble(temp[j]) / UnitGridLength;
mWorkshopInfoList[mWorkshopInfoList.Count - 1].BottomRoadside = tempDouble;
}
if (input[i][9] != "")
{
string[] temp = input[i][9].Split('-');
double[] tempDouble = new double[2];
for (int j = 0; j < temp.Length; j++) tempDouble[j] = Convert.ToDouble(temp[j]) / UnitGridLength;
mWorkshopInfoList[mWorkshopInfoList.Count - 1].LeftRoadside = tempDouble;
}
if (input[i][10] != "")
{
string[] temp = input[i][10].Split('-');
double[] tempDouble = new double[2];
for (int j = 0; j < temp.Length; j++) tempDouble[j] = Convert.ToDouble(temp[j]) / UnitGridLength;
mWorkshopInfoList[mWorkshopInfoList.Count - 1].RightRoadside = tempDouble;
}
if (input[i][11] == "") mWorkshopInfoList[mWorkshopInfoList.Count - 1].Type = 0;
else mWorkshopInfoList[mWorkshopInfoList.Count - 1].Type = Convert.ToInt32(input[i][11]);
}
foreach (WorkshopDTO workshop in mWorkshopInfoList)
{
if (workshop.Type == 1) ExportWorkshopIndex = workshop.Index;
}
//그리드에 입력 결과 출력
mDataManagement.PrintWorkshopDataOnGrid(grdWorkshopInfo, mWorkshopInfoList);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
/// <summary>
/// Workshop Matrix 정보 읽기 버튼 클릭 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// 최초 구현 : 유상현, 2020년 5월 12일
/// 최종 수정 : 유상현, 2020년 5월 12일
/// </remarks>
private void openWorkshopMatrixInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!IsWorkshopInfoReady) MessageBox.Show("작업장 정보를 먼저 불러와야 합니다.");
else
{
try
{
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.Filter = "CSV Files|*.csv";
myOpenFileDialog.InitialDirectory = path;
List<string[]> input = new List<string[]>();
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFileName = myOpenFileDialog.FileName;
string tempFileName = selectedFileName.Substring(selectedFileName.LastIndexOf("\\") + 1);
tempFileName = tempFileName.Remove(tempFileName.Length - 4);
OpenedArrangementMatrixFileName = tempFileName;
StreamReader sr = new StreamReader(selectedFileName, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
input.Add(temp);
}
}
mArrangementMatrixInfoList = new List<ArrangementMatrixInfoDTO>();
for (int i = 1; i < input.Count; i++)
{
mArrangementMatrixInfoList.Add(new ArrangementMatrixInfoDTO(Convert.ToInt32(input[i][0]), input[i][1], Convert.ToInt32(input[i][2]), input[i][3], Convert.ToDouble(input[i][4]) / UnitGridLength, Convert.ToDouble(input[i][5]) / UnitGridLength, Convert.ToDouble(input[i][6]) / UnitGridLength, Convert.ToDouble(input[i][7]) / UnitGridLength, Convert.ToInt32(input[i][8])));
}
foreach (ArrangementMatrixInfoDTO matrixInfoDTO in mArrangementMatrixInfoList) mWorkshopInfoList[matrixInfoDTO.WorkshopIndex].ArrangementMatrixInfoList.Add(matrixInfoDTO);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
/// <summary>
/// Block 정보 읽기 버튼 클릭 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// 최초 구현 : 주수헌, 2015년 9월 16일
/// 최종 수정 : 정용국, 2016년 02월 25일
/// </remarks>
private void openBlockInfomationBToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!IsWorkshopInfoReady) MessageBox.Show("작업장 정보를 먼저 불러와야 합니다.");
else
{
try
{
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.Filter = "CSV Files|*.csv";
myOpenFileDialog.InitialDirectory = path;
List<string[]> input = new List<string[]>();
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFileName = myOpenFileDialog.FileName;
string tempFileName = selectedFileName.Substring(selectedFileName.LastIndexOf("\\") + 1);
tempFileName = tempFileName.Remove(tempFileName.Length - 4);
OpenedBlockFileName = tempFileName;
StreamReader sr = new StreamReader(selectedFileName, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
input.Add(temp);
}
IsBlockInfoReady = true;
}
//블록 입력 정보 정제
mBlockInfoList = new List<BlockDTO>();
mBlockInfoList = mDataManagement.RefineInputBlockData(input, mWorkshopInfoList, UnitGridLength);
//그리드에 입력 결과 출력
mDataManagement.PrintBlockDataOnGrid(grdBlockInfo, mBlockInfoList);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
/// <summary>
/// 닫기 버튼 클릭 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void endEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// 블록 배치 정보를 3차원으로 가시화하는 창 출력
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// </remarks>
private void dViewerVToolStripMenuItem_Click(object sender, EventArgs e)
{
frmResultsViewer myfrmResultsViewer;
myfrmResultsViewer = new frmResultsViewer(mResultInfo, mWorkshopInfoList);
// 2016년 11월 28일 주수헌 수정, BLF, Greedy 모두 날짜 개념이 들어가므로 아래의 구분은 무효
////BLF 알고리즘
//if (ArrangementAlgorithmMode == 0) myfrmResultsViewer = new frmResultsViewer(mResultInfo, mWorkshopInfoList);
////Greedy 알고리즘
//else myfrmResultsViewer = new frmResultsViewer(mBlockInfoList, mWorkshopInfoList, mUnitcellInfoList);
myfrmResultsViewer.Show();
}
/// <summary>
/// 블록배치 정보 출력
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// 최초 작성 : 주수헌, 2015년 9월 19일
/// </remarks>
private void reportRToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (mResultInfo != null)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string FilePath = dialog.SelectedPath;
string FileName = FilePath + "\\" + OpenedWorkshopFileName + "_" + OpenedBlockFileName;
mResultsManagement.PrintArrangementResult(mResultInfo, FileName);
}
else MessageBox.Show("결과 정보가 없습니다.");
}
}
/// <summary>
/// BLF 알고리즘 버튼 클릭 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// 최초 작성 : 정용국, 2016년 01월 20일
/// 수정 작성 : 유상현, 2020년 05월 13일
private void bLFAlgorithmBToolStripMenuItem_Click(object sender, EventArgs e)
{
//mDataManagement.UpdateWorkshopDataOfGrid(grdWorkshopInfo, mWorkshopInfoList);
//mDataManagement.UpdateBlockDataOfGrid(grdBlockInfo, mBlockInfoList);
if (mBlockInfoList != null)
{
//모든 블록의 입고/출고 날짜 저장 + 가장 빠른 날짜, 가장 늦은 날짜 계산
DateTime[] simDates = new DateTime[2];
simDates = mBlockArrangement.CalcEarliestAndLatestDates(mBlockInfoList);
DateTime startDate = new DateTime();
DateTime finishDate = new DateTime();
//추천된 시뮬레이션 시작일, 종료일을 기준으로 사용자가 UI에서 시작일, 종료일 선택
using (var form = new frmArrangementRangeSetting(simDates[0], simDates[1]))
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
startDate = form.StartDate;
finishDate = form.FinishDate;
}
}
//Chart 초기화(작업장 별 차트 + Tab page)
mResultsManagement.InitializeIndividualWorkshopChart(mWorkshopInfoList, mChartList, chtWorkshop1, tabChart);
//Chart 초기화(전체 요약 차트)
mResultsManagement.InitializeTotalWorkshopChart(chtTotal);
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
//입력한 날짜를 기준으로 BLF 알고리즘 시작
mArrangementResultList.Clear();
if (IsWorkshopInfoReady && IsBlockInfoReady)
{
// WorkshopMatrix 초기설정 세팅
// Input : 작업장 정보 리스트, 작업장 배치 불가 구역 리스트
// Output : 작업장 매트릭스 리스트 List<Int32[,]>
List<Int32[,]> ArrangementMatrixList = mBlockArrangement.InitializeArrangementMatrix(mWorkshopInfoList);
// RunBLFAlgorithm
// Input : 작업장 정보리스트, 블록정보리스트, 작업장 매트릭스리스트, 시작날짜, 끝 날짜
// Output : Result
mResultInfo = mBlockArrangement.RunBLFAlgorithmWithAddress(mBlockInfoList, ArrangementMatrixList, mWorkshopInfoList, startDate, finishDate, toolStripProgressBar1, toolStripStatusLabel1);
reportRToolStripMenuItem1.Enabled = true;
dViewerVToolStripMenuItem.Enabled = true;
dCumlatedOccupyingVToolStripMenuItem.Enabled = true;
}
else
{
MessageBox.Show("입력 정보가 부족합니다.");
}
sw.Stop();
//배치 결과 Chart에 출력
mResultsManagement.DrawChart(mResultInfo, mChartList, chtTotal);
//배치 결과 요약 메시지 박스 출력
mResultsManagement.PrintBLFAlgorithmResultsSummary(mResultInfo, sw);
//알고리즘 모드 = BLF 알고리즘
ArrangementAlgorithmMode = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
/// <summary>
/// 여유 작업 공간을 고려한 BLF 알고리즘
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// 최초 작성 : 유상현, 2020년 05월 17일
/// 수정 작성 :
private void bLFWithSlackToolStripMenuItem_Click(object sender, EventArgs e)
{
//mDataManagement.UpdateWorkshopDataOfGrid(grdWorkshopInfo, mWorkshopInfoList);
//mDataManagement.UpdateBlockDataOfGrid(grdBlockInfo, mBlockInfoList);
int Slack = Convert.ToInt32(Math.Ceiling(InputSlack / UnitGridLength));
if (mBlockInfoList != null)
{
//모든 블록의 입고/출고 날짜 저장 + 가장 빠른 날짜, 가장 늦은 날짜 계산
DateTime[] simDates = new DateTime[2];
simDates = mBlockArrangement.CalcEarliestAndLatestDates(mBlockInfoList);
DateTime startDate = new DateTime();
DateTime finishDate = new DateTime();
//추천된 시뮬레이션 시작일, 종료일을 기준으로 사용자가 UI에서 시작일, 종료일 선택
using (var form = new frmArrangementRangeSetting(simDates[0], simDates[1]))
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
startDate = form.StartDate;
finishDate = form.FinishDate;
}
}
//Chart 초기화(작업장 별 차트 + Tab page)
mResultsManagement.InitializeIndividualWorkshopChart(mWorkshopInfoList, mChartList, chtWorkshop1, tabChart);
//Chart 초기화(전체 요약 차트)
mResultsManagement.InitializeTotalWorkshopChart(chtTotal);
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
//입력한 날짜를 기준으로 BLF 알고리즘 시작
mArrangementResultList.Clear();
if (IsWorkshopInfoReady && IsBlockInfoReady)
{
// WorkshopMatrix 초기설정 세팅
// Input : 작업장 정보 리스트, 작업장 배치 불가 구역 리스트
// Output : 작업장 매트릭스 리스트 List<Int32[,]>
List<Int32[,]> ArrangementMatrixList = mBlockArrangement.InitializeArrangementMatrixWithSlack(mWorkshopInfoList, Slack);
// RunBLFAlgorithm
// Input : 작업장 정보리스트, 블록정보리스트, 작업장 매트릭스리스트, 시작날짜, 끝 날짜
// Output : Result
mResultInfo = mBlockArrangement.RunBLFAlgorithmWithSlack(mBlockInfoList, ArrangementMatrixList, mWorkshopInfoList, startDate, finishDate, toolStripProgressBar1, toolStripStatusLabel1, Slack);
reportRToolStripMenuItem1.Enabled = true;
dViewerVToolStripMenuItem.Enabled = true;
dCumlatedOccupyingVToolStripMenuItem.Enabled = true;
}
else
{
MessageBox.Show("입력 정보가 부족합니다.");
}
sw.Stop();
//배치 결과 Chart에 출력
mResultsManagement.DrawChart(mResultInfo, mChartList, chtTotal);
//배치 결과 요약 메시지 박스 출력
mResultsManagement.PrintBLFAlgorithmResultsSummary(mResultInfo, sw);
//알고리즘 모드 = BLF 알고리즘
ArrangementAlgorithmMode = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
/// <summary>
/// 여유 작업 공간을 고려한 BLF 알고리즘 + 우선 배치기능 추가
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// 최초 작성 : 유상현, 2020년 05월 17일
/// 수정 작성 :
private void bLFWithPriorityToolStripMenuItem_Click(object sender, EventArgs e)
{
//mDataManagement.UpdateWorkshopDataOfGrid(grdWorkshopInfo, mWorkshopInfoList);
//mDataManagement.UpdateBlockDataOfGrid(grdBlockInfo, mBlockInfoList);
int Slack = Convert.ToInt32(Math.Ceiling(InputSlack / UnitGridLength));
if (mBlockInfoList != null)
{
//모든 블록의 입고/출고 날짜 저장 + 가장 빠른 날짜, 가장 늦은 날짜 계산
DateTime[] simDates = new DateTime[2];
simDates = mBlockArrangement.CalcEarliestAndLatestDates(mBlockInfoList);
DateTime startDate = new DateTime();
DateTime finishDate = new DateTime();
//추천된 시뮬레이션 시작일, 종료일을 기준으로 사용자가 UI에서 시작일, 종료일 선택
using (var form = new frmArrangementRangeSetting(simDates[0], simDates[1]))
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
startDate = form.StartDate;
finishDate = form.FinishDate;
}
}
//Chart 초기화(작업장 별 차트 + Tab page)
mResultsManagement.InitializeIndividualWorkshopChart(mWorkshopInfoList, mChartList, chtWorkshop1, tabChart);
//Chart 초기화(전체 요약 차트)
mResultsManagement.InitializeTotalWorkshopChart(chtTotal);
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
//입력한 날짜를 기준으로 BLF 알고리즘 시작
mArrangementResultList.Clear();
if (IsWorkshopInfoReady && IsBlockInfoReady)
{
// WorkshopMatrix 초기설정 세팅
// Input : 작업장 정보 리스트, 작업장 배치 불가 구역 리스트
// Output : 작업장 매트릭스 리스트 List<Int32[,]>
List<Int32[,]> ArrangementMatrixList = mBlockArrangement.InitializeArrangementMatrixWithSlack(mWorkshopInfoList, Slack);
// RunBLFAlgorithm
// Input : 작업장 정보리스트, 블록정보리스트, 작업장 매트릭스리스트, 시작날짜, 끝 날짜
// Output : Result
mResultInfo = mBlockArrangement.RunBLFAlgorithmWithSlackWithPriority(mBlockInfoList, ArrangementMatrixList, mWorkshopInfoList, startDate, finishDate, toolStripProgressBar1, toolStripStatusLabel1, Slack);
reportRToolStripMenuItem1.Enabled = true;
dViewerVToolStripMenuItem.Enabled = true;
dCumlatedOccupyingVToolStripMenuItem.Enabled = true;
}
else
{
MessageBox.Show("입력 정보가 부족합니다.");
}
sw.Stop();
//배치 결과 Chart에 출력
mResultsManagement.DrawChart(mResultInfo, mChartList, chtTotal);
//배치 결과 요약 메시지 박스 출력
mResultsManagement.PrintBLFAlgorithmResultsSummary(mResultInfo, sw);
//알고리즘 모드 = BLF 알고리즘
ArrangementAlgorithmMode = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
/// <summary>
/// 여유 작업 공간을 고려한 BLF 알고리즘 + 우선 배치기능 추가 + 해상크레인 출고장 기능 추가
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// 최초 작성 : 유상현, 2020년 06월 29일
/// 수정 작성 :
private void bLFWithFlotidsToolStripMenuItem_Click(object sender, EventArgs e)
{
//mDataManagement.UpdateWorkshopDataOfGrid(grdWorkshopInfo, mWorkshopInfoList);
//mDataManagement.UpdateBlockDataOfGrid(grdBlockInfo, mBlockInfoList);
int Slack = Convert.ToInt32(Math.Ceiling(InputSlack / UnitGridLength));
if (mBlockInfoList != null)
{
//모든 블록의 입고/출고 날짜 저장 + 가장 빠른 날짜, 가장 늦은 날짜 계산
DateTime[] simDates = new DateTime[2];
simDates = mBlockArrangement.CalcEarliestAndLatestDates(mBlockInfoList);
DateTime startDate = new DateTime();
DateTime finishDate = new DateTime();
//추천된 시뮬레이션 시작일, 종료일을 기준으로 사용자가 UI에서 시작일, 종료일 선택
using (var form = new frmArrangementRangeSetting(simDates[0], simDates[1]))
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
startDate = form.StartDate;
finishDate = form.FinishDate;
}
}
//Chart 초기화(작업장 별 차트 + Tab page)
mResultsManagement.InitializeIndividualWorkshopChart(mWorkshopInfoList, mChartList, chtWorkshop1, tabChart);
//Chart 초기화(전체 요약 차트)
mResultsManagement.InitializeTotalWorkshopChart(chtTotal);
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
//입력한 날짜를 기준으로 BLF 알고리즘 시작
mArrangementResultList.Clear();
if (IsWorkshopInfoReady && IsBlockInfoReady)
{
// WorkshopMatrix 초기설정 세팅
// Input : 작업장 정보 리스트, 작업장 배치 불가 구역 리스트
// Output : 작업장 매트릭스 리스트 List<Int32[,]>
List<Int32[,]> ArrangementMatrixList = mBlockArrangement.InitializeArrangementMatrixWithSlack(mWorkshopInfoList, Slack);
// RunBLFAlgorithm
// Input : 작업장 정보리스트, 블록정보리스트, 작업장 매트릭스리스트, 시작날짜, 끝 날짜
// Output : Result
mResultInfo = mBlockArrangement.RunBLFAlgorithmWithFloatingCrane(mBlockInfoList, ArrangementMatrixList, mWorkshopInfoList, startDate, finishDate, toolStripProgressBar1, toolStripStatusLabel1, Slack, ExportWorkshopIndex);
reportRToolStripMenuItem1.Enabled = true;
dViewerVToolStripMenuItem.Enabled = true;
dCumlatedOccupyingVToolStripMenuItem.Enabled = true;
}
else
{
MessageBox.Show("입력 정보가 부족합니다.");
}
sw.Stop();
//배치 결과 Chart에 출력
mResultsManagement.DrawChart(mResultInfo, mChartList, chtTotal);
//배치 결과 요약 메시지 박스 출력
mResultsManagement.PrintBLFAlgorithmResultsSummary(mResultInfo, sw);
//알고리즘 모드 = BLF 알고리즘
ArrangementAlgorithmMode = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
//private void dCumlatedOccupyingVToolStripMenuItem_Click(object sender, EventArgs e)
//{
// List<double[,]> CumulatedGridOccupationMatrix = new List<double[,]>();
// CumulatedGridOccupationMatrix = mBlockArrangement.CalculateOccupiedDaysAteachGrid(mWorkshopInfoList, mResultInfo.BlockResultList, mResultInfo.ArrangementStartDate, mResultInfo.ArrangementFinishDate);
// if (CumulatedGridOccupationMatrix != null)
// {
// for (int i = 0; i < CumulatedGridOccupationMatrix.Count; i++)
// {
// mResultsManagement.PrintArrangementMatrixResult(CumulatedGridOccupationMatrix[i], OpenedWorkshopFileName, OpenedBlockFileName, i);
// }
// }
// else
// {
// MessageBox.Show("파일을 출력할 수 없습니다.");
// }
//}
private void clearAllAToolStripMenuItem_Click(object sender, EventArgs e)
{
//모든 데이터 삭제
ClearAllData();
}
//모든 데이터를 전부 초기화함 (입력 데이터도 포함)
void ClearAllData()
{
IsWorkshopInfoReady = false;
IsBlockInfoReady = false;
mBlockArrangement = new BlockArrangementMgr();
mBlockInfoList = new List<BlockDTO>();
mWorkshopInfoList = new List<WorkshopDTO>();
mResultInfo = new ArrangementResultWithDateDTO();
mArrangementResultList = new List<ArrangementResultDTO>();
mChartList = new List<Chart>();
grdBlockInfo.Rows.Clear();
grdWorkshopInfo.Rows.Clear();
tabChart.TabPages.Clear();
//
// tabChart
//
this.tabChart.Controls.Add(this.tabPage1);
this.tabChart.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabChart.Location = new System.Drawing.Point(3, 23);
this.tabChart.Name = "tabChart";
this.tabChart.SelectedIndex = 0;
this.tabChart.Size = new System.Drawing.Size(571, 285);
this.tabChart.TabIndex = 3;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.chtWorkshop1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(563, 259);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Workshop 1";
this.tabPage1.UseVisualStyleBackColor = true;
chtTotal.Series.Clear();
chtWorkshop1.Series.Clear();
}
//입력 데이터는 그대로 + 결과만 초기화함
void ClearResultsData()
{
mBlockArrangement = new BlockArrangementMgr();
mResultInfo = new ArrangementResultWithDateDTO();
mArrangementResultList = new List<ArrangementResultDTO>();
mChartList = new List<Chart>();
tabChart.TabPages.Clear();
//
// tabChart
//
this.tabChart.Controls.Add(this.tabPage1);
this.tabChart.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabChart.Location = new System.Drawing.Point(3, 23);
this.tabChart.Name = "tabChart";
this.tabChart.SelectedIndex = 0;
this.tabChart.Size = new System.Drawing.Size(571, 285);
this.tabChart.TabIndex = 3;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.chtWorkshop1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(563, 259);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Workshop 1";
this.tabPage1.UseVisualStyleBackColor = true;
chtTotal.Series.Clear();
chtWorkshop1.Series.Clear();
}
private void clearResultsRToolStripMenuItem_Click(object sender, EventArgs e)
{
ClearResultsData();
}
private void openPlateConfigToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!IsWorkshopInfoReady) MessageBox.Show("작업장 정보를 먼저 불러와야 합니다.");
else
{
try
{
mPlateConfigList.Clear();
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.InitialDirectory = path;
List<string> TargetCSVFiles = new List<string>();
//대상 폴더를 선택하고, 해당 폴더 하위의 모든 CSV 파일의 이름을 가져옴
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
//주수헌 임시로 박아둔 경로, 나중에 바꿔야 함
string Fullpath = myOpenFileDialog.FileName;
string FileName = myOpenFileDialog.SafeFileName;
string selectedDirectory = Fullpath.Replace(FileName, "");
if (Directory.Exists(selectedDirectory))
{
DirectoryInfo direc = new DirectoryInfo(selectedDirectory);
foreach (FileInfo f in direc.GetFiles())
{
if (f.Extension.ToLower().CompareTo(".csv") == 0)
{
string strCsvFileName = direc.FullName + f.Name;
TargetCSVFiles.Add(strCsvFileName);
}
}
}
//CSV의 주판 정보를 하나씩 읽어서 MainPlateDTO에 저장함
for (int i = 0; i < TargetCSVFiles.Count; i++)
{
string strTargetCSVFile = TargetCSVFiles[i];
string PlateName = strTargetCSVFile.Replace(selectedDirectory, "");
PlateName = PlateName.Substring(0, PlateName.Length - 4);
List<string[]> Plateinput = new List<string[]>();
StreamReader sr = new StreamReader(strTargetCSVFile, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
Plateinput.Add(temp);
}
int RowCount = Plateinput.Count;
int ColCount = Plateinput[0].GetLength(0);
double[,] tempPlateConfig = new double[RowCount, ColCount];
//주판 형상 채우기
for (int j = 0; j < RowCount; j++)
{
for (int k = 0; k < ColCount; k++)
{
tempPlateConfig[j, k] = Convert.ToDouble(Plateinput[j][k]);
}
}
PlateConfigDTO tempConfig = new PlateConfigDTO(PlateName, RowCount, ColCount);
tempConfig.PlateConfig = tempPlateConfig;
mPlateConfigList.Add(tempConfig);
}
//팝업창으로 결과를 확인
MessageBox.Show(TargetCSVFiles.Count.ToString() + "개의 주판 형상 정보가 정상적으로 로드 되었습니다.");
mDataManagement.PrintPlateDataOnFrid(grdBlockInfo, mPlateConfigList);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void openPlateDateInfomationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mPlateConfigList.Count==0) MessageBox.Show("주판 정보를 먼저 불러와야 합니다.");
else
{
try
{
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.Filter = "CSV Files|*.csv";
myOpenFileDialog.InitialDirectory = path;
List<string[]> input = new List<string[]>();
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFileName = myOpenFileDialog.FileName;
string tempFileName = selectedFileName.Substring(selectedFileName.LastIndexOf("\\") + 1);
tempFileName = tempFileName.Remove(tempFileName.Length - 4);
OpenedBlockFileName = tempFileName;
StreamReader sr = new StreamReader(selectedFileName, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
input.Add(temp);
}
}
// 주판의 정보에 입출고 날짜 정보 입력하기
for (int i = 1; i < input.Count; i++)
{
if (mPlateConfigList[i-1].Name == input[i][1])
{
mPlateConfigList[i - 1].InitialImportDate = DateTime.Parse(input[i][2]);
mPlateConfigList[i - 1].PlanImportDate = DateTime.Parse(input[i][2]);
mPlateConfigList[i - 1].InitialExportDate = DateTime.Parse(input[i][3]);
mPlateConfigList[i - 1].PlanExportDate = DateTime.Parse(input[i][3]);
TimeSpan Leadtime = mPlateConfigList[i - 1].PlanExportDate - mPlateConfigList[i - 1].PlanImportDate;
mPlateConfigList[i - 1].LeadTime = Leadtime.Days;
}
//선호작업장, 선호 지번 입력
List<int> tempPreferWorkShop = new List<int>();
bool PreferWorkShop = true;
if (input[i][4] == "") PreferWorkShop = false;
if (PreferWorkShop == false) //선호지번 값이 없는 경우
{
//모든 지번을 선호지번으로 가짐
int totalWorkShop = mWorkshopInfoList.Count;
for (int j = 0; j < totalWorkShop; j++) tempPreferWorkShop.Add(j);
mPlateConfigList[i - 1].PreferWorkShopIndexList = tempPreferWorkShop;
}
else//선호지번 값이 있는 경우
{
string[] temp = input[i][4].Split('/');
for (int j = 0; j < temp.Length; j++) tempPreferWorkShop.Add(Convert.ToInt32(temp[j]));
mPlateConfigList[i - 1].PreferWorkShopIndexList = tempPreferWorkShop;
}
}
IsPlateInfoReady = true;
//팝업창으로 결과를 확인
MessageBox.Show((input.Count-1).ToString() + "개의 주판정보가 정상적으로 로드 되었습니다.");
//그리드에 결과 표시
mDataManagement.PrintPlateDataOnFrid(grdBlockInfo, mPlateConfigList);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
// 행렬 회전을 위한 데이터 입출력 및 회전 함수 짜기 - 1월 29일까지
// BLF 알고리즘 내용 정리해서 PPT로 순서도로 정리하기
// (추가) 시간을 고려한 배치 중, BLF외 다른 논문 찾고 PPT로 정리
private void rotateTestToolStripMenuItem_Click(object sender, EventArgs e)
{
//행렬 A를 불러와서, 90 , 180, 270도 씩 회전하는 코드를 짜보자
//csv 파일로 테스트용 행렬 파일 읽어오는 코드를 짜야함
double[,] inputmatrix = null;
double[,] outputmatrix = null;
try
{
string path = Environment.CurrentDirectory.ToString();
myOpenFileDialog.Filter = "CSV Files|*.csv";
myOpenFileDialog.InitialDirectory = path;
List<double[]> input = new List<double[]>();
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFileName = myOpenFileDialog.FileName;
string tempFileName = selectedFileName.Substring(selectedFileName.LastIndexOf("\\") + 1);
tempFileName = tempFileName.Remove(tempFileName.Length - 4);
OpenedWorkshopFileName = tempFileName;
StreamReader sr = new StreamReader(selectedFileName, Encoding.GetEncoding("euc-kr"));
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] temp = s.Split(',');
double[] tempda = new double[temp.Length];
for (int i = 0; i < temp.Length; i++)
{
double tempd = Convert.ToDouble(temp[i]);
tempda[i] = tempd;
}
input.Add(tempda);
}
double[,] input_2d = new double[input.Count, input[0].Length];
for (int i=0; i < input_2d.GetLength(0); i++)
{
for (int j = 0; j < input_2d.GetLength(1); j++)
{
input_2d[i,j] = input[i][j];
}
}
inputmatrix = input_2d;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
// 행렬 회전하는 함수(RotateMatrix)를 짜고, 불러와서 사용한다.
outputmatrix = RotateMatrix(inputmatrix, 90);
// 출력
string outpath = Environment.CurrentDirectory.ToString();
var filepath = outpath + "/RotatedMatrix.csv";
using (StreamWriter writer = new StreamWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write)))
{
for (int i = 0; i < outputmatrix.GetLength(0); i++)
{
for (int j = 0; j < outputmatrix.GetLength(1); j++)
{
writer.Write(outputmatrix[i, j]);
writer.Write(',');
}
writer.WriteLine();
}
}
}
// 회전된 행렬을 csv 파일로 출력해주는코드
//90, 180, 270도 회전만 하면됨
public double[,] RotateMatrix(double[,] inputmatrix, int degree)
{
int new_row = inputmatrix.GetLength(1);
int new_column = inputmatrix.GetLength(0);
double[,] Resultmatrix = new double[new_row, new_column];
//행렬을 회전하는 함수 짤 것
if (degree == 90)
{
for (int i = 0; i < new_row; i++)
{
for (int j = 0; j < new_column; j++)
{
Resultmatrix[i, j] = inputmatrix[ new_column - j -1 , i ];
}
}
}
else if (degree == 180)
{ }
else if (degree == 270)
{ }
else
{
string error = "올바른 각도를 선택하십시오";
; MessageBox.Show(error);
}
return Resultmatrix;
}
private void reportRToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void fileFToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void chtTotal_Click(object sender, EventArgs e)
{
}
private void grdWorkshopInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void setParametersToolStripMenuItem_Click(object sender, EventArgs e)
{
frmSetParameter myfrmSetParameter;
myfrmSetParameter = new frmSetParameter();
// 2016년 11월 28일 주수헌 수정, BLF, Greedy 모두 날짜 개념이 들어가므로 아래의 구분은 무효
////BLF 알고리즘
//if (ArrangementAlgorithmMode == 0) myfrmResultsViewer = new frmResultsViewer(mResultInfo, mWorkshopInfoList);
////Greedy 알고리즘
//else myfrmResultsViewer = new frmResultsViewer(mBlockInfoList, mWorkshopInfoList, mUnitcellInfoList);
var SetParamResult = myfrmSetParameter.ShowDialog();
if (SetParamResult == DialogResult.OK)
{
string val = myfrmSetParameter.temp1;
if (myfrmSetParameter.temp1 != "") UnitGridLength = Convert.ToDouble(myfrmSetParameter.temp1);
if (myfrmSetParameter.temp2 != "") InputSlack = Convert.ToDouble(myfrmSetParameter.temp2) / 2;
}
int testttttt = 1;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
public class UnitcellDTO
{
public int BlockIndex { get; set; }
public bool IsOccupied { get; set; }
public int Address { get; set; }
public UnitcellDTO(int _blockIndex, bool _isOccupied, int _address)
{
BlockIndex = _blockIndex;
IsOccupied = _isOccupied;
Address = _address;
}
public UnitcellDTO Clone()
{
return new UnitcellDTO(BlockIndex, IsOccupied, Address);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
public class WorkshopDTO
{
List<int> mLocatedBlockIndexList = new List<int>();
List<int[]> mAddressInfoList = new List<int[]>(); //지번의 시작 위치와 행,열의 갯수를 나타내기 위한 리스트 int[4] = [지번 시작행, 지번 시작열,지번 행길이,지번 열길이]
double mAreaUtilization = 0.0;
int mNumOfLocatedBlocks = 0;
public int Index { get; set; }
public string Name { get; set; }
public double RowCount { get; set; }
public double ColumnCount { get; set; }
public int NumOfAddress { get; set; }
public double RowLocation { get; set; }
public double ColumnLocation { get; set; }
public double[] UpperRoadside { get; set; }
public double[] BottomRoadside { get; set; }
public double[] LeftRoadside { get; set; }
public double[] RightRoadside { get; set; }
public double[] AddressColumnLocation { get; set; }
public string RoadSide { get; set; }
public int Type { get; set; }
public List<int> LocatedBlockIndexList
{
get
{
List<int> _getter = null;
if (mLocatedBlockIndexList != null)
{
_getter = new List<int>();
for (int i = 0; i < mLocatedBlockIndexList.Count; i++) _getter.Add(mLocatedBlockIndexList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mLocatedBlockIndexList = new List<int>();
for (int i = 0; i < value.Count; i++) mLocatedBlockIndexList.Add(value[i]);
}
}
}
public List<int[]> AddressInfoList
{
get
{
List<int[]> _getter = null;
if (mAddressInfoList != null)
{
_getter = new List<int[]>();
for (int i = 0; i < mAddressInfoList.Count; i++) _getter.Add(mAddressInfoList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mAddressInfoList = new List<int[]>();
for (int i = 0; i < value.Count; i++) mAddressInfoList.Add(value[i]);
}
}
}
public List<ArrangementMatrixInfoDTO> ArrangementMatrixInfoList = new List<ArrangementMatrixInfoDTO>();
public double AreaUtilization
{
get { return mAreaUtilization; }
set { mAreaUtilization = value ; }
}
public int NumOfLocatedBlocks
{
get { return mNumOfLocatedBlocks; }
set { mNumOfLocatedBlocks = value; }
}
public WorkshopDTO(int _index, string _name, double _rowCount, double _colCount, int _numOfAddress)
{
Index = _index;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
NumOfAddress = _numOfAddress;
AddressColumnLocation = new double[NumOfAddress];
//지번 자동 할당
for (int i = 0; i < NumOfAddress; i++)
{
AddressColumnLocation[i] = (ColumnCount / NumOfAddress) * Convert.ToDouble(i);
}
}
public WorkshopDTO(int _index, string _name, double _rowCount, double _colCount, int _numOfAddress, double _RowLocation, double _ColumnLocation, double[] _UpperRoadside, double[] _BottomRoadside, double[] _LeftRoadside, double[] _RightRoadside)
{
Index = _index;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
NumOfAddress = _numOfAddress;
RowLocation = _RowLocation;
ColumnLocation = _ColumnLocation;
UpperRoadside = _UpperRoadside;
BottomRoadside = _BottomRoadside;
LeftRoadside = _LeftRoadside;
RightRoadside = _RightRoadside;
AddressColumnLocation = new double[NumOfAddress];
//지번 자동 할당
for (int i = 0; i < NumOfAddress; i++)
{
AddressColumnLocation[i] = (ColumnCount / NumOfAddress) * Convert.ToDouble(i);
}
}
public WorkshopDTO()
{
}
public WorkshopDTO Clone()
{
WorkshopDTO tempWorkshopDTO = new WorkshopDTO(Index, Name, RowCount, ColumnCount, NumOfAddress);
if (ArrangementMatrixInfoList.Count != 0) tempWorkshopDTO.ArrangementMatrixInfoList = ArrangementMatrixInfoList;
tempWorkshopDTO.RowLocation = RowLocation;
tempWorkshopDTO.ColumnLocation = ColumnLocation;
tempWorkshopDTO.UpperRoadside = UpperRoadside;
tempWorkshopDTO.BottomRoadside = BottomRoadside;
tempWorkshopDTO.LeftRoadside = LeftRoadside;
tempWorkshopDTO.RightRoadside = RightRoadside;
tempWorkshopDTO.Type = Type;
return tempWorkshopDTO;
}
}
public class ArrangementMatrixInfoDTO
{
public int Index { get; set; }
public string Name { get; set; }
public int WorkshopIndex { get; set; }
public string WorkshopName { get; set; }
public double RowLocation { get; set; }
public double ColumnLocation { get; set; }
public double RowCount { get; set; }
public double ColumnCount { get; set; }
public int type { get; set; }
public ArrangementMatrixInfoDTO(int _Index, string _Name, int _WorkshopIndex, string _WorkshopName, double _RowLocation, double _ColumnLocation, double _RowCount, double _ColumnCount, int _type)
{
Index = _Index;
Name = _Name;
WorkshopIndex = _WorkshopIndex;
WorkshopName = _WorkshopName;
RowLocation = _RowLocation;
ColumnLocation = _ColumnLocation;
RowCount = _RowCount;
ColumnCount = _ColumnCount;
type = _type;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface
{
public interface IDataManagement
{
//작업장 정보, 블록 정보 불러오기
void PrintWorkshopDataOnGrid(DataGridView _datagrid, List<WorkshopDTO> _workshopList);
void PrintBlockDataOnGrid(DataGridView _datagrid, List<BlockDTO> _blockList);
void PrintPlateDataOnFrid(DataGridView _datagrid, List<PlateConfigDTO> _plaeList);
List<BlockDTO> RefineInputBlockData(List<string[]> _inputStringList, List<WorkshopDTO> _workshopList, double _UnitGridLength);
//작업장 정보, 블록 정보 갱신하기
void UpdateWorkshopDataOfGrid(DataGridView _datagrid, List<WorkshopDTO> _workshopList);
void UpdateBlockDataOfGrid(DataGridView _datagrid, List<BlockDTO> _blockList);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
/// 수정 일자 : 이동건, 2016년 2월 19일
public class BlockDTO
{
private List<int> mPreferAddressIndexList = new List<int>();
private List<int> mPreferWorkShopIndexList = new List<int>();
public int Index { get; set; }
public string Project { get; set; }
public string Name { get; set; }
public double RowCount { get; set; }
public double ColumnCount { get; set; }
public double UpperSideCount { get; set; }
public double BottomSideCount { get; set; }
public double LeftSideCount { get; set; }
public double RightSideCount { get; set; }
public int Orientation { get; set; }
public double Leadtime { get; set; }
public DateTime InitialImportDate { get; set; }
public DateTime InitialExportDate { get; set; }
public DateTime ImportDate { get; set; }
public DateTime ExportDate { get; set; }
public DateTime ActualImportDate { get; set; }
public DateTime ActualExportDate { get; set; }
public List<int> PreferWorkShopIndexList
{
get
{
List<int> _getter = null;
if (mPreferWorkShopIndexList != null)
{
_getter = new List<int>();
for (int i = 0; i < mPreferWorkShopIndexList.Count; i++) _getter.Add(mPreferWorkShopIndexList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mPreferWorkShopIndexList = new List<int>();
for (int i = 0; i < value.Count; i++) mPreferWorkShopIndexList.Add(value[i]);
}
}
}
public List<int> PreferAddressIndexList
{
get
{
List<int> _getter = null;
if (mPreferAddressIndexList != null)
{
_getter = new List<int>();
for (int i = 0; i < mPreferAddressIndexList.Count; i++) _getter.Add(mPreferAddressIndexList[i]);
}
return _getter;
}
set
{
if (value != null)
{
mPreferAddressIndexList = new List<int>();
for (int i = 0; i < value.Count; i++) mPreferAddressIndexList.Add(value[i]);
}
}
}
public double LocatedRow { get; set; }
public double LocatedColumn { get; set; }
public int LocatedWorkshopIndex { get; set; }
public int CurrentLocatedWorkshopIndex { get; set; }
public int CurrentLocatedAddressIndex { get; set; }
public int ActualLocatedWorkshopIndex { get; set; }
public int ActualLocatedAddressIndex { get; set; }
public bool IsLocated { get; set; }
public bool IsDelayed { get; set; }
public int DelayedTime { get; set; }
public bool IsRoadSide { get; set; }
public bool IsConditionSatisfied { get; set; }
public bool IsFinished { get; set; }
public bool IsPrior { get; set; }
public bool IsFloatingCraneExportBlock { get; set; }
public int SearchDirection { get; set; }
public int ArrangementDirection { get; set; }
public BlockDTO(int _index, string _project, string _name, double _rowCount, double _colCount, double _uppCount, double _botCount, double _lefCount, double _rigCount, List<int> _preferWorkShopIndexList, List<int> _preferAddressIndexList, double _leadtime, DateTime _ImportDate, DateTime _ExportDate, DateTime _actualImporteDate, DateTime _actualExportDate)
{
Index = _index;
Project = _project;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
UpperSideCount = _uppCount;
BottomSideCount = _botCount;
LeftSideCount = _lefCount;
RightSideCount = _rigCount;
Leadtime = _leadtime;
InitialImportDate = _ImportDate;
InitialExportDate = _ExportDate;
ImportDate = _ImportDate;
ExportDate = _ExportDate;
LocatedRow = -1;
LocatedColumn = -1;
CurrentLocatedWorkshopIndex = -1;
CurrentLocatedAddressIndex = -1;
ActualLocatedWorkshopIndex = -1;
ActualLocatedAddressIndex = -1;
ActualImportDate = _actualImporteDate;
ActualExportDate = _actualExportDate;
for (int i = 0; i < _preferWorkShopIndexList.Count; i++) mPreferWorkShopIndexList.Add(_preferWorkShopIndexList[i]);
for (int i = 0; i < _preferAddressIndexList.Count; i++) mPreferAddressIndexList.Add(_preferAddressIndexList[i]);
IsLocated = false;
IsFinished = false;
IsDelayed = false;
DelayedTime = 0;
IsRoadSide = false;
IsConditionSatisfied = false;
}
//최종
public BlockDTO(int _index, string _project, string _name, double _rowCount, double _colCount, double _uppCount, double _botCount, double _lefCount, double _rigCount, List<int> _preferWorkShopIndexList, List<int> _preferAddressIndexList, double _leadtime, DateTime _ImportDate, DateTime _ExportDate, DateTime _actualImporteDate, DateTime _actualExportDate, bool _IsRoadSide, bool _IsPrior, int _SearchDirection, int _ArrangementDirection)
{
Index = _index;
Project = _project;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
UpperSideCount = _uppCount;
BottomSideCount = _botCount;
LeftSideCount = _lefCount;
RightSideCount = _rigCount;
Leadtime = _leadtime;
InitialImportDate = _ImportDate;
InitialExportDate = _ExportDate;
ImportDate = _ImportDate;
ExportDate = _ExportDate;
LocatedRow = -1;
LocatedColumn = -1;
CurrentLocatedWorkshopIndex = -1;
CurrentLocatedAddressIndex = -1;
ActualLocatedWorkshopIndex = -1;
ActualLocatedAddressIndex = -1;
ActualImportDate = _actualImporteDate;
ActualExportDate = _actualExportDate;
for (int i = 0; i < _preferWorkShopIndexList.Count; i++) mPreferWorkShopIndexList.Add(_preferWorkShopIndexList[i]);
for (int i = 0; i < _preferAddressIndexList.Count; i++) mPreferAddressIndexList.Add(_preferAddressIndexList[i]);
IsLocated = false;
IsFinished = false;
IsDelayed = false;
DelayedTime = 0;
IsRoadSide = _IsRoadSide;
IsConditionSatisfied = _IsRoadSide;
IsPrior = _IsPrior;
SearchDirection = _SearchDirection;
ArrangementDirection = _ArrangementDirection;
}
//public BlockDTO(int _index, string _project, string _name, double _rowCount, double _colCount, double _uppCount, double _botCount, double _lefCount, double _rigCount, List<int> _preferWorkShopIndexList, List<int> _preferAddressIndexList, double _leadtime, DateTime _ImportDate, DateTime _ExportDate, DateTime _actualImporteDate, DateTime _actualExportDate, double _LocatedRow, double _LocatedColumn, bool _IsLocated)
//{
// Index = _index;
// Project = _project;
// Name = _name;
// RowCount = _rowCount;
// ColumnCount = _colCount;
// UpperSideCount = _uppCount;
// BottomSideCount = _botCount;
// LeftSideCount = _lefCount;
// RightSideCount = _rigCount;
// Leadtime = _leadtime;
// InitialImportDate = _ImportDate;
// InitialExportDate = _ExportDate;
// ImportDate = _ImportDate;
// ExportDate = _ExportDate;
// LocatedRow = _LocatedRow;
// LocatedColumn = _LocatedColumn;
// CurrentLocatedWorkshopIndex = -1;
// CurrentLocatedAddressIndex = -1;
// ActualLocatedWorkshopIndex = -1;
// ActualLocatedAddressIndex = -1;
// ActualImportDate = _actualImporteDate;
// ActualExportDate = _actualExportDate;
// for (int i = 0; i < _preferWorkShopIndexList.Count; i++) mPreferWorkShopIndexList.Add(_preferWorkShopIndexList[i]);
// for (int i = 0; i < _preferAddressIndexList.Count; i++) mPreferAddressIndexList.Add(_preferAddressIndexList[i]);
// IsLocated = _IsLocated;
// IsFinished = false;
// IsDelayed = false;
// DelayedTime = 0;
// IsRoadSide = false;
// IsConditionSatisfied = false;
//}
public BlockDTO(int _index, string _project, string _name, double _rowCount, double _colCount, List<int> _preferWorkShopIndexList, List<int> _preferAddressIndexList, double _leadtime, DateTime _ImportDate, DateTime _ExportDate, DateTime _actualImporteDate, DateTime _actualExportDate)
{
Index = _index;
Project = _project;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
Leadtime = _leadtime;
InitialImportDate = _ImportDate;
InitialExportDate = _ExportDate;
ImportDate = _ImportDate;
ExportDate = _ExportDate;
LocatedRow = -1;
LocatedColumn = -1;
CurrentLocatedWorkshopIndex = -1;
CurrentLocatedAddressIndex = -1;
ActualLocatedWorkshopIndex = -1;
ActualLocatedAddressIndex = -1;
ActualImportDate = _actualImporteDate;
ActualExportDate = _actualExportDate;
for (int i = 0; i < _preferWorkShopIndexList.Count; i++) mPreferWorkShopIndexList.Add(_preferWorkShopIndexList[i]);
for (int i = 0; i < _preferAddressIndexList.Count; i++) mPreferAddressIndexList.Add(_preferAddressIndexList[i]);
IsLocated = false;
IsFinished = false;
IsDelayed = false;
DelayedTime = 0;
IsRoadSide = false;
IsConditionSatisfied = false;
}
// IsRoadSide 추가
public BlockDTO(int _index, string _project, string _name, double _rowCount, double _colCount, List<int> _preferWorkShopIndexList, List<int> _preferAddressIndexList, double _leadtime, DateTime _ImportDate, DateTime _ExportDate, DateTime _actualImporteDate, DateTime _actualExportDate, bool _IsRoadSide)
{
Index = _index;
Project = _project;
Name = _name;
RowCount = _rowCount;
ColumnCount = _colCount;
Leadtime = _leadtime;
InitialImportDate = _ImportDate;
InitialExportDate = _ExportDate;
ImportDate = _ImportDate;
ExportDate = _ExportDate;
LocatedRow = -1;
LocatedColumn = -1;
CurrentLocatedWorkshopIndex = -1;
CurrentLocatedAddressIndex = -1;
ActualLocatedWorkshopIndex = -1;
ActualLocatedAddressIndex = -1;
ActualImportDate = _actualImporteDate;
ActualExportDate = _actualExportDate;
for (int i = 0; i < _preferWorkShopIndexList.Count; i++) mPreferWorkShopIndexList.Add(_preferWorkShopIndexList[i]);
for (int i = 0; i < _preferAddressIndexList.Count; i++) mPreferAddressIndexList.Add(_preferAddressIndexList[i]);
IsLocated = false;
IsFinished = false;
IsDelayed = false;
DelayedTime = 0;
IsRoadSide = _IsRoadSide;
IsConditionSatisfied = _IsRoadSide;
}
public BlockDTO Clone()
{
return new BlockDTO(Index, Project, Name, RowCount, ColumnCount, UpperSideCount, BottomSideCount, LeftSideCount, RightSideCount, PreferWorkShopIndexList, PreferAddressIndexList, Leadtime, ImportDate, ExportDate, ActualImportDate, ActualExportDate, IsRoadSide, IsPrior, SearchDirection, ArrangementDirection);
}
//public BlockDTO Clone(int isLocated)
//{
// return new BlockDTO(Index, Project, Name, RowCount, ColumnCount, UpperSideCount, BottomSideCount, LeftSideCount, RightSideCount, PreferWorkShopIndexList, PreferAddressIndexList, Leadtime, ImportDate, ExportDate, ActualImportDate, ActualExportDate, LocatedRow, LocatedColumn, IsLocated);
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eoba.Shipyard.ArrangementSimulator.DataTransferObject;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Forms;
using System.Diagnostics;
namespace Eoba.Shipyard.ArrangementSimulator.BusinessComponent.Interface
{
public interface IResultsManagement
{
//차트 초기화
void InitializeIndividualWorkshopChart(List<WorkshopDTO> _workshopInfoList, List<Chart> _chartList, Chart _chart, TabControl _tabPage);
void InitializeTotalWorkshopChart(Chart _chart);
//배치 결과 차트에 출력
void DrawChart(ArrangementResultWithDateDTO _resultInfo, List<Chart> _chartList, Chart _chart);
void DrawChart(ArrangementResultWithDateDTO _resultInfo, List<Chart> _chartList, Chart _chart, bool IsPlateArrangement);
//배치 결과 출력
List<UnitcellDTO[,]> GenterateArrangementMatrixFromBlockinfo(List<BlockDTO> InpuBlockList, List<UnitcellDTO[,]> WorkShopArrangementInfo);
List<UnitcellDTO[,]> GenterateArrangementMatrixFromPlateinfo(List<PlateConfigDTO> InpuBlockList, List<UnitcellDTO[,]> WorkShopArrangementInfo);
void PrintArrangementResult(ArrangementResultWithDateDTO _resultInfo, string _fileName);
void PrintArrangementMatrixListResultWithDate(List<UnitcellDTO[,]> ArrangementMatrix, string _workshopFileName, string _blockFileName, ArrangementResultWithDateDTO _resultInfo, int _selectedDate);
void PrintArrangementMatrixResult(UnitcellDTO[,] ArrangementMatrix, string _workshopFileName, string _blockFileName);
void PrintArrangementMatrixResult(double[,] ArrangementMatrix, string _workshopFileName, string _blockFileName, int workshopNum);
void PrintBLFAlgorithmResultsSummary(ArrangementResultWithDateDTO _resultInfo, Stopwatch _sw);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Eoba.Shipyard.ArrangementSimulator.DataTransferObject
{
public class ArrangementResultDTO
{
public List<UnitcellDTO[,]> ArrangementResultList { get; set; }
public List<WorkshopDTO> ResultWorkShopInfo { get; set; }
public List<BlockDTO> ResultBlockList { get; set; }
//투입일을 고려한 날짜별 배치를 위한 변수
public DateTime ArrangementDate { get; set; }
public List<BlockDTO> ImportedBlockList { get; set; }
public List<BlockDTO> ExportedBlockList { get; set; }
public ArrangementResultDTO(List<UnitcellDTO[,]> _arrangementResult, List<WorkshopDTO> _resultWorkShopInfo,List<BlockDTO> _resultBlockList, DateTime _arrangementDate, List<BlockDTO> _importBlockList, List<BlockDTO> _exportBlockList)
{
ArrangementResultList = _arrangementResult;
ResultWorkShopInfo = _resultWorkShopInfo;
ResultBlockList = _resultBlockList;
ArrangementDate = _arrangementDate;
ImportedBlockList = _importBlockList;
ExportedBlockList = _exportBlockList;
}
public ArrangementResultDTO()
{
}
public ArrangementResultDTO Clone()
{
return new ArrangementResultDTO(ArrangementResultList, ResultWorkShopInfo, ResultBlockList,ArrangementDate,ImportedBlockList,ExportedBlockList);
}
}
}
//List<UnitcellDTO[,]> CurrentArrangementMatrix = ArrangementMatrix;
//List<BlockDTO> CurrentArrangementedBlockList = new List<BlockDTO>();
//List<List<BlockDTO>> TotalDailyArragnementedBlockList = new List<List<BlockDTO>>();
//List<List<UnitcellDTO[,]>> TotalArrangementResult = new List<List<UnitcellDTO[,]>>();
//List<BlockDTO> BlockList = new List<BlockDTO>();
//List<List<BlockDTO>> TotalBlockImportLogList = new List<List<BlockDTO>>();
//List<List<BlockDTO>> TotalBlockExportLogList = new List<List<BlockDTO>>();
//List<List<BlockDTO>> TotalNotArrangementBlockList = new List<List<BlockDTO>>();<file_sep>Helix Toolkit is a collection of 3D components for .NET. Currently it contains one component that adds functionality to the WPF 3D model (Media3D namespace), and one WPF component that creates a similar scene graph for DirectX (based on SharpDX).
[](https://ci.appveyor.com/project/objorke/helix-toolkit)
Description | Value
--------------------|-----------------------
License | The MIT License (MIT)
Web page | http://helix-toolkit.org/
Documentation | http://docs.helix-toolkit.org/
Forum | http://forum.helix-toolkit.org/
Chat | https://gitter.im/helix-toolkit/helix-toolkit
Source repository | http://github.com/helix-toolkit/helix-toolkit
Latest build | http://ci.appveyor.com/project/objorke/helix-toolkit
Issue tracker | http://github.com/helix-toolkit/helix-toolkit/issues
NuGet packages | http://www.nuget.org/packages?q=HelixToolkit
StackOverflow | http://stackoverflow.com/questions/tagged/helix-3d-toolkit
Twitter | https://twitter.com/hashtag/Helix3DToolkit
| 6a91dcda0e829634db4235865d8b9b7757d5cae4 | [
"Markdown",
"C#"
] | 19 | C# | jonathan-ship/SpatialArrangement | a725caceded548faac59eeacc40f351ddb58316c | af8684a59676f78de76c5a8e01e25e2a7571fe81 |
refs/heads/master | <repo_name>RogerChern/mxnext<file_sep>/mxnext/tvm/fpn_roi_assign.py
import numpy as np
import mxnet as mx
def fpn_roi_assign(F=mx.ndarray, rois=None, rcnn_stride=None,
roi_canonical_scale=None, roi_canonical_level=None):
############ constant #############
scale0 = roi_canonical_scale
lvl0 = roi_canonical_level
k_min = np.log2(min(rcnn_stride))
k_max = np.log2(max(rcnn_stride))
with mx.name.Prefix("fpn_roi_assgin: "):
x1, y1, x2, y2 = F.split(rois, num_outputs=4, axis=-1)
rois_area = (x2 - x1 + 1) * (y2 - y1 + 1)
rois_scale = F.sqrt(rois_area)
target_lvls = F.floor(lvl0 + F.log2(rois_scale / scale0 + 1e-6))
target_lvls = F.clip(target_lvls, k_min, k_max)
target_stride = F.pow(2, target_lvls).astype('uint8')
outputs = []
for i, s in enumerate(rcnn_stride):
lvl_rois = F.zeros_like(rois)
lvl_inds = (target_stride == s).astype('float32')
lvl_inds = F.broadcast_like(lvl_inds, lvl_rois)
lvl_rois = F.where(lvl_inds, rois, lvl_rois)
outputs.append(lvl_rois)
return outputs
<file_sep>/mxnext/tvm/decode_bbox.py
import math
import mxnet as mx
def _corner_to_center(F, boxes):
boxes = F.slice_axis(boxes, axis=-1, begin=-4, end=None)
xmin, ymin, xmax, ymax = F.split(boxes, axis=-1, num_outputs=4)
width = xmax - xmin + 1
height = ymax - ymin + 1
x = xmin + (width - 1) * 0.5
y = ymin + (height - 1) * 0.5
return x, y, width, height
def _corner_to_corner(F, boxes):
boxes = F.slice_axis(boxes, axis=-1, begin=-4, end=None)
xmin, ymin, xmax, ymax = F.split(boxes, axis=-1, num_outputs=4)
return xmin, ymin, xmax, ymax
def _bbox_transform_xywh(F, anchors, deltas, means, stds):
ax, ay, aw, ah = _corner_to_center(F, anchors) # anchor
dx, dy, dw, dh = F.split(deltas, axis=-1, num_outputs=4)
# delta
dx = dx * stds[0] + means[0]
dy = dy * stds[1] + means[1]
dw = dw * stds[2] + means[2]
dh = dh * stds[3] + means[3]
# prediction
px = F.broadcast_add(F.broadcast_mul(dx, aw), ax)
py = F.broadcast_add(F.broadcast_mul(dy, ah), ay)
pw = F.broadcast_mul(F.exp(dw), aw)
ph = F.broadcast_mul(F.exp(dh), ah)
x1 = px - 0.5 * (pw - 1.0)
y1 = py - 0.5 * (ph - 1.0)
x2 = px + 0.5 * (pw - 1.0)
y2 = py + 0.5 * (ph - 1.0)
return x1, y1, x2, y2
def _bbox_transform_xyxy(F, anchors, deltas, means, stds):
ax1, ay1, ax2, ay2 = _corner_to_corner(F, anchors)
aw = ax2 - ax1 + 1
ah = ay2 - ay1 + 1
dx1, dy1, dx2, dy2 = F.split(deltas, axis=-1, num_outputs=4)
# delta
dx1 = dx1 * stds[0] + means[0]
dy1 = dy1 * stds[1] + means[1]
dx2 = dx2 * stds[2] + means[2]
dy2 = dy2 * stds[3] + means[3]
# prediction
x1 = F.broadcast_add(F.broadcast_mul(dx1, aw), ax1)
y1 = F.broadcast_add(F.broadcast_mul(dy1, ah), ay1)
x2 = F.broadcast_add(F.broadcast_mul(dx2, aw), ax2)
y2 = F.broadcast_add(F.broadcast_mul(dy2, ah), ay2)
return x1, y1, x2, y2
def decode_bbox(F, anchors, deltas, im_infos, means, stds, class_agnostic, bbox_decode_type='xywh'):
"""
anchors: (#img, #roi, #cls * 4)
deltas: (#img, #roi, #cls * 4)
im_infos: (#img, 3), [h, w, scale]
means: (4, ), [x, y, h, w]
stds: (4, ), [x, y, h, w]
class_agnostic: bool
Returns:
bbox: (#img, #roi, 4), [x1, y1, x2, y2]
"""
with mx.name.Prefix("decode_bbox: "):
if class_agnostic:
# TODO: class_agnostic should predict only 1 class
# class_agnostic predicts 2 classes
deltas = F.slice_axis(deltas, axis=-1, begin=-4, end=None)
if not class_agnostic:
# add class axis, layout (img, roi, cls, coord)
deltas = F.reshape(deltas, [0, 0, -4, -1, 4]) # TODO: extend to multiple anchors
anchors = F.expand_dims(anchors, axis=-2)
if bbox_decode_type == 'xywh':
x1, y1, x2, y2 = _bbox_transform_xywh(F, anchors, deltas, means, stds)
elif bbox_decode_type == 'xyxy':
x1, y1, x2, y2 = _bbox_transform_xyxy(F, anchors, deltas, means, stds)
else:
raise NotImplementedError("decode_bbox only supports xywh or xyxy bbox_decode_type")
if im_infos is not None:
# add roi axis, layout (img, roi, coord)
im_infos = F.expand_dims(im_infos, axis=1)
if not class_agnostic:
# add class axis, layout (img, roi, cls, coord)
im_infos = F.expand_dims(im_infos, axis=-2)
im_infos = F.split(im_infos, axis=-1, num_outputs=3)
x1 = F.maximum(F.broadcast_minimum(x1, im_infos[1] - 1.0), 0)
y1 = F.maximum(F.broadcast_minimum(y1, im_infos[0] - 1.0), 0)
x2 = F.maximum(F.broadcast_minimum(x2, im_infos[1] - 1.0), 0)
y2 = F.maximum(F.broadcast_minimum(y2, im_infos[0] - 1.0), 0)
out = F.concat(x1, y1, x2, y2, dim=-1)
if not class_agnostic:
out = F.reshape(out, [0, 0, -3, -2])
return out
def decode_rbbox(F, anchors, deltas, im_infos, means, stds):
"""
anchors: (#img, #roi, #cls * 4)
deltas: (#img, #roi, #cls * 5)
im_infos: (#img, 3), [h, w, scale]
means: (5, ), [x, y, h, w, r]
stds: (5, ), [x, y, h, w, r]
class_agnostic: bool
Returns:
bbox: (#img, #roi, 5), [x, y, h, w, r]
"""
with mx.name.Prefix("decode_rbbox: "):
# add roi axis, layout (img, roi, coord)
im_infos = F.expand_dims(im_infos, axis=1)
# TODO: class_agnostic should predict only 1 class
# class_agnostic predicts 2 classes
# (#img, #roi, 5)
deltas = F.slice_axis(deltas, axis=-1, begin=-5, end=None)
ax, ay, aw, ah = _corner_to_center(F, anchors) # (#img, #roi, 1)
h, w, scale = F.split(im_infos, axis=-1, num_outputs=3) # (#img, 1)
dx, dy, dw, dh, dr = F.split(deltas, axis=-1, num_outputs=5)
# delta
dx = dx * stds[0] + means[0]
dy = dy * stds[1] + means[1]
dw = dw * stds[2] + means[2]
dh = dh * stds[3] + means[3]
dr = dr * stds[4] + means[4]
# prediction
px = F.broadcast_add(F.broadcast_mul(dx, aw), ax)
py = F.broadcast_add(F.broadcast_mul(dy, ah), ay)
pw = F.broadcast_mul(F.exp(dw), aw)
ph = F.broadcast_mul(F.exp(dh), ah)
pr = (2 * math.pi) * dr % (2 * math.pi)
rbbox = F.concat(px, py, pw, ph, pr, dim=-1)
return rbbox
if __name__ == "__main__":
import mxnet as mx
anchors = mx.nd.array([10, 20, 55, 77, 10, 20, 50, 77]).reshape([2, 1, 4])
im_infos = mx.nd.array([76, 72, 1, 76, 76, 1]).reshape([2, 3])
deltas = mx.nd.array([0, 0, 0, 0.1, 0.3, 0.1, 0.2, 0.4, 0.5, 0.1, 0.2, 0.1, 0, 0, 0, 0, 0.3, 0.1, 0.2, 0.4, 0.5, 0.1, 0.2, 0.1]).reshape([2, 1, 12])
agnostic_deltas = mx.nd.array([0, 0, 0, 0.1, 0.3, 0.1, 0.2, 0.4, 0, 0, 0, 0, 0.3, 0.1, 0.2, 0.4]).reshape([2, 1, 8])
means = (0.04, 0.01, 0.03, 0.02)
stds = (0.5, 0.1, 0.1, 0.5)
for class_agnostic in [True, False]:
for bbox_decode_type in ['xyxy', 'xywh']:
print("Test class_agnostic {}, bbox_decode_type {}".format(class_agnostic, bbox_decode_type))
o1 = mx.nd.contrib.DecodeBBox(
rois=anchors,
bbox_pred=agnostic_deltas if class_agnostic else deltas,
im_info=im_infos,
bbox_mean=means,
bbox_std=stds,
class_agnostic=class_agnostic,
bbox_decode_type=bbox_decode_type
)
o2 = decode_bbox(
mx.ndarray,
anchors,
agnostic_deltas if class_agnostic else deltas,
im_infos,
means,
stds,
class_agnostic,
bbox_decode_type=bbox_decode_type
)
print(o1)
print(o2.shape)
print(o1 - o2)
# rrbox tests
anchors = mx.nd.array(
[
[10, 20, 55, 77],
[10, 20, 50, 77],
]
).reshape([2, 1, 4]) # (#img, #roi, 4)
im_infos = mx.nd.array(
[
[76, 72, 1],
[76, 76, 1],
]
).reshape([2, 3]) # (#img, 3)
deltas = mx.nd.array(
[
[
[0.0, 0.0, 0.0, 0.1, 0.1],
[0.5, 0.1, 0.2, 0.1, 0.3],
],
[
[0.0, 0.0, 0.0, 0.0, 0.1],
[0.5, 0.1, 0.2, 0.1, 0.3],
],
]
).reshape([2, 1, 10]) # (#img, #roi, #cls * 5)
means = (0.04, 0.01, 0.03, 0.02, 0.02)
stds = (0.5, 0.1, 0.1, 0.5, 0.5)
o2 = decode_rbbox(
mx.ndarray,
anchors,
deltas,
im_infos,
means,
stds,
)
print(o2)
<file_sep>/mxnext/tvm/encode_bbox.py
import math
import mxnet as mx
def _corner_to_center(F, boxes):
boxes = F.slice_axis(boxes, axis=-1, begin=-4, end=None)
xmin, ymin, xmax, ymax = F.split(boxes, axis=-1, num_outputs=4)
width = xmax - xmin + 1
height = ymax - ymin + 1
x = xmin + (width - 1) * 0.5
y = ymin + (height - 1) * 0.5
return x, y, width, height
def encode_rbbox(F, anchors, assigned_gt_bboxes, im_infos, means, stds):
"""
encode rotated bounding boxes
Args:
F: mx.ndarray or mx.symbol
anchors: (#img, #roi, #cls * 4)
assigned_gt_bboxes: (#img, #roi, 5)
im_infos: (#img, 3)
means: (5, )
stds: (5, )
Returns:
deltas: (#img, #roi, #cls * 5)
"""
with mx.name.Prefix("encode_rbbox: "):
x, y, w, h, r = F.split(assigned_gt_bboxes, axis=-1, num_outputs=5)
ax, ay, aw, ah = _corner_to_center(F, anchors) # anchor
dx = (x - ax) / aw # the r is in radian and the positive direction is clockwise
dy = (y - ay) / ah
dw = F.log(w / aw)
dh = F.log(h / ah)
dr = r % (2 * math.pi) / (2 * math.pi)
dx = (dx - means[0]) / stds[0]
dy = (dy - means[1]) / stds[1]
dw = (dw - means[2]) / stds[2]
dh = (dh - means[3]) / stds[3]
dr = (dr - means[4]) / stds[4]
deltas = F.concat(dx, dy, dw, dh, dr, dim=-1)
return deltas
if __name__ == "__main__":
anchors = mx.nd.array(
[
[10, 20, 55, 77],
[10, 20, 50, 77],
]
).reshape([2, 1, 4]) # (#img, #roi, 4)
im_infos = mx.nd.array(
[
[76, 72, 1],
[76, 76, 1],
]
).reshape([2, 3]) # (#img, 3)
deltas = mx.nd.array(
[
[
[0.0, 0.0, 0.0, 0.1, 0.1],
[0.5, 0.1, 0.2, 0.1, 0.3],
],
[
[0.0, 0.0, 0.0, 0.0, 0.1],
[0.5, 0.1, 0.2, 0.1, 0.3],
],
]
).reshape([2, 1, 10]) # (#img, #roi, #cls * 5)
gts = mx.nd.array(
[
[
[45.84, 49.66, 48.35, 62.20, 1.06],
],
[
[41.89, 49.66, 43.10, 62.20, 1.06],
],
]
).reshape([2, 1, 5]) # (#img, #roi, 5)
means = (0.04, 0.01, 0.03, 0.02, 0.02)
stds = (0.5, 0.1, 0.1, 0.5, 0.5)
o1 = encode_rbbox(
mx.ndarray,
anchors,
gts,
im_infos,
means,
stds,
)
print(o1)
print(deltas)
<file_sep>/mxnext/tvm/get_top_proposal.py
import mxnet as mx
def get_top_proposal(F=mx.ndarray, score=None, bbox=None, batch_size=None, top_n=None):
with mx.name.Prefix("get_top_proposal: "):
score = F.reshape(score, shape=[0, -3, -2])
argsort_score = F.argsort(score, axis=-1, is_ascend=False)
argsort_score = F.slice_axis(argsort_score, axis=-1, begin=0, end=top_n)
arange_index = F.arange(0, batch_size).reshape([batch_size, 1])
arange_index = F.broadcast_axis(arange_index, axis=1, size=top_n).reshape(-1)
top_indexes = F.stack(arange_index, argsort_score.reshape(-1).astype("float32"))
sort_score = F.gather_nd(score, top_indexes).reshape([-4, -1, top_n, 1]) # (#img, #proposal, 1)
sort_bbox = F.gather_nd(bbox, top_indexes).reshape([-4, -1, top_n, 4]) # (#img, #proposal, 4)
return sort_bbox, sort_score<file_sep>/mxnext/tvm/rpn_target.py
import mxnet as mx
def _bbox_encode(F, ex_rois, gt_rois):
ex_x1, ex_y1, ex_x2, ex_y2 = F.split(ex_rois, num_outputs=4, axis=-1)
gt_x1, gt_y1, gt_x2, gt_y2 = F.split(gt_rois, num_outputs=4, axis=-1)
ex_widths = ex_x2 - ex_x1 + 1.0
ex_heights = ex_y2 - ex_y1 + 1.0
ex_ctr_x = ex_x1 + 0.5 * (ex_widths - 1.0)
ex_ctr_y = ex_y1 + 0.5 * (ex_heights - 1.0)
gt_widths = gt_x2 - gt_x1 + 1.0
gt_heights = gt_y2 - gt_y1 + 1.0
gt_ctr_x = gt_x1 + 0.5 * (gt_widths - 1.0)
gt_ctr_y = gt_y1 + 0.5 * (gt_heights - 1.0)
targets_dx = (gt_ctr_x - ex_ctr_x) / (ex_widths + 1e-14)
targets_dy = (gt_ctr_y - ex_ctr_y) / (ex_heights + 1e-14)
targets_dw = F.log(gt_widths / ex_widths)
targets_dh = F.log(gt_heights / ex_heights)
return F.concat(targets_dx, targets_dy, targets_dw, targets_dh, dim=-1)
def _fpn_rpn_target_batch(F, feat_list, anchor_list, gt_bboxes, im_infos, num_image, num_anchor,
max_side, stride_list, allowed_border, sample_per_image, fg_fraction, fg_thr, bg_thr):
assert len(feat_list) == len(anchor_list) == len(stride_list)
max_side = max_side // min(stride_list)
with mx.name.Prefix("fpn_rpn_target: "):
# prepare anchors
lvl_anchors = []
for features, anchors in zip(feat_list, anchor_list):
anchors = F.slice_like(anchors, features, axes=(2, 3)) # (1, 1, h, w, #anchor * 4)
anchors = F.reshape(anchors, shape=(1, -1, num_anchor, 4)) # (1, h * w, #anchor, 4)
anchors = F.transpose(anchors, (0, 2, 1, 3)) # (1, #anchor, h * w, 4)
lvl_anchors.append(anchors)
anchors = F.concat(*lvl_anchors, dim=2) # (1, #anchor, h' * w', 4)
anchors = F.broadcast_axis(anchors, axis=0, size=num_image) # (n, #anchor, h' * w', 4)
anchors = F.reshape(anchors, shape=(0, -3, -2)) # (n, #anchor * h' * w', 4)
# prepare output
cls_label_shape = F.slice_axis(anchors, axis=-1, begin=0, end=1).reshape([num_image, -1]) # (n, h * w * #anchor)
rpn_cls_label = F.ones_like(cls_label_shape) * -1 # -1 for ignore
# prepare gt, valid
gt_bboxes # (n, #gt, 4)
im_infos # (n, 3)
h, w, _ = F.split(im_infos, num_outputs=3, axis=-1) # (n, 1)
x1, y1, x2, y2 = F.split(anchors, num_outputs=4, axis=-1, squeeze_axis=True) # (n, h * w * #anchor)
valid = (x1 >= -allowed_border) * \
F.broadcast_lesser(x2, w + allowed_border) * \
(y1 >= -allowed_border) * \
F.broadcast_lesser(y2, h + allowed_border) # (n, h * w * #anchor)
######################## assgining #######################
iou_a2gt_list = list()
for i in range(num_image):
anchors_this = F.slice_axis(anchors, axis=0, begin=i, end=i+1).reshape([-1, 4])
gt_bboxes_this = F.slice_axis(gt_bboxes, axis=0, begin=i, end=i+1).reshape([-1, 4])
iou_a2gt_this = F.contrib.box_iou(anchors_this, gt_bboxes_this, format="corner") # (h * w * #anchor, #gt)
iou_a2gt_list.append(iou_a2gt_this)
iou_a2gt = F.stack(*iou_a2gt_list, axis=0) # (n, h * w * #anchor, #gt)
matched_gt_idx = F.argmax(iou_a2gt, axis=-1) # (n, h * w * #anchor)
max_iou_a = F.max(iou_a2gt, axis=-1) # (n, h * w * #anchor)
max_iou_gt = F.max(iou_a2gt, axis=-2) # (n, #gt)
# choose anchors with IoU < bg_thr
matched = max_iou_a < bg_thr
rpn_cls_label = F.where(matched * valid, F.zeros_like(rpn_cls_label), rpn_cls_label)
# choose anchors with max IoU to gts
max_iou_gt = F.expand_dims(max_iou_gt, axis=1) # (n, 1, #gt)
matched = F.broadcast_equal(iou_a2gt, max_iou_gt) * (iou_a2gt > 0) # (n, h * w * #anchor, #gt)
matched = F.sum(matched, axis=-1) # (n, h * w * #anchor)
matched = matched > 0
rpn_cls_label = F.where(matched * valid, F.ones_like(rpn_cls_label), rpn_cls_label)
# choose anchors with IoU >= fg_thr
matched = max_iou_a >= fg_thr
rpn_cls_label = F.where(matched * valid, F.ones_like(rpn_cls_label), rpn_cls_label)
######################## sampling ##########################
# rpn_cls_label is 1 for fg, 0 for bg and -1 for ignore
############################################################
# simulate random sampling by add a random number [0, 0.5] to each label and sort
randp = F.random.uniform(0, 0.5, shape=(num_image, max_side ** 2 * num_anchor))
randp = F.slice_like(randp, rpn_cls_label)
rpn_cls_label_p = rpn_cls_label + randp
# filter out excessive fg samples
fg_value = F.topk(rpn_cls_label_p, k=int(sample_per_image * fg_fraction), ret_typ='value')
sentinel_value = F.slice_axis(fg_value, axis=-1, begin=-1, end=None) # (n, 1)
matched = rpn_cls_label_p >= 1
matched = matched * F.broadcast_lesser(rpn_cls_label_p, sentinel_value)
rpn_cls_label = F.where(matched, F.ones_like(rpn_cls_label) * -1, rpn_cls_label)
num_pos = (rpn_cls_label == 1).sum(axis=-1, keepdims=True) # (n, 1)
# filter out excessive bg samples
matched = rpn_cls_label_p < 1
rpn_cls_label_p = F.where(matched, rpn_cls_label_p + 3, rpn_cls_label_p)
# now [3, 3.5] for bg, [2, 2.5] for ignore and [1, 1.5] for fg
bg_value = F.topk(rpn_cls_label_p, k=sample_per_image, ret_typ='value')
sentinel_value = F.slice_axis(bg_value, axis=-1, begin=-1, end=None) # (n, 1)
matched = rpn_cls_label_p >= 3
matched = matched * F.broadcast_lesser(rpn_cls_label_p, sentinel_value)
rpn_cls_label = F.where(matched, F.ones_like(rpn_cls_label) * -1, rpn_cls_label)
# simulate num_bg = sample_per_image - num_fg by removing samples with randint < num_bg
matched = rpn_cls_label == 0
randint = F.random.randint(0, sample_per_image, shape=(num_image, max_side ** 2 * num_anchor))
randint = F.slice_like(randint, matched)
randint = randint.astype("float32") * matched
matched = F.where(F.broadcast_lesser(randint, num_pos), matched, F.zeros_like(matched))
rpn_cls_label = F.where(matched, F.ones_like(rpn_cls_label) * -1, rpn_cls_label)
# regression target
matched = (rpn_cls_label == 1).reshape(-1)
ones = F.ones_like(anchors).reshape([-1, 4])
zeros = F.zeros_like(anchors).reshape([-1, 4])
rpn_reg_weight = F.where(matched, ones, zeros)
# get matched gt box
matched_gt_box_list = list()
for i in range(num_image):
matched_gt_idx_this = F.slice_axis(matched_gt_idx, axis=0, begin=i, end=i+1).reshape(-1)
gt_bboxes_this = F.slice_axis(gt_bboxes, axis=0, begin=i, end=i+1).reshape([-1, 4])
matched_gt_box_list.append(F.take(gt_bboxes_this, matched_gt_idx_this))
matched_gt_box = F.stack(*matched_gt_box_list, axis=0)
rpn_reg_target = _bbox_encode(F, anchors, matched_gt_box)
# prepare output, current data order
# rpn_cls_label: [n, #anchor * h' * w']
# rpn_reg_target: [n, #anchor * h' * w', 4]
# rpn_reg_weight: [n, #anchor * h' * w', 4]
rpn_reg_target = F.reshape(rpn_reg_target, shape=(num_image, num_anchor, -1, 4)) # (n, #anchor, h' * w', 4)
rpn_reg_target = F.transpose(rpn_reg_target, axes=(0, 1, 3, 2)) # (n, #anchor, 4, h' * w')
rpn_reg_target = F.reshape(rpn_reg_target, shape=(0, -3, -2))
rpn_reg_weight = F.reshape(rpn_reg_weight, shape=(num_image, num_anchor, -1, 4)) # (n, #anchor, h' * w', 4)
rpn_reg_weight = F.transpose(rpn_reg_weight, axes=(0, 1, 3, 2)) # (n, #anchor, 4, h' * w')
rpn_reg_weight = F.reshape(rpn_reg_weight, shape=(0, -3, -2))
rpn_cls_label = F.identity(rpn_cls_label, name="rpn_cls_label")
rpn_reg_target = F.identity(rpn_reg_target * rpn_reg_weight, name="rpn_reg_target")
rpn_reg_weight = F.identity(rpn_reg_weight, name="rpn_reg_weight")
return rpn_cls_label, rpn_reg_target, rpn_reg_weight
def _rpn_target_batch(F, features, anchors, gt_bboxes, im_infos, num_image, num_anchor,
max_side, feature_stride, allowed_border, sample_per_image, fg_fraction, fg_thr, bg_thr):
max_side = max_side // feature_stride
# prepare output
anchors = F.slice_like(anchors, features, axes=(2, 3)) # (1, 1, h, w, #anchor * 4)
anchors = anchors.reshape([-3, -2]).reshape([0, 0, -1, 4]) # (1, h, w, #anchor, 4)
anchors = F.broadcast_axis(anchors, axis=0, size=num_image) # (n, h, w, #anchor, 4)
cls_label_shape = F.slice_axis(anchors, axis=-1, begin=0, end=1).reshape([num_image, -1]) # (n, h * w * #anchor)
rpn_cls_label = F.ones_like(cls_label_shape) * -1 # -1 for ignore
# prepare anchor, gt, valid
anchors = F.reshape(anchors, shape=(num_image, -1, 4)) # (n, h * w * #anchor, 4)
gt_bboxes # (n, #gt, 4)
im_infos # (n, 3)
h, w, _ = F.split(im_infos, num_outputs=3, axis=-1) # (n, 1)
x1, y1, x2, y2 = F.split(anchors, num_outputs=4, axis=-1, squeeze_axis=True) # (n, h * w * #anchor)
valid = (x1 >= -allowed_border) * \
F.broadcast_lesser(x2, w + allowed_border) * \
(y1 >= -allowed_border) * \
F.broadcast_lesser(y2, h + allowed_border) # (n, h * w * #anchor)
######################## assgining #######################
iou_a2gt_list = list()
for i in range(num_image):
anchors_this = F.slice_axis(anchors, axis=0, begin=i, end=i+1).reshape([-1, 4])
gt_bboxes_this = F.slice_axis(gt_bboxes, axis=0, begin=i, end=i+1).reshape([-1, 4])
iou_a2gt_this = F.contrib.box_iou(anchors_this, gt_bboxes_this, format="corner") # (h * w * #anchor, #gt)
iou_a2gt_list.append(iou_a2gt_this)
iou_a2gt = F.stack(*iou_a2gt_list, axis=0) # (n, h * w * #anchor, #gt)
matched_gt_idx = F.argmax(iou_a2gt, axis=-1) # (n, h * w * #anchor)
max_iou_a = F.max(iou_a2gt, axis=-1) # (n, h * w * #anchor)
max_iou_gt = F.max(iou_a2gt, axis=-2) # (n, #gt)
# choose anchors with IoU < bg_thr
matched = max_iou_a < bg_thr
rpn_cls_label = F.where(matched * valid, F.zeros_like(rpn_cls_label), rpn_cls_label)
# choose anchors with max IoU to gts
max_iou_gt = F.expand_dims(max_iou_gt, axis=1) # (n, 1, #gt)
matched = F.broadcast_equal(iou_a2gt, max_iou_gt) * (iou_a2gt > 0) # (n, h * w * #anchor, #gt)
matched = F.sum(matched, axis=-1) # (n, h * w * #anchor)
matched = matched > 0
rpn_cls_label = F.where(matched * valid, F.ones_like(rpn_cls_label), rpn_cls_label)
# choose anchors with IoU >= fg_thr
matched = max_iou_a >= fg_thr
rpn_cls_label = F.where(matched * valid, F.ones_like(rpn_cls_label), rpn_cls_label)
######################## sampling ##########################
# rpn_cls_label is 1 for fg, 0 for bg and -1 for ignore
############################################################
# simulate random sampling by add a random number [0, 0.5] to each label and sort
randp = F.random.uniform(0, 0.5, shape=(num_image, max_side ** 2 * num_anchor))
randp = F.slice_like(randp, rpn_cls_label)
rpn_cls_label_p = rpn_cls_label + randp
# filter out excessive fg samples
fg_value = F.topk(rpn_cls_label_p, k=int(sample_per_image * fg_fraction), ret_typ='value')
sentinel_value = F.slice_axis(fg_value, axis=-1, begin=-1, end=None) # (n, 1)
matched = rpn_cls_label_p >= 1
matched = matched * F.broadcast_lesser(rpn_cls_label_p, sentinel_value)
rpn_cls_label = F.where(matched, F.ones_like(rpn_cls_label) * -1, rpn_cls_label)
# filter out excessive bg samples
matched = rpn_cls_label_p < 1
rpn_cls_label_p = F.where(matched, rpn_cls_label_p + 3, rpn_cls_label_p)
# now [3, 3.5] for bg, [2, 2.5] for ignore and [1, 1.5] for fg
fg_value = F.topk(rpn_cls_label_p, k=sample_per_image - int(sample_per_image * fg_fraction), ret_typ='value')
sentinel_value = F.slice_axis(fg_value, axis=-1, begin=-1, end=None) # (n, 1)
matched = rpn_cls_label_p >= 3
matched = matched * F.broadcast_lesser(rpn_cls_label_p, sentinel_value)
rpn_cls_label = F.where(matched, F.ones_like(rpn_cls_label) * -1, rpn_cls_label)
# regression target
matched = (rpn_cls_label == 1).reshape(-1)
ones = F.ones_like(anchors).reshape([-1, 4])
zeros = F.zeros_like(anchors).reshape([-1, 4])
rpn_reg_weight = F.where(matched, ones, zeros)
# get matched gt box
matched_gt_box_list = list()
for i in range(num_image):
matched_gt_idx_this = F.slice_axis(matched_gt_idx, axis=0, begin=i, end=i+1).reshape(-1)
gt_bboxes_this = F.slice_axis(gt_bboxes, axis=0, begin=i, end=i+1).reshape([-1, 4])
matched_gt_box_list.append(F.take(gt_bboxes_this, matched_gt_idx_this))
matched_gt_box = F.stack(*matched_gt_box_list, axis=0)
rpn_reg_target = _bbox_encode(F, anchors, matched_gt_box)
# reshape output
rpn_cls_label = F.reshape(rpn_cls_label, shape=(num_image, -1, num_anchor))
rpn_cls_label = F.reshape_like(rpn_cls_label, features, lhs_begin=1, lhs_end=2, rhs_begin=2, rhs_end=4)
rpn_cls_label = F.transpose(rpn_cls_label, axes=(0, 3, 1, 2)).reshape([num_image, -1])
rpn_reg_target = F.reshape(rpn_reg_target, shape=(num_image, -1, num_anchor * 4))
rpn_reg_target = F.reshape_like(rpn_reg_target, features, lhs_begin=1, lhs_end=2, rhs_begin=2, rhs_end=4)
rpn_reg_target = F.transpose(rpn_reg_target, axes=(0, 3, 1, 2))
rpn_reg_weight = F.reshape(rpn_reg_weight, shape=(num_image, -1, num_anchor * 4))
rpn_reg_weight = F.reshape_like(rpn_reg_weight, features, lhs_begin=1, lhs_end=2, rhs_begin=2, rhs_end=4)
rpn_reg_weight = F.transpose(rpn_reg_weight, axes=(0, 3, 1, 2))
return rpn_cls_label, rpn_reg_target, rpn_reg_weight
def test_rpn_target():
import numpy as np
# anchor generation
stride = 16
aspects = (0.5, 1.0, 2.0)
scales = (2, 4, 8, 16, 32)
max_side = 1200
feat_h = 75
feat_w = 50
base_anchor = np.array([0, 0, stride - 1, stride - 1])
w = base_anchor[2] - base_anchor[0] + 1
h = base_anchor[3] - base_anchor[1] + 1
x_ctr = base_anchor[0] + 0.5 * (w - 1)
y_ctr = base_anchor[1] + 0.5 * (h - 1)
w_ratios = np.round(np.sqrt(w * h / aspects))
h_ratios = np.round(w_ratios * aspects)
ws = (np.outer(w_ratios, scales)).reshape(-1)
hs = (np.outer(h_ratios, scales)).reshape(-1)
base_anchor = np.stack(
[x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (hs - 1),
x_ctr + 0.5 * (ws - 1),
y_ctr + 0.5 * (hs - 1)],
axis=1)
shift_x = np.arange(0, max_side // stride, dtype=np.float32) * stride
shift_y = np.arange(0, max_side // stride, dtype=np.float32) * stride
grid_x, grid_y = np.meshgrid(shift_x, shift_y)
grid_x, grid_y = grid_x.reshape(-1), grid_y.reshape(-1)
grid = np.stack([grid_x, grid_y, grid_x, grid_y], axis=1)
all_anchor = grid[:, None, :] + base_anchor[None, :, :]
all_anchor = all_anchor.reshape(1, 1, max_side // stride, max_side // stride, -1)
anchors = mx.nd.array(all_anchor, dtype="float32")
cls_prob = mx.nd.random_normal(0, 1, shape=[1, len(aspects) * len(scales), feat_h, feat_w])
gt_bboxes = mx.nd.array(
[[200, 200, 300, 300],
[300, 300, 500, 500],
[-1, -1, -1, -1],
[200, 200, 300, 300],
[400, 300, 500, 500],
[-1, -1, -1, -1],
]).reshape(2, 3, 4)
im_infos = mx.nd.array([[1200, 800, 2], [1200, 800, 2]]).reshape(2, 3)
rpn_cls_label, rpn_reg_target, rpn_reg_weight = _rpn_target_batch(mx.ndarray, cls_prob,
anchors, gt_bboxes, im_infos, 2, 15, max_side, stride, 0, 256, 0.5, 0.7, 0.3)
print(len(np.where(rpn_cls_label[1].asnumpy() == 0)[0]))
print(np.where(rpn_cls_label[1].asnumpy() > 0))
print(np.where(rpn_reg_weight[1].asnumpy() > 0))
print(rpn_reg_target[1][np.where(rpn_reg_weight[1].asnumpy() > 0)])
rpn_cls_label, rpn_reg_target, rpn_reg_weight = _fpn_rpn_target_batch(mx.ndarray, [cls_prob],
[anchors], gt_bboxes, im_infos, 2, 15, max_side, [stride], 0, 256, 0.5, 0.7, 0.3)
print(len(np.where(rpn_cls_label[1].asnumpy() == 0)[0]))
print(np.where(rpn_cls_label[1].asnumpy() > 0))
print(np.where(rpn_reg_weight[1].asnumpy() > 0))
print(rpn_reg_target[1][np.where(rpn_reg_weight[1].asnumpy() > 0)])
from core.detection_input import AnchorTarget2D
class AnchorTarget2DParam:
class generate:
short = 800 // 16
long = 1200 // 16
stride = 16
scales = (2, 4, 8, 16, 32)
aspects = (0.5, 1.0, 2.0)
class assign:
allowed_border = 0
pos_thr = 0.7
neg_thr = 0.3
min_pos_thr = 0.0
class sample:
image_anchor = 256
pos_fraction = 0.5
anchor_target = AnchorTarget2D(AnchorTarget2DParam)
record = {"im_info": im_infos.asnumpy()[1], "gt_bbox": gt_bboxes.asnumpy()[1]}
anchor_target.apply(record)
print(len(np.where(record["rpn_cls_label"] == 0)[0]))
print(np.where(record["rpn_cls_label"] > 0))
print(np.where(record["rpn_reg_weight"] > 0))
print(record["rpn_reg_target"][np.where(record["rpn_reg_weight"] > 0)])
class AnchorTarget2DParam:
def __init__(self):
self.generate = self._generate()
class _generate:
def __init__(self):
self.stride = (4, 8, 16, 32, 64)
self.short = (200, 100, 50, 25, 13)
self.long = (334, 167, 84, 42, 21)
scales = (8)
aspects = (0.5, 1.0, 2.0)
class assign:
allowed_border = 0
pos_thr = 0.7
neg_thr = 0.3
min_pos_thr = 0.0
class sample:
image_anchor = 256
pos_fraction = 0.5
def test_fpn_rpn_target():
import numpy as np
# anchor generation
strides = (4, 8, 16, 32, 64)
aspects = (0.5, 1.0, 2.0)
scales = (8, )
max_side = 1400
feat_hs = (200, 100, 50, 25, 13)
feat_ws = (334, 167, 84, 42, 21)
anchor_list = []
feat_list = []
for stride, feat_h, feat_w in zip(strides, feat_hs, feat_ws):
base_anchor = np.array([0, 0, stride - 1, stride - 1])
w = base_anchor[2] - base_anchor[0] + 1
h = base_anchor[3] - base_anchor[1] + 1
x_ctr = base_anchor[0] + 0.5 * (w - 1)
y_ctr = base_anchor[1] + 0.5 * (h - 1)
w_ratios = np.round(np.sqrt(w * h / aspects))
h_ratios = np.round(w_ratios * aspects)
ws = (np.outer(w_ratios, scales)).reshape(-1)
hs = (np.outer(h_ratios, scales)).reshape(-1)
base_anchor = np.stack(
[x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (hs - 1),
x_ctr + 0.5 * (ws - 1),
y_ctr + 0.5 * (hs - 1)],
axis=1)
shift_x = np.arange(0, max_side // stride, dtype=np.float32) * stride
shift_y = np.arange(0, max_side // stride, dtype=np.float32) * stride
grid_x, grid_y = np.meshgrid(shift_x, shift_y)
grid_x, grid_y = grid_x.reshape(-1), grid_y.reshape(-1)
grid = np.stack([grid_x, grid_y, grid_x, grid_y], axis=1)
all_anchor = grid[:, None, :] + base_anchor[None, :, :]
all_anchor = all_anchor.reshape(1, 1, max_side // stride, max_side // stride, -1)
anchors = mx.nd.array(all_anchor, dtype="float32")
cls_prob = mx.nd.random_normal(0, 1, shape=[1, len(aspects) * len(scales), feat_h, feat_w])
anchor_list.append(anchors)
feat_list.append(cls_prob)
gt_bboxes = mx.nd.array(
[[217.62, 240.54, 255.61, 297.29],
[ 1. , 240.24, 346.63, 426. ],
[388.66, 69.92, 497.07, 346.54],
[135.57, 249.43, 156.89, 277.22],
# [ 31.28, 344. , 98.4 , 383.83],
# [ 59.63, 287.36, 134.7 , 327.66],
# [ 1.36, 164.33, 192.92, 261.7 ],
# [ 0. , 262.81, 61.16, 298.58],
# [119.4 , 272.51, 143.22, 305.76],
# [141.47, 267.91, 172.66, 302.77],
# [155.97, 168.95, 181. , 185.08],
# [157.2 , 114.15, 174.06, 128.97],
# [ 98.75, 304.78, 108.53, 309.35],
# [166.03, 256.36, 173.85, 273.94],
# [ 86.41, 293.97, 109.37, 304.15],
# [ 70.14, 296.16, 78.42, 299.74],
# [ 0. , 210.9 , 190.36, 308.88],
# [ 96.69, 297.09, 103.53, 300.95],
# [497.25, 203.4 , 618.26, 231.01],
[-1, -1, -1, -1],
[217.62, 240.54, 255.61, 297.29],
[ 1. , 240.24, 346.63, 426. ],
[388.66, 69.92, 497.07, 346.54],
[135.57, 249.43, 156.89, 277.22],
# [ 31.28, 344. , 98.4 , 383.83],
# [ 59.63, 287.36, 134.7 , 327.66],
# [ 1.36, 164.33, 192.92, 261.7 ],
# [ 0. , 262.81, 61.16, 298.58],
# [119.4 , 272.51, 143.22, 305.76],
# [141.47, 267.91, 172.66, 302.77],
# [155.97, 168.95, 181. , 185.08],
# [157.2 , 114.15, 174.06, 128.97],
# [ 98.75, 304.78, 108.53, 309.35],
# [166.03, 256.36, 173.85, 273.94],
# [ 86.41, 293.97, 109.37, 304.15],
# [ 70.14, 296.16, 78.42, 299.74],
# [ 0. , 210.9 , 190.36, 308.88],
# [ 96.69, 297.09, 103.53, 300.95],
# [497.25, 203.4 , 618.26, 231.01],
[-1, -1, -1, -1]]).reshape(2, 5, 4)
im_infos = mx.nd.array([[800, 1077, 2], [800, 1077, 2]]).reshape(2, 3)
rpn_cls_label, rpn_reg_target, rpn_reg_weight = _fpn_rpn_target_batch(mx.ndarray, feat_list,
anchor_list, gt_bboxes, im_infos, 2, 3, max_side, strides, 0, 256, 0.5, 0.7, 0.3)
print(len(np.where(rpn_cls_label[1].asnumpy() == 0)[0]))
print(np.where(rpn_cls_label[1].asnumpy() > 0))
# print(np.where(rpn_reg_weight[1].asnumpy() > 0))
# print(rpn_reg_target[1][np.where(rpn_reg_weight[1].asnumpy() > 0)])
class AnchorTarget2DParam:
def __init__(self):
self.generate = self._generate()
class _generate:
def __init__(self):
self.stride = (4, 8, 16, 32, 64)
self.short = (200, 100, 50, 25, 13)
self.long = (334, 167, 84, 42, 21)
scales = (8, )
aspects = (0.5, 1.0, 2.0)
class assign:
allowed_border = 0
pos_thr = 0.7
neg_thr = 0.3
min_pos_thr = 0.0
class sample:
image_anchor = 256
pos_fraction = 0.5
from models.FPN.input import PyramidAnchorTarget2D
anchor_target = PyramidAnchorTarget2D(AnchorTarget2DParam())
record = {"im_info": im_infos.asnumpy()[1], "gt_bbox": gt_bboxes.asnumpy()[1]}
anchor_target.apply(record)
print(len(np.where(record["rpn_cls_label"] == 0)[0]))
print(np.where(record["rpn_cls_label"] > 0))
# print(np.where(record["rpn_reg_weight"] > 0))
# print(record["rpn_reg_target"][np.where(record["rpn_reg_weight"] > 0)])
print(np.sum(np.abs(rpn_reg_weight[1].asnumpy() - record["rpn_reg_weight"])))
print(np.sum(np.abs(rpn_reg_target[1].asnumpy() - record["rpn_reg_target"])))
if __name__ == "__main__":
test_fpn_rpn_target()
<file_sep>/mxnext/backbone/resnet_v1d_helper.py
from __future__ import division
from ..simple import reluconv, conv, pool, relu, add, whiten, var, fixbn, to_fp16, avg_pool
from ..complicate import normalizer_factory
depth_config = {
50: (3, 4, 6, 3),
101: (3, 4, 23, 3),
152: (3, 8, 36, 3),
200: (3, 24, 36, 3)
}
def resnet_unit(data, name, filter, stride, dilate, proj, norm):
conv1 = conv(data, name=name + "_conv1", filter=filter // 4)
bn1 = norm(data=conv1, name=name + "_bn1")
relu1 = relu(bn1, name=name + "_relu1")
conv2 = conv(relu1, name=name + "_conv2", filter=filter // 4, kernel=3, stride=stride, dilate=dilate)
bn2 = norm(data=conv2, name=name + "_bn2")
relu2 = relu(bn2, name=name + "_relu2")
conv3 = conv(relu2, name=name + "_conv3", filter=filter)
bn3 = norm(data=conv3, name=name + "_bn3")
if proj:
if not name.startswith("stage1"):
shortcut = avg_pool(data, stride=stride, pad=0, pooling_convention="full", name=name + "_avgpool")
else:
shortcut = data
shortcut = conv(shortcut, name=name + "_sc", filter=filter)
shortcut = norm(shortcut, name=name + "_sc_bn")
else:
shortcut = data
eltwise = add(bn3, shortcut, name=name + "_plus")
return relu(eltwise, name=name + "_relu")
def resnet_stage(data, name, num_block, filter, stride, dilate, norm):
s, d = stride, dilate
data = resnet_unit(data, "{}_unit1".format(name), filter, s, d, True, norm)
for i in range(2, num_block + 1):
data = resnet_unit(data, "{}_unit{}".format(name, i), filter, 1, d, False, norm)
return data
def resnet_c1(data, norm):
data = conv(data, filter=32, kernel=3, stride=2, name="conv0_0")
data = norm(data, name='bn0_0')
data = relu(data, name='relu0_0')
data = conv(data, filter=32, kernel=3, name="conv0_1")
data = norm(data, name='bn0_1')
data = relu(data, name='relu0_1')
data = conv(data, filter=64, kernel=3, name="conv0_2")
data = norm(data, name='bn0_2')
data = relu(data, name='relu0_2')
data = pool(data, name="pool0", kernel=3, stride=2, pool_type='max')
return data
def resnet_c2(data, num_block, stride, dilate, norm):
return resnet_stage(data, "stage1", num_block, 256, stride, dilate, norm)
def resnet_c3(data, num_block, stride, dilate, norm):
return resnet_stage(data, "stage2", num_block, 512, stride, dilate, norm)
def resnet_c4(data, num_block, stride, dilate, norm):
return resnet_stage(data, "stage3", num_block, 1024, stride, dilate, norm)
def resnet_c5(data, num_block, stride, dilate, norm):
return resnet_stage(data, "stage4", num_block, 2048, stride, dilate, norm)
<file_sep>/mxnext/initializer.py
# encoding: utf-8
"""
MXNeXt is a wrapper around the original MXNet Symbol API
@version: 0.1
@author: <NAME>
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mxnet as mx
import numpy as np
from mxnet.initializer import Initializer, register
def gauss(std):
return mx.init.Normal(sigma=std)
def one_init():
return mx.init.One()
def zero_init():
return mx.init.Zero()
def constant(val):
return mx.init.Constant(val)
@register
class Custom(Initializer):
def __init__(self, arr):
super(Custom, self).__init__(arr=arr)
self.arr = arr
def _init_weight(self, _, arr):
val = mx.nd.array(self.arr)
assert val.size == arr.size, "init shape {} is not compatible with weight shape {}".format(val.shape, arr.shape)
arr[:] = val.reshape_like(arr)
def custom(arr):
return Custom(arr)
<file_sep>/mxnext/backbone/resnext.py
from __future__ import division
from ..simple import reluconv, conv, pool, relu, add, whiten, var, fixbn, to_fp16
from ..complicate import normalizer_factory
__all__ = ["Builder"]
class Builder(object):
depth_config = {
50: (3, 4, 6, 3),
101: (3, 4, 23, 3),
152: (3, 8, 36, 3),
200: (3, 24, 36, 3)
}
@classmethod
def resnext_unit(cls, data, name, filter, stride, dilate, proj, num_group, norm_type, norm_mom, ndev):
"""
One resnext unit is comprised of 2 or 3 convolutions and a shortcut.
:param data:
:param name:
:param filter:
:param stride:
:param dilate:
:param proj:
:param num_group:
:param norm_type:
:param norm_mom:
:param ndev:
:return:
"""
norm = normalizer_factory(type=norm_type, ndev=ndev, mom=norm_mom)
if num_group == 32:
multip_factor = 0.5
elif num_group == 64:
multip_factor = 1.0
conv1 = conv(data=data, name=name + "_conv1", filter=int(filter * multip_factor))
bn1 = norm(data=conv1, name=name + "_bn1")
relu1 = relu(bn1)
conv2 = conv(data=relu1, name=name + "_conv2", filter=int(filter * multip_factor), kernel=3,
num_group=num_group, stride=stride, dilate=dilate)
bn2 = norm(data=conv2, name=name + "_bn2")
relu2 = relu(bn2)
conv3 = conv(data=relu2, name=name + "_conv3", filter=filter)
bn3 = norm(data=conv3, name=name + "_bn3")
if proj:
shortcut_conv = conv(data, name=name + "_sc", filter=filter, stride=stride)
shortcut = norm(data=shortcut_conv, name=name + "_sc_bn")
else:
shortcut = data
return relu(add(bn3, shortcut, name=name + "_plus"))
@classmethod
def resnext_stage(cls, data, name, num_block, filter, stride, dilate, num_group, norm_type, norm_mom, ndev):
"""
One resnext stage is comprised of multiple resnext units. Refer to depth config for more information.
:param data:
:param name:
:param num_block:
:param filter:
:param stride:
:param dilate:
:param norm_type:
:param norm_mom:
:param ndev:
:return:
"""
s, d = stride, dilate
data = cls.resnext_unit(data, "{}_unit1".format(name), filter, s, d, True, num_group, norm_type, norm_mom, ndev)
for i in range(2, num_block + 1):
data = cls.resnext_unit(data, "{}_unit{}".format(name, i), filter, 1, d, False, num_group, norm_type, norm_mom, ndev)
return data
@classmethod
def resnext_c1(cls, data, use_3x3_conv0, use_bn_preprocess, norm_type, norm_mom, ndev):
"""
Resnext C1 is comprised of irregular initial layers.
:param data: image symbol
:param use_3x3_conv0: use three 3x3 convs to replace one 7x7 conv
:param use_bn_preprocess: use batchnorm as the whitening layer, introduced by tornadomeet
:param norm_type: normalization method of activation, could be local, fix, sync, gn, in, ibn
:param norm_mom: normalization momentum, specific to batchnorm
:param ndev: num of gpus for sync batchnorm
:return: C1 symbol
"""
# preprocess
if use_bn_preprocess:
data = whiten(data, name="bn_data")
norm = normalizer_factory(type=norm_type, ndev=ndev, mom=norm_mom)
# C1
if use_3x3_conv0:
data = conv(data, filter=64, kernel=3, stride=2, name="conv0_0")
data = norm(data, name='bn0_0')
data = relu(data, name='relu0_0')
data = conv(data, filter=64, kernel=3, name="conv0_1")
data = norm(data, name='bn0_1')
data = relu(data, name='relu0_1')
data = conv(data, filter=64, kernel=3, name="conv0_2")
data = norm(data, name='bn0_2')
data = relu(data, name='relu0_2')
else:
data = conv(data, filter=64, kernel=7, stride=2, name="conv0")
data = norm(data, name='bn0')
data = relu(data, name='relu0')
data = pool(data, name="pool0", kernel=3, stride=2, pool_type='max')
return data
@classmethod
def resnext_c2(cls, data, num_block, stride, dilate, num_group, norm_type, norm_mom, ndev):
return cls.resnext_stage(data, "stage1", num_block, 256, stride, dilate, num_group, norm_type, norm_mom, ndev)
@classmethod
def resnext_c3(cls, data, num_block, stride, dilate, num_group, norm_type, norm_mom, ndev):
return cls.resnext_stage(data, "stage2", num_block, 512, stride, dilate, num_group, norm_type, norm_mom, ndev)
@classmethod
def resnext_c4(cls, data, num_block, stride, dilate, num_group, norm_type, norm_mom, ndev):
return cls.resnext_stage(data, "stage3", num_block, 1024, stride, dilate, num_group, norm_type, norm_mom, ndev)
@classmethod
def resnext_c5(cls, data, num_block, stride, dilate, num_group, norm_type, norm_mom, ndev):
return cls.resnext_stage(data, "stage4", num_block, 2048, stride, dilate, num_group, norm_type, norm_mom, ndev)
@classmethod
def resnext_factory(cls, depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type="local", norm_mom=0.9, ndev=None, fp16=False):
num_c2_unit, num_c3_unit, num_c4_unit, num_c5_unit = cls.depth_config[depth]
data = var("data")
if fp16:
data = to_fp16(data, "data_fp16")
c1 = cls.resnext_c1(data, use_3x3_conv0, use_bn_preprocess, norm_type, norm_mom, ndev)
c2 = cls.resnext_c2(c1, num_c2_unit, 1, 1, num_group, norm_type, norm_mom, ndev)
c3 = cls.resnext_c3(c2, num_c3_unit, 2, 1, num_group, norm_type, norm_mom, ndev)
c4 = cls.resnext_c4(c3, num_c4_unit, 2, 1, num_group, norm_type, norm_mom, ndev)
c5 = cls.resnext_c5(c4, num_c5_unit, 2, 1, num_group, norm_type, norm_mom, ndev)
return c1, c2, c3, c4, c5
@classmethod
def resnext_c4_factory(cls, depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type="local", norm_mom=0.9, ndev=None, fp16=False):
c1, c2, c3, c4, c5 = cls.resnext_factory(depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type, norm_mom, ndev, fp16)
return c4
@classmethod
def resnext_c5_factory(cls, depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type="local", norm_mom=0.9, ndev=None, fp16=False):
c1, c2, c3, c4, c5 = cls.resnext_factory(depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type, norm_mom, ndev, fp16)
return c5
@classmethod
def resnext_c4c5_factory(cls, depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type="local", norm_mom=0.9, ndev=None, fp16=False):
c1, c2, c3, c4, c5 = cls.resnext_factory(depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type, norm_mom, ndev, fp16)
return c4, c5
@classmethod
def resnext_fpn_factory(cls, depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type="local", norm_mom=0.9, ndev=None, fp16=False):
c1, c2, c3, c4, c5 = cls.resnext_factory(depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type, norm_mom, ndev, fp16)
return c2, c3, c4, c5
def get_backbone(self, variant, depth, endpoint, normalizer, num_group, fp16):
# parse variant
if variant == "mxnet":
use_bn_preprocess = True
use_3x3_conv0 = False
else:
raise KeyError("Unknown backbone variant {}".format(variant))
# parse endpoint
if endpoint == "c4":
factory = self.resnext_c4_factory
elif endpoint == "c5":
factory = self.resnext_c5_factory
elif endpoint == "c4c5":
factory = self.resnext_c4c5_factory
elif endpoint == "fpn":
factory = self.resnext_fpn_factory
else:
raise KeyError("Unknown backbone endpoint {}".format(endpoint))
return factory(depth, use_3x3_conv0, use_bn_preprocess, num_group, norm_type=normalizer, fp16=fp16)
# TODO: hook import with ResNeXtV1Builder
# import sys
# sys.modules[__name__] = ResNeXtV1Builder()
if __name__ == "__main__":
#############################################################
# python -m mxnext.backbone.resnext
#############################################################
h = Builder()
sym = h.get_backbone("mxnet", 50, "fpn", normalizer_factory(type="fixbn"), 32, fp16=True)
import mxnet as mx
sym = mx.sym.Group(sym)
mx.viz.print_summary(sym)
<file_sep>/mxnext/tvm/proposal.py
from mxnext.tvm.decode_bbox import decode_bbox
import mxnet as mx
def proposal(cls_prob, bbox_pred, im_info, anchors, rpn_pre_nms_top_n, rpn_post_nms_top_n,
threshold, scales, ratios, feature_stride, batch_size, max_side,
output_score=False, name=None, variant="tvm"):
with mx.name.Prefix("proposal: "):
return _proposal(F=mx.symbol, cls_prob=cls_prob, bbox_pred=bbox_pred,
im_info=im_info, anchors=anchors, batch_size=batch_size, max_side=max_side,
rpn_pre_nms_top_n=rpn_pre_nms_top_n, rpn_post_nms_top_n=rpn_post_nms_top_n,
threshold=threshold, scales=scales, ratios=ratios, feature_stride=feature_stride,
output_score=output_score, variant=variant)
def _proposal(
F=mx.ndarray,
cls_prob=None,
bbox_pred=None,
anchors=None,
im_info=None,
batch_size=1,
max_side=-1,
rpn_pre_nms_top_n=None,
rpn_post_nms_top_n=None,
threshold=None,
rpn_min_size=None,
scales=None,
ratios=None,
feature_stride=None,
output_score=None,
variant=None):
"""
cls_prob: (#img, #anchor * 2, h, w) or (#img, #anchor, h, w)
bbox_pred: (#img, #anchor * 4, h, w)
im_info: (#img, 3), [valid_h, valid_w, scale]
Returns:
proposal: (#img, #proposal, 4) or (#img * #proposal, 5)
proposal_score: (#img, #proposal, 1) or (#img * #proposal, 1)
"""
########### constant ##########
num_anchor = len(scales) * len(ratios)
max_side = max_side // feature_stride
########### meshgrid ##########
xx = F.arange(0, max_side).reshape([1, max_side])
xx = F.broadcast_axis(xx, axis=0, size=max_side).reshape([1, 1, max_side, max_side])
xx = F.slice_like(xx, cls_prob, axes=(2, 3))
xx = F.broadcast_axis(xx, axis=0, size=batch_size).reshape([batch_size, -1])
yy = F.arange(0, max_side).reshape([max_side, 1])
yy = F.broadcast_axis(yy, axis=1, size=max_side).reshape([1, 1, max_side, max_side])
yy = F.slice_like(yy, cls_prob, axes=(2, 3))
yy = F.broadcast_axis(yy, axis=0, size=batch_size).reshape([batch_size, -1])
########### slice anchor ##########
anchors = F.slice_like(anchors, cls_prob, axes=(2, 3)) # (1, 1, h, w, #anchor * 4)
anchors = F.reshape(anchors, [-3, -2]) # (1, h, w, #anchor * 4), fold first two axes
anchors = F.broadcast_axis(anchors, axis=0, size=batch_size) # (#img, h, w, #anchor * 4)
anchors = anchors.reshape([0, -1, 4]) # (#img, h * w * #anchor, 4)
########### argsort ##########
cls_prob = F.slice_axis(cls_prob, axis=1, begin=-num_anchor, end=None)
cls_prob = F.transpose(cls_prob, axes=[0, 2, 3, 1]) # (#img, h, w, #anchor)
cls_prob = F.reshape(cls_prob, shape=[-1, num_anchor])
cls_prob = F.where(F.broadcast_lesser(xx, F.floor(im_info.slice_axis(axis=1, begin=1, end=2) / feature_stride)).reshape(-1), cls_prob, -F.ones_like(cls_prob))
cls_prob = F.where(F.broadcast_lesser(yy, F.floor(im_info.slice_axis(axis=1, begin=0, end=1) / feature_stride)).reshape(-1), cls_prob, -F.ones_like(cls_prob))
cls_prob = F.reshape(cls_prob, shape=[batch_size, -1]) # (#img, h * w * #anchor)
bbox_pred = F.transpose(bbox_pred, axes=[0, 2, 3, 1]) # (#img, h, w, #anchor * 4)
bbox_pred = F.reshape(bbox_pred, shape=[0, 0, 0, -4, -1, 4]) # (#img, h, w, #anchor, 4)
bbox_pred = F.reshape(bbox_pred, shape=[0, -1, 4]) # (#img, h * w * #anchor, 4)
argsort_cls_prob = F.argsort(cls_prob, axis=-1, is_ascend=False)
argsort_cls_prob = F.slice_axis(argsort_cls_prob, axis=-1, begin=0, end=rpn_pre_nms_top_n)
arange_index = F.arange(0, batch_size).reshape([batch_size, 1])
arange_index = F.broadcast_axis(arange_index, axis=1, size=rpn_pre_nms_top_n).reshape(-1)
top_indexes = F.stack(arange_index, argsort_cls_prob.reshape(-1).astype("float32"))
sort_cls_prob = F.gather_nd(cls_prob, top_indexes).reshape([-4, -1, rpn_pre_nms_top_n, 1]) # (#img, #proposal, 1)
sort_bbox_pred = F.gather_nd(bbox_pred, top_indexes).reshape([-4, -1, rpn_pre_nms_top_n, 4]) # (#img, #proposal, 4)
sort_anchor = F.gather_nd(anchors, top_indexes).reshape([-4, -1, rpn_pre_nms_top_n, 4]) # (#img, #proposal, 4)
########### decode ###########
bbox = decode_bbox(F, sort_anchor, sort_bbox_pred, im_info,
(0, 0, 0, 0), (1, 1, 1, 1), True)
# return bbox, sort_cls_prob
########### nms ############
# TVM only works for 6-tuple bbox, make it happy
# 6-tuple bbox is (class_id, score, x1, y1, x2, y2)
score_bbox = F.concat(F.zeros_like(sort_cls_prob), sort_cls_prob, bbox, dim=-1)
bbox = F.contrib.box_nms(score_bbox, overlap_thresh=threshold, id_index=0)
bbox_score = F.slice_axis(bbox, axis=-1, begin=1, end=2)
bbox_score = F.slice_axis(bbox_score, axis=1, begin=0, end=rpn_post_nms_top_n)
bbox_coord = F.slice_axis(bbox, axis=-1, begin=-4, end=None)
bbox_coord = F.slice_axis(bbox_coord, axis=1, begin=0, end=rpn_post_nms_top_n)
# bbox_pad = F.broadcast_axis(F.slice_axis(bbox_coord, axis=1, begin=0, end=1), axis=1, size=rpn_post_nms_top_n)
# bbox_coord = F.where(bbox_coord >= 0, bbox_coord, bbox_pad)
################ formatting ##################
if variant == "simpledet":
pass
elif variant == "tvm":
roi_index = F.arange(0, batch_size).reshape([batch_size, 1, 1])
roi_index = F.broadcast_axis(roi_index, axis=1, size=rpn_post_nms_top_n)
bbox_coord = F.concat(roi_index, bbox_coord, dim=-1)
bbox_coord = F.reshape(bbox_coord, [-3, -2])
bbox_score = F.reshape(bbox_score, [-3, -2])
else:
raise ValueError("Unknown proposal variant: {}".format(variant))
if output_score:
return bbox_coord, bbox_score
else:
return bbox_coord
def test_meshgrid():
h = 7
w = 10
shift_x = mx.nd.arange(0, w, repeat=h)
grid_x = shift_x.reshape([w, h]).transpose()
shift_y = mx.nd.arange(0, h, repeat=w)
grid_y = shift_y.reshape([h, w])
grid_x, grid_y = grid_x.reshape(-1), grid_y.reshape(-1)
print(grid_x)
print(grid_y)
import numpy as np
shift_x = np.arange(0, w, dtype=np.float32)
shift_y = np.arange(0, h, dtype=np.float32)
grid_x, grid_y = np.meshgrid(shift_x, shift_y)
grid_x, grid_y = grid_x.reshape(-1), grid_y.reshape(-1)
print(grid_x)
print(grid_y)
def test_proposal():
import numpy as np
# anchor generation
stride = 16
aspects = (0.5, 1.0, 2.0)
scales = (2, 4, 8, 16, 32)
max_side = 1200
feat_h = 75
feat_w = 50
base_anchor = np.array([0, 0, stride - 1, stride - 1])
w = base_anchor[2] - base_anchor[0] + 1
h = base_anchor[3] - base_anchor[1] + 1
x_ctr = base_anchor[0] + 0.5 * (w - 1)
y_ctr = base_anchor[1] + 0.5 * (h - 1)
w_ratios = np.round(np.sqrt(w * h / aspects))
h_ratios = np.round(w_ratios * aspects)
ws = (np.outer(w_ratios, scales)).reshape(-1)
hs = (np.outer(h_ratios, scales)).reshape(-1)
base_anchor = np.stack(
[x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (hs - 1),
x_ctr + 0.5 * (ws - 1),
y_ctr + 0.5 * (hs - 1)],
axis=1)
shift_x = np.arange(0, max_side // stride, dtype=np.float32) * stride
shift_y = np.arange(0, max_side // stride, dtype=np.float32) * stride
grid_x, grid_y = np.meshgrid(shift_x, shift_y)
grid_x, grid_y = grid_x.reshape(-1), grid_y.reshape(-1)
grid = np.stack([grid_x, grid_y, grid_x, grid_y], axis=1)
all_anchor = grid[:, None, :] + base_anchor[None, :, :]
all_anchor = all_anchor.reshape(1, 1, max_side // stride, max_side // stride, -1)
cls_prob = mx.nd.random_normal(0, 1, shape=[1, len(aspects) * len(scales), feat_h, feat_w])
cls_prob = mx.nd.concat(mx.nd.zeros_like(cls_prob), cls_prob, dim=1)
bbox_pred = mx.nd.random_normal(0, 0.1, shape=[1, len(aspects) * len(scales) * 4, feat_h, feat_w])
im_info = mx.nd.array([[1111, 701, 1.0]])
anchors = mx.nd.array(all_anchor, dtype="float32")
bbox1 = mx.nd.contrib.Proposal(
cls_prob, bbox_pred, im_info, 10, 10, 0.01, 0, scales, aspects, stride, False, False
)
print(bbox1)
bbox2 = _proposal(F=mx.ndarray, cls_prob=cls_prob, bbox_pred=bbox_pred, anchors=anchors,
im_info=im_info, batch_size=1, max_side=max_side, rpn_pre_nms_top_n=10, rpn_post_nms_top_n=10,
threshold=0.01, rpn_min_size=0, scales=scales, ratios=aspects, feature_stride=stride,
variant="tvm")
print(bbox2)
# print(bbox1 - bbox2[0])
if __name__ == "__main__":
mx.random.seed(123)
test_proposal()
<file_sep>/mxnext/backbone/resnext_helper.py
from __future__ import division
from ..simple import reluconv, conv, pool, relu, add, whiten, var, fixbn, to_fp16
from ..complicate import normalizer_factory
depth_config = {
50: (3, 4, 6, 3),
101: (3, 4, 23, 3),
152: (3, 8, 36, 3),
200: (3, 24, 36, 3)
}
def resnext_unit(data, name, filter, stride, dilate, proj, group, channel_per_group, norm):
conv1 = conv(data=data, name=name + "_conv1", filter=group * channel_per_group * filter // 256)
bn1 = norm(data=conv1, name=name + "_bn1")
relu1 = relu(bn1)
conv2 = conv(data=relu1, name=name + "_conv2", filter=group * channel_per_group * filter // 256, kernel=3, num_group=group, stride=stride, dilate=dilate)
bn2 = norm(data=conv2, name=name + "_bn2")
relu2 = relu(bn2)
conv3 = conv(data=relu2, name=name + "_conv3", filter=filter)
bn3 = norm(data=conv3, name=name + "_bn3")
if proj:
shortcut_conv = conv(data, name=name + "_sc", filter=filter, stride=stride)
shortcut = norm(data=shortcut_conv, name=name + "_sc_bn")
else:
shortcut = data
eltwise = add(bn3, shortcut, name=name + "_plus")
return relu(eltwise, name=name + "_relu")
def resnext_stage(data, name, num_block, filter, stride, dilate, group, channel_per_group, norm):
s, d = stride, dilate
data = resnext_unit(data, "{}_unit1".format(name), filter, s, d, True, group, channel_per_group, norm)
for i in range(2, num_block + 1):
data = resnext_unit(data, "{}_unit{}".format(name, i), filter, 1, d, False, group, channel_per_group, norm)
return data
def resnext_c1(data, norm):
data = conv(data, filter=64, kernel=7, stride=2, name="conv0")
data = norm(data, name='bn0')
data = relu(data, name='relu0')
data = pool(data, name="pool0", kernel=3, stride=2, pool_type='max')
return data
def resnext_c2(data, num_block, stride, dilate, group, channel_per_group, norm):
return resnext_stage(data, "stage1", num_block, 256, stride, dilate, group, channel_per_group, norm)
def resnext_c3(data, num_block, stride, dilate, group, channel_per_group, norm):
return resnext_stage(data, "stage2", num_block, 512, stride, dilate, group, channel_per_group, norm)
def resnext_c4(data, num_block, stride, dilate, group, channel_per_group, norm):
return resnext_stage(data, "stage3", num_block, 1024, stride, dilate, group, channel_per_group, norm)
def resnext_c5(data, num_block, stride, dilate, group, channel_per_group, norm):
return resnext_stage(data, "stage4", num_block, 2048, stride, dilate, group, channel_per_group, norm)
<file_sep>/doc/monkey.md
### Monkey Patch Technique for Extending Existing Operators
```python
# file: monkey.py
import config
import mxnext as X
old_conv = X.conv
def conv(**kwargs):
# Do anything you want here according to config
# Thus config will never contaminate the wrapper
return old_conv(**kwargs)
X.conv = conv
```
```python
# file: start_point.py
import monkey # import monkey patch before import mxnext
import mxnext as X
```<file_sep>/mxnext/__init__.py
from .simple import *
from .complicate import *
from .initializer import *
from .debug import *
<file_sep>/mxnext/debug.py
"""
Debug Op
author: <NAME>
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
import marshal
import types
import uuid
import mxnet as mx
import numpy as np
__all__ = ["forward_debug", "backward_debug"]
np.set_printoptions(threshold=np.inf, precision=4, linewidth=120)
class DebugOperator(mx.operator.CustomOp):
def __init__(self, **kwargs):
super(DebugOperator, self).__init__()
self.pos = kwargs.get("pos", None)
self.num_args = int(kwargs.get("num_args", 1))
self.do_forward = bool(kwargs.get("do_forward", False))
self.do_backward = bool(kwargs.get("do_backward", False))
if "callback" in kwargs:
callback_func_code = marshal.loads(json.loads(kwargs["callback"]).encode("latin"))
self.callback = types.FunctionType(callback_func_code, globals())
def forward(self, is_train, req, in_data, out_data, aux):
if self.do_forward:
aux[0] += 1
in_data_cpu = [aux[0].context.device_id] + [aux[0].asscalar()] + [_.asnumpy() for _ in in_data]
self.callback(*in_data_cpu)
for o, r, i in zip(out_data, req, in_data):
self.assign(o, r, i)
def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
if self.do_backward:
aux[0] += 1
out_grad_cpu = [aux[0].context.device_id] + [aux[0].asscalar()] + [_.asnumpy() for _ in out_grad]
self.callback(*out_grad_cpu)
for i, r, o in zip(in_grad, req, out_grad):
self.assign(i, r, o)
@mx.operator.register("Debug")
class DebugProp(mx.operator.CustomOpProp):
def __init__(self, **kwargs):
super(DebugProp, self).__init__(need_top_grad=True)
self._kwargs = kwargs
def list_arguments(self):
inputs = ['data']
num_args = int(self._kwargs.get("num_args", 1))
for i in range(1, num_args):
inputs.append("data%d" % i)
return inputs
def list_auxiliary_states(self):
return ["num_iter"]
def list_outputs(self):
outputs = ['output']
num_args = int(self._kwargs.get("num_args", 1))
for i in range(1, num_args):
outputs.append("output%d" % i)
return outputs
def declare_backward_dependency(self, out_grad, in_data, out_data):
return out_grad
def infer_shape(self, in_shape):
return in_shape, in_shape, [(1, )]
def create_operator(self, ctx, shapes, dtypes):
return DebugOperator(**self._kwargs)
def Debug(data, type="nchw", num_args=1, **kwargs):
kwargs.update({"pos": type, "data": data, "num_args": num_args, "do_forward": True})
return mx.sym.Custom(op_type="Debug", **kwargs)
def default_print_function(dev_id, num_iter, *inputs):
if dev_id == 0:
print("num_iter: {}".format(num_iter))
for i, input in enumerate(inputs):
print("input{}: {}".format(i, input))
def forward_debug(*data, callback=None, **kwargs):
"""
Args:
data: Iterable[mx.Symbol], symbols we want to get the output
callback: a callable with signature (dev_id, num_iter, *data) -> None.
The callback will receive a list of mx.ndarray as the same order of symbols.
You can print or save the ndarray for debug usage.
Returns:
data: Iterable[mx.Symbol], the same symbols as the inputs
"""
kwargs.update({"data": data[0], "num_args": len(data), "do_forward": True})
# if len(input_symbols) > 1, give them names
for i, v in enumerate(data[1:], start=1):
kwargs.update({"data%d" % i: v})
callback = callback or default_print_function
callback_code = marshal.dumps(callback.__code__)
kwargs["callback"] = json.dumps(callback_code.decode("latin"))
num_iter = mx.sym.var("num_iter_{}".format(uuid.uuid4()), init=mx.init.Constant(0))
return mx.sym.Custom(op_type="Debug", num_iter=num_iter, **kwargs)
def backward_debug(*data, callback=None, **kwargs):
"""
Args:
data: Iterable[mx.Symbol], symbols we want to get the output
callback: a callable with signature (dev_id, num_iter, *data) -> None.
The callback will receive a list of mx.ndarray as the same order of symbols.
You can print or save the ndarray for debug usage.
Returns:
data: Iterable[mx.Symbol], the same symbols as the inputs
"""
kwargs.update({"data": data[0], "num_args": len(data), "do_backward": True})
# if len(input_symbols) > 1, give them names
for i, v in enumerate(data[1:], start=1):
kwargs.update({"data%d" % i: v})
callback = callback or default_print_function
callback_code = marshal.dumps(callback.__code__)
kwargs["callback"] = json.dumps(callback_code.decode("latin"))
num_iter = mx.sym.var("num_iter_{}".format(uuid.uuid4()), init=mx.init.Constant(0))
return mx.sym.Custom(op_type="Debug", num_iter=num_iter, **kwargs)
if __name__ == "__main__":
x = mx.sym.var("x")
y = mx.sym.var("y")
x = forward_debug(x)
x = backward_debug(x)
x = forward_debug(x, callback=lambda dev_id, num_iter, a: print("a forward = {}".format(a)))
x = backward_debug(x, callback=lambda dev_id, num_iter, a: print("a backward = {}".format(a)))
# (x, y) = forward_debug(x, y, callback=lambda dev_id, num_iter, a, b: print("a + b = {}".format(a + b)))
# (x, y) = backward_debug(x, y, callback=lambda dev_id, num_iter, a, b: print("a + b backward = {}".format(a + b)))
x = x * 2
z = x + y # type: mx.sym.Symbol
print(z.get_internals())
exe = z.simple_bind(mx.cpu(), x=(2, ), y=(2, ), grad_req="write")
exe.forward(x=mx.nd.ones(2), y=mx.nd.full(2, val=2))
exe.backward(mx.nd.ones(2))
exe.forward(x=mx.nd.ones(2), y=mx.nd.full(2, val=2))
exe.backward(mx.nd.ones(2))
exe.forward(x=mx.nd.ones(2), y=mx.nd.full(2, val=2))
exe.backward(mx.nd.ones(2))
exe.outputs[0].wait_to_read()
exe.grad_arrays[0].wait_to_read()
| ffe9f9d4f2cc35fdacc187de1b7fa759d4bcb376 | [
"Markdown",
"Python"
] | 13 | Python | RogerChern/mxnext | 14be3a5f7bd3054f3c9e4b712465e03ad248c3fc | 16aa3570fa6a4be1d20269a96b6df39cafd7e1fd |
refs/heads/master | <file_sep>package com.zll.androiddebug.adapters;
import android.support.v7.widget.CardView;
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.ImageView;
import android.widget.TextView;
import com.zll.androiddebug.R;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by zhang on 15/5/20.
*/
public class RecylerAdapter extends RecyclerView.Adapter<RecylerAdapter.ViewHolder> {
private static final String TAG="RecylerAdapter";
private List<String> mDataSet;
private OnItemClickListener onItemClickListener;
public RecylerAdapter(List<String> myDataSet) {
this.mDataSet = myDataSet;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.text.setText(mDataSet.get(i));
}
@Override
public int getItemCount() {
return mDataSet.size();
}
@Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
//Log.d(TAG,""+holder+" onViewRecycled");
}
@Override
public boolean onFailedToRecycleView(ViewHolder holder) {
//Log.d(TAG,""+holder+"onFailedToRecycleView "+super.onFailedToRecycleView(holder));
return super.onFailedToRecycleView(holder);
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
@InjectView(R.id.img)
ImageView img;
@InjectView(R.id.text)
TextView text;
ViewHolder(View view) {
super(view);
ButterKnife.inject(this, view);
}
@Override
public void onClick(View v) {
}
}
public interface OnItemClickListener{
void onItemClick(View v,int position);
}
}
<file_sep>package com.zll.androiddebug.activities;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.zll.androiddebug.R;
import com.zll.androiddebug.views.widget.LinkTouchMovementMethod;
import com.zll.androiddebug.views.widget.NoUnderlineClickableSpan;
import com.zll.androiddebug.views.widget.TouchableSpan;
public class SpannableStringActivity extends AppCompatActivity {
private TextView spanTextview;
private View spanBox;
private EditText editText;
private Button change;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spannable_string);
TextView textView = (TextView) findViewById(R.id.textview);
spanTextview = (TextView) findViewById(R.id.sp_textview);
spanBox = findViewById(R.id.span_box);
editText = (EditText) findViewById(R.id.edit_text);
change = (Button) findViewById(R.id.change);
String desc = "你好这是一段描述,哈哈,#狂拽炫酷#,啦啦啦##123#234##";
SpannableString spannableString = new SpannableString(desc);
final String label = "狂拽炫酷";
int startIndex = desc.indexOf(label);
int endIndex = startIndex + label.length();
if (TextUtils.equals(String.valueOf(desc.charAt(startIndex - 1)), "#") && TextUtils.equals(String.valueOf(desc.charAt(endIndex)), "#")) {
NoUnderlineClickableSpan clickableSpan = new NoUnderlineClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(SpannableStringActivity.this, label, Toast.LENGTH_SHORT).show();
}
};
spannableString.setSpan(clickableSpan, startIndex - 1, endIndex + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
NoUnderlineClickableSpan clickableSpan = new NoUnderlineClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(SpannableStringActivity.this, "HAHAHAHA", Toast.LENGTH_SHORT).show();
}
};
spannableString.setSpan(clickableSpan, endIndex + 3, endIndex + 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);
textView.setLinkTextColor(Color.RED);
//textView.setMovementMethod(new LinkTouchMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
//textView.setFocusable(false);
//textView.setClickable(false);
textView.setLongClickable(false);
textView.setHighlightColor(Color.TRANSPARENT);
//textView.setSingleLine();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SpannableStringActivity.this, "TextView........", Toast.LENGTH_SHORT).show();
}
});
//spanTest(spanTextview);
test(spanTextview);
editTest();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_spannable_string, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void spanTest(TextView textView) {
spanBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SpannableStringActivity.this, "this is a textView", Toast.LENGTH_SHORT).show();
}
});
textView.setMovementMethod(LinkMovementMethod.getInstance());
//textView.setFocusable(false);
//textView.setClickable(false);
textView.append("你好啊,这是用来测试标签的spannableString,");
final String labelOne = "#标签一#";
final String labelTwo = "#标签二#";
SpannableString label_one = new SpannableString(labelOne);
Drawable d = getResources().getDrawable(R.mipmap.ic_launcher);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
label_one.setSpan(new ImageSpan(d), 0, labelOne.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(label_one);
textView.append(",------");
SpannableString label_two = new SpannableString(labelTwo);
label_two.setSpan(new LabelSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(SpannableStringActivity.this, labelTwo, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SpannableStringActivity.this, LinearRecyclerViewActivity.class);
startActivity(intent);
}
}, 0, labelTwo.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(label_two);
textView.append("啦啦啦啦");
}
abstract class LabelSpan extends ClickableSpan {
@Override
public void onClick(View widget) {
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(getResources().getColor(R.color.tab_text_pressed));
ds.setUnderlineText(false);
ds.bgColor = Color.BLUE;
}
}
private void test(TextView textView) {
textView.setMovementMethod(new LinkTouchMovementMethod());
textView.setHighlightColor(Color.GRAY);
textView.append("你好啊,这是用来测试标签的spannableString,");
for (int i = 0; i < 3; i++) {
SpannableString label = new SpannableString("#label" + i + "#");
final int finalI = i;
TouchableSpan touchableSpan = new TouchableSpan() {
@Override
public boolean onTouch(View widget, MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN) {
Log.e("", "ACTION_DOWN");
} else if (m.getAction() == MotionEvent.ACTION_UP) {
Log.e("", "ACTION_UP =" + finalI);
}
return false;
}
};
label.setSpan(touchableSpan, 0, label.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(label);
textView.append("-------");
}
textView.append("啦啦啦啦");
}
private void editTest() {
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = editText.getText().toString();
if (TextUtils.isEmpty(str)) {
return;
}
str = str.replace('#', '#');
editText.append(str);
char[] array = str.toCharArray();
int chineseCount = 0;
int englishCount = 0;
for (int i = 0; i < array.length; i++) {
if ((char) (byte) array[i] != array[i]) {
chineseCount++;
} else {
englishCount++;
}
}
Log.e("", String.format("chineseCount=%d , englishCount=%d", chineseCount, englishCount));
}
});
}
private int replaceLabel(String str, int start) {
int index = str.indexOf('#', start);
if (index != -1) {
return str.indexOf('#', index);
}
return -1;
}
}
<file_sep>package com.zll.androiddebug.activities;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.zll.androiddebug.R;
import com.zll.androiddebug.adapters.HeaderRecylerAdapter;
import com.zll.androiddebug.adapters.RecylerAdapter;
import com.zll.androiddebug.utils.EndlessRecyclerOnScrollListener;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SwipeRefreshLayoutActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener{
@InjectView(R.id.my_recycler_view)
RecyclerView myRecyclerView;
@InjectView(R.id.swipe_container)
SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView.Adapter adapter;
private LinearLayoutManager layoutManager;
private List<String> dataSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_refresh);
ButterKnife.inject(this);
dataSet = new ArrayList<>();
for (int i = 0; i < EndlessRecyclerOnScrollListener.PAGESIZE; i++) {
dataSet.add("This is CardView " + (i + 1));
}
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright);
swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.background_dark);
layoutManager = new LinearLayoutManager(this);
//layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
myRecyclerView.setLayoutManager(layoutManager);
myRecyclerView.setHasFixedSize(false);
myRecyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new RecylerAdapter(dataSet);
adapter = new HeaderRecylerAdapter(dataSet);
myRecyclerView.setAdapter(adapter);
myRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
@Override
public void onLoadMore(final int current_page) {
Log.e(TAG, "load more: " + current_page);
myRecyclerView.postDelayed(new Runnable() {
@Override
public void run() {
for (int i = (current_page) * EndlessRecyclerOnScrollListener.PAGESIZE; i < (current_page + 1) * EndlessRecyclerOnScrollListener.PAGESIZE; i++) {
dataSet.add("This is CardView " + (i + 1));
adapter.notifyDataSetChanged();
}
}
}, 1500);
}
});
((HeaderRecylerAdapter) adapter).setOnItemClickListener(new HeaderRecylerAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(SwipeRefreshLayoutActivity.this, dataSet.get(position - 1), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onRefresh() {
myRecyclerView.postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(SwipeRefreshLayoutActivity.this,"刷新完成",Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
},4000);
}
}
<file_sep># AndroidDebug
Android debug project
<file_sep>package com.zll.androiddebug.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.zll.androiddebug.BuildConfig;
import java.util.List;
public class LocationService extends Service {
private static final String TAG = "LOCATIONSERVICE";
private LocationManager locationManager;
public LocationService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
Log.d("LocationService", "LocationService onCreate");
}
if (locationManager == null) {
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (BuildConfig.DEBUG) {
Log.d("LocationService", "LocationService onStartCommand");
}
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
Toast.makeText(LocationService.this, "" + location.getLatitude() + " ," + location.getLongitude() + "", Toast.LENGTH_SHORT).show();
Log.e(TAG, String.format("onLocationChanged location is : Latitude=%s,Longitude=%s,Time=%s ",
location.getLatitude(), location.getLongitude(), location.getTime()));
//locationManager.removeUpdates(this);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(networkProvider, 0, 0, locationListener);
locationManager.requestLocationUpdates(gpsProvider, 0, 0, locationListener);
Location lastLocation = getLastKnownLocation();
if (lastLocation != null) {
Log.e(TAG, String.format("location is : Latitude=%s,Longitude=%s,Time=%s ", lastLocation.getLatitude(), lastLocation.getLongitude(), lastLocation.getTime()));
} else {
Log.e(TAG, "lastLocation is null");
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if (BuildConfig.DEBUG) {
Log.d("LocationService", "LocationService onDestroy");
}
stopSelf();
super.onDestroy();
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l != null) {
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
}
return bestLocation;
}
}
<file_sep>package com.zll.androiddebug;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.zll.androiddebug.activities.AnimationActivity;
import com.zll.androiddebug.activities.BaseActivity;
import com.zll.androiddebug.activities.GridRecyclerViewActivity;
import com.zll.androiddebug.activities.LinearRecyclerViewActivity;
import com.zll.androiddebug.activities.LocationActivity;
import com.zll.androiddebug.activities.SpannableStringActivity;
import com.zll.androiddebug.activities.SwipeRefreshLayoutActivity;
import com.zll.androiddebug.utils.AppUtil;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends BaseActivity implements View.OnClickListener {
@InjectView(R.id.linear_recycler)
TextView linearRecycler;
@InjectView(R.id.grid_recycler)
TextView gridRecycler;
@InjectView(R.id.swipe_refresh)
TextView swipeRefresh;
@InjectView(R.id.spannable)
TextView spannable;
@InjectView(R.id.textview)
TextView textView;
@InjectView(R.id.animation)
TextView animation;
@InjectView(R.id.location)
TextView location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
linearRecycler.setOnClickListener(this);
gridRecycler.setOnClickListener(this);
swipeRefresh.setOnClickListener(this);
spannable.setOnClickListener(this);
animation.setOnClickListener(this);
location.setOnClickListener(this);
Log.d("", "系统相册路径=" + AppUtil.getGalleryPath());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.linear_recycler:
intent = new Intent(MainActivity.this, LinearRecyclerViewActivity.class);
startActivity(intent);
break;
case R.id.grid_recycler:
intent = new Intent(MainActivity.this, GridRecyclerViewActivity.class);
startActivity(intent);
break;
case R.id.swipe_refresh:
intent = new Intent(MainActivity.this, SwipeRefreshLayoutActivity.class);
startActivity(intent);
break;
case R.id.spannable:
intent = new Intent(MainActivity.this, SpannableStringActivity.class);
startActivity(intent);
break;
case R.id.animation:
intent = new Intent(MainActivity.this, AnimationActivity.class);
startActivity(intent);
break;
case R.id.location:
intent = new Intent(MainActivity.this, LocationActivity.class);
startActivity(intent);
break;
}
}
}
| 3f36e70255bd7b9f4d483f303efcb39f5f567954 | [
"Markdown",
"Java"
] | 6 | Java | zhangliuliu/AndroidDebug | 5a4835e83cba99efc3b2862485c96554f1d384d6 | efd49de144472f689b63c385cb8f0e4bf66b7f29 |
refs/heads/main | <repo_name>peporerto/loggin<file_sep>/src/App.js
import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import Navegate from './componets/navegate';
import Tdoform from './componets/Tdoform';
import {todos} from './todos.json'
function App() {
const [ users,setdatos] = useState(todos);
const addUser = (user) => {
console.log(user)
setdatos([
...users,
user
])
}
const deleteUser = id => {
console.log(id)
setdatos(users.filter(user => user.title !== id))
}
return (
<div className="App">
<nav className="navbar navbar-dark bg-dark">
<a href="" className="text-white">
tasks
<span className= "badge badge-pill badge bg-light ml-2"
>
<h6 className="text-black" >{todos.length}</h6>
</span>
</a>
</nav>
<div className ="container">
<div className ="row mt-4">
<Tdoform addUser={addUser} />
<Navegate users={users} deleteUser={deleteUser} />
</div>
</div>
<img src={logo} className="App-logo" alt="logo" />
</div>
);
}
export default App;
| b989491e56a6a385e0fff57172e5a299af5873a6 | [
"JavaScript"
] | 1 | JavaScript | peporerto/loggin | b0a6c70695c377e0dab2d34aa19d07d448a2b10f | 7b2b0736ce41735c2655c43f23a286830dd90c0c |
refs/heads/main | <repo_name>emannygarhi/Kintown<file_sep>/plus.php
<?php require_once 'functions.php';?>
<?php if(session_status() == PHP_SESSION_NONE ){
session_start();
}
?>
<?php
if(!isset($_SESSION['auth'])){
$_SESSION['flash']['error'] = "vous n'avez pas le droit d'acceder a cette page";
header('location: index.php');
exit();
}
?>
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>plusId528
</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"><!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
body{
width: 100%;
height: 100vh;
background: #eee;
}
.center{
width: 90%;
margin-right: auto;
margin-left: auto;
background:white;
min-height:700px;
padding: 30px 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index_account.php"><b><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<a class="nav-link" href="index_account.php"> <button type="button" class="btn btn-sm btn-outline-danger">Accueil</button></a></li>
</ul>
<form class="d-flex">
<li class="nav-item">
<a class="nav-link" href="logout.php"> <button type="button" class="btn btn-sm btn-outline-primary">Se deconnecter</button></a></li>
</form>
</div>
</div>
</nav>
<div class="center">
<h2><b>Details</b></h2>
<?php require_once '../cops/db.php'; ?>
<div class="card mb-3" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-10">
<img src="../picture/<?php echo $_GET['photo']; ?>" class="card-img" alt="...">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><i><?php echo $_GET['titre']; ?></i></h5>
<p class="card-text"><i><?php echo $_GET['content']; ?></i></p>
</div>
</div>
</div>
</div>
</div>
</div>
<?php require 'footer.php ' ; ?><file_sep>/login.php
<?php require 'functions.php';?>
<?php if(session_status() == PHP_SESSION_NONE ){
session_start();
session_destroy();
}
?>
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>Connexion</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
body{
width: 100%;
height: 100vh;
background: #eee;
}
.center{
width: 80%;
margin-right: auto;
margin-left: auto;
background:white;
min-height:70px;
padding: 30px 30px;
}
</style>
<!-- Custom styles for this template -->
<link href="css/app.css" rel="stylesheet">
</head>
<body>
<main>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index.php"><b><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link" href="index.php"> <button type="button" class="btn btn-sm btn-outline-danger">Accueil</button></a></li>
<a class="nav-link" href="register.php"> <button type="button" class="btn btn-sm btn-outline-danger">Créer un compte</button></a></li>
</ul>
</div>
</div>
</nav>
<div class="center">
<h1>connecter vous</h1>
<form action="" method="POST">
<div class="form-group">
<label for="">Email</label>
<input type="text" name="username" class="form-control" />
</div>
<div class="form-group">
<label for="">Mot de passe<a href="forget.php">(j'ai oublié mon mot de passe)</a></label>
<input type="<PASSWORD>" name="password" class="form-control" />
</div>
<br>
<input type="checkbox" name="remember" id="remembercheckbox"/> <label for="remembercheckbox">Se souvenir de moi</label>
<br></br>
<button type="submit" class="btn btn-primary">Se connecter</button><br></br>
<p >
<a href="register.php">Je n'ai pas de compte</a>
</p>
</form></div>
<?php if(!empty($_POST) && !empty($_POST['username']) && !empty($_POST['password'])){
require_once 'db.php';
require_once'functions.php';
$req = $pdo->prepare('SELECT * FROM users WHERE email = :username');
$req->execute(['username' => $_POST['username']]);
$user = $req->fetch();
if(password_verify($_POST['password'], $user->password )){
session_start();
if (isset($_POST['remember'])) {
setcookie('user_id',$user ->id, time() + 360 * 24 * 5, '/','localhost',false,true);
}
$_SESSION['auth'] = $user;
$_SESSION['flash'] ['success']= 'vous etes maintenant connecter ';
header('Location: index_account.php');
exit();
}else{
$_SESSION['flash']['danger'] = 'Identifiant ou mot de passe incorrecte';
}
}
?>
<?php require 'footer.php'; ?>
<file_sep>/register.php
<?php require 'functions.php';?>
<?php if(session_status() == PHP_SESSION_NONE ){
session_start();
session_destroy();
}
?>
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>Inscription</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
body{
width: 100%;
height: 100vh;
background: #eee;
}
.center{
width: 80%;
margin-right: auto;
margin-left: auto;
background:white;
min-height:70px;
padding: 30px 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index.php"><b><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link" href="index.php"> <button type="button" class="btn btn-sm btn-outline-danger">Accueil</button></a></li>
<a class="nav-link" href="login.php"> <button type="button" class="btn btn-sm btn-outline-danger">Se connecter</button></a>
</li>
</ul>
</div>
</div>
</nav>
<?php
if(!empty($_POST)){
$errors = array();
require_once 'db.php';
if(empty($_POST['username']) || !preg_match('/^[a-zA-z0-9 _]+$/', $_POST['username'])){
$errors['username'] = "votre Prebom et Nom ne sont pas valide (alphanumerique)";
}
if(empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$errors['email'] = "votre email n'est pas valide";
}else {
$req = $pdo->prepare('SELECT id FROM users WHERE email = ?');
$req->execute([$_POST['email']]);
$user = $req->fetch();
if($user){
$errors['email'] = 'cet email est deja utilisé pour un autre compte';
}
}
if(empty($_POST['password']) || $_POST['password'] != $_POST['password_confirm']){
$errors['password'] = "vous devez entrez un mot de passe valide";
}
if(empty($errors)){
$req = $pdo->prepare("INSERT INTO users SET username = ?, password = ?, email = ?, confirmation_token = ?, confirmed_at = NOW()");
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$_SESSION['auth'] = $username;
$token = str_random(6);
$req->execute([$_POST['username'],$password,$_POST['email'], $token]);
$user_id = $pdo->lastInsertId();
header('location: login.php');
exit();
}
}
?>
<?php if(!empty($errors)): ?>
<div class="alert alert-danger">
<p>Vous n'avez pas remplie le formulaire correctement</p>
<ul>
<?php foreach($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<div class="center">
<h1>Créer un compte </h1>
<form action="" method="POST">
<div class="form-group">
<label for="">Prenom et Nom (ex:gedeon kalala) </label>
<input type="text" name="username" class="form-control" />
</div>
<div class="form-group">
<label for="">Email</label>
<input type="text" name="email" class="form-control" />
</div>
<div class="form-group">
<label for="">Mot de passe</label>
<input type="<PASSWORD>" name="password" class="form-control" />
</div>
<div class="form-group">
<label for="">confirmer votre mot de passe</label>
<input type="password" name="password_confirm" class="form-control" />
</div><br>
<button type="submit" class="btn btn-primary">Créer un compte</button>
<br></br>
<p >
<a href="login.php">J'ai déjà un compte</a>
</p>
</form>
</div>
<?php require 'footer.php'; ?><file_sep>/activite.php
<?php require'functions.php';?>
<?php if(session_status() == PHP_SESSION_NONE ){
session_start();
}
?>
<?php
if(!isset($_SESSION['auth'])){
$_SESSION['flash']['error'] = "vous n'avez pas le droit d'acceder a cette page";
header('location: login.php');
exit();
}
?>
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>Accueil</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"><!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
.all_article{
margin-left: 40px;
}
.all_article{
display: flex;
flex-wrap: wrap;
align-content: space-around;
}
.card{
margin-right: 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index_account.php"><b><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<a class="nav-link" href="index_account.php"> <button type="button" class="btn btn-sm btn-outline-danger">Accueil</button></a></li>
</ul>
<form class="d-flex">
<li class="nav-item">
<a class="nav-link" href="logout.php"> <button type="button" class="btn btn-sm btn-outline-primary">Se deconnecter</button></a></li>
</form>
</div>
</div>
</nav>
<h4>Connexion <b><?= $_SESSION['auth']->username;?></h1><h5>(<?= $_SESSION['auth']->email;?>)</b></h5><br>
<h5>Nos actualité & activité</h1>
<main class="all_article">
<?php require_once 'db.php';
$req = $pdo->prepare('SELECT * FROM all_article ORDER BY id DESC');
$req->execute();
while($reponse = $req->fetch(PDO::FETCH_OBJ)) { ?>
<div class="card" style="width: 17rem;">
<a href="plus.php?titre=<?php echo $reponse->titre;?>&content=<?php echo $reponse->content ?>&photo=
<?php echo $reponse->photo?>" class="btn btn-secondary">
<img src="../picture/<?php echo $reponse->photo ?>" class="card-img-top" alt="..."></a>
<div class="card-body">
<h5 class="card-title "><i><b class = "bg-info"><?php echo $reponse->titre; ?></b></i></h5>
<p class="card-text"><small class="text-muted"><?php echo $reponse->date_article; ?></small></p><br>
<a href="plus.php?titre=<?php echo $reponse->titre;?>&content=<?php echo $reponse->content ?>&photo=
<?php echo $reponse->photo?>" class="btn btn-sm btn-outline-danger">Plus</a>
</div>
</div>
</div>
<?php } ?>
</main>
</div>
</div>
</div>
<?php require 'footer.php ' ; ?><file_sep>/index_account.php
<?php require 'functions.php';?>
<?php if(session_status() == PHP_SESSION_NONE ){
session_start();
}
?>
<?php
if(!isset($_SESSION['auth'])){
$_SESSION['flash']['error'] = "vous n'avez pas le droit d'acceder a cette page";
header('location: login.php');
exit();
}
?>
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>Accueil</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"><!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
.menu{
margin-left: 30px;
}
.menu{
display: flex;
flex-wrap: wrap;
align-content: space-around;
}
.card{
margin-right: 10px;
}
.all_article{
margin-left: 30px;
}
.all_article{
display: flex;
flex-wrap: wrap;
align-content: space-around;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index_account.php"><b><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
</ul>
<form class="d-flex">
<li class="nav-item">
<a class="nav-link" href="logout.php"> <button type="button" class="btn btn-sm btn-outline-primary">Se deconnecter</button></a></li>
</form>
</div>
</div>
</nav>
<main class="menu">
<h4>Connexion <b class = "bg-info">¤ <?= $_SESSION['auth']->username;?></b></h1></main>
<main class="menu">
<h5>(<?= $_SESSION['auth']->email;?>)</b> </h5>
</main>
<br><?php require_once 'db.php';
$req = $pdo->prepare('SELECT * FROM commentaire ORDER BY id DESC');
$req->execute();
while($reponse = $req->fetch(PDO::FETCH_OBJ)) { ?>
<section id="hero">
<div class="text-danger">
<main class="menu">
<p class="animated fadeInDown "><b><i><h4><?php echo $reponse->comment; ?></h4></b></i></p>
<?php }?>
</main>
</div>
</section>
<main class="menu">
<div class="card" style="width: 18rem;">
<img src="../photo/restaurant.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>RESTAURANT</b></b></i> </p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/restau.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/lounge.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>LOUNGE BAR</b></b></i></p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/lounge.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/terrasse.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>TERRASSE & NIGHT-CLUB</b></b></i></p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/terrasse.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/fleuve.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>ESPACE AU BORD DU FLEUVE</b></b></i></p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/fleuve.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/hotel.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>HOTEL</b></b></i> </p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/hotel.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/salle.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>SALLE DE CINEMA</b></b></i></p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/salle.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
<div class="card" style="width: 18rem;">
<img src="../photo/autre.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title"><i><b class = "bg-info">Kin</b><b class = "bg-danger">Town</b></b></i> </h5>
<p class="card-text"><b>AUTRES</b></b></i></p>
<div class="d-flex justify-content-between align-items-center">
<a href="../revu/autre.php"> <button type="button" class="btn btn-sm btn-outline-danger">Voir</button></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<br>
<br>
<br>
<main class="menu">
<h2 class="pb-3 border-bottom text-danger"><b><i>Actualités & Activités</i></b> </h2>
</main>
<main class="all_article">
<?php require_once 'db.php';
$req = $pdo->prepare('SELECT * FROM all_article ORDER BY id DESC');
$req->execute();
while($reponse = $req->fetch(PDO::FETCH_OBJ)) { ?>
<div class="card" style="width: 17rem;">
<a href="plus.php?titre=<?php echo $reponse->titre;?>&content=<?php echo $reponse->content ?>&photo=
<?php echo $reponse->photo?>" class="btn btn-danger">
<img src="../picture/<?php echo $reponse->photo ?>" class="card-img-top" alt="..."></a>
<div class="card-body">
<h5 class="card-title "><i><b class = "bg-info"><?php echo $reponse->titre; ?></b></i></h5>
<p class="card-text"><small class="text-muted"><?php echo $reponse->date_article; ?></small></p><br>
<a href="plus.php?titre=<?php echo $reponse->titre;?>&content=<?php echo $reponse->content ?>&photo=
<?php echo $reponse->photo?>" class="btn btn-sm btn-outline-danger">Plus de détail</a>
</div>
</div>
</div>
<?php } ?>
</main>
</div>
<?php require 'footer.php ' ; ?><file_sep>/forget.php
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>, <NAME>, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.83.1">
<title>KinGo</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/navbar-static/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.0/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.0/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
<style type="text/css">
body{
width: 100%;
height: 100vh;
background: #eee;
}
.center{
width: 80%;
margin-right: auto;
margin-left: auto;
background:white;
min-height:70px;
padding: 30px 30px;
}
</style>
<!-- Custom styles for this template -->
<link href="css/app.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="index.php"><b>Kin<b class = "bg-danger">Place</b></b></i></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link" href="index.php">Accueil</a></li>
</ul>
</div>
</div>
</nav>
<div class="center">
<h1>Mot de passe oublier</h1>
<form action="" method="POST">
<div class="form-group">
<label for="">Email</label>
<input type="text" name="email" class="form-control" />
</div>
<br>
<label for="">Mots de passe </label>
<input type="text" name="password" class="form-control" />
<br>
<label for="">confirmation du mot de passe</label>
<input type="text" name="password" class="form-control" />
<br>
<button type="submit" class="btn btn-primary">Se connecter</button>
</form></div>
<?php if(!empty($_POST) && !empty($_POST['email'])){
require_once 'db.php';
require_once'functions.php';
$req = $pdo->prepare('SELECT * FROM users WHERE email = ? AND confirmed_at is NOT NULL');
$req->execute([$_POST['email']]);
$user = $req->fetch();
if($user){
session_start();
$reset_token = str_random(6);
$pdo->prepare('UPDATE users SET reset_token = ?, reset_at = NOW() WHERE id = ?')->execute([$reset_token, $user->id]);
header('Location: login.php');
exit();
}else{
$_SESSION['flash']['danger'] = 'aucun compte ne correspond a cet adresse';
}
}
?>
<?php require 'footer.php'; ?><file_sep>/README.md
# Kintown
hebergement gratuit
<file_sep>/db.php
<?php
$pdo = new PDO('mysql:dbname=tuto;host=localhost', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>
<?php
$conn = mysqli_connect("localhost","root","","tuto");
if ($conn===false)
{
die("erreur; non connecter au serveur .".
mysqli_connect_error());
}
?> | 3709e7ed8b54507b28abe6f27015b9a57e34ee7e | [
"Markdown",
"PHP"
] | 8 | PHP | emannygarhi/Kintown | 32ecc144fc7bc6428c2e3d21dc613567c3830c22 | 8d81a4717922ab5464993136aca4776fe3d3a31a |
refs/heads/master | <file_sep>using UnityEngine;
using WindowsInput.Native;
using WindowsInput;
//Used to simulate a button on the keyboard via the InputSimulator
public class VirtualKeyboardButton : MonoBehaviour
{
private IKeyboardSimulator keyboardSim;
private Rigidbody rb;
private Vector3 unpressedPos, pressedPos;
private float previousLerpPos, lerpPos;
[Min(0f)] [SerializeField] private float maxKeyPressDistance , resistence;
[Range(0f, 1f)] [SerializeField] private float keyPressRange = 0.1f;
[SerializeField] private VirtualKeyCode key;
// Start is called before the first frame update
void Start()
{
keyboardSim = FindObjectOfType<VRInputController>().VRInput.Keyboard;
rb = GetComponent<Rigidbody>();
unpressedPos = gameObject.transform.localPosition;
pressedPos = gameObject.transform.localPosition + (gameObject.transform.transform.forward * maxKeyPressDistance);
}
//Force the button to immediately be in the pressed state
public void PressButton()
{
lerpPos = 1f;
transform.localPosition = Vector3.Lerp(unpressedPos, pressedPos, lerpPos);
}
//Force the button to immediately be in the unpressed state
public void ReleaseButton()
{
lerpPos = 0f;
transform.localPosition = Vector3.Lerp(unpressedPos, pressedPos, lerpPos);
}
//Requires a constant press from a UI Collider to press the button
private void OnCollisionStay(Collision collision)
{
if(collision.gameObject.layer == gameObject.layer)
{
lerpPos += Time.deltaTime / resistence;
}
}
// Update is called once per frame
void Update()
{
//Minimising performance hit from active buttons
if(lerpPos != 0)
{
//lerpPos 0 = Button unpressed, lerpPos 1 = Button fully pressed
//Update position of the button
transform.localPosition = Vector3.Lerp(unpressedPos, pressedPos, lerpPos);
//Simulate keyboard input if button is pressed enough
if (lerpPos >= keyPressRange)
keyboardSim.KeyDown(key);
else
keyboardSim.KeyUp(key);
//If button is not being pressed down, begin releasing button
if (lerpPos <= previousLerpPos)
{
//Button is no longer being pressed
lerpPos -= Time.deltaTime / resistence;
}
//Limit button position alpha to be between 0 and 1, then update the previous position
lerpPos = Mathf.Clamp(lerpPos, 0, 1);
previousLerpPos = lerpPos;
}
}
}
<file_sep>using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class FakeMouse : MonoBehaviour
{
private Canvas canvas;
public EventSystem es;
private RectTransform rect;
public UnityEngine.UI.Selectable[] entered, pointerUp; //over
private bool clicking;
// Start is called before the first frame update
void Start()
{
canvas = GetComponentInParent<Canvas>();
rect = GetComponent<RectTransform>();
}
public void Click()
{
clicking = true;
var toPointerUpNextUpdate = new List<UnityEngine.UI.Selectable>();
foreach (var obj in entered)
{
obj.OnPointerDown(new PointerEventData(EventSystem.current));
toPointerUpNextUpdate.Add(obj);
}
//foreach (var obj in over)
//{
// obj.OnPointerDown(new PointerEventData(EventSystem.current));
// toPointerUpNextUpdate.Add(obj);
//}
pointerUp = toPointerUpNextUpdate.ToArray();
}
public void EndClick() => clicking = false;
// Update is called once per frame
void Update()
{
//Removed mouse over properties for streamlining
var enteredThisUpdate = new List<UnityEngine.UI.Selectable>();
//var mouseOver = new List<UnityEngine.UI.Selectable>();
var overlapping = new List<UnityEngine.UI.Selectable>();
var noOverlap = new List<UnityEngine.UI.Selectable>();
foreach (var obj in canvas.GetComponentsInChildren<UnityEngine.UI.Selectable>())
{
if (Overlapping(rect, obj.GetComponent<RectTransform>()))
{
overlapping.Add(obj);
obj.OnPointerEnter(new PointerEventData(EventSystem.current));
enteredThisUpdate.Add(obj);
}
else
{
noOverlap.Add(obj);
}
}
//foreach (var obj in overlapping)
//{
// if(entered.Contains(obj) || mouseOver.Contains(obj))
// {
// mouseOver.Add(obj);
// //Mouse Over Event?
// }
// else
// {
// enteredThisUpdate.Add(obj);
// obj.OnPointerEnter(new PointerEventData(EventSystem.current));
// }
//}
foreach (var obj in noOverlap)
{
if (entered.Contains(obj)) //|| over.Contains(obj)
{
if(clicking && pointerUp.Contains(obj))
{
var ptrUp = pointerUp.ToList();
ptrUp.Remove(obj);
pointerUp = ptrUp.ToArray();
}
obj.OnPointerExit(new PointerEventData(EventSystem.current));
}
}
if(clicking == false)
{
foreach (var obj in pointerUp)
{
obj.OnPointerUp(new PointerEventData(EventSystem.current));
}
}
entered = enteredThisUpdate.ToArray();
//over = mouseOver.ToArray();
}
private bool Overlapping(RectTransform check, RectTransform overlap)
{
if(check.localPosition.y <= overlap.localPosition.y + overlap.rect.yMax &&
check.localPosition.y >= overlap.localPosition.y + overlap.rect.yMin &&
check.localPosition.x <= overlap.localPosition.x + overlap.rect.xMax &&
check.localPosition.x >= overlap.localPosition.x + overlap.rect.xMin)
{
return true;
}
return false;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CounterRotation : MonoBehaviour
{
[SerializeField] GameObject pointTo;
private void Start()
{
if(pointTo == null)
{
pointTo = FindObjectOfType<Camera>().gameObject;
}
}
// Update is called once per frame
void Update()
{
transform.LookAt(pointTo.transform);
transform.Rotate(new Vector3(0, 180, 0));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseActivator : MonoBehaviour
{
public MonoBehaviour active;
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.W))
{
active.enabled = !active.enabled;
}
}
}
<file_sep>using UnityEngine;
using WindowsInput;
public class VRMouseInput : MonoBehaviour
{
private MouseSimulator mouseSim;
public FakeMouse fauxMouse;
[SerializeField] private string inputAxisName;
[Range (0,3)][SerializeField] private int mouseInput = 0;
[Range(0, 1)] [SerializeField] private float axisRequirement = 0.5f;
[SerializeField] private Canvas affectedCanvas;
[SerializeField] private Camera affectedCamera;
public float inputAxis;
private bool mouseDown;
private Vector2 uiCanvasOffset;
public Vector2 mousePosition;
// Start is called before the first frame update
void Start()
{
mouseSim = new MouseSimulator(FindObjectOfType<VRInputController>().VRInput);
uiCanvasOffset = new Vector2(affectedCanvas.pixelRect.size.x / 2, affectedCanvas.pixelRect.size.y / 2);
}
// Update is called once per frame
void Update()
{
var viewPortRaw = affectedCamera.WorldToViewportPoint(transform.position);
mousePosition = new Vector2(viewPortRaw.x * affectedCanvas.pixelRect.size.x, viewPortRaw.y * affectedCanvas.pixelRect.size.y);
mousePosition -= uiCanvasOffset;
//Working approximation of the handheld position to the canvas, exaggerates a little too much near edges, clamping required.
fauxMouse.transform.localPosition = (affectedCamera.transform.position - transform.position).z >= 0? new Vector2(mousePosition.x, mousePosition.y) : new Vector2(-mousePosition.x, -mousePosition.y);
inputAxis = Input.GetAxis(inputAxisName);
if(inputAxis < axisRequirement && mouseDown)
{
mouseDown = false;
fauxMouse.EndClick();
}
else if(inputAxis >= axisRequirement)
{
mouseDown = true;
fauxMouse.Click();
}
//Not working as of yet.
//var simMousePos = affectedCamera.WorldToScreenPoint(fauxMouse.position); //+ new Vector3(uiCanvasOffset.x,0,uiCanvasOffset.y); //was mousePosition
}
}
| 4a2ffa56e354cb7e63d1fa95ab2115ef2756f1ac | [
"C#"
] | 5 | C# | Chapmania/VR-UI_UnityPlugin | 6fdbf1a9a3f4df862e2ba3057f104f88e8ad818e | d57a16ed66d7a8906e0c76cd1a75a81c508d1379 |
refs/heads/master | <file_sep>import csv
import sklearn.linear_model as sk
import numpy as np
import matplotlib.pyplot as pp
def readData(data):
a = [[],[]]
with open(data, 'rb') as file:
reader = csv.reader(file)
for row in reader:
a[0].append(int(row[0].split(' ')[0]))
a[1].append(float(row[0].split(' ')[1]))
return a
def matrixify(a):
matrix = []
for i in a:
matrix.append([i, 1]) #i is x1, 1 is x0
return matrix
def dematrixify(a):
array = []
for i in a:
array.append(i[0])
return array
def main():
a = readData('movie_data.csv')
x = matrixify(a[0]) #SGDRegressor needs independent variables in an individual array/matrix
y = a[1] #Output doesn't have to be in individual arrays
reg = sk.SGDRegressor(loss='squared_loss', penalty='none', n_iter=1000, fit_intercept=False)
reg.fit(x,y)
#Make Scatter Plot with scikit's "answers"
xaxis = matrixify(np.arange(0,11))
yaxis = reg.predict(xaxis)
xaxis = dematrixify(xaxis)
fig = pp.figure()
ax = fig.gca()
ax.axis([0,10,0,10])
ax.set_xlabel('Number of Explosions in Film')
ax.set_ylabel('James\' Rating of Film')
ax.set_title('Scikit Found M = '+str(reg.coef_[0])+'and B = '+str(reg.coef_[1]))
ax.plot(a[0],a[1],'o')
ax.plot(xaxis, yaxis)
fig.show()
raw_input(' ')
if __name__ == '__main__':
main()<file_sep>import matplotlib.pyplot as pp
import numpy as np
#Function I chose to graph, (x-5)^2
def f(a):
return np.square(a-5)
#First derivative of above function for finding slope of gradient line
def slope(a):
return (2*a)-10
#Used to find y-intercept in creating gradient line
def intercept(a, m):
return m*a - f(a)
def main():
x = np.arange(0,11) #numbers 1- 10
g = 0.1 #learning rate
a = 8 #initial position
#Initialize Graph
fig = pp.figure()
chrt = fig.gca()
chrt.axis([0,10,0,30])
fig.show()
#Plot our function
chrt.plot(x,f(x))
fig.canvas.draw()
i = raw_input(' ')
while i != 'q':
#Plot point A
chrt.plot(a,f(a),'o')
fig.canvas.draw()
i = raw_input(' ')
#Display gradient line at point A
m = slope(a)
b = intercept(a, m)
chrt.plot(x, (m*x)-b)
fig.canvas.draw()
i = raw_input(' ')
#Use gradient descent algorithm to get new point
newA = a - (g*m)
print 'A is now: ', newA
#Display new point A on Equation Line
chrt.plot(newA, f(newA), '^')
fig.canvas.draw()
i = raw_input(' ')
#Set A to New A and reset
chrt.cla()
a = newA
chrt.axis([0,10,0,30])
chrt.plot(x,f(x))
if __name__ == '__main__':
main()
<file_sep>=======================
Machine Learning Primer
=======================
Description
------------
This repository contains files to supplement the presentation I am giving for the Data Science Colorado Meetup group on July 1st, 2015 at Galvanize Platte.
You can find the presentation slides in this repo or with this link `A Primer on Machine Learning <https://docs.google.com/presentation/d/1rFoSPMGrWEwU8U-Ej49B6mqv8ikyAzIfVj0ryqZPVNA/edit?usp=sharing>`_
Package Versions used for Python Scripts
----------------------------------
* Python 2.7.9
* NumPy 1.9.2
* Matplotlib 1.4.3
* Scikit-Learn 0.15.2
I haven't checked compatibility with other versions. I strongly recommend downloading the `Anaconda <https://store.continuum.io/cshop/anaconda/>`_ stack. It will provide you with everything required to run the scripts in this repo.
Summary of Scripts
------------------
display_linefit_graphic.py
This is a Python script that displays 4 regression line plots to compare how well a line will fit the data based upon the m and b variables
gradient_descent_button.py
This is a Python script that shows gradient descent algorithm applied against the plot of f(x) = (x - 5)^2.
gradient_descent_movie.py
This is a Python script that displays a 3D graph of the linear regression cost function with respect to parameters m and b and also a scatter plot graph with regression line. Both graphs are based upon the data found in movie_data.csv The script steps through the algorithm and plots new 3D points on the left graph and new regression lines on the right graph.
scikit_gradient_descent.py
This Python script is a scikit-learn implentation of stochastic gradient descent that reads the data from movie_data.csv, fits the data to a S.G.D. regressor, and outputs a scatter plot and regression line.
<file_sep>import random
import matplotlib.pyplot as pp
from matplotlib.lines import Line2D
import numpy as np
#Creates 10 randomish data points
def genBoringScat():
x = []
y = []
for i in range(0,10):
x.append(random.uniform(1,10))
y.append(x[-1]+random.normalvariate(0,1))
#if I had to do it over I might instead use scikit-learn's sklearn.datasets.make_regression function
return [x, y]
#Formats individual charts and returns error (sum of squares)
def makeRegChart(ax, a, m, b):
error = 0
ax.axis([0,10,0,10])
ax.set_title('M = '+str(m)+', B = '+str(b))
ax.plot(a[0],a[1],'o')
ax.plot(a[0],np.add(np.multiply(m,a[0]),b))
for n in range(0,len(a[0])):
line = Line2D([a[0][n],a[0][n]],[a[1][n],np.add(np.multiply(m,a[0][n]),b)])
ax.add_line(line)
error += np.square(a[1][n]- np.add(np.multiply(m,a[0][n]),b))
return 'M = '+str(m)+' and B = '+str(b)+' has a Sum of Squares of '+str(error)
#Creates 4 different regression lines to fit data
def showRegLines(a):
error = []
fig, axarr = pp.subplots(2, 2)
error.append(makeRegChart(axarr[0,0], a, 0, 5))
error.append(makeRegChart(axarr[0,1], a, .5, 2))
error.append(makeRegChart(axarr[1,0], a, 2, -5))
error.append(makeRegChart(axarr[1,1], a, 1, 0))
fig.canvas.draw()
fig.show()
for e in error:
print e
raw_input('')
def main():
a = genBoringScat()
showRegLines(a)
if __name__ == "__main__":
main()
<file_sep>import csv
from matplotlib import cm
import matplotlib.pyplot as pp
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
#Imports data from CSV and returns 2 arrays: x array and y array respectively
def readData(data):
a = [[],[]]
with open(data, 'rb') as file:
reader = csv.reader(file)
for row in reader:
a[0].append(int(row[0].split(' ')[0]))
a[1].append(float(row[0].split(' ')[1]))
return a
#Returns cost of function at point m, b
def cost(a, m, b):
cost = 0.0
for i in range(0,len(a)):
y = a[1][i]
x = a[0][i]
cost += np.square(y - (m*x+b))
return cost
#Returns gradient of cost function in an array with m first, then b
def gradCost(a, m, b):
gradM = 0.0
gradB = 0.0
N = len(a[0])
for i in range(0,N):
y = a[1][i]
x = a[0][i]
gradM += -x*(y-(m*x+b))
gradB += -1*(y-(m*x+b))
return [2*N*gradM, 2*N*gradB]
def main():
#loop related variables and data initialization
a = readData('movie_data.csv')
inp = ' '
i = 0
#initial variables
m = -2.5
b = -15
g = 0.00001 #cheated and chose a good one for convergence
#drawing the initial 3d cost function chart
fig = pp.figure()
mrange = np.arange(-4,4.2,.2)
brange = np.arange(-20,21)
mrange, brange = np.meshgrid(mrange, brange)
z = cost(a,mrange,brange)
hillChart = fig.add_subplot(121, projection='3d')
hillChart.cla() #workaround for "gridline transparency issue"
hillChart.plot_surface(mrange,brange,z,alpha=.5, rstride = 3, cstride = 3, cmap=cm.coolwarm)
hillChart.axis([-4,4,-20,20])
hillChart.set_xlabel('m')
hillChart.set_ylabel('b')
hillChart.set_zlabel('Cost')
hillChart.set_title('Cost Function for m, b')
#drawing the initial scatter plot of movie rating data
xrange = np.arange(0,11)
yrange = np.add(np.multiply(m,xrange),b)
scatChart = fig.add_subplot(122)
scatChart.cla() #workaround for "gridline transparency issue"
scatChart.axis([0,10,0,10])
scatChart.set_xlabel('Number of Explosions in Film')
scatChart.set_ylabel('James\' Rating of Film')
scatChart.set_title('Rating Based on Number of Explosions')
scatChart.plot(xrange,yrange)
scatChart.plot(a[0],a[1],'o')
fig.show()
raw_input('')
while i < 1000:
z1 = cost(a,m,b)
yrange = np.add(np.multiply(m,xrange),b)
hillChart.plot([m],[b],[z1], "s", markeredgecolor = "r", markerfacecolor = "r")
scatChart.cla()
scatChart.axis([0,10,0,10])
scatChart.set_xlabel('Number of Explosions in Film')
scatChart.set_ylabel('James\' Rating of Film')
scatChart.set_title('Rating Based on Number of Explosions')
scatChart.plot(xrange, yrange)
scatChart.plot(a[0],a[1],'o')
fig.canvas.draw()
grad = gradCost(a,m,b)
newM = m - .2*g*grad[0]
newB = b - g*grad[1]
m = newM
b = newB
if (i % 50 == 49): #used for 'pauses' to examine charts and to prevent too many points from being plotted
inp = raw_input('')
hillChart.cla()
hillChart.plot_surface(mrange,brange,z,alpha=.5, rstride = 3, cstride = 3, cmap=cm.coolwarm)
hillChart.axis([-4,4,-20,20])
hillChart.set_xlabel('m')
hillChart.set_ylabel('b')
hillChart.set_zlabel('Cost')
hillChart.set_title('Cost Function for m, b')
i += 1
print m, b
if __name__ == '__main__':
main() | 0e8f13554ef641dfc8d27fa9e68ec7fec6867672 | [
"Python",
"reStructuredText"
] | 5 | Python | mshans66/Machine_Learning_Primer | 08eab19b5568174b9670db3c04e2d16874984725 | 8697f578e696a3d13cf1e0f970ab4aca3a834804 |
refs/heads/master | <repo_name>cryptochain/monero-full-node<file_sep>/docker-build.sh
#!/bin/bash
docker build -t monerod-docker .
<file_sep>/Dockerfile
# Usage: docker run --restart=always -v /var/data/blockchain-xmr:/root/.bitmonero -p 18080:18080 -p 18081:18081 --name=monerod -td kannix/monero-full-node
FROM ubuntu:16.04
ENV MONERO_VERSION=0.12.0.0 MONERO_SHA256=928ad08ff0dea2790c7777a70e610b2d33c35a5df5900fbb050cc8c659237636
RUN apt-get update && apt-get install -y curl bzip2
# RUN useradd -ms /bin/bash monero
# USER monero
# WORKDIR /home/monero
WORKDIR /root
RUN curl https://downloads.getmonero.org/cli/monero-linux-x64-v$MONERO_VERSION.tar.bz2 -O &&\
echo "$MONERO_SHA256 monero-linux-x64-v$MONERO_VERSION.tar.bz2" | sha256sum -c - &&\
tar -xjvf monero-linux-x64-v$MONERO_VERSION.tar.bz2 &&\
rm monero-linux-x64-v$MONERO_VERSION.tar.bz2 &&\
mv ./monero-v$MONERO_VERSION/* .
# blockchain location
VOLUME /root/.bitmonero
VOLUME /root/monero-config
EXPOSE 18080 18081 28080 28081
RUN ./monerod --help
ENTRYPOINT ["./monerod"]
CMD ["--config-file=/root/monero-config/bitmonero.conf", "--rpc-bind-ip=0.0.0.0", "--confirm-external-bind"]
<file_sep>/README.md
# monero-full-node
docker image to run a monero full network node
<file_sep>/docker-run.sh
#!/bin/bash
NAME="monerod-testnet"
docker run -td --name $NAME \
-p 28080:28080 \
-p 28081:28081 \
-v $PWD/data:/root/.bitmonero \
-v $PWD/config:/root/monero-config \
monerod-docker
<file_sep>/data/README.md
# Blochain Data Folder
| 264c52d27047b5143eecc30128627b88e8f764eb | [
"Markdown",
"Dockerfile",
"Shell"
] | 5 | Shell | cryptochain/monero-full-node | 1b2312df8e25e5dc7d78bf85526d126d47618454 | cc68c669f9d835fc6874b2d86a0a748d0581022d |
refs/heads/master | <repo_name>Xutop/DeepLearning<file_sep>/Caffe/MobileNet/getList.py
import os
data = '101_ObjectCategories'
path = os.listdir(data)
path.sort()
vp = 0.105
file = open('train.txt','w')
fv = open('val.txt','w')
i = 0
for line in path:
subdir = data +'/'+line
childpath = os.listdir(subdir)
mid = int(vp*len(childpath))
for child in childpath[:mid]:
subpath = data+'/'+line+'/'+child;
d = ' %s' %(i)
t = subpath + d
fv.write(t +'\n')
for child in childpath[mid:]:
subpath = data+'/'+line+'/'+child;
d = ' %s' %(i)
t = subpath + d
file.write(t +'\n')
i=i+1
file.close()
fv.close()<file_sep>/Caffe/unet/train_Unet.sh
#!/usr/bin/env sh
set -e
/home/core/Research/UnetCompetition/caffe-unet-src/build/tools/caffe train --solver=/home/core/Research/UnetCompetition/Unet_solver.prototxt $@
<file_sep>/Caffe/unet/MyUnet.py
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 15 14:10:40 2016
# my U-net
@author: core
"""
import numpy as np
from google.protobuf import text_format
#import caffe
caffe_root = '/home/core/Research/caffe-master/' # this file should be run from {caffe_root}/examples (otherwise change this line)
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe , h5py
from caffe import layers as L, params as P
train_net_path = '/home/core/Research/UnetCompetition/myUnet_train.prototxt'
test_net_path = '/home/core/Research/UnetCompetition/myUnet_test.prototxt'
solver_config_path = '/home/core/Research/UnetCompetition/myUnet_solver.prototxt'
#convolution and relu
def conv_relu(bottom,nout,ks=3,stride=1,pad=0):
conv = L.Convolution(bottom, kernel_size=ks, stride=stride,
num_output=nout, pad=pad, weight_filler=dict(type='xavier'),
param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2,decay_mult=0)])
return conv, L.ReLU(conv,in_place=True)
#deconvolution and relu
def deconv_relu(bottom,nout,ks=2,stride=2,pad=0):
deconv = L.Deconvolution(bottom,convolution_param=dict(num_output=nout, kernel_size=ks,
stride=stride,pad=pad,weight_filler=dict(type='xavier')),
param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2,decay_mult=0)])
return deconv, L.ReLU(deconv,in_place=True)
#maxpooling
def max_pool(bottom,ks=2,stride=2):
return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride)
### define U-net
def custom_net(hdf5,batch_size):
# define your own net!
n = caffe.NetSpec()
#keep this data layer for all networks
#HDF5 DATA LAYER
n.data, n.label = L.HDF5Data(batch_size=batch_size, source=hdf5,
ntop=2)
# n.conv_d0a_b = L.Convolution(n.data,kernel_size=3,num_output=64,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d0b = L.ReLU(n.conv_d0a_b)
# n.conv_d0b_c = L.Convolution(n.relu_d0b,kernel_size=3,num_output=64,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d0c = L.ReLU(n.conv_d0b_c)
# n.pool_d0c_1a = L.Pooling(n.relu_d0c, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.conv_d0a_b,n.relu_d0b = conv_relu(n.data,64)
n.conv_d0b_c,n.relu_d0c = conv_relu(n.relu_d0b,64)
n.pool_d0c_1a = max_pool(n.relu_d0c)
# n.conv_d1a_b = L.Convolution(n.pool_d0c_1a,kernel_size=3,num_output=128,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d1b = L.ReLU(n.conv_d1a_b)
# n.conv_d1b_c = L.Convolution(n.relu_d1b,kernel_size=3,num_output=128,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d1c = L.ReLU(n.conv_d1b_c)
# n.pool_d1c_2a = L.Pooling(n.relu_d1c, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.conv_d1a_b,n.relu_d1b = conv_relu(n.pool_d0c_1a,128)
n.conv_d1b_c,n.relu_d1c = conv_relu(n.relu_d1b,128)
n.pool_d1c_2a = max_pool(n.relu_d1c)
# n.conv_d2a_b = L.Convolution(n.pool_d1c_2a,kernel_size=3,num_output=256,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d2b = L.ReLU(n.conv_d2a_b)
# n.conv_d2b_c = L.Convolution(n.relu_d2b,kernel_size=3,num_output=256,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d2c = L.ReLU(n.conv_d2b_c)
# n.pool_d2c_3a = L.Pooling(n.relu_d2c, kernel_size=2,stride = 2,pool = P.Pooling.MAX)
n.conv_d2a_b,n.relu_d2b = conv_relu(n.pool_d1c_2a,256)
n.conv_d2b_c,n.relu_d2c = conv_relu(n.relu_d2b,256)
n.pool_d2c_3a = max_pool(n.relu_d2c)
# n.conv_d3a_b = L.Convolution(n.pool_d2c_3a,kernel_size=3,num_output=512,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d3b = L.ReLU(n.conv_d3a_b)
# n.conv_d3b_c = L.Convolution(n.relu_d3b,kernel_size=3,num_output=512,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d3c = L.ReLU(n.conv_d3b_c)
# n.dropout_d3c = L.Dropout(n.relu_d3c,dropout_ratio=0.5)
# n.pool_d3c_4a = L.Pooling(n.relu_d3c, kernel_size=2,stride = 2,pool = P.Pooling.MAX)
n.conv_d3a_b,n.relu_d3b = conv_relu(n.pool_d2c_3a,512)
n.conv_d3b_c,n.relu_d3c = conv_relu(n.relu_d3b,512)
n.dropout_d3c = L.Dropout(n.relu_d3c,dropout_ratio=0.5)
n.pool_d3c_4a = max_pool(n.dropout_d3c)
# n.conv_d4a_b = L.Convolution(n.pool_d3c_4a,kernel_size=3,num_output=1024,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d4b = L.ReLU(n.conv_d4a_b)
# n.conv_d4b_c = L.Convolution(n.relu_d4b,kernel_size=3,num_output=1024,pad=0,weight_filler=dict(type='xavier'))
# n.relu_d4c = L.ReLU(n.conv_d4b_c)
# n.dropout_d4c = L.Dropout(n.relu_d4c,dropout_ratio=0.5)
# #n.upconv_d4c_u3a = L.DeConvolution(n.dropout_d4c,num_output = 512, pad=0, kernel_size=2,stride=2,weight_filler=dict(type='xavier'))
# n.upconv_d4c_u3a = L.Deconvolution(n.dropout_d4c)
# n.relu_u3a = L.ReLU(n.upconv_d4c_u3a)
n.conv_d4a_b,n.relu_d4b = conv_relu(n.pool_d3c_4a,1024)
n.conv_d4b_c,n.relu_d4c = conv_relu(n.relu_d4b,1024)
n.dropout_d4c = L.Dropout(n.relu_d4c,dropout_ratio=0.5)
n.upconv_d4c_u3a,n.relu_u3a = deconv_relu(n.dropout_d4c,512)
# n.crop_d3c_d3cc = L.Crop(n.relu_d3c,n.relu_u3a)
# n.concat_d3cc_u3a_b = L.Concat(n.relu_u3a,n.crop_d3c_d3cc)
# n.conv_u3b_c = L.Convolution(n.concat_d3cc_u3a_b,num_output=512,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u3c = L.ReLU(n.conv_u3b_c)
# n.conv_u3c_d = L.Convolution(n.relu_u3c, num_output=512,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u3d = L.ReLU(n.conv_u3c_d)
# #n.upconv_u3d_u2a = L.Deconvolution(n.relu_u3d, num_output=256,pad =0,kernel_size=2,stride=2,weight_filler=dict(type='xavier'))
# n.upconv_u3d_u2a = L.Deconvolution(n.relu_u3d)
# n.relu_u2a = L.ReLU(n.upconv_u3d_u2a)
n.crop_d3c_d3cc = L.Crop(n.relu_d3c,n.relu_u3a)
n.concat_d3cc_u3a_b = L.Concat(n.relu_u3a,n.crop_d3c_d3cc)
n.conv_u3b_c,n.relu_u3c = conv_relu(n.concat_d3cc_u3a_b,512)
n.conv_u3c_d,n.relu_u3d = conv_relu(n.relu_u3c,512)
n.upconv_u3d_u2a,n.relu_u2a = deconv_relu(n.relu_u3d,256)
# n.crop_d2c_d2cc = L.Crop(n.relu_d2c,n.relu_u2a)
# n.concat_d2cc_u2a_b = L.Concat(n.relu_u2a,n.crop_d2c_d2cc)
# n.conv_u2b_c = L.Convolution(n.concat_d2cc_u2a_b,num_output=256,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u2c = L.ReLU(n.conv_u2b_c)
# n.conv_u2c_d = L.Convolution(n.relu_u2c, num_output=256,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u2d = L.ReLU(n.conv_u2c_d)
# #n.upconv_u2d_u1a = L.Deconvolution(n.relu_u2d, num_output=128,pad =0,kernel_size=2,stride=2,weight_filler=dict(type='xavier'))
# n.upconv_u2d_u1a = L.Deconvolution(n.relu_u2d)
# n.relu_u1a = L.ReLU(n.upconv_u2d_u1a)
n.crop_d2c_d2cc = L.Crop(n.relu_d2c,n.relu_u2a)
n.concat_d2cc_u2a_b = L.Concat(n.relu_u2a,n.crop_d2c_d2cc)
n.conv_u2b_c,n.relu_u2c = conv_relu(n.concat_d2cc_u2a_b,256)
n.conv_u2c_d,n.relu_u2d = conv_relu(n.relu_u2c,256)
n.upconv_u2d_u1a,n.relu_u1a = deconv_relu(n.relu_u2d,128)
# n.crop_d1c_d1cc = L.Crop(n.relu_d1c,n.relu_u1a)
# n.concat_d1cc_u1a_b = L.Concat(n.relu_u1a,n.crop_d1c_d1cc)
# n.conv_u1b_c = L.Convolution(n.concat_d1cc_u1a_b,num_output=128,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u1c = L.ReLU(n.conv_u1b_c)
# n.conv_u1c_d = L.Convolution(n.relu_u1c, num_output=128,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u1d = L.ReLU(n.conv_u1c_d)
# #n.upconv_u1d_u0a = L.Deconvolution(n.relu_u1d, num_output=64,pad =0,kernel_size=2,stride=2,weight_filler=dict(type='xavier'))
# n.upconv_u1d_u0a = L.Deconvolution(n.relu_u1d)
# n.relu_u0a = L.ReLU(n.upconv_u1d_u0a)
n.crop_d1c_d1cc = L.Crop(n.relu_d1c,n.relu_u1a)
n.concat_d1cc_u1a_b = L.Concat(n.relu_u1a,n.crop_d1c_d1cc)
n.conv_u1b_c,n.relu_u1c = conv_relu(n.concat_d1cc_u1a_b,128)
n.conv_u1c_d,n.relu_u1d = conv_relu(n.relu_u1c,128)
n.upconv_u1d_u0a,n.relu_u0a = deconv_relu(n.relu_u1d,128)
# n.crop_d0c_d0cc = L.Crop(n.relu_d0c,n.relu_u0a)
# n.concat_d0cc_u0a_b = L.Concat(n.relu_u0a,n.crop_d0c_d0cc)
# n.conv_u0b_c = L.Convolution(n.concat_d0cc_u0a_b,num_output=64,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u0c = L.ReLU(n.conv_u0b_c)
# n.conv_u0c_d = L.Convolution(n.relu_u0c, num_output=64,pad=0,kernel_size=3,weight_filler=dict(type='xavier'))
# n.relu_u0d = L.ReLU(n.conv_u0c_d)
n.crop_d0c_d0cc = L.Crop(n.relu_d0c,n.relu_u0a)
n.concat_d0cc_u0a_b = L.Concat(n.relu_u0a,n.crop_d0c_d0cc)
n.conv_u0b_c,n.relu_u0c = conv_relu(n.concat_d0cc_u0a_b,64)
n.conv_u0c_d,n.relu_u0d = conv_relu(n.relu_u0c,64)
n.conv_u0d_score = L.Convolution(n.relu_u0d, num_output=2,pad=0,kernel_size=1,
weight_filler= dict(type='xavier'),
param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)])
# keep this loss layer for all networks
n.loss = L.SoftmaxWithLoss(n.conv_u0d_score, n.label,loss_param=dict(ignore_label=2))
return n.to_proto()
with open(train_net_path, 'w') as f:
f.write(str(custom_net('list_train.txt', 1)))
with open(test_net_path, 'w') as f:
f.write(str(custom_net('list_test.txt', 1)))
### define solver
from caffe.proto import caffe_pb2
model = caffe_pb2.NetParameter()
text_format.Merge(open(train_net_path).read(), model)
model.force_backward = True
open(train_net_path, 'w').write(str(model))
s = caffe_pb2.SolverParameter()
# Set a seed for reproducible experiments:
# this controls for randomization in training.
s.random_seed = 0xCAFFE
# Specify locations of the train and (maybe) test networks.
s.train_net = train_net_path
s.test_net.append(test_net_path)
s.test_interval = 500 # Test after every 500 training iterations.
s.test_iter.append(100) # Test on 100 batches each time we test.
s.max_iter = 10000 # no. of times to update the net (training iterations)
# EDIT HERE to try different solvers
# solver types include "SGD", "Adam", and "Nesterov" among others.
s.type = "SGD"
# Set the initial learning rate for SGD.
s.base_lr = 0.01 # EDIT HERE to try different learning rates
# Set momentum to accelerate learning by
# taking weighted average of current and previous updates.
s.momentum = 0.9
# Set weight decay to regularize and prevent overfitting
s.weight_decay = 5e-4
# Set `lr_policy` to define how the learning rate changes during training.
# This is the same policy as our default LeNet.
s.lr_policy = 'inv'
s.gamma = 0.0001
s.power = 0.75
# EDIT HERE to try the fixed rate (and compare with adaptive solvers)
# `fixed` is the simplest policy that keeps the learning rate constant.
# s.lr_policy = 'fixed'
# Display the current training loss and accuracy every 1000 iterations.
s.display = 1000
# Snapshots are files used to store networks we've trained.
# We'll snapshot every 5K iterations -- twice during training.
s.snapshot = 5000
s.snapshot_prefix = 'my_Unet'
# Train on the GPU
s.solver_mode = caffe_pb2.SolverParameter.GPU
# Write the solver to a temporary file and return its filename.
with open(solver_config_path, 'w') as f:
f.write(str(s))
### load the solver and create train and test nets
solver = None # ignore this workaround for lmdb data (can't instantiate two solvers on the same data)
solver = caffe.get_solver(solver_config_path)
### solve
niter = 250 # EDIT HERE increase to train for longer
test_interval = niter / 10
# losses will also be stored in the log
train_loss = np.zeros(niter)
test_acc = np.zeros(int(np.ceil(niter / test_interval)))
# the main solver loop
for it in range(niter):
solver.step(1) # SGD by Caffe
# store the train loss
train_loss[it] = solver.net.blobs['loss'].data
# run a full test every so often
# (Caffe can also do this for us and write to a log, but we show here
# how to do it directly in Python, where more complicated things are easier.)
if it % test_interval == 0:
print ('Iteration', it, 'testing...')
correct = 0
for test_it in range(100):
solver.test_nets[0].forward()
correct += sum(solver.test_nets[0].blobs['score'].data.argmax(1)
== solver.test_nets[0].blobs['label'].data)
test_acc[it // test_interval] = correct / 1e4
<file_sep>/Caffe/Logistic_Regression/logistic_regression.py
import numpy as np
import matplotlib.pyplot as pyplot
import os
import caffe
import h5py
import shutil
import tempfile
import sklearn
import sklearn.cross_validation
import sklearn.datasets
import sklearn.linear_model
import pandas as pd
# Synthesize a dataset of 10,000 4-vectors for
# binary classification with 2 informative features and 2 noise features.
X, y = sklearn.datasets.make_classification(n_samples=10000,n_features=4,n_redundant=0,
n_informative=2, n_clusters_per_class=2,hypercube=False, random_state=0)
# Split into train and test
X, Xt, y, yt = sklearn.cross_validation.train_test_split(X, y)
# Visualize sample of the data
ind = np.random.permutation(X.shape[0])[:1000] #Randomly permute a sequence, or return a permuted range.
df = pd.DataFrame(X[ind])
_ = pd.scatter_matrix(df,figsize=(9,9),diagonal='kde', marker='o',s=40, alpha=0.4,c=y[ind])
# using kcikit-learn SGD logistic regression
clf = sklearn.linear_model.SGDClassifier(loss='log',n_iter=1000,penalty='l2',alpha=5e-4,class_weight='auto')
clf.fit(X,y)
yt_pred = clf.predict(Xt)
#print 'Accuracy: {:,3f}'.format(sklearn.metrics.accuracy_score(yt,yt_pred))
# Save the dataset to HDF5 for loading in Caffe.
dirname = 'data'
train_filename = os.path.join(dirname,'train.h5')
test_filename = os.path.join(dirname,'test.h5')
# HDF5DataLayer source should be a file containing a list of HDF5 filenames.
# To show this off, we'll list the same data file twice.
with h5py.File(train_filename,'w') as f:
f['data'] = X
f['label'] = y.astype(np.float32)
with open(os.path.join(dirname ,'train.txt'),'w') as f:
f.write(train_filename + '\n')
f.write(train_filename + '\n')
# HDF5 is pretty efficient, but can be further compressed.
comp_kwargs = {'compression':'gzip','compression_opts':1}
with h5py.File(test_filename,'w') as f:
f.create_dataset('data',data=Xt, **comp_kwargs)
f.create_dataset('label',data=yt.astype(np.float32), **comp_kwargs)
with open(os.path.join(dirname,'test.txt'),'w') as f:
f.write(test_filename + '\n')
# Let's define logistic regression in Caffe through Python net specification. This is a
# quick and natural way to define nets that sidesteps manually editing the protobuf model
from caffe import layers as L
from caffe import params as P
def logreg(hdf5, batch_size):
# logistic regression: data, matrix multiplication, and 2-class softmax loss
n=caffe.NetSpec()
n.data,n.label = L.HDF5Data(batch_size=batch_size,source=hdf5,ntop=2)
n.ip1 = L.InnerProduct(n.data,num_output=2,weight_filler=dict(type='xavier'))
n.accuracy = L.Accuracy(n.ip1,n.label)
n.loss = L.SoftmaxWithLoss(n.ip1,n.label)
return n.to_proto()
train_net_path = 'logreg_auto_train.prototxt'
with open(train_net_path, 'w') as f:
f.write(str(logreg('data/train.txt', 10)))
test_net_path = 'logreg_auto_test.prototxt'
with open(test_net_path, 'w') as f:
f.write(str(logreg('data/test.txt', 10)))
# Now, we'll define our "solver" which trains the network by specifying
# the locations of the train and test nets we defined above, as well as
# setting values for various parameters used for learning, display, and
# "snapshotting".
from caffe.proto import caffe_pb2
def solver(train_net_path,test_net_path):
s = caffe_pb2.SolverParameter()
# specify locations of the train and test networks.
s.train_net = train_net_path
s.test_net.append(test_net_path)
s.test_interval = 1000 # Test after every 1000 training iterations
s.test_iter.append(250)# Test 250 'batches' each time
s.max_iter = 10000 # max iteration
# Set the initial learning rate for stochastic gradient descent(SGD)
s.base_lr = 0.01
# Set `lr_policy` to define how the learning rate changes during training.
# Here, we 'step' the learning rate by multiplying it by a factor `gamma`
# every `stepsize` iterations.
s.lr_policy = 'step'
s.gamma = 0.1
s.stepsize = 5000
# Set other optimization parameters. Setting a non-zero `momentum` takes a
# weighted average of the current gradient and previous gradients to make
# learning more stable. L2 weight decay regularizes learning, to help prevent
# the model from overfitting.
s.momentum = 0.9
s.weight_decay = 5e-4
# Display the current training loss and accuracy every 1000 iterations.
s.display = 1000
# Snapshots are files used to store networks we've trained. Here, we'll
# snapshot every 10K iterations -- just once at the end of training.
# For larger networks that take longer to train, you may want to set
# snapshot < max_iter to save the network and training state to disk during
# optimization, preventing disaster in case of machine crashes, etc.
s.snapshot = 10000
s.snapshot_prefix = 'data/train'
# We'll train on the CPU for fair benchmarking against scikit-learn.
# Changing to GPU should result in much faster training!
s.solver_mode = caffe_pb2.SolverParameter.CPU
return s
solver_path = 'logreg_solver.prototxt'
with open(solver_path,'w') as f:
f.write(str(solver(train_net_path,test_net_path)))
# Time to learn and evaluate our Caffeinated logistic regression in Python.
caffe.set_mode_cpu()
solver = caffe.get_solver(solver_path)
solver.solve()
accuracy = 0
batch_size = solver.test_nets[0].blobs['data'].num
test_iters = int(len(Xt) / batch_size)
for i in range(test_iters):
solver.test_nets[0].forward()
accuracy += solver.test_nets[0].blobs['accuracy'].data
accuracy /= test_iters
# print "Accuracy: {:.3f}".format(accuracy)
# add a relu in logistic net
#def nonlinear_net(hdf5, batch_size):
# # one small nonlinearity, one leap for model kind
# n = caffe.NetSpec()
# n.data, n.label = L.HDF5Data(batch_size=batch_size, source=hdf5, ntop=2)
# # define a hidden layer of dimension 40
# n.ip1 = L.InnerProduct(n.data, num_output=40, weight_filler=dict(type='xavier'))
# # transform the output through the ReLU (rectified linear) non-linearity
# n.relu1 = L.ReLU(n.ip1, in_place=True)
# # score the (now non-linear) features
# n.ip2 = L.InnerProduct(n.ip1, num_output=2, weight_filler=dict(type='xavier'))
# # same accuracy and loss as before
# n.accuracy = L.Accuracy(n.ip2, n.label)
# n.loss = L.SoftmaxWithLoss(n.ip2, n.label)
# return n.to_proto()
#
#train_net_path = 'nonlinear_auto_train.prototxt'
#with open(train_net_path, 'w') as f:
# f.write(str(nonlinear_net('data/train.txt', 10)))
#
#test_net_path = 'nonlinear_auto_test.prototxt'
#with open(test_net_path, 'w') as f:
# f.write(str(nonlinear_net('data/test.txt', 10)))
#
#solver_path = 'nonlinear_logreg_solver.prototxt'
#with open(solver_path, 'w') as f:
# f.write(str(solver(train_net_path, test_net_path)))<file_sep>/Caffe/unet/hdf5.py
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 22 14:38:08 2016
Create HDF5 files
@author: core
"""
#import necessary lib
import cv2
from PIL import Image
import numpy as np
import os
import h5py
Train_Dir = 'train'
Hdf5_File = ['hdf5_train.h5']
List_File = ['list_train.txt']
trainList = os.listdir(Train_Dir)
trainDataList=[]
trainMaskList=[]
for filename in trainList:
if 'mask' in filename:
trainMaskList.append('train/'+filename)
else:
trainDataList.append('train/'+filename)
# 图片大小为96*32,单通道
datas = np.zeros((len(trainDataList), 1, 420,580))
# label大小为1*2
masks = np.zeros((len(trainMaskList), 1, 244,404))
for ii, file in enumerate(trainDataList):
# hdf5文件要求数据是float或者double格式
# 同时caffe中Hdf5DataLayer不允许使用transform_param,
# 所以要手动除以256
inImage=cv2.imread(file,0).astype(np.float32)
datas[ii, :, :, :] = inImage / 256
outImage=cv2.imread(file[:-4]+'_mask.tif',0).astype(np.float32)
outImage=cv2.resize(outImage,(404,244))
masks[ii, :, :, :] = outImage / 256
if ii % 100 ==0 and ii>0 or ii == len(trainDataList)-1:
# 写入hdf5文件
with h5py.File('hdf5_tain_'+str(ii//100)+'.h5', 'w') as f:
f.create_dataset('data', data = datas[ii-100:ii,:,:,:])
f.create_dataset('label', data = masks[ii-100:ii,:,:,:])
f.close()
# 写入列表文件,可以有多个hdf5文件
with open('list_train.txt', 'w') as f:
f.write(os.path.abspath('hdf5_tain_'+str(ii//100)+'.h5') + '\n')
f.close()
break<file_sep>/Caffe/CustomTest/MyTest.py
# Test different net structure and hyperparameter
from pylab import *
caffe_root = '/home/core/Tool/caffe-master/' # this file should be run from {caffe_root}/examples (otherwise change this line)
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
from caffe import layers as L, params as P
train_net_path = 'train.prototxt'
test_net_path = 'test.prototxt'
solver_config_path = 'solver.prototxt'
### define net
def customNet(lmdb,batch_size):
#define Lenet
n = caffe.NetSpec()
n.data, n.label = L.Data(batch_size=batch_size, backend=P.Data.LMDB, source=lmdb, transform_param=dict(scale=1./255),ntop=2)
n.conv1 = L.Convolution(n.data, kernel_size=3, num_output=20, weight_filler=dict(type='xavier'))
n.bn1 = L.BatchNorm(n.conv1,in_place=True)
n.scale1 = L.Scale(n.bn1,bias_term=True,bias_filler=dict(value=0),filler=dict(value=1))
n.conv2 = L.Convolution(n.scale1, kernel_size=3,stride=2, num_output=20, weight_filler=dict(type='xavier'))
n.bn2 = L.BatchNorm(n.conv2,in_place=True)
n.scale2 = L.Scale(n.bn2,bias_term=True,bias_filler=dict(value=0),filler=dict(value=1))
# n.pool1 = L.Pooling(n.scale2, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.conv3 = L.Convolution(n.scale2, kernel_size=3, num_output=50, weight_filler = dict(type='xavier'))
n.bn3 = L.BatchNorm(n.conv3,in_place=True)
n.scale3 = L.Scale(n.bn3,bias_term=True,bias_filler=dict(value=0),filler=dict(value=1))
n.conv4 = L.Convolution(n.scale3, kernel_size=3, stride=2,num_output=50, weight_filler=dict(type='xavier'))
n.bn4 = L.BatchNorm(n.conv4,in_place=True)
n.scale4 = L.Scale(n.bn4,bias_term=True,bias_filler=dict(value=0),filler=dict(value=1))
# n.pool2 = L.Pooling(n.scale4, kernel_size=2, stride=2, pool=P.Pooling.MAX)
n.fc1 = L.InnerProduct(n.scale4, num_output=500, weight_filler=dict(type='xavier'))
n.relu1 = L.ReLU(n.fc1, in_place=True)
n.fc2 = L.InnerProduct(n.relu1, num_output=100, weight_filler=dict(type='xavier'))
n.relu2 = L.ReLU(n.fc2, in_place=True)
n.score = L.InnerProduct(n.relu2,num_output=10, weight_filler=dict(type='xavier'))
n.loss = L.SoftmaxWithLoss(n.score, n.label)
return n.to_proto()
with open(train_net_path,'w') as f:
f.write(str(customNet('data/mnist_train_lmdb',64)))
with open(test_net_path,'w') as f:
f.write(str(customNet('data/mnist_test_lmdb',100)))
### define solver
from caffe.proto import caffe_pb2
s = caffe_pb2.SolverParameter()
# Set a seed for reproducible experiments:
# this controls for randomization in training.
s.random_seed = 0xCAFFE
# Specify locations of the train and (maybe) test networks.
s.train_net = train_net_path
s.test_net.append(test_net_path)
s.test_interval = 100 # Test after every 500 training iterations.
s.test_iter.append(100) # Test on 100 batches each time we test.
s.max_iter = 1000 # no. of times to update the net (training iterations)
# solver types include "SGD", "Adam", and "Nesterov" among others.
s.type = "SGD"
# Set the initial learning rate for SGD.
s.base_lr = 0.01
# Set momentum to accelerate learning by
# taking weighted average of current and previous updates.
s.momentum = 0.9
# Set weight decay to regularize and prevent overfitting
s.weight_decay = 5e-4
# Set `lr_policy` to define how the learning rate changes during training.
# This is the same policy as our default LeNet.
s.lr_policy = 'inv'
s.gamma = 0.0001
s.power = 0.75
# `fixed` is the simplest policy that keeps the learning rate constant.
# s.lr_policy = 'fixed'
# Display the current training loss and accuracy every 1000 iterations.
s.display = 100
# Snapshots are files used to store networks we've trained.
# We'll snapshot every 5K iterations -- twice during training.
s.snapshot = 5000
s.snapshot_prefix = 'custom_net'
# Train on the CPU
s.solver_mode = caffe_pb2.SolverParameter.CPU
# Write the solver to a temporary file and return its filename.
with open(solver_config_path, 'w') as f:
f.write(str(s))
### load the solver and create train and test nets
solver = None # ignore this workaround for lmdb data (can't instantiate two solvers on the same data)
solver = caffe.get_solver(solver_config_path)
### solve
niter = 1000 # EDIT HERE increase to train for longer
test_interval = niter / 10
# losses will also be stored in the log
train_loss = zeros(niter)
test_acc = zeros(int(np.ceil(niter / test_interval)))
# the main solver loop
for it in range(niter):
solver.step(1) # SGD by Caffe
# store the train loss
train_loss[it] = solver.net.blobs['loss'].data
# run a full test every so often
# (Caffe can also do this for us and write to a log, but we show here
# how to do it directly in Python, where more complicated things are easier.)
if it % test_interval == 0:
print 'Iteration', it, 'testing...'
correct = 0
for test_it in range(100):
solver.test_nets[0].forward()
correct += sum(solver.test_nets[0].blobs['score'].data.argmax(1)
== solver.test_nets[0].blobs['label'].data)
test_acc[it // test_interval] = correct / 1e4
print test_acc<file_sep>/Caffe/Object_Recogintion/classification.py
import caffe
import matplotlib.pyplot as plt
import numpy as np
caffe_root = '/home/core/Tool/caffe-master/'
model_def = 'deploy.prototxt'
model_weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
caffe.set_mode_cpu()
net = caffe.Net(model_def, # model structure
model_weights, #model trained weights
caffe.TEST) # use test mode
# load the mean ImageNet image (as distributed with Caffe) for subtraction
mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
mu = mu.mean(1).mean(1) # average over pixels to obtain the mean (BGR) pixel values
print 'mean-subtracted values:', zip('BGR', mu)
# create transformer for the input called 'data'
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1)) # move image channels to outermost dimension
transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap('data', (2,1,0)) # swap channels from RGB to BGR
# set the size of the input (we can skip this if we're happy
# with the default; we can also change it later, e.g., for different batch sizes)
net.blobs['data'].reshape(50, # batch size
3, # 3-channel (BGR) images
227, 227) # image size is 227x227
image = caffe.io.load_image('cat.jpg')
transformed_image = transformer.preprocess('data', image)
plt.imshow(image)
# copy the image data into the memory allocated for the net
net.blobs['data'].data[...] = transformed_image
### perform classification
output = net.forward()
output_prob = output['prob'][0] # the output probability vector for the first image in the batch
print 'predicted class is:', output_prob.argmax()
# sort top five predictions from softmax output
top_inds = output_prob.argsort()[::-1][:5]<file_sep>/Caffe/ResNet/ResNet.py
# impletation of ResNet50 using caffe python
import caffe
from caffe import layers as L
from caffe import params as P
# define main network
def Conv_BN_Scale(bottom, ks, nout, pad, stride):
conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout,
pad=pad, bias_term=True)
bn = L.BatchNorm(conv, use_global_stats=True, in_place=True) # in_place can speed up
scale = L.Scale(bn,bias_term=True, in_place=True)
return conv, bn, scale
def block(bottom, nout, branch1=False, initial_stride=2):
'''defination of ResNet block'''
if branch1:
# conv1 = L.Convolution(bottom,num_output=4*nout, kernel_size=1, pad=0,
# stride=1,bias_term=False)
# bn1 = L.BatchNorm(conv1, use_global_stats=True, in_place=True)
# scale1 = L.Scale(bn1, bias_term=True, in_place=True)
conv1, bn1, scale1 = Conv_BN_Scale(bottom, 1, 4*nout, 0, initial_stride)
else:
initial_stride = 1
# conv2a = L.Convolution(bottom,num_output=nout, kernel_size=1, pad=0,
# stride=1,bias_term=False)
# bn2a = L.BatchNorm(conv2a, use_global_stats=True, in_place=True)
# scale2a = L.Scale(bn2a, bias_term=True, in_place=True)
conv2a, bn2a, scale2a = Conv_BN_Scale(bottom, 1, nout, 0, initial_stride)
relu2a = L.ReLU(scale2a, in_place=True)
# conv2b = L.Convolution(relu2a,num_output=nout, kernel_size=3, pad=1,
# stride=1,bias_term=False)
# bn2b = L.BatchNorm(conv2b, use_global_stats=True, in_place=True)
# scale2b = L.Scale(bn2b, bias_term=True, in_place=True)
conv2b, bn2b, scale2b = Conv_BN_Scale(relu2a, 3, nout, 1, 1)
relu2b = L.ReLU(scale2b, in_place=True)
# conv2c = L.Convolution(relu2b,num_output=4*nout, kernel_size=1, pad=0,
# stride=1,bias_term=False)
# bn2c = L.BatchNorm(conv2c, use_global_stats=True, in_place=True)
# scale2c = L.Scale(bn2c, bias_term=True, in_place=True)
conv2c, bn2c, scale2c = Conv_BN_Scale(relu2b, 1, 4*nout, 0, 1)
if branch1:
elt = L.Eltwise(scale1, scale2c, in_place=True)
else:
elt = L.Eltwise(bottom, scale2c)
res2a_relu = L.ReLU(elt, in_place=True)
if branch1:
return conv1,bn1,scale1, \
conv2a, bn2a, scale2a, relu2a, \
conv2b, bn2b, scale2b, relu2b, \
conv2c, bn2c, scale2c, \
elt, res2a_relu
else:
return conv2a, bn2a, scale2a, relu2a, \
conv2b, bn2b, scale2b, relu2b, \
conv2c, bn2c, scale2c, \
elt, res2a_relu
def ResNet50():
n = caffe.NetSpec()
n.data = L.DummyData(shape=[dict(dim=[1,2,224,224])])
n.conv1, n.bn_conv1, n.scale_conv1 = Conv_BN_Scale(n.data, 7, 64,3,2)
n.conv1_relu = L.ReLU(n.scale_conv1, in_place=True)
n.pool1 = L.Pooling(n.conv1_relu, kernel_size=3, stride=2, pool=P.Pooling.MAX)
n.conv2a_b1, n.bn2a_b1, n.scale2a_b1, n.conv2a_b2a, n.bn2a_b2a, n.scale2a_b2a,\
n.relu2a_b2a, n.conv2a_b2b, n.bn2a_b2b, n.scale2a_b2b, n.relu2a_b2b, \
n.conv2a_b2c, n.bn2a_b2c, n.scale2a_b2c, n.elt2a, n.relu2a = block(n.pool1, 64, branch1=True, initial_stride=1)
n.conv2b_b2a, n.bn2b_b2a, n.scale2b_b2a,\
n.relu2b_b2a, n.conv2b_b2b, n.bn2b_b2b, n.scale2b_b2b, n.relu2b_b2b, \
n.conv2b_b2c, n.bn2b_b2c, n.scale2b_b2c, n.elt2b, n.relu2b = block(n.relu2a, 64)
n.conv2c_b2a, n.bn2c_b2a, n.scale2c_b2a,\
n.relu2c_b2a, n.conv2c_b2b, n.bn2c_b2b, n.scale2c_b2b, n.relu2c_b2b, \
n.conv2c_b2c, n.bn2c_b2c, n.scale2c_b2c, n.elt2c, n.relu2c = block(n.relu2b, 64)
n.conv3a_b1, n.bn3a_b1, n.scale3a_b1, n.conv3a_b2a, n.bn3a_b2a, n.scale3a_b2a,\
n.relu3a_b2a, n.conv3a_b2b, n.bn3a_b2b, n.scale3a_b2b, n.relu3a_b2b, \
n.conv3a_b2c, n.bn3a_b2c, n.scale3a_b2c, n.elt3a, n.relu3a = block(n.relu2c, 128, branch1=True)
n.conv3b_b2a, n.bn3b_b2a, n.scale3b_b2a,\
n.relu3b_b2a, n.conv3b_b2b, n.bn3b_b2b, n.scale3b_b2b, n.relu3b_b2b, \
n.conv3b_b2c, n.bn3b_b2c, n.scale3b_b2c, n.elt3b, n.relu3b = block(n.relu3a, 128)
n.conv3c_b2a, n.bn3c_b2a, n.scale3c_b2a,\
n.relu3c_b2a, n.conv3c_b2b, n.bn3c_b2b, n.scale3c_b2b, n.relu3c_b2b, \
n.conv3c_b2c, n.bn3c_b2c, n.scale3c_b2c, n.elt3c, n.relu3c = block(n.relu3b, 128)
n.conv3d_b2a, n.bn3d_b2a, n.scale3d_b2a,\
n.relu3d_b2a, n.conv3d_b2b, n.bn3d_b2b, n.scale3d_b2b, n.relu3d_b2b, \
n.conv3d_b2c, n.bn3d_b2c, n.scale3d_b2c, n.elt3d, n.relu3d = block(n.relu3c, 128)
n.conv4a_b1, n.bn4a_b1, n.scale4a_b1, n.conv4a_b2a, n.bn4a_b2a, n.scale4a_b2a,\
n.relu4a_b2a, n.conv4a_b2b, n.bn4a_b2b, n.scale4a_b2b, n.relu4a_b2b, \
n.conv4a_b2c, n.bn4a_b2c, n.scale4a_b2c, n.elt4a, n.relu4a = block(n.relu3d, 256, branch1=True)
n.conv4b_b2a, n.bn4b_b2a, n.scale4b_b2a,\
n.relu4b_b2a, n.conv4b_b2b, n.bn4b_b2b, n.scale4b_b2b, n.relu4b_b2b, \
n.conv4b_b2c, n.bn4b_b2c, n.scale4b_b2c, n.elt4b, n.relu4b = block(n.relu4a, 256)
n.conv4c_b2a, n.bn4c_b2a, n.scale4c_b2a,\
n.relu4c_b2a, n.conv4c_b2b, n.bn4c_b2b, n.scale4c_b2b, n.relu4c_b2b, \
n.conv4c_b2c, n.bn4c_b2c, n.scale4c_b2c, n.elt4c, n.relu4c = block(n.relu4b, 256)
n.conv4d_b2a, n.bn4d_b2a, n.scale4d_b2a,\
n.relu4d_b2a, n.conv4d_b2b, n.bn4d_b2b, n.scale4d_b2b, n.relu4d_b2b, \
n.conv4d_b2c, n.bn4d_b2c, n.scale4d_b2c, n.elt4d, n.relu4d = block(n.relu4c, 256)
n.conv4e_b2a, n.bn4e_b2a, n.scale4e_b2a,\
n.relu4e_b2a, n.conv4e_b2b, n.bn4e_b2b, n.scale4e_b2b, n.relu4e_b2b, \
n.conv4e_b2c, n.bn4e_b2c, n.scale4e_b2c, n.elt4e, n.relu4e = block(n.relu4d, 256)
n.conv4f_b2a, n.bn4f_b2a, n.scale4f_b2a,\
n.relu4f_b2a, n.conv4f_b2b, n.bn4f_b2b, n.scale4f_b2b, n.relu4f_b2b, \
n.conv4f_b2c, n.bn4f_b2c, n.scale4f_b2c, n.elt4f, n.relu4f = block(n.relu4e, 256)
n.conv5a_b1, n.bn5a_b1, n.scale5a_b1, n.conv5a_b2a, n.bn5a_b2a, n.scale5a_b2a,\
n.relu5a_b2a, n.conv5a_b2b, n.bn5a_b2b, n.scale5a_b2b, n.relu5a_b2b, \
n.conv5a_b2c, n.bn5a_b2c, n.scale5a_b2c, n.elt5a, n.relu5a = block(n.relu4f, 512, branch1=True)
n.conv5b_b2a, n.bn5b_b2a, n.scale5b_b2a,\
n.relu5b_b2a, n.conv5b_b2b, n.bn5b_b2b, n.scale5b_b2b, n.relu5b_b2b, \
n.conv5b_b2c, n.bn5b_b2c, n.scale5b_b2c, n.elt5b, n.relu5b = block(n.relu5a, 512)
n.conv5c_b2a, n.bn5c_b2a, n.scale5c_b2a,\
n.relu5c_b2a, n.conv5c_b2b, n.bn5c_b2b, n.scale5c_b2b, n.relu5c_b2b, \
n.conv5c_b2c, n.bn5c_b2c, n.scale5c_b2c, n.elt5c, n.relu5c = block(n.relu5b, 512)
n.pool5 = L.Pooling(n.relu5c, kernel_size=7, stride=1, pool=P.Pooling.AVE)
n.fc1000 = L.InnerProduct(n.pool5, num_output=1000)
n.prob = L.Softmax(n.fc1000)
return n.to_proto()
with open('myResNet50.prototxt','w') as f:
f.write(str(ResNet50())) | c10244a48d5b4a2ef88dc125941f7e9f641f983b | [
"Python",
"Shell"
] | 8 | Python | Xutop/DeepLearning | 6a7c9002b2fcc2e487f9eac9ba8cbc6c0aaff9d2 | 4411998fccda695e04706536af2f4861f9b74bed |
refs/heads/master | <repo_name>camigthompson/cursello<file_sep>/README.md
# cursello
Task tracking curses client. Meant to be similar to [trello](https://trello.com).
## Contributing
I would some love pull requests. I've tried to make issues that point to pretty self contained changes. Check those out, then make a pull request.
<file_sep>/cursello.py
#!/usr/bin/env python2.7
import curses
from curses.textpad import rectangle
import time
class List:
def __init__(self, name):
self.name = name
self.size = 0
self.items = []
self.archived = []
def add(self, item):
self.items.append(item)
self.size += 1
def archive(self, n):
self.archived.append(self.items[n])
del self.items[n]
self.size -= 1
stdscr = curses.initscr()
curses.noecho()
curses.start_color()
stdscr.refresh()
def refresh_lists(stdscr, data, ilist, itemw):
at = 1
for i, items in enumerate(data):
width = max(max(map(len, items.items) + [0]), len(items.name)) + 1
rectangle(stdscr, 0, at - 1, items.size + 2, at + width)
if i == ilist:
stdscr.addstr(1, at, items.name, curses.A_UNDERLINE)
for j, item in enumerate(items.items):
if j == itemw:
stdscr.addstr(j + 2, at, item, curses.A_BOLD)
else:
stdscr.addstr(j + 2, at, item)
else:
y = 1
stdscr.addstr(y, at, items.name)
for j, item in enumerate(items.items):
y += 1
stdscr.addstr(y, at, item)
at += width + 2
def new_item(stdscr, data, ilist):
stdscr.addstr(curses.LINES - 1, 0, "Enter item description, then press enter:", curses.A_BOLD)
i = stdscr.getch()
stdscr.addstr(curses.LINES - 1, 0, " ", curses.A_BOLD)
st = chr(i)
while i != 10:
debug(stdscr, str(st), style=curses.A_UNDERLINE)
stdscr.refresh()
i = stdscr.getch()
if i < 256:
st += chr(i)
stdscr.addstr(curses.LINES - 1, 0, " ", curses.A_BOLD)
data[ilist].add(st)
def new_list(stdscr, data, ilist):
stdscr.addstr(curses.LINES - 1, 0, "Enter the name of the new list, then press enter:", curses.A_BOLD)
i = stdscr.getch()
stdscr.addstr(curses.LINES - 1, 0, " ", curses.A_BOLD)
st = chr(i)
while i != 10:
debug(stdscr, str(st), style=curses.A_UNDERLINE)
stdscr.refresh()
i = stdscr.getch()
if i < 256:
st += chr(i)
stdscr.addstr(curses.LINES - 1, 0, " ", curses.A_BOLD)
data.append(List(st))
ilist = len(data) - 1
def init(stdscr):
stdscr.addstr(curses.LINES - 1, 0, "(q) to quit. (o) to add an item to a list. Vim style movement.", curses.A_BOLD)
def debug(stdscr, msg, style=curses.A_DIM):
stdscr.addstr(curses.LINES - 1, 0, msg, style)
def main(stdscr):
ilist = 0
item = 0
data = [List("To Do"), List("Done")]
while True:
refresh_lists(stdscr, data, ilist, item)
stdscr.refresh()
c = stdscr.getch()
# Move down within list
if c == ord('j'):
item = min(item + 1, data[ilist].size - 1)
# Move up within list
elif c == ord('k'):
item = max(item - 1, 0)
# Move right to next list
elif c == ord('l'):
ilist = min(ilist + 1, len(data) - 1)
item = min(item, data[ilist].size - 1)
# Move left to next list
elif c == ord('h'):
ilist = max(ilist - 1, 0)
item = min(item, data[ilist].size - 1)
# Create new item in list
elif c == ord('o'):
new_item(stdscr, data, ilist)
# Create new list
elif c == ord('a'):
new_list(stdscr, data, ilist)
# Quit
elif c == ord('q'):
break
else:
pass
curses.wrapper(main)
| e57f83e1dbab3e31f3450115f072c4a229a0b53d | [
"Markdown",
"Python"
] | 2 | Markdown | camigthompson/cursello | 5250e315112265f1545be59363870168ee16a155 | ce25de797209d8430c7dda630a0864864d883fa8 |
refs/heads/master | <repo_name>lizhming/paper.io<file_sep>/docs/se/liu/ida/paperio/Player.html
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (10.0.2) on Thu Jan 10 08:40:27 CET 2019 -->
<title>Player</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2019-01-10">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Player";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10,"i13":10,"i14":6,"i15":10,"i16":10,"i17":10,"i18":10,"i19":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "../../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../se/liu/ida/paperio/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../se/liu/ida/paperio/PaperIO.STATE.html" title="enum in se.liu.ida.paperio"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?se/liu/ida/paperio/Player.html" target="_top">Frames</a></li>
<li><a href="Player.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>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<!-- ======== START OF CLASS DATA ======== -->
<main role="main">
<div class="header">
<div class="subTitle"><span class="packageLabelInType">Package</span> <a href="../../../../se/liu/ida/paperio/package-summary.html">se.liu.ida.paperio</a></div>
<h2 title="Class Player" class="title">Class Player</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>se.liu.ida.paperio.Player</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><code>java.lang.Comparable<<a href="../../../../se/liu/ida/paperio/Player.html" title="class in se.liu.ida.paperio">Player</a>></code></dd>
</dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><code><a href="../../../../se/liu/ida/paperio/BotPlayer.html" title="class in se.liu.ida.paperio">BotPlayer</a></code>, <code><a href="../../../../se/liu/ida/paperio/HumanPlayer.html" title="class in se.liu.ida.paperio">HumanPlayer</a></code></dd>
</dl>
<hr>
<pre>abstract class <span class="typeNameLabel">Player</span>
extends java.lang.Object
implements java.lang.Comparable<<a href="../../../../se/liu/ida/paperio/Player.html" title="class in se.liu.ida.paperio">Player</a>></pre>
<div class="block">An abstract class for a general player in the game. Human player and bot player differs a bit but their common logic
is specified here. It keeps track of players position, speed, color, owned and contested tiles and name. Two players
can also be compared that compares number of owned tiles of the player.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Field</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private java.awt.Color</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#color">color</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private <a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#currentTile">currentTile</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#dx">dx</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#dy">dy</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#height">height</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private java.lang.Boolean</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#isAlive">isAlive</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>(package private) java.lang.String</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#name">name</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#tilesContested">tilesContested</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>private java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#tilesOwned">tilesOwned</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#width">width</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#x">x</a></span></code></th>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#y">y</a></span></code></th>
<td class="colLast"> </td>
</tr>
</table>
</li>
</ul>
</section>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Constructor</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr class="altColor">
<th class="colConstructorName" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#%3Cinit%3E(int,int,java.awt.Color)">Player</a></span>​(int height,
int width,
java.awt.Color color)</code></th>
<td class="colLast">
<div class="block">Initializes a player on a random spot on the game area with specified color</div>
</td>
</tr>
</table>
</li>
</ul>
</section>
<!-- ========== METHOD SUMMARY =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#checkCollision(se.liu.ida.paperio.Tile)">checkCollision</a></span>​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</code></th>
<td class="colLast">
<div class="block">Kills the player contesting a tile when travelling on it</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#compareTo(se.liu.ida.paperio.Player)">compareTo</a></span>​(<a href="../../../../se/liu/ida/paperio/Player.html" title="class in se.liu.ida.paperio">Player</a> player)</code></th>
<td class="colLast">
<div class="block">Compares two players by the number of tiles owned.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#contestToOwned()">contestToOwned</a></span>()</code></th>
<td class="colLast">
<div class="block">Sets contested tiles to owned by player</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#die()">die</a></span>()</code></th>
<td class="colLast">
<div class="block">Logic for when player gets killed.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>(package private) java.lang.Boolean</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getAlive()">getAlive</a></span>()</code></th>
<td class="colLast">
<div class="block">Get alive state of player</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>(package private) java.awt.Color</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getColor()">getColor</a></span>()</code></th>
<td class="colLast"> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getDx()">getDx</a></span>()</code></th>
<td class="colLast">
<div class="block">Get the players speed in x direction</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getDy()">getDy</a></span>()</code></th>
<td class="colLast">
<div class="block">Get the players speed in y direction</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>(package private) java.lang.String</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getName()">getName</a></span>()</code></th>
<td class="colLast">
<div class="block">Get name of player</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>(package private) double</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getPercentOwned()">getPercentOwned</a></span>()</code></th>
<td class="colLast">
<div class="block">Get as a percentage how much of the total game area a player owns</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>(package private) java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getTilesContested()">getTilesContested</a></span>()</code></th>
<td class="colLast">
<div class="block">Get tiles contested by player</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>(package private) java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>></code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getTilesOwned()">getTilesOwned</a></span>()</code></th>
<td class="colLast">
<div class="block">Get tiles owned by player</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getX()">getX</a></span>()</code></th>
<td class="colLast">
<div class="block">The x position in the tile system</div>
</td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>(package private) int</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#getY()">getY</a></span>()</code></th>
<td class="colLast">
<div class="block">The y position in the tile system</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>(package private) abstract void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#move()">move</a></span>()</code></th>
<td class="colLast">
<div class="block">Abstract method to move the player</div>
</td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#removeTileOwned(se.liu.ida.paperio.Tile)">removeTileOwned</a></span>​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</code></th>
<td class="colLast">
<div class="block">Remove a tile from owned</div>
</td>
</tr>
<tr id="i16" class="altColor">
<td class="colFirst"><code>void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#setAlive(java.lang.Boolean)">setAlive</a></span>​(java.lang.Boolean alive)</code></th>
<td class="colLast">
<div class="block">Set alive state of player</div>
</td>
</tr>
<tr id="i17" class="rowColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#setCurrentTile(se.liu.ida.paperio.Tile)">setCurrentTile</a></span>​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> currentTile)</code></th>
<td class="colLast">
<div class="block">Set tile to be current tile</div>
</td>
</tr>
<tr id="i18" class="altColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#setTileContested(se.liu.ida.paperio.Tile)">setTileContested</a></span>​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</code></th>
<td class="colLast">
<div class="block">Add tile to players list of contested tiles</div>
</td>
</tr>
<tr id="i19" class="rowColor">
<td class="colFirst"><code>(package private) void</code></td>
<th class="colSecond" scope="row"><code><span class="memberNameLink"><a href="../../../../se/liu/ida/paperio/Player.html#setTileOwned(se.liu.ida.paperio.Tile)">setTileOwned</a></span>​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</code></th>
<td class="colLast">
<div class="block">Add tile to players list of owned tiles</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a id="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a id="x">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>x</h4>
<pre>int x</pre>
</li>
</ul>
<a id="y">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>y</h4>
<pre>int y</pre>
</li>
</ul>
<a id="dx">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>dx</h4>
<pre>int dx</pre>
</li>
</ul>
<a id="dy">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>dy</h4>
<pre>int dy</pre>
</li>
</ul>
<a id="color">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>color</h4>
<pre>private java.awt.Color color</pre>
</li>
</ul>
<a id="tilesOwned">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tilesOwned</h4>
<pre>private java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>> tilesOwned</pre>
</li>
</ul>
<a id="tilesContested">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tilesContested</h4>
<pre>private java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>> tilesContested</pre>
</li>
</ul>
<a id="height">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>height</h4>
<pre>int height</pre>
</li>
</ul>
<a id="width">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>width</h4>
<pre>int width</pre>
</li>
</ul>
<a id="name">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>name</h4>
<pre>java.lang.String name</pre>
</li>
</ul>
<a id="isAlive">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isAlive</h4>
<pre>private java.lang.Boolean isAlive</pre>
</li>
</ul>
<a id="currentTile">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>currentTile</h4>
<pre>private <a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> currentTile</pre>
</li>
</ul>
</li>
</ul>
</section>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a id="<init>(int,int,java.awt.Color)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Player</h4>
<pre>Player​(int height,
int width,
java.awt.Color color)</pre>
<div class="block">Initializes a player on a random spot on the game area with specified color</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>height</code> - height of game area player is constructed in</dd>
<dd><code>width</code> - width of game area player is constructed in</dd>
<dd><code>color</code> - the color of the player</dd>
</dl>
</li>
</ul>
</li>
</ul>
</section>
<!-- ============ METHOD DETAIL ========== -->
<section role="region">
<ul class="blockList">
<li class="blockList"><a id="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a id="getX()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getX</h4>
<pre>int getX()</pre>
<div class="block">The x position in the tile system</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>x position in the tile system</dd>
</dl>
</li>
</ul>
<a id="getY()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getY</h4>
<pre>int getY()</pre>
<div class="block">The y position in the tile system</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>y position in the tile system</dd>
</dl>
</li>
</ul>
<a id="getColor()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getColor</h4>
<pre>java.awt.Color getColor()</pre>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>color of the player</dd>
</dl>
</li>
</ul>
<a id="move()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>move</h4>
<pre>abstract void move()</pre>
<div class="block">Abstract method to move the player</div>
</li>
</ul>
<a id="die()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>die</h4>
<pre>void die()</pre>
<div class="block">Logic for when player gets killed. Turns all associated tiles to neutral</div>
</li>
</ul>
<a id="setTileOwned(se.liu.ida.paperio.Tile)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTileOwned</h4>
<pre>void setTileOwned​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</pre>
<div class="block">Add tile to players list of owned tiles</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>t</code> - Tile to be added to players owned list</dd>
</dl>
</li>
</ul>
<a id="removeTileOwned(se.liu.ida.paperio.Tile)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removeTileOwned</h4>
<pre>void removeTileOwned​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</pre>
<div class="block">Remove a tile from owned</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>t</code> - tile to be removed from owned</dd>
</dl>
</li>
</ul>
<a id="getTilesOwned()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTilesOwned</h4>
<pre>java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>> getTilesOwned()</pre>
<div class="block">Get tiles owned by player</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Tiles owned by player</dd>
</dl>
</li>
</ul>
<a id="getPercentOwned()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPercentOwned</h4>
<pre>double getPercentOwned()</pre>
<div class="block">Get as a percentage how much of the total game area a player owns</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>percentage of how much of the total game area a player owns</dd>
</dl>
</li>
</ul>
<a id="setTileContested(se.liu.ida.paperio.Tile)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTileContested</h4>
<pre>void setTileContested​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</pre>
<div class="block">Add tile to players list of contested tiles</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>t</code> - Tile to be added to players contested list</dd>
</dl>
</li>
</ul>
<a id="getTilesContested()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTilesContested</h4>
<pre>java.util.ArrayList<<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a>> getTilesContested()</pre>
<div class="block">Get tiles contested by player</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Tiles contested by player</dd>
</dl>
</li>
</ul>
<a id="contestToOwned()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>contestToOwned</h4>
<pre>void contestToOwned()</pre>
<div class="block">Sets contested tiles to owned by player</div>
</li>
</ul>
<a id="checkCollision(se.liu.ida.paperio.Tile)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>checkCollision</h4>
<pre>void checkCollision​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> t)</pre>
<div class="block">Kills the player contesting a tile when travelling on it</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>t</code> - tile which contested owner should get killed</dd>
</dl>
</li>
</ul>
<a id="setCurrentTile(se.liu.ida.paperio.Tile)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCurrentTile</h4>
<pre>void setCurrentTile​(<a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio">Tile</a> currentTile)</pre>
<div class="block">Set tile to be current tile</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>currentTile</code> - tile to be set as current tile</dd>
</dl>
</li>
</ul>
<a id="getDx()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDx</h4>
<pre>int getDx()</pre>
<div class="block">Get the players speed in x direction</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Players speed in x direction</dd>
</dl>
</li>
</ul>
<a id="getDy()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDy</h4>
<pre>int getDy()</pre>
<div class="block">Get the players speed in y direction</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Players speed in y direction</dd>
</dl>
</li>
</ul>
<a id="getName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>java.lang.String getName()</pre>
<div class="block">Get name of player</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>Name of player</dd>
</dl>
</li>
</ul>
<a id="getAlive()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getAlive</h4>
<pre>java.lang.Boolean getAlive()</pre>
<div class="block">Get alive state of player</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>alive state of player</dd>
</dl>
</li>
</ul>
<a id="setAlive(java.lang.Boolean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAlive</h4>
<pre>public void setAlive​(java.lang.Boolean alive)</pre>
<div class="block">Set alive state of player</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>alive</code> - alive state of player</dd>
</dl>
</li>
</ul>
<a id="compareTo(se.liu.ida.paperio.Player)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>compareTo</h4>
<pre>public int compareTo​(<a href="../../../../se/liu/ida/paperio/Player.html" title="class in se.liu.ida.paperio">Player</a> player)</pre>
<div class="block">Compares two players by the number of tiles owned.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>compareTo</code> in interface <code>java.lang.Comparable<<a href="../../../../se/liu/ida/paperio/Player.html" title="class in se.liu.ida.paperio">Player</a>></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>player</code> - Player to compare this to</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>1 if this owns more tiles than player, -1 if player owns more tiles than this or 0 otherwise</dd>
</dl>
</li>
</ul>
</li>
</ul>
</section>
</li>
</ul>
</div>
</div>
</main>
<!-- ========= END OF CLASS DATA ========= -->
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../se/liu/ida/paperio/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../se/liu/ida/paperio/PaperIO.STATE.html" title="enum in se.liu.ida.paperio"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../se/liu/ida/paperio/Tile.html" title="class in se.liu.ida.paperio"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?se/liu/ida/paperio/Player.html" target="_top">Frames</a></li>
<li><a href="Player.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>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
</footer>
</body>
</html>
<file_sep>/README.md
# paper.io
Java game based on [paper.io](http://paper-io.com). Made by [<NAME>](https://github.com/vilhelmmelkstam) and [<NAME>](https://github.com/adamhalim).
Paper.io är ett relativt nytt spel online som kom i samma våg som många andra .io-spel så som agar.io och slither.io. Spelet finns under länken paper-io.com. Spelet är ett online multiplayer där man på en värld möter andra spelare.
När en spelare går med hamnar man på en slumpmässig server med andra spelare. Världen består av ett avgränsat kvadratiskt område där man först får ett litet område. Man kan sedan utöka sitt område genom att åka ut ur sitt område och rama in ett nytt område som sedan läggs till i ditt ursprungliga område när spelaren återvänder till området. Dock kan andra spelare köra över din svans medan du är på jakt efter nytt område för att förstöra dig. Spelet går då ut på att skaffa så stort område som möjligt.
### Funktionella krav
* Programmet ska kunna hantera minst en spelare och en datorspelare.
* Det ska finnas en live scoreboard medan man spelar.
* Programmet ska tillåta användare att välja namn.
* Spelet ska ha ett grafiskt gränssnitt.
* Spelet ska följa regler för Paper.io
* När en spelare kör på en annan spelares svans utanför dess område ska den som blir överkörd förstöras.
* Spelare genereras på slumpmässig, icke ockuperad, plats.
* Varje spelare ska ha annorlunda färg
* Om två spelare kolliderar rakt på ska den spelaren med minst andel av totalytan förstöras.
* Om en spelare kolliderar med väggen förstörs spelaren.
### Icke-funktionella krav
* Spelet ska vara skrivet i Java.
* Programmet ska ha en god objektorienterad design.
* Designen ska finnas dokumenterad, t.ex. i diagramform.
* Programmet ska vara så lätt att lära sig att en normalbegåvad labbassistent kan hantera det efter några minuters utbildning.
### Ideer till ytterligare funktionalitet
* Local multiplayer för fler spelare.
* Online multiplayer för fler spelare. (Väldigt extra funktionalitet)
* Smartare bots som analyserar närheten för att avgöra rörelser.
* Styra storlek på banan, antal datorspelare och hastighet själv.
* Möjlighet att spela med Power-Ups.
* Spara och visa highscores.
## Dokumentation
[Javadocs](https://vilhelmmelkstam.github.io/paper.io) finns tillgängligt.
### Övergripande kodstruktur
UML-diagrammet ser ut såhär:

Projektet består av åtta stycken klasser; `PaperIO`, `Menu`, `Board`, `Painter`, `Player`, `HumanPlayer`, `BotPlayer` och `Tile`.
#### [PaperIO](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/PaperIO.html)
`PaperIO` är huvudklassen med `main`-metoden. Denna klass ansvarar för att skapa och styra över fönster samt hålla koll på nuvarande `STATE` samt att byta mellan olika `STATE`:s.
#### [Menu](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/Menu.html)
`PaperIO` har en `Menu` som är huvudmenyn och ansvarar för att ta emot spelinställningar och starttryckning.
#### [Board](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/Board.html)
`Board` är logikklassen för spelet och ansvarar för spelets logik. `Board` skapar och administrerar spelplan, spelare och knappbindningar. Har även en timer för att uppdatera logiken i ticks. Klassen har en eller två `Painter`:s.
#### [Painter](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/Painter.html)
`Painter` används av `Board` för att rita spelplanen och spelare på den. En `Painter` ritar utifrån ens `Player`:s perspektiv och det den ser. Två `Painter`:s används för att visa splitscreen.
#### [Player](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/Player.html)
`Player` är en abstrakt klass som sköter all grundläggande logik för spelare. Det enda som skiljer sig åt mellan de klasser som ärver från `Player` är vad som får dem att röra på sig. Resten av logiken så som att hålla koll på namn, färg, ägda och omstridda `Tile`s, position och hastighetens riktning m.m.
#### [HumanPlayer](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/HumanPlayer.html)
`HumanPlayer` ärver från `Player` och är en spelare som kontrolleras av en männinska via tangentbordet. `HumanPlayer` ansvarar för att hålla koll på vilken riktning den ska röra sig i nästa tick samt att sedan röra sig enligt det.
#### [BotPlayer](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/BotPlayer.html)
`BotPlayer` ärver från `Player` och är en datorstyrd spelare. `BotPlayer` har logik för att bestämma riktning för att inte åka utanför banan men är annars slumpmässigt styrd.
#### [Tile](https://vilhelmmelkstam.github.io/paper.io/se/liu/ida/paperio/Tile.html)
`Tile` är en ruta i rutnätet. En `Tile` har en färg, en position och kan ha en ägare och en omstridd ägare. Dess färg beror på ägare och omstridd ägare.
<file_sep>/src/se/liu/ida/paperio/Board.java
package se.liu.ida.paperio;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Timer;
import java.util.*;
/**
* The board class is the class responsible for main game logic. This class initializes the tile grid, players and
* keeps track of them. Board is also specifies key bindings, fills enclosed areas and keeps track of a timer to tick
* through game logic. Board draws the live scoreboard but uses one or two Painter:s to draw the game area and players
* on it.
*/
public class Board extends JPanel {
private final int areaHeight;
private final int areaWidth;
private Tile[][] gameArea;
private final int scale = 20;
private int botNumber;
private ArrayList<Player> players = new ArrayList<>();
private ArrayList<HumanPlayer> humanPlayers = new ArrayList<>();
private HashMap<Tile, Player> tilePlayerMap = new HashMap<>();
private int tickCounter = 0;
private final int tickReset;
private ArrayList<Player> deadBots = new ArrayList<>();
private boolean paused = true;
private ActionListener actionListener;
private ArrayList<Painter> painters = new ArrayList<>();
private HashMap<Player, Painter> player_painter = new HashMap<>();
private List<Color> colorList = new ArrayList<>(Arrays.asList(Color.magenta, Color.green, Color.red,
Color.blue, Color.orange, Color.yellow, Color.pink, new Color(142,12,255),
new Color(255,43,119), new Color(100,255,162)));
/**
* Creates board for singleplayer
* @param actionListener listener for key presses and state updates
* @param p1name <NAME> player
* @param areaHeight height of game area
* @param areaWidth width of game area
* @param gameSpeed game speed between 1 and 5, 5 being the fastest
* @param botNumber number of bots to have in game
*/
Board(ActionListener actionListener, String p1name, int areaHeight, int areaWidth, int gameSpeed, int botNumber){
this.actionListener = actionListener;
this.areaHeight = areaHeight;
this.areaWidth = areaWidth;
this.botNumber = botNumber;
int[] speeds = {12, 10, 8, 6, 4};
tickReset = speeds[gameSpeed - 1];
players.add(new HumanPlayer(areaHeight, areaWidth, new Color((int)(Math.random() * 0x1000000)), p1name));
humanPlayers.add((HumanPlayer)players.get(0));
initBoard();
painters.add(new Painter(scale, this, humanPlayers.get(0), players));
player_painter.put(humanPlayers.get(0), painters.get(0));
}
/**
* Creates board for multiplayer
* @param actionListener listener for key presses and state updates
* @param p1name name of player 1
* @param p2name name of player 2
* @param areaHeight height of game area
* @param areaWidth width of game area
* @param gameSpeed game speed between 1 and 5, 5 being the fastest
* @param botNumber number of bots to have in game
*/
Board(ActionListener actionListener, String p1name, String p2name, int areaHeight, int areaWidth, int gameSpeed, int botNumber) {
this.actionListener = actionListener;
this.areaHeight = areaHeight;
this.areaWidth = areaWidth;
this.botNumber = botNumber;
int[] speeds = {12, 10, 8, 6, 4};
tickReset = speeds[gameSpeed - 1];
players.add(new HumanPlayer(areaHeight, areaWidth, new Color((int)(Math.random() * 0x1000000)), p1name));
players.add(new HumanPlayer(areaHeight, areaWidth, new Color((int)(Math.random() * 0x1000000)), p2name));
humanPlayers.add((HumanPlayer)players.get(0));
humanPlayers.add((HumanPlayer)players.get(1));
initBoard();
painters.add(new Painter(scale, this, humanPlayers.get(0), players));
painters.add(new Painter(scale, this, humanPlayers.get(1), players));
player_painter.put(humanPlayers.get(0), painters.get(0));
player_painter.put(humanPlayers.get(1), painters.get(1));
}
/**
* Initializes necessary variables, timer, players etc required for the board
*/
private void initBoard(){
this.gameArea = new Tile[areaHeight][areaWidth];
for(int i = 0; i < gameArea.length; i++){
for(int j = 0; j < gameArea[i].length; j++){
gameArea[i][j] = new Tile(j,i);
}
}
specifyKeyActions();
setBackground(Color.BLACK);
// Adds new bots and give them a color either from colorList or randomized
for(int i = 0; i < botNumber; i++){
if(i > 9){
players.add(new BotPlayer(gameArea.length,gameArea[0].length,
new Color((int)(Math.random() * 0x1000000))));
}else {
players.add(new BotPlayer(gameArea.length, gameArea[0].length, colorList.get(i)));
}
}
// Gives each player a starting area and makes sure that they don't spawn too close to each other
for(int i = 0; i < players.size(); i++){
// If bot is too close to another bot, remove it and create a new one instead
if(!checkSpawn(players.get(i))){
players.remove(players.get(i));
i--;
if(botNumber > 9){
players.add(new BotPlayer(gameArea.length,gameArea[0].length,
new Color((int)(Math.random() * 0x1000000))));
}else {
players.add(new BotPlayer(gameArea.length,gameArea[0].length, colorList.get(i)));
}
continue;
}else {
startingArea(players.get(i));
}
}
// Starts a timer to tick the game logic
final int INITIAL_DELAY = 0;
final int PERIOD_INTERVAL = 1000/60;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(),
INITIAL_DELAY, PERIOD_INTERVAL);
}
/**
* Specifies necessary key bindings and key actions for game
*/
private void specifyKeyActions(){
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
if(humanPlayers.size() == 1){
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveUP");
am.put("moveUP", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_UP);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "moveDOWN");
am.put("moveDOWN", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {humanPlayers.get(0).setNextKey(KeyEvent.VK_DOWN);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "moveLEFT");
am.put("moveLEFT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_LEFT);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveRIGHT");
am.put("moveRIGHT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_RIGHT);
}
});
}else if(humanPlayers.size() == 2){
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "moveP1UP");
am.put("moveP1UP", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(1).setNextKey(KeyEvent.VK_UP);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "moveP1DOWN");
am.put("moveP1DOWN", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {humanPlayers.get(1).setNextKey(KeyEvent.VK_DOWN);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "moveP1LEFT");
am.put("moveP1LEFT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(1).setNextKey(KeyEvent.VK_LEFT);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveP1RIGHT");
am.put("moveP1RIGHT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(1).setNextKey(KeyEvent.VK_RIGHT);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "moveP2UP");
am.put("moveP2UP", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_W);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "moveP2DOWN");
am.put("moveP2DOWN", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {humanPlayers.get(0).setNextKey(KeyEvent.VK_S);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "moveP2LEFT");
am.put("moveP2LEFT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_A);
}
});
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "moveP2RIGHT");
am.put("moveP2RIGHT", new AbstractAction() {
public void actionPerformed(ActionEvent evt) { humanPlayers.get(0).setNextKey(KeyEvent.VK_D);
}
});
}
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "pause");
am.put("pause", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
ActionEvent action = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "pause");
actionListener.actionPerformed(action);
}
});
}
/**
* Marks all tiles in the starting area of a player to owned by player
* @param player player to generate starting area for
*/
private void startingArea(Player player){
int x = player.getX();
int y = player.getY();
if(!checkSpawn(player)){
Player playerCopy = new BotPlayer(gameArea.length,gameArea[0].length, player.getColor());
startingArea(playerCopy);
}
for(int i = x-1; i <= x+1; i++){
for(int j = y-1; j <= y+1; j++){
player.setTileOwned(getTile(i,j));
}
}
}
/**
* Makes sure that a player doesn't spawn on, or too close to another player. Range is set to ±9 square tiles
* @param player Player that you want to check surroundings for other players
* @return True if nobody is close, False otherwise
*/
private boolean checkSpawn(Player player){
int x = player.getX();
int y = player.getY();
for(int i = x-3; i <= x+3; i++) {
for (int j = y - 3; j <= y + 3; j++) {
if (getTile(i, j).getOwner() != null || getTile(i, j).getContestedOwner() != null ) {
return false;
}
}
}
return true;
}
/**
* Overrides paintComponent and is called whenever everything should be drawn on the screen
* @param g Graphics element used to draw elements on screen
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < painters.size(); i++){
//Set clipping area for painter
g.setClip(getWidth()/painters.size() * i,0,getWidth()/painters.size(),getHeight());
//Move graphics to top-left of clipping area
g.translate(getWidth()/painters.size() * i,0);
//Painter paints area
painters.get(i).draw(g);
//Move graphics back to top-left of window
g.translate(-getWidth()/painters.size() * i,0);
}
try {
drawScoreboard(g);
} catch(IndexOutOfBoundsException ignored){
}
Toolkit.getDefaultToolkit().sync();
}
/**
* Draws the live scoreboard up in the rightmost corner
* @param g Graphics object received as argument in paintComponent method
*/
private void drawScoreboard(Graphics g) {
g.setFont(new Font("Monospaced", Font.PLAIN, 16));
FontMetrics fontMetrics = g.getFontMetrics();
int fontHeight = fontMetrics.getHeight();
int barWidth;
int barHeight = fontHeight + 4;
Player player;
String string;
Color color;
double highestPercentOwned = players.get(0).getPercentOwned();
Collections.sort(players);
for(int i = 0; i < Integer.min(5, players.size()); i++){
player = players.get(i);
string = String.format("%.2f%% - " + player.getName(), player.getPercentOwned());
color = player.getColor();
barWidth = (int)((player.getPercentOwned() / highestPercentOwned)*(getWidth()/4));
g.setColor(player.getColor());
g.fillRect(getWidth() - barWidth, barHeight*i, barWidth,barHeight);
// If color is perceived as dark set the font color to white, else black
if(0.299*color.getRed() + 0.587*color.getGreen() + 0.114*color.getBlue() < 127){
g.setColor(Color.WHITE);
}else{
g.setColor(Color.BLACK);
}
g.drawString(string, 2+getWidth() - barWidth, barHeight*i + fontHeight);
}
}
/**
* Method responsible for main logic of the game. Checks collisions and if enclosures should be filled.
*/
private void tick(){
Player player;
tilePlayerMap.clear();
for (int i = 0; i < players.size(); i++) {
player = players.get(i);
player.move();
// Kill player if player moves outside game area
if(player.getX() < 0 || player.getX() >= areaWidth || player.getY() < 0 || player.getY() >= areaHeight){
player.die();
}else{
Tile tile = getTile(player.getX(), player.getY());
player.checkCollision(tile);
player.setCurrentTile(tile);
findCollision(player, tile);
// If player is outside their owned territory
if (tile.getOwner() != player && player.getAlive()) {
player.setTileContested(tile);
// If player arrives back to an owned tile
} else if (player.getTilesContested().size() > 0) {
player.contestToOwned();
fillEnclosure(player);
}
}
// If BotPlayer is killed, add it to deadBots list
if(player instanceof BotPlayer && !player.getAlive()){
deadBots.add(player);
}
}
respawnBots();
boolean allKilled = true;
for(HumanPlayer humanPlayer : humanPlayers){
humanPlayer.updateD();
// Sets painter to stop drawing if humanPlayer is dead
player_painter.get(humanPlayer).setDraw(humanPlayer.getAlive());
allKilled = allKilled && !humanPlayer.getAlive();
}
if(allKilled){
endGame();
}
// Remove dead players
players.removeIf(p -> !p.getAlive());
}
/**
* Method to end game and tell this to PaperIO class
*/
private void endGame(){
JOptionPane.showMessageDialog(this, "You lost, game over", "GAME OVER", JOptionPane.PLAIN_MESSAGE);
actionListener.actionPerformed(new ActionEvent(this, 0, "End Game"));
}
/**
* Method that respawns dead bots after a set interval
*/
private void respawnBots(){
for(int i = 0; i < deadBots.size(); i++){
if(deadBots.get(i).getAlive()){
Player player = new BotPlayer(gameArea.length,gameArea[0].length,
new Color((int)(Math.random() * 0x1000000)));
startingArea(player);
players.add(player);
deadBots.remove(deadBots.get(i));
}
}
}
/**
* Method that detects player-to-player head on collision
* @param player Player you want to check collision for
* @param tile Tile that Player currently is on
*/
private void findCollision(Player player, Tile tile) {
// If corresponding tile is found in tilePlayerMap
if(tilePlayerMap.containsKey(tile)) {
// Iterate through all entries in tilePlayerMap, if the Tile in entry matches Tile in input,
// compare sizes between players and destroy one of them. The player with the largest tiles contested
// survives. If both players have the same amount of tiles contested, the player with the most tiles
// owned survives. If both players have the same amount of tiles contested and tiles owned,
// the first player added to Players list dies.
for(Map.Entry<Tile, Player> entry : tilePlayerMap.entrySet()) {
if (entry.getKey() == tile) {
if (entry.getValue().getTilesContested().size() > player.getTilesContested().size()) {
entry.getValue().die();
} else if (entry.getValue().getTilesContested().size() < player.getTilesContested().size()) {
player.die();
} else if (entry.getValue().getTilesContested().size() == player.getTilesContested().size()) {
if (entry.getValue().getTilesOwned().size() > player.getTilesOwned().size()) {
entry.getValue().die();
} else {
player.die();
}
}
}
}
}else { // If no corresponding tile is found, add tile and player to tilePlayerMap
tilePlayerMap.put(tile, player);
}
// Remove dead players
players.removeIf(p -> !p.getAlive());
}
/**
* Controls tick counter of game which is needed to make game smooth.
*/
private void updateTick(){
tickCounter++;
tickCounter %= tickReset;
}
/**
* After a player has traveled out to enclose an area the area needs to be filled. This method depends on that the
* Player.contestedToOwned() method has been called. The method works by doing a depth first search from each tile
* adjacent to a tile owned by the player sent as parameter. If the DFS algorithm finds a boundary we know it is not
* enclosed and should not be filled. The boundary is the smallest rectangle surrounding all owned tiles by the
* player to minimize cost of method. If the DFS can't find the boundary or if the one the DFS starts on we know it
* should be filled.
* @param player The player whose enclosure to be filled
*/
private void fillEnclosure(Player player) {
// Set boundary
int maxX = 0;
int minX = gameArea[0].length;
int maxY = 0;
int minY = gameArea.length;
for (Tile t : player.getTilesOwned()) {
if(t.getX() > maxX) maxX = t.getX();
if(t.getX() < minX) minX = t.getX();
if(t.getY() > maxY) maxY = t.getY();
if(t.getY() < minY) minY = t.getY();
}
// Necessary collections for DFS to work
ArrayList<Tile> outside = new ArrayList<>();
ArrayList<Tile> inside = new ArrayList<>();
ArrayList<Tile> visited = new ArrayList<>();
HashSet<Tile> toCheck = new HashSet<>();
// Add all adjacent tiles
int y;
int x;
for(Tile t : player.getTilesOwned()){
y = t.getY();
x = t.getX();
if(y -1 >= 0) toCheck.add(gameArea[y-1][x]);
if(y + 1 < gameArea.length) toCheck.add(gameArea[y+1][x]);
if(x - 1 >= 0) toCheck.add(gameArea[y][x-1]);
if(x + 1 < gameArea[y].length) toCheck.add(gameArea[y][x+1]);
}
// Loop over all tiles to do DFS from
for(Tile t : toCheck){
if(!inside.contains(t)){
Stack<Tile> stack = new Stack<>();
boolean cont = true;
Tile v;
visited.clear();
// DFS algorithm
stack.push(t);
while((!stack.empty()) && cont){
v = stack.pop();
if(!visited.contains(v) && (v.getOwner() != player)){
y = v.getY();
x = v.getX();
if(outside.contains(v) //If already declared as outside
|| x < minX || x > maxX || y < minY || y > maxY //If outside of boundary
|| x == gameArea[0].length -1 || x == 0 || y == 0 || y == gameArea.length -1){ // If it is a edge tile
cont = false;
}else{
visited.add(v);
if(y -1 >= 0) stack.push(gameArea[y-1][x]);
if(y + 1 < gameArea.length) stack.push(gameArea[y+1][x]);
if(x - 1 >= 0) stack.push(gameArea[y][x-1]);
if(x + 1 < gameArea[y].length) stack.push(gameArea[y][x+1]);
}
}
}
if(cont){ // If DFS don't find boundary
inside.addAll(visited);
}else{
outside.addAll(visited);
}
}
}
// Set all enclosed tiles to be owned by player
for(Tile t : inside){
player.setTileOwned(t);
}
}
/**
* Set board to paused mode, meaning logic and graphics are not updated
* @param b True if game should be paused, false otherwise
*/
void setPaused(Boolean b){
paused = b;
}
/**
* Get height of game area
* @return height of game area
*/
int getAreaHeight() {
return areaHeight;
}
/**
* Get width of game area
* @return width of game area
*/
int getAreaWidth() {
return areaWidth;
}
/**
* Get current tick counter
* @return current tick counter
*/
int getTickCounter() {
return tickCounter;
}
/**
* Get how often tick is reset, impacting speed of game
* @return how often tick is reset
*/
int getTickReset() {
return tickReset;
}
/**
* Get tile at position (x,y)
* @param x x position of tile
* @param y y position of tile
* @return tile at position (x,y)
*/
Tile getTile(int x, int y){
return gameArea[y][x];
}
/**
* ScheduleTask is responsible for receiving and responding to timer calls
*/
private class ScheduleTask extends TimerTask {
/**
* Gets called by timer at specified interval. Calls tick at specified rate and repaint each time
*/
@Override
public void run() {
if(!paused) {
updateTick();
if (tickCounter == 0) {
tick();
}
repaint();
}
}
}
}<file_sep>/src/se/liu/ida/paperio/PaperIO.java
package se.liu.ida.paperio;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* PaperIO is the main class used to start window and keep track of current state and switch between states.
*/
public class PaperIO extends JFrame implements ActionListener{
private Board board;
private Menu menu;
private JPanel cards;
/**
* Initializes a new occurrence of game
*/
private PaperIO(){
initUI();
}
/**
* Specifies size, title and layout etc for game
*/
private void initUI(){
setSize(1000, 1000);
setResizable(true);
setVisible(true);
setTitle("paper.io");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
menu = new Menu(this);
cards = new JPanel(new CardLayout());
cards.add(menu, "menu");
add(cards);
}
/**
* Enum with all possible game states
*/
private enum STATE{
GAME,
MENU
}
/**
* Sets game state to specified state
* @param s STATE game should be set to
*/
private void setState(STATE s){
CardLayout cardLayout = (CardLayout) cards.getLayout();
if(s == STATE.GAME){
cardLayout.show(cards, "board");
board.setPaused(false);
}else if(s == STATE.MENU){
cardLayout.show(cards, "menu");
board.setPaused(true);
}
}
/**
* Reacts to game actions such as game start and game paused
* @param e event to react to
*/
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "Play Singleplayer":
board = new Board(this, menu.getP1Name(), menu.getAreaHeight(), menu.getAreaWidth(), menu.getGameSpeed(), menu.getBotNumber());
cards.add(board, "board");
setState(STATE.GAME);
break;
case "Play Multiplayer":
board = new Board(this, menu.getP1Name(), menu.getP2Name(), menu.getAreaHeight(), menu.getAreaWidth(), menu.getGameSpeed(), menu.getBotNumber());
cards.add(board, "board");
setState(STATE.GAME);
break;
case "End Game":
setState(STATE.MENU);
break;
}
}
public static void main(String[] args) {
System.setProperty("sun.java2d.opengl", "True");
EventQueue.invokeLater(PaperIO::new);
}
} | 930de78e5365fa89e845a74a9b569a869219e5da | [
"Markdown",
"Java",
"HTML"
] | 4 | HTML | lizhming/paper.io | da3502f911391c494c49afe0060015545d851411 | 8759e7d1ba5e742fdcac98992413e337208c2ed2 |
refs/heads/main | <repo_name>yR-DEV/jump-jet-auto-frontend<file_sep>/src/components/vehicle/Vehicle.jsx
import React from 'react';
import './Vehicle.css';
const Vehicle = () => {
return (
<div>
Vehicle hooked up
</div>
)
}
export default Vehicle;<file_sep>/src/services/AppointmentService.js
import axios from 'axios';
const APPOINTMENT_REST_API_BASEURL = "";
class AppointmentService {
getAppointments() {
return axios.get(APPOINTMENT_REST_API_BASEURL);
}
deleteAppointment(appointmentId) {
return axios.delete(APPOINTMENT_REST_API_BASEURL + '/' + appointmentId);
}
postAppointment(appointmentNew) {
return axios.post(APPOINTMENT_REST_API_BASEURL, appointmentNew);
}
putAppointment(appointmentUpdated) {
return axios.put(APPOINTMENT_REST_API_BASEURL, appointmentUpdated);
}
}
export default new AppointmentService();<file_sep>/src/components/vehicle/VehicleService.jsx
import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState, useEffect } from "react";
import axios from "axios";
function Vehicle() {
const [stateVehicle, setVehicleState] = useState([]);
const [addTableDisplay, setAddTableDisplay] = useState(false);
const [updateTableDisplay, setUpdateTableDisplay] = useState(false);
useEffect(() => {
getVehicle();
}, []);
const getVehicle = () => {
axios
.get("http://localhost:8080/api/vehicles")
.then(response => {
setVehicleState(response.data);
})
};
const deleteVehicle = vin => {
axios
.delete(`http://localhost:8080/api/delete/vehicle/${vin}`)
.then(response => {
getVehicle();
})
}
const submit = e => {
let vin = e.target[0].value;
let brand = e.target[1].value;
let model = e.target[2].value;
let year = e.target[3].value;
let mileage = e.target[4].value;
let color = e.target[5].value;
let data = {
vin,
brand,
model,
year,
mileage,
color
};
postVehicle(data);
};
const postVehicle = data => {
axios
.post("http://localhost:8080/api/add/vehicle", data)
.then(response => {
getVehicle();
})
};
const update = e => {
let vin = e.target[0].value;
let brand = e.target[1].value;
let model = e.target[2].value;
let year = e.target[3].value;
let mileage = e.target[4].value;
let color = e.target[5].value;
let data = {
vin,
brand,
model,
year,
mileage,
color
};
putVehicle(data, vin);
};
const putVehicle = (data, vin) => {
axios
.put(`http://localhost:8080/api/update/vehicle/${vin}`, data)
.then(response => {
getVehicle();
})
};
return (
<div>
{addTableDisplay === false ? (null) : (
<div className="jumbotron">
<form onSubmit={e => {
e.preventDefault();
submit(e);
setAddTableDisplay(false)
}}>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> VIN </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="vin" name="vin" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Brand </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="brand" name="brand" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Model </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="model" name="model" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Year </label>
<div className="col-sm-10">
<input type="number" min="1900" max="2900" className="form-control" id="year" name="year" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Mileage </label>
<div className="col-sm-10">
<input type="number" className="form-control" id="mileage" name="mileage" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Color </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="color" name="color" required />
</div>
</div>
<input type="submit" className="btn btn-primary btn-sm" value="Submit" />
</form>
</div>)}
{updateTableDisplay === false ? (null) : (
<div className="jumbotron">
<form onSubmit={e => {
e.preventDefault();
update(e);
setUpdateTableDisplay(false)
}}>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> VIN </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="vin" name="vin" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Brand </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="brand" name="brand" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Model </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="model" name="model" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Year </label>
<div className="col-sm-10">
<input type="number" min="1900" max="2900" className="form-control" id="year" name="year" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Mileage </label>
<div className="col-sm-10">
<input type="number" className="form-control" id="mileage" name="mileage" required />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Color </label>
<div className="col-sm-10">
<input type="text" className="form-control" id="color" name="color" required />
</div>
</div>
<input type="submit" className="btn btn-secondary btn-sm" value="Update" />
</form>
</div>)}
<div className="container">
<button onClick={() => { setAddTableDisplay(true); setUpdateTableDisplay(false) }} className="btn btn-outline-primary btn-sm">Vehicle Registration</button>
<button onClick={() => { setUpdateTableDisplay(true); setAddTableDisplay(false) }} className="btn btn-outline-primary btn-sm">Vehicle Update</button>
</div>
<div className="container">
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">VIN</th>
<th scope="col">Brand</th>
<th scope="col">Model</th>
<th scope="col">Year</th>
<th scope="col">Mileage</th>
<th scope="col">Color</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{stateVehicle.map(d => (
<tr>
<td>{d.vin}</td>
<td>{d.brand}</td>
<td>{d.model}</td>
<td>{d.year}</td>
<td>{d.mileage}</td>
<td>{d.color}</td>
<td>
<button onClick={() => deleteVehicle(d.vin)} className="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
export default Vehicle;
<file_sep>/src/components/vehicle/AddVehicle.jsx
import React from "react";
import axios from "axios";
import 'bootstrap/dist/css/bootstrap.min.css';
function AddVechicle() {
const submit = e => {
let vin = e.target[0].value;
let brand = e.target[1].value;
let model = e.target[2].value;
let year = e.target[3].value;
let mileage = e.target[4].value;
let color = e.target[5].value;
let data = {
vin,
brand,
model,
year,
mileage,
color
};
postVehicle(data);
};
const postVehicle = data => {
axios.post("http://localhost:8080/api/add/vehicle", data)
};
return (
<div className="vechicleService">
<form onSubmit={e =>{
e.preventDefault();
submit(e);
}}>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> VIN </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="vin" name="vin" />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Brand </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="brand" name="brand" />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Model </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="model" name="model" />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Year </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="year" name="year" />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Mileage </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="mileage" name="mileage" />
</div>
</div>
<div className="form-group row">
<label className="col-sm-2 col-form-label"> Color </label>
<div className="col-sm-4">
<input type="text" className="form-control" id="color" name="color" />
</div>
</div>
<input type="submit" className="btn btn-primary" value="Submit" />
</form>
</div>
);
}
export default AddVechicle;
<file_sep>/src/components/customer/Customer.jsx
import React from 'react';
import './Customer.css';
const Customer = () => {
return (
<div>
Customer hooked up
</div>
)
}
export default Customer;<file_sep>/src/services/VehicleService.js
import axios from 'axios';
const VEHICLE_REST_API_BASEURL = "http://localhost:8080/api/vehicles"
class VehicleService {
getVehicles() {
return axios.get(VEHICLE_REST_API_BASEURL);
}
deleteVehicle(vehicleId) {
return axios.delete(VEHICLE_REST_API_BASEURL + '/' + vehicleId);
}
postVehicle(vehicleNew) {
return axios.post(VEHICLE_REST_API_BASEURL, vehicleNew);
}
putVehicle(vehicleUpdated) {
return axios.put(VEHICLE_REST_API_BASEURL, vehicleUpdated);
}
}
export default new VehicleService();<file_sep>/src/services/CustomerService.js
import axios from 'axios';
const CUSTOMER_REST_API_BASEURL = ""
class CustomerService {
getCustomers() {
return axios.get(CUSTOMER_REST_API_BASEURL);
}
deleteCustomer(customerId) {
return axios.delete(CUSTOMER_REST_API_BASEURL + '/' + customerId);
}
postCustomer(customerNew) {
return axios.post(CUSTOMER_REST_API_BASEURL, customerNew);
}
putAppointment(customerUpdated) {
return axios.put(CUSTOMER_REST_API_BASEURL, customerUpdated);
}
}
export default new CustomerService();<file_sep>/src/components/employee/EmployeeForm.jsx
import React from 'react';
import axios from 'axios';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import employeeComponent from './Employee';
import './Employee.css';
import 'bootstrap/dist/css/bootstrap.min.css';
const EmployeeForm = () => {
const handleSubmit = (event) => {
event.preventDefault();
let employee = {
employeeId: event.target.employeeId.value,
employeeLastName: event.target.employeeLastName.value,
employeeFirstName: event.target.employeeFirstName.value,
employeePhoneNumnber: event.target.employeePhoneNumber.value,
employeeTitle: event.target.employeeTitle.value
};
postAPIAxios(employee);
}
const postAPIAxios = (employee) => {
axios.post('http://localhost:6064/employee/', employee)
.then(response => {
console.log('posted');
})
}
return (
<div className="container">
<div className="jumbotron">
<h1>New Employee Form</h1>
<div className="container-sm">
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="employeeId" className="form-label">Employee ID: </label>
<input type="number" className="form-control" id="employeeId" name="employeeId" aria-describedby="emailHelp" />
</div>
<div className="mb-3">
<label htmlFor="employeeLastName" className="form-label">Employee Last Name: </label>
<input type="text" className="form-control" id="employeeLastName" name="employeeLastName" aria-describedby="employeeLastNameHelp" />
</div>
<div className="mb-3">
<label htmlFor="employeeFirstName" className="form-label">Employee First Name: </label>
<input type="text" className="form-control" id="employeeFirstName" name="employeeFirstName" aria-describedby="employeeFirstNameHelp" />
</div>
<div className="mb-3">
<label htmlFor="employeePhoneNumber" className="form-label">Employee Phone Number: </label>
<input type="text" className="form-control" id="employeePhoneNumber" name="employeePhoneNumber" aria-describedby="emailHelp" />
</div>
<div className="mb-3">
<label htmlFor="employeeTitle" className="form-label">Employee Title: </label>
<input type="text" className="form-control" id="employeeTitle" name="employeeTitle" aria-describedby="emailHelp" />
</div>
<button type="submit" className="btn btn-primary">Submit New Employee</button>
<Link to="/employees">
<button className="btn btn-danger">Cancel New Employee</button>
</Link>
</form>
</div>
</div>
</div>
)
}
export default EmployeeForm;<file_sep>/src/components/employee/EmployeeList.jsx
import React, { useEffect } from 'react';
const EmployeeList = (props) => {
useEffect(() => {
props.getAPIAxios();
return () => props.clearState();
}, []);
const employeeSelect = (event) => {
props.handleEmployeeSelect(event.target.id);
}
const employeeDelete = (event) => {
props.deleteAPIAxios(event.target.id);
}
return (
<div className="container">
<div className="jumbotron">
<h1> Employees List </h1>
<table className="container">
<tbody>
{
props.employees.map(employee => {
return (
<tr className="row" key={employee.employeeId}>
<td className="col-2">{employee.employeeId}</td>
<td className="col-2">{employee.employeeFirstName} {employee.employeeLastName}</td>
<td className="col-2">{employee.employeePhoneNumber}</td>
<td className="col-2">{employee.employeeTitle}</td>
<td className="col-1"><button className="btn btn-primary" id={employee.employeeId} onClick={employeeSelect}>Select</button></td>
<td className="col-1"><button className="btn btn-danger" id={employee.employeeId} onClick={employeeDelete}>Delete</button></td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)
}
export default EmployeeList;<file_sep>/src/App.jsx
// Dependency imports
import React, { useState } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
// Style imports
import './App.css';
// Component imports
import Header from './components/navbar/Navbar';
import Landing from './components/landing/Landing';
import Employee from './components/employee/Employee';
import EmployeeForm from './components/employee/EmployeeForm';
import VehicleService from './components/vehicle/VehicleService';
import AddVehicle from './components/vehicle/AddVehicle';
import Customer from './components/customer/Customer';
import Appointment from './components/appointment/Appointment';
import ListJobCardsComponent from './components/jobcard/ListJobCardsComponent';
import CreateJobCardComponent from './components/jobcard/CreateJobCardComponent';
const App = () => {
const [state, setState] = useState([]);
const setEmployeeToAppState = (employeeId) => {
console.log('-------------------------------------------');
console.log('we in main app with ');
console.log('EMPLOYEE ID NUMBER: ' + employeeId);
console.log('this will be set in state and work progression of creating job card');
console.log('will continue below');
console.log('--------------------------------------------');
}
return (
<div className="App">
<Router>
{/* Links to pages located in the Header Component */}
<Header />
<Route path="/employees">
<Employee setEmployeeToAppState={setEmployeeToAppState}/>
</Route>
<Route path="/add-employee">
<EmployeeForm />
</Route>
<Route path="/vehicles">
<VehicleService />
</Route>
<Route path="/add-vehicle">
<AddVehicle />
</Route>
<Route path="/customer">
<Customer />
</Route>
<Route path="/appointment">
<Appointment />
</Route>
<Route path="/jobcards">
<ListJobCardsComponent />
</Route>
<Route path="/add-jobcard">
<CreateJobCardComponent />
</Route>
<Route exact path="/">
<Landing />
</Route>
</Router>
</div>
);
}
export default App;
| f0efc4d20ef2557af1b83dc6e18cf113beab732d | [
"JavaScript"
] | 10 | JavaScript | yR-DEV/jump-jet-auto-frontend | 60fe99292aa780fe3e1eb625f840b3881f93e6b0 | 85a5188fec6aee8e02b09319f92db659334e40ca |
refs/heads/master | <repo_name>klapmo/RaceStandings<file_sep>/src/app/services/data.service.ts
import { Injectable } from '@angular/core';
//Importing Angular HTTP module
import { HttpHeaders, HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
racers_url: string = "https://ergast.com/api/f1/2019/5/driverStandings.json"
getRacers() {
return this.http.get(this.racers_url)
}
}
<file_sep>/src/app/racers/racers.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';
@Component({
selector: 'app-racers',
templateUrl: './racers.component.html',
styleUrls: ['./racers.component.css']
})
export class RacersComponent implements OnInit {
racers:Object;
constructor( private data: DataService) { }
ngOnInit() {
//This will fire as soon as the route HOME is encountered
this.data.getRacers().subscribe(racerData => {
this.racers = racerData['MRData']['StandingsTable']['StandingsLists'][0]['DriverStandings'];
console.log(racerData)
})
}
}
| 3089f3090314f6db30a2e3fd7159c34e47e430ae | [
"TypeScript"
] | 2 | TypeScript | klapmo/RaceStandings | a5618afee13283aac25e55c3fb73190a09c132b0 | 37a0d888503867d81bd7c5e11a495db7a5eceabd |
refs/heads/master | <file_sep>package com.kenova.mpesa.mpesa.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Aaron at 6/27/2020
**/
public class AccessToken {
@SerializedName("access_token")
@Expose
public String accessToken;
@SerializedName("expires_in")
@Expose
private String expiresIn;
public AccessToken(String accessToken, String expiresIn) {
this.accessToken = accessToken;
this.expiresIn = expiresIn;
}
}
<file_sep>rootProject.name='LNM Tutorial'
include ':app'
<file_sep># Lipa Na MPesa Android Integration Tutorial
## What is LNM?
Lipa Na Mpesa(LNM) is a payment SDK offered by Safaricom service provider, that facilitates easy payment integration in mobile and web applications by a sim toolkit(STK) push message.
The STK push asks for a pin for the app user to authorize the payments, then the transaction is saved on the backend of the application.
##Integration
To quickly integrate the system to your existing app, do:
1. Clone the repository
2. Copy the AppConstants.java, MainActivity.java (Remember to rename it and add to manifest), & mpesa directory with all its content.
3. Copy the dependencies in build.gradle(app) and add them to yours
4. Copy the two lines at the end of gradle.properties
5. Change values in AppConstants.java
6. Refactor and run your application
## Callback URL
This is the URL that the Service provider(Safaricom) will use to send payment information to your backend.
For callback url, look at this repository for sample code you can host: https://github.com/Kenovators/LNM-Callback-Url
| 0ea5cff9036ea1dd179dc592d87d99759b55c0fe | [
"Markdown",
"Java",
"Gradle"
] | 3 | Java | Kenovators/LNM-Tutorial | 3cdddb839ee71f7b2a60ed641646746efbe8db84 | b3234c672bfc00c8d1ed900b949ef1394b5cfcbb |
refs/heads/main | <file_sep># MaximumScoreWord
1. A list of words, a list of alphabets(might be repeating) and score of every alphabet from a to z.
2. You have to find the maximum score of any valid set of words formed by using the given alphabets.
3. A word can not be used more than one time.
4. Each alphabet can be used only once.
5. It is not necessary to use all the given alphabets
<file_sep>import java.io.*;
import java.util.*;
public class MaxScoreWord {
public static int maxscore(String[] words, int[] fre, int[] score, int index) {
if (index == words.length) {
return 0;
}
int scoreno = 0 + maxscore(words, fre, score, index + 1); //when word is not included in set
int scoreword = 0; //when word is included then we have to check whether frequency is in limit of that wordset
String word = words[index];
boolean flag = true; // if word is included
for (int i = 0; i < word.length(); i++) { //this is for takeing charater so score are added eaisly
char ch = word.charAt(i);
if (fre[ch - 'a'] == 0) { //checking frequency
flag = false; //if beyond limit then make flag false so word will not included
}
fre[ch - 'a']--;
scoreword += score[ch - 'a'];
}
int scoreyes = 0;
if (flag) {
scoreyes = scoreword + maxscore(words, fre, score, index + 1);
}
for (int i = 0; i < word.length(); i++) { //this is for takeing charater so score are added eaisly
char ch = word.charAt(i);
fre[ch - 'a']++;
}
return Math.max(scoreno, scoreyes);
}
public static void main(String[]args){
Scanner s=new Scanner(System.in);
int noofwords=s.nextInt();
String []words=new String[noofwords];
for (int i=0;i<words.length;i++){
words[i]=s.next();
}
int noofletters=s.nextInt();
char[] letters=new char[noofletters];
for (int i=0;i<letters.length;i++){
letters[i]=s.next().charAt(0);
}
int [] score=new int[26];
for (int i=0;i<score.length;i++){
score[i]=s.nextInt();
}
if(words==null || words.length==0 || letters==null || letters.length==0 || score.length==0){
System.out.println(0);
return;
}
int []fre=new int[score.length];
for(char ch: letters){
fre[ch-'a']++;
}
System.out.println(maxscore(words,fre,score,0));
}
}
| 1b163d85d4ca1bb37367076663f75156450ff43b | [
"Markdown",
"Java"
] | 2 | Markdown | PratyushPriyam14/MaximumScoreWord | e6acca73d8f1963c41d21c573c8fe161dcf9d25f | be064b8dec87d4b72a80f6a6df80de188c4892be |
refs/heads/master | <file_sep>sudo docker ps -a -q | sudo xargs docker rm
<file_sep>kubectl get pods | grep Evicted | awk '{print $1}' | xargs kubectl delete pod
kubectl get pods --all-namespaces | grep Evicted | awk '{print $2 " --namespace=" $1}' | xargs kubectl delete pod
<file_sep>sudo docker images | grep none | awk '{print $3}' | xargs sudo docker rmi
| 73430238c92ac3097ac9906af612519abddb6260 | [
"Shell"
] | 3 | Shell | lawrencecrane/scripts | aa33c4e2766585969837860cf0d7782b043e404e | 33d110b7810b8a40bb41b3ac8263ebee01346e65 |
refs/heads/main | <repo_name>gotopie/obs-scripts<file_sep>/Auto Record.lua
local obs = obslua;
local var = {}
--
-- Helpers
--
local info = function(msg)
obs.script_log(obs.LOG_INFO, "INFO: "..msg)
end
local warn = function(msg)
obs.script_log(obs.LOG_WARNING, "WARNING: "..msg)
end
local split = function(s, sep)
local fields = {}
local sep = sep or " "
local pattern = string.format("([^%s]+)", sep)
string.gsub(s, pattern, function(c) fields[#fields + 1] = c end)
return fields
end
--
-- Code
--
local start_recording_timerproc = function()
obs.remove_current_callback()
obs.obs_frontend_recording_start()
info("RECORDING STARTED")
end
local stop_recording_timerproc = function()
obs.remove_current_callback()
obs.obs_frontend_recording_stop()
info ("RECORDING STOPPED")
end
local check_for_active_sources = function()
if not (var.sources_count > 0) or var.enabled == false then
return
end
local source_active = false
for i,s in ipairs(var.sources) do
if var.sources[s] == true then
source_active = true
break
end
end
if var.source_active ~= source_active then
obs.timer_remove(start_recording_timerproc)
obs.timer_remove(stop_recording_timerproc)
if source_active then -- begin recording
if (var.start_timer > 0) then
info("Recording timer started. ("..var.start_timer.."s)")
else
start_recording_timerproc()
end
obs.timer_add(start_recording_timerproc, var.start_timer * 1000)
elseif var.source_active ~= nil then -- stop recording
if (var.stop_timeout > 0) then
info("There are no sources active. Recording will stop in "..var.stop_timeout.."s")
else
stop_recording_timerproc()
end
obs.timer_add(stop_recording_timerproc, var.stop_timeout * 1000)
end
var.source_active = source_active
end
end
--
-- handlers
--
local on_source_activated = function(cd)
local src = obs.calldata_source(cd, "source")
if src == nil then
warn("Source activated but calldata is nil")
return
end
local name = obs.obs_source_get_name(src)
if var.sources[name] ~= nil then
info("Source activated: "..name)
var.sources[name] = true
end
check_for_active_sources()
end
local on_source_deactivated = function(cd)
local src = obs.calldata_source(cd, "source")
if src == nil then
warn("Source deactivated but calldata is nil")
return
end
local name = obs.obs_source_get_name(src)
if var.sources[name] ~= nil then
info("Source deactivated: "..name)
var.sources[name] = false
end
check_for_active_sources()
end
--
-- Script setup
--
function script_description()
return "Automatically begin recording when a source is activated, and stop recording when the source is deactivated after a specified timeout"
end
function script_properties()
local props = obs.obs_properties_create()
obs.obs_properties_add_bool(props, "enabled", "Enabled")
obs.obs_properties_add_text(props, "source_list", "Sources", obs.OBS_TEXT_MULTILINE)
obs.obs_properties_add_int(props, "start_timer", "Start timer (sec)", 0, 100000, 1)
obs.obs_properties_add_int(props, "stop_timeout", "Stop timeout (sec)", 0, 100000, 1)
return props
end
function script_defaults(settings)
obs.obs_data_set_default_int(settings, "stop_timeout", 10)
obs.obs_data_set_default_bool(settings, "enabled", true)
end
function script_update(settings)
var.enabled = obs.obs_data_get_bool(settings, "enabled")
var.stop_timeout = obs.obs_data_get_int(settings, "stop_timeout")
var.start_timer = obs.obs_data_get_int(settings, "start_timer")
var.sources = split(obs.obs_data_get_string(settings, "source_list"), "\n")
info("Settings changed")
info("Stop timeout: "..var.stop_timeout..". Start timer: "..var.start_timer)
local sources_count = 0
info("Sources:")
for i, s in ipairs(var.sources) do
var.sources[s] = false
info(s)
sources_count = sources_count + 1
end
if not (sources_count > 0) then info("<No sources specified>") end
var.sources_count = sources_count
local enable_str
if var.enabled then enable_str = "ENABLED" else enable_str = "DISABLED" end
info("Currently "..enable_str)
check_for_active_sources()
end
function script_load(settings)
local sh = obs.obs_get_signal_handler()
obs.signal_handler_connect(sh, "source_activate", on_source_activated)
obs.signal_handler_connect(sh, "source_deactivate", on_source_deactivated)
end | 74b227230f051e36728c87cff549246c2afec63c | [
"Lua"
] | 1 | Lua | gotopie/obs-scripts | 179db887020a3dfedd70a87b4a19494b246aa591 | 49071102af6bab71ea03af40079f19a0624620e2 |
refs/heads/master | <repo_name>pedrocarrico/gfaa<file_sep>/README.md
== README
Good Fucking Austerity Advice repo.
An experimental project inspired by [Good Fucking Design Advice](http://www.goodfuckingdesignadvice.com).
<file_sep>/app/controllers/public_controller.rb
class PublicController < ApplicationController
helper_method :advice
protected
def generate_advice(id)
chain = Advice.order('RANDOM()')
chain = chain.where('id != (?)', id) if id.present?
chain.first
end
def advice
@advice ||= generate_advice(params[:id])
end
end
| 39ab56c0884077859a3553d5106a91630c1eed8f | [
"Markdown",
"Ruby"
] | 2 | Markdown | pedrocarrico/gfaa | 7439075a1ac255d48bdecb7f4a36f6d6ebe5606e | a578a63345d7fd5224d68c21c60e550551191105 |
refs/heads/master | <file_sep>import discord,os
import asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix='ay ')
@bot.event
async def on_ready():
game = discord.Activity(name="Under Development", type=discord.ActivityType.playing)
await bot.change_presence(status=discord.Status.dnd, activity=game)
@bot.command()
async def say(ctx,*,args):
embed = discord.Embed(title=str(ctx.author), description=args, color=0x0000ff)
await ctx.send(embed=embed)
await ctx.message.delete()
@bot.command()
async def hi(ctx):
user = ctx.author.mention
await ctx.send("Hello "+str(user))
@bot.command()
async def dothis(ctx):
await ctx.send("Done :sunglasses:")
@bot.group()
async def ign(ctx):
embed = discord.Embed(title="No IGN", description="No IGN Added!", color=0xff0000)
await ctx.send(embed=embed)
@ign.command()
async def add(ctx,*,inp):
await ctx.send("Your IGN : "+str(inp))
@bot.command()
async def profile(ctx):
embed = discord.Embed(title=str(ctx.author.mention), description='', color=0x0000ff)
await ctx.send(embed=embed)
bot.run(os.getenv('token')) | 8ce07ecd119ededf84c30df29c2fd5e515e5686a | [
"Python"
] | 1 | Python | axel565/panbox | da5b56818d416734ee4c97ff402e817e9245cc87 | b9cc5cb3455bf56b80fe21618d499a67caa167d2 |
refs/heads/master | <file_sep>webjobsvs
=========
<file_sep>using System.IO;
using EnvDTE;
using System.Xml;
using System.Xml.Linq;
namespace LigerShark.WebJobsVs
{
class WebJobCreator
{
public void AddReference(Project currentProject, Project selectedProject)
{
if (currentProject.Object is VSLangProj.VSProject)
{
var project = currentProject.Object as VSLangProj.VSProject;
project.References.AddProject(selectedProject);
}
else if (currentProject.Object is VsWebSite.VSWebSite)
{
var project = currentProject.Object as VsWebSite.VSWebSite;
try
{
project.References.AddFromProject(selectedProject);
}
catch
{
// Reference was already added. TODO: don't use try/catch for this.
}
}
}
public void CreateFolders(Project currentProject, string schedule, string projectName, string relativePath)
{
//Create a File under Properties Folder which will contain information about all WebJobs
//https://github.com/ligershark/webjobsvs/issues/6
// Check if the WebApp is C# or VB
string dir = GetProjectDirectory(currentProject);
var propertiesFolderName = "Properties";
if (currentProject.CodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVB)
{
propertiesFolderName = "My Project";
}
DirectoryInfo info = new DirectoryInfo(Path.Combine(dir, propertiesFolderName));
string readmeFile = Path.Combine(info.FullName, "WebJobs.xml");
// Copy File if it does not exit
if (!File.Exists(readmeFile))
AddReadMe(readmeFile);
//Add a WebJob info to it
XDocument doc = XDocument.Load(readmeFile);
XElement root = new XElement("WebJob");
root.Add(new XAttribute("Project", projectName));
root.Add(new XAttribute("RelativePath", relativePath));
root.Add(new XAttribute("Schedule", schedule));
doc.Element("WebJobs").Add(root);
doc.Save(readmeFile);
currentProject.ProjectItems.AddFromFile(readmeFile);
}
private static string GetProjectDirectory(Project project)
{
if (project.Object is VSLangProj.VSProject)
return Path.GetDirectoryName(project.FullName);
return project.Properties.Item("fullPath").Value.ToString();
}
private static void AddReadMe(string destinationFileName)
{
string dir = Path.GetDirectoryName(typeof(WebJobCreator).Assembly.Location);
string readme = Path.Combine(dir, "job", Path.GetFileName(destinationFileName));
File.Copy(readme, destinationFileName, true);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using EnvDTE;
using EnvDTE80;
using LigerShark.WebJobsVs.Dialog;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio;
namespace LigerShark.WebJobsVs
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(GuidList.guidWebJobsVsPkgString)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
public sealed class WebJobsVsPackage : Package
{
private DTE2 _dte;
private string _webjobsPkgName = "WebJobsBuilder";
protected override void Initialize()
{
base.Initialize();
_dte = GetService(typeof(DTE)) as DTE2;
OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (null != mcs)
{
CommandID cmdId = new CommandID(GuidList.guidWebJobsVsCmdSet, (int)PkgCmdIDList.WebJobsAddProject);
OleMenuCommand button = new OleMenuCommand(ButtonClicked, cmdId);
button.BeforeQueryStatus += button_BeforeQueryStatus;
mcs.AddCommand(button);
}
}
void button_BeforeQueryStatus(object sender, EventArgs e)
{
var button = (OleMenuCommand)sender;
var project = GetSelectedProjects().ElementAt(0);
button.Visible = project.IsWebProject();
}
public static bool HasExtender(Project proj, string extenderName)
{
try
{
var extenderNames = (object[])proj.ExtenderNames;
return extenderNames.Length > 0 && extenderNames.Any(extenderNameObject => extenderNameObject.ToString() == extenderName);
}
catch
{
// Ignore
}
return false;
}
private void ButtonClicked(object sender, EventArgs e)
{
Project currentProject = GetSelectedProjects().ElementAt(0);
var projects = _dte.Solution.GetAllNonWebProjects();
var names = from p in projects
where p.UniqueName != currentProject.UniqueName
select p.Name;
ProjectSelector2 selector = new ProjectSelector2(names);
bool? isSelected = selector.ShowDialog();
if (isSelected.HasValue && isSelected.Value)
{
WebJobCreator creator = new WebJobCreator();
var selectedProject = projects.First(p => p.Name == selector.SelectedProjectName);
creator.AddReference(currentProject, selectedProject);
var relativePath = new Uri(currentProject.FullName).MakeRelativeUri(new Uri(selectedProject.FullName)).ToString();
relativePath = relativePath.Replace("/", "\\");
creator.CreateFolders(currentProject, selector.Schedule, selector.SelectedProjectName, relativePath);
// ensure that the NuGet package is installed in the project as well
InstallWebJobsNuGetPackage(currentProject);
}
}
public IEnumerable<Project> GetSelectedProjects()
{
var items = (Array)_dte.ToolWindows.SolutionExplorer.SelectedItems;
foreach (UIHierarchyItem selItem in items)
{
var item = selItem.Object as Project;
if (item != null)
{
yield return item;
}
}
}
// TODO: Extract NuGet specifics to helper class
private bool InstallWebJobsNuGetPackage(EnvDTE.Project project)
{
bool installedPkg = false;
try
{
var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
IVsPackageInstallerServices installerServices = componentModel.GetService<IVsPackageInstallerServices>();
if (!installerServices.IsPackageInstalled(project, _webjobsPkgName))
{
_dte.StatusBar.Text = @"Installing WebJobs NuGet package, this may take a minute...";
IVsPackageInstaller installer = (IVsPackageInstaller)componentModel.GetService<IVsPackageInstaller>();
installer.InstallPackage("All", project, _webjobsPkgName, (System.Version)null, false);
_dte.StatusBar.Text = @"Finished installing WebJobs NuGet package";
}
}
catch (Exception ex)
{
installedPkg = false;
LogMessageWriteLineFormat(
"Unable to install [{0}] NuGet package. Error: {1}",
_webjobsPkgName,
ex.ToString());
}
return installedPkg;
}
private void LogMessageWriteLineFormat(string message, params object[] args)
{
if (string.IsNullOrWhiteSpace(message)) { return; }
string fullMessage = string.Format(message, args);
Trace.WriteLine(fullMessage);
Debug.WriteLine(fullMessage);
IVsActivityLog log = GetService(typeof(SVsActivityLog)) as IVsActivityLog;
if (log == null) return;
int hr = log.LogEntry(
(UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION,
this.ToString(),
fullMessage);
}
}
}<file_sep>using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace WebJobs {
public class ReadWebJobsConfigFile : Task {
public string ConfigFile { get; set; }
[Output]
public ITaskItem[] JobsFound { get; set; }
public override bool Execute() {
// read the xml file and populate the JobsFound result
if (File.Exists(ConfigFile)) {
var doc = XDocument.Load(ConfigFile);
var jobs = from wj in doc.Root.Elements("WebJob")
select new {
RelPath = wj.Attribute("RelativePath").Value,
Schedule = wj.Attribute("Schedule").Value
};
var resultList = new List<ITaskItem>();
foreach (var job in jobs) {
var item = new TaskItem(job.RelPath);
item.SetMetadata("Schedule", job.Schedule);
resultList.Add(item);
}
JobsFound = resultList.ToArray();
}
else {
Log.LogMessage("web jobs config file not found at [{0}]", ConfigFile);
}
return !Log.HasLoggedErrors;
}
}
}
<file_sep>// Guids.cs
// MUST match guids.h
using System;
namespace LigerShark.WebJobsVs
{
static class GuidList
{
public const string guidWebJobsVsPkgString = "e42a8517-258b-48d1-a92e-aba474d8def8";
public const string guidWebJobsVsCmdSetString = "c18c51ba-3e45-4ff2-acae-e8b665020949";
public static readonly Guid guidWebJobsVsCmdSet = new Guid(guidWebJobsVsCmdSetString);
};
} | 0b32b921fda573ae26b93ce10f9eba00dd85106c | [
"Markdown",
"C#"
] | 5 | Markdown | n3rd/webjobsvs | 7b2d6d6b30c682556ea1cabda534f13b94ea6bed | 4c929d88e92f161ae519e257d630251ed299fb9b |
refs/heads/master | <file_sep>opencv-python
matplotlib
numpy
pillow
pytest
sklearn
opencv-contrib-python
<file_sep>import os
from libraries import frame_splitter
FRAMES_DIR = './example_frames'
SPLIT_FRAMES_DIR = './splitted'
frames = os.listdir(FRAMES_DIR)
for frame in frames:
path = os.path.join(FRAMES_DIR, frame)
print(path)
splitter = frame_splitter.StereoFrameSplitter(path)
left, right = splitter.get_stereo_frames()
left_file = os.path.join(SPLIT_FRAMES_DIR, f'l_{frame}')
right_file = os.path.join(SPLIT_FRAMES_DIR, f'r_{frame}')
left.save(left_file)
right.save(right_file)
<file_sep>import cv2
import numpy as np
from matplotlib import pyplot as plt
class DisparityMap:
def draw(self, left_image, right_image, map_path):
left = cv2.imread(left_image)
left = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY)
right = cv2.imread(right_image)
right = cv2.cvtColor(right, cv2.COLOR_BGR2GRAY)
stereo = cv2.StereoBM_create(
numDisparities=64, blockSize=5
) # StereoSGBM_create
disparity = stereo.compute(left, right)
plt.imshow(disparity, 'gray')
plt.savefig(map_path, dpi=199)
plt.close()
class DisparityMap2:
# https://rdmilligan.wordpress.com/2016/05/23/disparity-of-stereo-images-with-python-and-opencv/
def draw(self, left_image, right_image, map_path):
window_size = 5
min_disp = 32
num_disp = 112 - min_disp
stereo = cv2.StereoSGBM_create(
minDisparity=min_disp,
numDisparities=num_disp,
uniquenessRatio=10,
speckleWindowSize=100,
speckleRange=32,
disp12MaxDiff=1,
P1=8 * 3 * window_size ** 2,
P2=32 * 3 * window_size ** 2,
)
# morphology settings
kernel = np.ones((12, 12), np.uint8)
image_left = cv2.imread(left_image)
image_right = cv2.imread(right_image)
disparity = stereo.compute(image_left, image_right)
disparity = (disparity - min_disp) / num_disp
threshold = cv2.threshold(disparity, 0.6, 1.0, cv2.THRESH_BINARY)[1]
morphology = cv2.morphologyEx(threshold, cv2.MORPH_OPEN, kernel)
plt.imshow(morphology, 'gray')
plt.savefig(map_path.replace('.png', '_morphologyd.png'), dpi=199)
plt.close()
plt.imshow(threshold, 'gray')
plt.savefig(map_path.replace('.png', '_threshold.png'), dpi=199)
plt.close()
plt.imshow(disparity, 'gray')
plt.savefig(map_path.replace('.png', '_disparity.png'), dpi=199)
plt.close()
<file_sep>import os
from libraries import disparity
FRAMES_DIR = './example_frames'
SPLIT_FRAMES_DIR = './splitted'
DISPARITY_MAPS_DIR = './disparity_maps3'
frames = os.listdir(FRAMES_DIR)
for frame in frames:
print(frame)
left_file = os.path.join(SPLIT_FRAMES_DIR, f'l_{frame}')
right_file = os.path.join(SPLIT_FRAMES_DIR, f'r_{frame}')
filename = frame.split('.')[0]
filename = f'{filename}.png'
map_path = os.path.join(DISPARITY_MAPS_DIR, filename)
draw = disparity.DisparityMap2()
draw.draw(left_file, right_file, map_path)
<file_sep>This repo contains sample images from a stereo webcam based on two sensors outputing one image stream.
**Article**: https://rk.edu.pl/en/quick-look-stereo-usb-webcam-and-stereo-vision/

<file_sep>import functools
from PIL import Image
class StereoFrameSplitter:
BORDER = 1
def __init__(self, image_file):
self.image_file = image_file
def get_stereo_frames(self):
left, right = self._get_subframes_regions()
left_image = self.image.crop(left)
right_image = self.image.crop(right)
return left_image, right_image
def _get_subframes_regions(self):
width, height = self.image.size
half_width = int(width / 2)
return [(0, 0, half_width - self.BORDER, height), (half_width + self.BORDER, 0, width, height)]
@functools.cached_property
def image(self):
return Image.open(self.image_file)
| 259860ea694b1c2d233617f2bd38796cc2f2a087 | [
"Markdown",
"Python",
"Text"
] | 6 | Text | riklaunim/stereo-webcam-python | f0dd0ac48e02d3300bb4e1015a8793e2bd9cb479 | 563bc7b224043e4baa061b1420ca5626b25cc69c |
refs/heads/main | <repo_name>SkullCutter02/snake-pro<file_sep>/src/test/java/SnakeProBrainTest_Reverse.java
import static org.junit.Assert.*;
import Controller.SnakeProBrain;
import Controller.TestGame;
import Model.BoardCell;
import org.junit.Test;
public class SnakeProBrainTest_Reverse {
// Want pictures of the test boards?
// https://tinyurl.com/wl4zelg
@Test
public void test_ReverseNorth() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G14);
brain.reverseSnake();
BoardCell nextCell = brain.testing_getNextCellInDir();
assertEquals("[1, 2, ]", nextCell.toString());
}
@Test
public void test_ReverseSouth() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G13);
brain.reverseSnake();
BoardCell nextCell = brain.testing_getNextCellInDir();
assertEquals("[4, 2, ]", nextCell.toString());
}
@Test
public void test_ReverseEast() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G12);
brain.reverseSnake();
BoardCell nextCell = brain.testing_getNextCellInDir();
assertEquals("[2, 4, ]", nextCell.toString());
}
@Test
public void test_ReverseWest() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G15);
brain.reverseSnake();
BoardCell nextCell = brain.testing_getNextCellInDir();
assertEquals("[3, 1, ]", nextCell.toString());
}
}
<file_sep>/src/main/java/View/SnakeProDisplay.java
package View;
import Model.SnakeProData;
import Model.Preferences;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
/**
* Controller.SnakeProBrain - The "View" in MVC
*
* @author CS60 instructors
*/
public class SnakeProDisplay {
/** reference to the board/snakePro data being drawn */
private SnakeProData theData;
/** the display where the board is drawn */
private Graphics theScreen;
/** width of the display in pixels */
private int width;
/** height of the display in pixels */
private int height;
/** a picture of a can of food */
public static Image imageFood;
/** Constructor
*
* @param theBoardInput the data being displayed
* @param theScreenInput the display to draw the board
* @param widthInput width of the display (in pixels)
* @param heightInput height of the display (in pixels)
*/
public SnakeProDisplay(SnakeProData theBoardInput, Graphics theScreenInput,
int widthInput, int heightInput) {
this.theScreen = theScreenInput;
this.theData = theBoardInput;
this.height = heightInput;
this.width = widthInput;
}
/* -------------------- */
/* Displaying the board */
/* -------------------- */
/**
* Re-draws the board, food, and snake (but not the buttons).
*/
public void updateGraphics() {
// Draw the background. DO NOT REMOVE!
this.clear();
// Draw the title
this.displayTitle();
// Draw the board and snake
// TODO: Add your code here :)
for(int i = 0; i < this.theData.getNumRows(); i++) {
for (int j = 0; j < this.theData.getNumColumns(); j++) {
this.drawSquare(j * Preferences.CELL_SIZE, i * Preferences.CELL_SIZE,
this.theData.getCellColor(i, j));
}
}
// The method drawSquare (below) will likely be helpful :)
// Draw the game-over message, if appropriate.
if (this.theData.getGameOver())
this.displayGameOver();
}
/**
* Draws a cell-sized square with its upper-left corner
* at the given pixel coordinates (i.e., x pixels to the right and
* y pixels below the upper-left corner) on the display.
*
* @param x x-coordinate of the square, between 0 and this.width-1 inclusive
* @param y y-coordinate of the square, between 0 and this.width-1 inclusive
* @param cellColor color of the square being drawn
*/
public void drawSquare(int x, int y, Color cellColor) {
this.theScreen.setColor(cellColor);
this.theScreen.fillRect(x, y, Preferences.CELL_SIZE,
Preferences.CELL_SIZE);
}
/**
* Draws the background. DO NOT MODIFY!
*/
void clear() {
this.theScreen.setColor(Preferences.COLOR_BACKGROUND);
this.theScreen.fillRect(0, 0, this.width, this.height);
this.theScreen.setColor(Preferences.TITLE_COLOR);
this.theScreen.drawRect(0, 0, this.width - 1,
Preferences.GAMEBOARDHEIGHT - 1);
}
/* ------------ */
/* Text Display */
/* ------------ */
/**
* Displays the title of the game.
*/
public void displayTitle() {
this.theScreen.setFont(Preferences.TITLE_FONT);
this.theScreen.setColor(Preferences.TITLE_COLOR);
this.theScreen.drawString(Preferences.TITLE,
Preferences.TITLE_X, Preferences.TITLE_Y);
}
/**
* Displays the game-over message.
*/
public void displayGameOver() {
this.theScreen.setFont(Preferences.GAME_OVER_FONT);
this.theScreen.setColor(Preferences.GAME_OVER_COLOR);
this.theScreen.drawString(Preferences.GAME_OVER_TEXT,
Preferences.GAME_OVER_X, Preferences.GAME_OVER_Y);
}
}
<file_sep>/src/test/java/SnakeProBrainTest_AdvancePede.java
import static org.junit.Assert.*;
import Controller.SnakeProBrain;
import Controller.TestGame;
import org.junit.Test;
public class SnakeProBrainTest_AdvancePede {
@Test
public void test_eatFood() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G1);
brain.updateSnake();
String boardString = brain.testing_toStringSnakeProData();
String correctBoardString = "******\n" + "*BBH *\n" + "* *\n"
+ "* *\n" + "* *\n" + "******\n";
// Sample debugging output:
// System.out.println("G1");
// System.out.println("Expected:");
// System.out.println(correctBoardString);
// System.out.println("Actual:");
// System.out.println(boardString);
assertEquals(correctBoardString, boardString);
}
@Test
public void test_noFoodEaten() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G2);
brain.updateSnake();
String boardString = brain.testing_toStringSnakeProData();
String correctBoardString = "******\n" + "* BH *\n" + "* X *\n"
+ "* *\n" + "* *\n" + "******\n";
// Sample debugging output:
// System.out.println("G2");
// System.out.println("Expected:");
// System.out.println(correctBoardString);
// System.out.println("Actual:");
// System.out.println(boardString);
assertEquals(correctBoardString, boardString);
}
}
<file_sep>/settings.gradle
rootProject.name = 'SnakePro'
<file_sep>/src/test/java/SnakeProBrainTest_GetNextCellFromBFS.java
import static org.junit.Assert.*;
import Controller.SnakeProBrain;
import Controller.TestGame;
import Model.BoardCell;
import org.junit.Test;
public class SnakeProBrainTest_GetNextCellFromBFS {
// Want pictures of the test boards?
// https://tinyurl.com/wl4zelg
@Test
public void testG1_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G1);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[1, 3, X]", nextCell.toString());
}
@Test
public void testG2_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G2);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, X]", nextCell.toString());
}
@Test
public void testG3_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G3);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[1, 3, ]", nextCell.toString());
}
@Test
public void testG4_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G4);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, ]", nextCell.toString());
}
@Test
public void testG5_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G5);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, ]", nextCell.toString());
}
@Test
public void testG6_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G6);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[1, 3, X]", nextCell.toString());
}
@Test
public void testG7_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G7);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, X]", nextCell.toString());
}
@Test
public void testG8_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G8);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[1, 3, ]", nextCell.toString());
}
@Test
public void testG9_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G9);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, ]", nextCell.toString());
}
@Test
public void testG10_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G10);
BoardCell nextCell = brain.getNextCellFromBFS();
assertEquals("[2, 2, ]", nextCell.toString());
System.out.println(brain.testing_toStringParent());
}
@Test
public void testG11_BFS() {
SnakeProBrain brain = SnakeProBrain.getTestGame(TestGame.G11);
BoardCell nextCell = brain.getNextCellFromBFS();
// NEED AN OR!
String possibleResult1 = "[1, 3, ]";
String possibleResult2 = "[2, 2, ]";
String nextCellString = nextCell.toString();
assertTrue(possibleResult1.equals(nextCellString)
|| possibleResult2.equals(nextCellString));
}
}
<file_sep>/src/main/java/Model/Preferences.java
package Model;
import java.awt.Color;
import java.awt.Font;
/**
* Model.Preferences - to avoid "magic numbers" within other code all unchanging
* variables should be stored here!
*
* This variables are labeled as final because they should not be changed outside of this class, hence their name
* Constants.
*
*/
public final class Preferences {
// Timing Constants:
public static final int REFRESH_RATE = 2;
public static final int FOOD_ADD_RATE = 25;
public static final int SLEEP_TIME = 30; // milliseconds between updates
// Sizing Constants:
public static final int NUM_CELLS_WIDE = 50;
public static final int NUM_CELLS_TALL = 30;
public static final int CELL_SIZE = 10;
private static final int SPACE_FOR_BUTTONS = 190;
public static final int GAMEBOARDHEIGHT = NUM_CELLS_TALL * CELL_SIZE
+ SPACE_FOR_BUTTONS;
// Colors Constants:
public static final Color COLOR_BACKGROUND = new Color(52, 152,219);
public static final Color COLOR_WALL = Color.BLUE;
public static final Color COLOR_FOOD = Color.ORANGE;
public static final Color COLOR_OPEN = Color.WHITE;
public static final Color COLOR_HEAD = Color.BLACK;
public static final Color COLOR_BODY = Color.GREEN;
// Text display - Title:
public static final int TITLE_X = 100;
public static final int TITLE_Y = 40;
public static final Font TITLE_FONT = new Font("Helvetica", Font.PLAIN, 30);
public static final Color TITLE_COLOR = new Color(236, 240, 241);
public static final String TITLE = "Snek Pro"; // TODO: Update the title!
// Text display - Game Over
public static final int GAME_OVER_X = 150;
public static final int GAME_OVER_Y = 200;
public static final Font GAME_OVER_FONT = new Font("Helvetica", Font.PLAIN, 60);
public static final Color GAME_OVER_COLOR = Color.BLUE;
public static final String GAME_OVER_TEXT = "Game Over";
}
| 909865b421d7b0cd508daf9ea605f38b88c27aba | [
"Java",
"Gradle"
] | 6 | Java | SkullCutter02/snake-pro | 14e91ff236829e6f212437e8133ee0f29e45dc0a | 19e0e0d499f812c6af31493ea2a1889bfd21f03d |
refs/heads/master | <file_sep>package com.migo.migoapp.model.repository
import com.migo.migoapp.model.db.AppDb
import com.migo.migoapp.model.db.PassDao
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.emuns.PassStatus
import com.migo.migoapp.model.emuns.PassTitleType
import com.migo.migoapp.model.emuns.PassType
import com.migo.migoapp.model.vo.PassListItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
class PassRepository constructor(db: AppDb) {
private val passDao: PassDao = db.passDao()
fun fetchStorePass(): ArrayList<PassListItem> {
val dayPasses = arrayListOf<Pass>()
dayPasses.add(
Pass(
name = "1 Day Pass",
price = "Rp 2.000",
type = PassType.DAY,
)
)
dayPasses.add(
Pass(
name = "3 Day Pass",
price = "Rp 5.000",
type = PassType.DAY
)
)
dayPasses.add(
Pass(
name = "7 Day Pass",
price = "Rp 10.000",
type = PassType.DAY
)
)
val hourPasses = arrayListOf<Pass>()
hourPasses.add(
Pass(
name = "1 Hour Pass",
price = "Rp 500",
type = PassType.HOUR
)
)
hourPasses.add(
Pass(
name = "8 Hour Pass",
price = "Rp 1.000",
type = PassType.HOUR
)
)
val passes = arrayListOf<PassListItem>()
passes.add(PassListItem(PassTitleType.DAY, dayPasses))
passes.add(PassListItem(PassTitleType.HOUR, hourPasses))
return passes
}
suspend fun getMyPass(): Flow<List<PassListItem>> {
return flow {
val passes = arrayListOf<PassListItem>()
val dayPasses = arrayListOf<Pass>()
val hourPasses = arrayListOf<Pass>()
val result = passDao.getAllPass()
result.forEach { pass ->
when (pass.type) {
PassType.DAY -> dayPasses.add(pass)
else -> hourPasses.add(pass)
}
}
if (dayPasses.isNotEmpty()) {
passes.add(PassListItem(PassTitleType.DAY, dayPasses))
}
if (hourPasses.isNotEmpty()) {
passes.add(PassListItem(PassTitleType.HOUR, hourPasses))
}
emit(passes)
}.flowOn(Dispatchers.IO)
}
suspend fun buyPass(pass: Pass): Flow<Pass?> {
return flow {
passDao.insertPass(pass)
emit(pass)
}.flowOn(Dispatchers.IO)
}
suspend fun activateMyPass(pass: Pass): Flow<Pass?> {
return flow {
passDao.updatePass(pass)
emit(pass)
}.flowOn(Dispatchers.IO)
}
}<file_sep># Pass App
A pass store application.
## Architecture
- MVVM
- Coroutines
- Hilt
- Jetpack
- OkHttp & Retrofit
## Screenshots
<table>
<tr>
<td>
<img src="screenshots/store.png"/>
</td>
<td>
<img src="screenshots/wallet.png">
</td>
<td>
<img src="screenshots/detail.png">
</td>
</tr>
</table><file_sep>package com.migo.migoapp.di
import android.content.Context
import com.migo.migoapp.model.db.AppDb
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DbModule {
@Singleton
@Provides
fun provideAppDb(@ApplicationContext context: Context): AppDb {
return AppDb.create(context, false)
}
}<file_sep>package com.migo.migoapp.model.db.vo
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.migo.migoapp.model.emuns.PassStatus
import com.migo.migoapp.model.emuns.PassType
import kotlinx.android.parcel.Parcelize
import java.util.*
@Entity(tableName = "pass")
@Parcelize
data class Pass(
@PrimaryKey
var id: String = "",
@ColumnInfo(name = "name")
var name: String? = null,
@ColumnInfo(name = "price")
var price: String? = null,
@ColumnInfo(name = "type")
var type: PassType? = null,
@ColumnInfo(name = "status")
var status: PassStatus = PassStatus.ACTIVATE,
@ColumnInfo(name = "activateDate")
var activateDate: Date = Date(),
@ColumnInfo(name = "activatedDate")
var activatedDate: Date? = null,
@ColumnInfo(name = "expireDate")
var expireDate: Date? = null,
): Parcelable<file_sep>package com.migo.migoapp.ui.store
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.migo.migoapp.R
import com.migo.migoapp.ui.base.BaseFragment
import com.migo.migoapp.widget.utility.GeneralUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_store.*
@AndroidEntryPoint
class StoreFragment : BaseFragment() {
private val viewModel: StoreViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rv_shop.also {
it.setHasFixedSize(true)
it.adapter = StorePassGroupAdapter(
viewModel.getStorePass(),
storeFuncListener
)
}
viewModel.buyPass.observe(viewLifecycleOwner, {
GeneralUtils.showToast(requireContext(), "${getString(R.string.purchase)} ${it.name}")
})
}
override fun getLayoutId(): Int {
return R.layout.fragment_store
}
private val storeFuncListener by lazy {
StoreFuncListener(
onBuyClick = { viewModel.buyPass(it) }
)
}
}<file_sep>package com.migo.migoapp.model.vo
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.emuns.PassTitleType
data class PassListItem(
val title: PassTitleType,
val passes: ArrayList<Pass> = arrayListOf()
)<file_sep>package com.migo.migoapp.di
import com.migo.migoapp.model.api.ApiService
import com.migo.migoapp.model.db.AppDb
import com.migo.migoapp.model.repository.ApiRepository
import com.migo.migoapp.model.repository.PassRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
@Module
@InstallIn(ViewModelComponent::class)
object RepoModule {
@Provides
fun provideApiRepository(apiService: ApiService): ApiRepository {
return ApiRepository(apiService)
}
@Provides
fun providePassRepository(db: AppDb): PassRepository {
return PassRepository(db)
}
}<file_sep>package com.migo.migoapp.ui.wallet
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.migo.migoapp.R
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.emuns.PassStatus
import com.migo.migoapp.model.emuns.PassType
import com.migo.migoapp.ui.viewholder.PassViewHolder
import com.migo.migoapp.widget.utility.GeneralUtils
import java.util.*
class WalletAdapter(
private val groupPos: Int,
private val passes: ArrayList<Pass>,
private val funcListener: WalletFuncListener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val mView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_pass, parent, false)
return PassViewHolder(mView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val pass = passes[position]
holder as PassViewHolder
holder.passName.text = pass.name
holder.passPrice.text = pass.price
when (pass.status) {
PassStatus.ACTIVATE -> {
holder.passBtn.text =
holder.passBtn.context.getString(R.string.activate)
holder.passBtn.isEnabled = true
}
PassStatus.ACTIVATED -> {
holder.passBtn.text =
holder.passBtn.context.getString(R.string.activated)
holder.passBtn.isEnabled = false
}
else -> {
holder.passBtn.text =
holder.passBtn.context.getString(R.string.expire)
holder.passBtn.isEnabled = false
}
}
holder.passBtn.setOnClickListener {
pass.status = PassStatus.ACTIVATED
pass.activatedDate = Date()
if (pass.type == PassType.DAY) {
pass.expireDate = GeneralUtils.getExpireTimeByDay(Date())
} else {
pass.expireDate = GeneralUtils.getExpireTimeByHour(Date())
}
funcListener.onActivateClick(groupPos, position, pass)
}
holder.passLayout.setOnClickListener { funcListener.onDetailClick(pass) }
}
override fun getItemCount(): Int {
return passes.size
}
fun updatePassStatus(pos: Int, pass: Pass) {
passes[pos] = pass
notifyItemChanged(pos)
}
}<file_sep>package com.migo.migoapp.model.api
import com.migo.migoapp.model.api.vo.ApiStatusItem
import retrofit2.Response
import retrofit2.http.GET
interface ApiService {
@GET("/status")
suspend fun getStatus(): Response<ApiStatusItem>
}<file_sep>plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'androidx.navigation.safeargs.kotlin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.migo.migoapp"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
abiFilters "armeabi-v7a", "arm64-v8a"
}
}
buildTypes {
debug {
zipAlignEnabled false
minifyEnabled false
debuggable true
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
zipAlignEnabled true
minifyEnabled true
debuggable false
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
kapt {
correctErrorTypes = true
arguments {
arg("room.schemaLocation", "$projectDir/schemas".toString())
}
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
// AndroidX
implementation "androidx.core:core-ktx:$ktx_version"
implementation "androidx.appcompat:appcompat:$appcompat_version"
implementation "androidx.activity:activity-ktx:$activity_ktx_version"
implementation "androidx.fragment:fragment-ktx:$fragment_ktx_version"
implementation "com.google.android.material:material:$material_version"
// KTX Extensions
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$ktx_extensions_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$ktx_extensions_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$ktx_extensions_version"
// Constraint Layout
implementation "androidx.constraintlayout:constraintlayout:$constraint_version"
// Lifecycle, ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_extensions_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_common_version"
// Navigation
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Hilt
implementation "com.google.dagger:hilt-android:$hilt_android_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_viewmodel_version"
implementation "androidx.hilt:hilt-work:$hilt_work_version"
kapt "androidx.hilt:hilt-compiler:$hilt_compiler_version"
// OkHttp
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_interceptor_version"
// Retrofit 2
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
// Kotlin Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
// Room
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
// Stetho
implementation "com.facebook.stetho:stetho:$stetho_version"
implementation "com.facebook.stetho:stetho-okhttp3:$stetho_version"
implementation "com.facebook.stetho:stetho-js-rhino:$stetho_version"
// Timber
implementation "com.jakewharton.timber:timber:$timber_version"
// Test
testImplementation "io.mockk:mockk:$mokk_version"
testImplementation "com.squareup.okhttp3:mockwebserver:$websocket_version"
testImplementation "junit:junit:$junit_version"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_test_version"
androidTestImplementation "io.mockk:mockk-android:$mokk_version"
androidTestImplementation "androidx.test.ext:junit:$android_test_ext_version"
androidTestImplementation "androidx.test.espresso:espresso-core:$espresso_version"
}<file_sep>package com.migo.migoapp.widget.utility
import android.content.Context
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.*
object GeneralUtils {
private val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
fun showToast(context: Context, text: String) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
}
fun generateId(): String {
return UUID.randomUUID().toString()
}
fun getDateTime(date: Date): String {
return formatter.format(date)
}
fun getExpireTimeByDay(date: Date): Date {
val calendar = Calendar.getInstance()
calendar.time = date
calendar.add(Calendar.DATE, 1)
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
calendar.set(Calendar.SECOND, 59)
calendar.set(Calendar.MILLISECOND, 0)
return calendar.time
}
fun getExpireTimeByHour(date: Date): Date {
val calendar = Calendar.getInstance()
calendar.time = date
calendar.add(Calendar.HOUR_OF_DAY, 1)
return calendar.time
}
}<file_sep>package com.migo.migoapp.ui.home
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.migo.migoapp.App
import com.migo.migoapp.R
import com.migo.migoapp.model.api.ApiResult.*
import com.migo.migoapp.ui.base.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.toolbar.*
@AndroidEntryPoint
class HomeFragment : BaseFragment() {
companion object {
val tabs = arrayListOf(
App.self.getString(R.string.tab_store),
App.self.getString(R.string.tab_wallet),
)
}
private val viewModel: HomeViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tv_title.text = getString(R.string.app_name)
toolbar?.also {
it.inflateMenu(R.menu.menu_home)
it.setOnMenuItemClickListener(onMenuItemClickListener)
}
viewpager.adapter = HomeViewPagerAdapter(this)
viewpager.registerOnPageChangeCallback(onPageChangeCallback)
TabLayoutMediator(layout_tab, viewpager) { tab, position ->
tab.text = tabs[position]
}.attach()
viewModel.apiStatus.observe(viewLifecycleOwner, {
when (it) {
is Loading -> {
tv_network_status.text =
getString(R.string.network_status_connecting)
tv_network_message.text =
getString(R.string.network_status_waiting)
}
is Loaded -> {
// DO-Nothing
}
is Success -> {
it.result?.let { item ->
tv_network_status.text = item.status.toString()
tv_network_message.text = item.message
}
}
is Error -> {
tv_network_status.text =
getString(R.string.network_status_disconnect)
tv_network_message.text = it.throwable.message.toString()
}
}
})
viewModel.getApiStatus()
}
override fun getLayoutId(): Int {
return R.layout.fragment_home
}
private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
if (position == 1) {
mainViewModel?.setupFetchData(true)
}
}
}
private val onMenuItemClickListener = Toolbar.OnMenuItemClickListener {
viewModel.getApiStatus()
false
}
}<file_sep>package com.migo.migoapp.ui.dialog
import android.os.Bundle
import android.view.View
import com.migo.migoapp.R
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.emuns.PassStatus
import com.migo.migoapp.ui.base.BaseDialogFragment
import com.migo.migoapp.widget.utility.GeneralUtils
import kotlinx.android.synthetic.main.dialog_pass_detail.*
class PassDetailDialogFragment : BaseDialogFragment() {
companion object {
private const val KEY_DATA = "data"
fun newInstance(pass: Pass): PassDetailDialogFragment {
val fragment = PassDetailDialogFragment()
val args = Bundle()
args.putParcelable(KEY_DATA, pass)
fragment.arguments = args
return fragment
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pass = arguments?.getParcelable<Pass>(KEY_DATA)
pass?.let {
tv_pass_title.text = it.name
when (it.status) {
PassStatus.ACTIVATE -> {
tv_pass_status.text = getString(R.string.activate)
tv_pass_activated_title.visibility = View.GONE
tv_pass_activated.visibility = View.GONE
tv_pass_expire_title.visibility = View.GONE
tv_pass_expire.visibility = View.GONE
}
PassStatus.ACTIVATED -> {
tv_pass_status.text = getString(R.string.activated)
tv_pass_activated_title.visibility = View.VISIBLE
tv_pass_activated.visibility = View.VISIBLE
tv_pass_expire_title.visibility = View.VISIBLE
tv_pass_expire.visibility = View.VISIBLE
}
else -> {
tv_pass_status.text = getString(R.string.expire)
tv_pass_activated_title.visibility = View.VISIBLE
tv_pass_activated.visibility = View.VISIBLE
tv_pass_expire_title.visibility = View.VISIBLE
tv_pass_expire.visibility = View.VISIBLE
}
}
tv_pass_activate.text = GeneralUtils.getDateTime(it.activateDate)
tv_pass_activated.text = it.activatedDate?.let { date -> GeneralUtils.getDateTime(date) }
tv_pass_expire.text = it.expireDate?.let { date -> GeneralUtils.getDateTime(date) }
}
btn_ok.setOnClickListener { dismiss() }
}
override fun getLayoutId(): Int {
return R.layout.dialog_pass_detail
}
override fun isFullLayout(): Boolean {
return false
}
}<file_sep>package com.migo.migoapp.ui.base
import androidx.lifecycle.ViewModel
abstract class BaseViewModel : ViewModel()<file_sep>const val API_PUBLIC_HOST_URL = "https://code-test.migoinc-dev.com"
const val API_PRIVATE_HOST_URL = "http://192.168.2.2"
const val DB_NAME = "app.db"<file_sep>package com.migo.migoapp.model.repository
import com.migo.migoapp.model.api.ApiService
import com.migo.migoapp.model.api.vo.ApiStatusItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.HttpException
class ApiRepository constructor(private val apiService: ApiService) {
suspend fun getApiStatus(): Flow<ApiStatusItem?> {
return flow {
val result = apiService.getStatus()
if (!result.isSuccessful) throw HttpException(result)
emit(result.body())
}.flowOn(Dispatchers.IO)
}
}<file_sep>package com.migo.migoapp.mockapi
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
class StatusApiTest : BaseApiTest() {
@Test
fun getStatus() {
enqueueResponse(ApiResult.Success, "status.json")
val result = runBlocking {
service.getStatus()
}
val request = mockWebServer.takeRequest()
assertEquals(request.path, "/status")
if (result.isSuccessful) {
val apiStatusItem = result.body()
assertEquals(apiStatusItem?.status, 200)
assertEquals(apiStatusItem?.message, "OK")
}
}
}<file_sep>rootProject.name = "MigoApp"
include ':app'
<file_sep>package com.migo.migoapp.model.emuns
enum class PassType(val value: Int) {
DAY(0),
HOUR(1)
}<file_sep>package com.migo.migoapp.ui.store
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.migo.migoapp.R
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.ui.viewholder.PassViewHolder
import com.migo.migoapp.widget.utility.GeneralUtils
class StorePassAdapter(
private val passes: List<Pass>,
private val funcListener: StoreFuncListener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val mView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_pass, parent, false)
return PassViewHolder(mView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val pass = passes[position]
holder as PassViewHolder
holder.passName.text = pass.name
holder.passPrice.text = pass.price
holder.passBtn.also {
it.text = holder.passBtn.context.getString(R.string.buy)
it.setOnClickListener {
pass.id = GeneralUtils.generateId()
funcListener.onBuyClick(pass)
}
}
}
override fun getItemCount(): Int {
return passes.size
}
}<file_sep>package com.migo.migoapp.model.emuns
enum class PassTitleType(val value: String) {
DAY("DAY PASS"),
HOUR("HOUR PASS")
}<file_sep>package com.migo.migoapp.ui.viewholder
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_pass.view.*
class PassViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var passName: TextView = itemView.tv_pass_name
var passPrice: TextView = itemView.tv_pass_price
var passBtn: Button = itemView.btn_action
var passLayout: ConstraintLayout = itemView.layout_pass
}<file_sep>package com.migo.migoapp.ui.wallet
import com.migo.migoapp.model.db.vo.Pass
class WalletFuncListener(
val onActivateClick: (groupPos: Int, passPos: Int, pass: Pass) -> Unit = { _, _, _ -> },
val onDetailClick: (pass: Pass) -> Unit = { },
)<file_sep>package com.migo.migoapp.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.migo.migoapp.model.api.ApiResult
import com.migo.migoapp.model.api.vo.ApiStatusItem
import com.migo.migoapp.model.repository.ApiRepository
import com.migo.migoapp.ui.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val apiRepository: ApiRepository
) : BaseViewModel() {
private val _apiStatus = MutableLiveData<ApiResult<ApiStatusItem>>()
val apiStatus: LiveData<ApiResult<ApiStatusItem>> = _apiStatus
fun getApiStatus() {
viewModelScope.launch {
apiRepository.getApiStatus()
.onStart { _apiStatus.value = ApiResult.loading() }
.catch { e -> _apiStatus.value = ApiResult.error(e) }
.onCompletion { _apiStatus.value = ApiResult.loaded() }
.collect { _apiStatus.value = ApiResult.success(it) }
}
}
}
<file_sep>package com.migo.migoapp.model.emuns
import API_PRIVATE_HOST_URL
import API_PUBLIC_HOST_URL
enum class ApiEnv(val url: String) {
PUBLIC(API_PUBLIC_HOST_URL),
PRIVATE(API_PRIVATE_HOST_URL)
}<file_sep>package com.migo.migoapp.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.migo.migoapp.ui.base.BaseViewModel
class MainViewModel : BaseViewModel() {
private val _isFetch = MutableLiveData<Boolean>()
val isFetch: LiveData<Boolean> = _isFetch
fun setupFetchData(isFetch: Boolean) {
_isFetch.value = isFetch
}
}<file_sep>package com.migo.migoapp.ui.home
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.migo.migoapp.ui.wallet.WalletFragment
import com.migo.migoapp.ui.store.StoreFragment
class HomeViewPagerAdapter(fragment: Fragment) :
FragmentStateAdapter(fragment) {
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> StoreFragment()
else -> WalletFragment()
}
}
}<file_sep>package com.migo.migoapp.ui.wallet
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.repository.PassRepository
import com.migo.migoapp.model.vo.PassListItem
import com.migo.migoapp.ui.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class WalletViewModel @Inject constructor(
private val passRepository: PassRepository
) : BaseViewModel() {
private val _myPass = MutableLiveData<List<PassListItem>>()
val myPass: LiveData<List<PassListItem>> = _myPass
private val _activateMyPass = MutableLiveData<Pass>()
val activateMyPass: LiveData<Pass> = _activateMyPass
private var _activatePassPos: Int = -1
private var _activateGroupPos: Int = -1
fun getAllPass() {
viewModelScope.launch {
passRepository.getMyPass()
.collect { _myPass.value = it }
}
}
fun activateMyPass(groupPos: Int, pos: Int, pass: Pass) {
viewModelScope.launch {
passRepository.activateMyPass(pass)
.collect {
_activateGroupPos = groupPos
_activatePassPos = pos
_activateMyPass.value = it
}
}
}
fun getActivatePassPos(): Int {
return _activatePassPos
}
fun getActivateGroupPos(): Int {
return _activateGroupPos
}
}<file_sep>package com.migo.migoapp.ui.wallet
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.migo.migoapp.R
import com.migo.migoapp.ui.base.BaseFragment
import com.migo.migoapp.ui.dialog.PassDetailDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_wallet.*
import timber.log.Timber
@AndroidEntryPoint
class WalletFragment : BaseFragment() {
private val viewModel: WalletViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val walletGroupAdapter = WalletGroupAdapter(walletFuncListener)
rv_wallet.also {
it.setHasFixedSize(true)
it.adapter = walletGroupAdapter
}
mainViewModel?.isFetch?.observe(viewLifecycleOwner, {
if (it) {
viewModel.getAllPass()
}
})
viewModel.myPass.observe(viewLifecycleOwner, {
if (it.isEmpty()) {
tv_empty_wallet.visibility = View.VISIBLE
} else {
tv_empty_wallet.visibility = View.GONE
}
walletGroupAdapter.setupData(it)
})
viewModel.activateMyPass.observe(viewLifecycleOwner, {
walletGroupAdapter.updatePassStatus(
viewModel.getActivateGroupPos(), viewModel.getActivatePassPos(), it
)
})
}
override fun getLayoutId(): Int {
return R.layout.fragment_wallet
}
private val walletFuncListener by lazy {
WalletFuncListener(
onActivateClick = { groupPos, pos, pass ->
viewModel.activateMyPass(groupPos, pos, pass)
},
onDetailClick = {
PassDetailDialogFragment.newInstance(it).show(
requireActivity().supportFragmentManager,
PassDetailDialogFragment::class.java.simpleName
)
}
)
}
}<file_sep>package com.migo.migoapp.model.db
import androidx.room.*
import com.migo.migoapp.model.db.vo.Pass
@Dao
interface PassDao {
@Query("SELECT * FROM pass")
fun getAllPass(): List<Pass>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPass(pass: Pass)
@Update
fun updatePass(pass: Pass)
}<file_sep>package com.migo.migoapp.ui.store
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.repository.PassRepository
import com.migo.migoapp.model.vo.PassListItem
import com.migo.migoapp.ui.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class StoreViewModel @Inject constructor(
private val passRepository: PassRepository
) : BaseViewModel() {
private val _buyPass = MutableLiveData<Pass>()
val buyPass: LiveData<Pass> = _buyPass
fun getStorePass(): ArrayList<PassListItem> {
return passRepository.fetchStorePass()
}
fun buyPass(pass: Pass) {
viewModelScope.launch {
passRepository.buyPass(pass)
.collect { _buyPass.value = it }
}
}
}<file_sep>package com.migo.migoapp.mockapi
enum class ApiResult {
Empty,
Success
}<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.31"
ext.gradle_version = '4.2.2'
ext.ktx_version = '1.6.0'
ext.ktx_extensions_version = '2.3.1'
ext.material_version = '1.5.0-alpha01'
ext.constraint_version = '2.0.4'
ext.appcompat_version = '1.4.0-alpha03'
ext.activity_ktx_version = '1.2.3'
ext.fragment_ktx_version = '1.3.5'
ext.lifecycle_extensions_version = "2.2.0"
ext.lifecycle_common_version = "2.3.1"
ext.nav_version = '2.3.5'
ext.hilt_android_version = '2.31-alpha'
ext.hilt_version = '2.35'
ext.hilt_compiler_version = '1.0.0'
ext.hilt_viewmodel_version = '1.0.0-alpha03'
ext.hilt_work_version = '1.0.0'
ext.okhttp_version = '4.9.1'
ext.okhttp_interceptor_version = '4.9.0'
ext.retrofit_version = '2.9.0'
ext.coroutines_version = '1.4.3'
ext.room_version = '2.3.0'
ext.coroutines_test_version = '1.3.9'
ext.stetho_version = "1.5.1"
ext.timber_version = '4.7.1'
ext.junit_version = '4.13.2'
ext.android_test_ext_version = '1.1.3'
ext.espresso_version = '3.4.0'
ext.mokk_version = '1.10.2'
ext.websocket_version = '4.9.1'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}<file_sep>package com.migo.migoapp.model.emuns
enum class PassStatus(val value: Int) {
ACTIVATE(0),
ACTIVATED(1),
EXPIRE(2),
}<file_sep>package com.migo.migoapp.ui.wallet
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.migo.migoapp.R
import com.migo.migoapp.model.db.vo.Pass
import com.migo.migoapp.model.vo.PassListItem
import com.migo.migoapp.ui.viewholder.PassGroupViewHolder
class WalletGroupAdapter(
private val funcListener: WalletFuncListener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var passGroup: List<PassListItem> = arrayListOf()
private var walletAdapterMap = hashMapOf<Int, WalletAdapter>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val mView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_pass_group, parent, false)
return PassGroupViewHolder(mView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val passListItem = passGroup[position]
val walletAdapter = WalletAdapter(position, passListItem.passes, funcListener)
walletAdapterMap[position] = walletAdapter
holder as PassGroupViewHolder
holder.groupTitle.text = passListItem.title.value
holder.groupRecyclerView.also {
it.setHasFixedSize(true)
it.adapter = walletAdapter
}
}
override fun getItemCount(): Int {
return passGroup.size
}
fun setupData(myPass: List<PassListItem>) {
passGroup = myPass
notifyDataSetChanged()
}
fun updatePassStatus(groupPod: Int, passPos: Int, pass: Pass) {
walletAdapterMap[groupPod]?.updatePassStatus(passPos, pass)
}
}<file_sep>package com.migo.migoapp.ui.store
import com.migo.migoapp.model.db.vo.Pass
class StoreFuncListener(
val onBuyClick: (pass: Pass) -> Unit = { },
)<file_sep>package com.migo.migoapp.ui.store
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.migo.migoapp.R
import com.migo.migoapp.model.vo.PassListItem
import com.migo.migoapp.ui.viewholder.PassGroupViewHolder
class StorePassGroupAdapter(
private val passGroup: List<PassListItem>,
private val funcListener: StoreFuncListener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val mView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_pass_group, parent, false)
return PassGroupViewHolder(mView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val passListItem = passGroup[position]
holder as PassGroupViewHolder
holder.groupTitle.text = passListItem.title.value
holder.groupRecyclerView.also {
it.setHasFixedSize(true)
it.adapter = StorePassAdapter(passListItem.passes, funcListener)
}
}
override fun getItemCount(): Int {
return passGroup.size
}
}<file_sep>package com.migo.migoapp.mockapi
import com.google.gson.Gson
import com.migo.migoapp.model.api.ApiService
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.buffer
import okio.source
import org.junit.After
import org.junit.Before
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
abstract class BaseApiTest {
lateinit var mockWebServer: MockWebServer
lateinit var service: ApiService
@Before
fun setup() {
mockWebServer = MockWebServer()
service = Retrofit.Builder()
.baseUrl(mockWebServer.url("/"))
.addConverterFactory(GsonConverterFactory.create(Gson()))
.build()
.create(ApiService::class.java)
}
@After
fun dropdown() {
mockWebServer.shutdown()
}
fun enqueueResponse(apiResult: ApiResult, fileName: String = "", headers: Map<String, String> = emptyMap()) {
when (apiResult) {
ApiResult.Empty -> mockWebServer.enqueue(MockResponse().setResponseCode(204))
ApiResult.Success -> {
val classloader = javaClass.classLoader
val inputStream = classloader.getResourceAsStream("api-response/$fileName")
val source = inputStream.source().buffer()
val mockResponse = MockResponse()
for ((key, value) in headers) {
mockResponse.addHeader(key, value)
}
mockWebServer.enqueue(mockResponse.setBody(source.readString(Charsets.UTF_8)))
}
}
}
}<file_sep>package com.migo.migoapp.model.db
import DB_NAME
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.migo.migoapp.model.db.vo.Pass
@Database(entities = [Pass::class], version = 1)
@TypeConverters(DateTimeConverter::class)
abstract class AppDb : RoomDatabase() {
companion object {
fun create(context: Context, useInMemory: Boolean = true): AppDb {
val databaseBuilder = when {
useInMemory -> Room.inMemoryDatabaseBuilder(
context,
AppDb::class.java
)
else -> Room.databaseBuilder(
context,
AppDb::class.java,
DB_NAME
)
}
return databaseBuilder
.fallbackToDestructiveMigration()
.build()
}
}
abstract fun passDao(): PassDao
}<file_sep>package com.migo.migoapp.model.api
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.text.TextUtils
import com.migo.migoapp.model.emuns.ApiEnv
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Interceptor
import okhttp3.Response
class ApiInterceptor(val context: Context) : Interceptor {
private var connectivityManager: ConnectivityManager? = null
override fun intercept(chain: Interceptor.Chain): Response {
var apiEnv = ApiEnv.PUBLIC
connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.let {
it?.allNetworks?.forEach { network ->
it.getNetworkCapabilities(network)?.let { capabilities ->
apiEnv = when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
ApiEnv.PRIVATE
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
ApiEnv.PRIVATE
}
else -> ApiEnv.PUBLIC
}
}
}
}
val request = chain.request()
val newRequest = buildRequest(request, apiEnv)
return chain.proceed(newRequest)
}
private fun buildRequest(request: Request, env: ApiEnv): Request {
val newDomain = env.url
val newHost = newDomain.toHttpUrlOrNull()?.host.toString()
val requestBuilder = request.newBuilder()
if (!TextUtils.isEmpty(newHost)) {
val newUrl = request.url.newBuilder().host(newHost).build()
requestBuilder.url(newUrl)
}
return requestBuilder.build()
}
}<file_sep>package com.migo.migoapp.ui.viewholder
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_pass_group.view.*
class PassGroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var groupTitle: TextView = itemView.tv_group_title
var groupRecyclerView: RecyclerView = itemView.rv_group
}<file_sep>package com.migo.migoapp.ui.main
import android.os.Bundle
import androidx.activity.viewModels
import com.migo.migoapp.R
import com.migo.migoapp.ui.base.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : BaseActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun getLayoutId(): Int {
return R.layout.activity_main
}
} | 626de2744a33cb45d6a6767182c7fb4795f6e8fe | [
"Markdown",
"Kotlin",
"Gradle"
] | 42 | Kotlin | davechao/PassApp | e91bd4d6d87cfcae2d9510dee14cc58ccdffbc87 | a8cd70613850a6abb5e1f00d89943d8cab6fa655 |
refs/heads/master | <repo_name>amfgkzz/my-solo-project<file_sep>/README.md
Koua's Fantasy Football App
<file_sep>/src/redux/sagas/delete-user-data.js
import { takeEvery, put as dispatch } from 'redux-saga/effects';
import axios from 'axios';
function* deleteUserTeam(action) {
try {
yield axios.delete(`/delete/team?team_id=${action.payload.team_id}&user_id=${action.payload.id}`);
yield dispatch({ type: 'GET_USER_TEAM' });
} catch (error) {
console.log('Error with delete team saga:', error);
}
}
function* releasePlayer(action) {
try {
yield axios.delete(`/delete/release-player?player_id=${action.payload}`);
yield dispatch({type: 'GET_USER_PLAYERS'});
} catch (error) {
console.log(`Error with start player saga: ${error}`);
}
}
// FIX: Add ability to delete leagues
// function* deleteUserLeague(action) {
// try {
// yield axios.delete(`/delete/league?league_id=${action.payload.league_id}&user_id=${action.payload.id}`);
// } catch (error) {
// console.log('Error with delete league saga:', error);
// }
// }
function* deleteUserDataSaga() {
yield takeEvery('DELETE_USER_TEAM', deleteUserTeam);
yield takeEvery('RELEASE_PLAYER', releasePlayer);
// FIX: Add ability to delete leagues
// yield takeEvery('DELETE_USER_LEAGUE', deleteUserLeague);
}
export default deleteUserDataSaga;
<file_sep>/src/redux/reducers/index.js
import { combineReducers } from 'redux';
import errors from '../reducers/Prime/errorsReducer';
import loginMode from '../reducers/Prime/loginModeReducer';
import user from '../reducers/Prime/userReducer';
// Koua's reducers
import playerList from './player-list';
import createdLeague from './created-leagues';
import createdTeam from './created-team';
import userTeamBench from './bench-team';
import userTeamStart from './start-team';
// rootReducer is the primary reducer for our entire project
// It bundles up all of the other reducers so our project can use them.
// This is imported in index.js as rootSaga
// Lets make a bigger object for our store, with the objects from our reducers.
// This is what we get when we use 'state' inside of 'mapStateToProps'
const rootReducer = combineReducers({
errors, // contains registrationMessage and loginMessage
loginMode, // will have a value of 'login' or 'registration' to control which screen is shown
user, // will have an id and username if someone is logged in
playerList,
createdLeague,
createdTeam,
userTeamBench,
userTeamStart,
});
export default rootReducer;
<file_sep>/server/routes/delete.data.js
const router = require('express').Router();
const pool = require('../modules/pool');
router.delete('/team', async(req, res)=>{
const client = await pool.connect();
try {
await client.query('BEGIN');
// Must update the user.team_id first before deleting team
const updateQuery = `UPDATE "user" SET "team_id"=NULL WHERE "user"."id"=$1`;
const deleteTeamPlayers = `DELETE FROM "user_players" WHERE "user_players"."user_team"=$1`;
const deleteQuery = `DELETE FROM "user_team" WHERE "user_team"."id"=$1`;
await client.query(updateQuery, [req.query.user_id]);
await client.query(deleteTeamPlayers, [req.query.team_id]);
await client.query(deleteQuery, [req.query.team_id]);
await client.query('COMMIT');
res.sendStatus(200);
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
});
router.delete('/release-player', (req, res)=>{
try {
const deleteQuery = `DELETE FROM "user_players"
WHERE "user_players"."player_id"=$1`;
pool.query(deleteQuery, [req.query.player_id]);
res.sendStatus(200);
} catch (error) {
throw error;
}
});
// FIX: Add ability to Delete leagues
// router.delete('/league', async(req, res)=>{
// const client = await pool.connect();
// try {
// await client.query('BEGIN');
// const updateQuery = `UPDATE "user" SET "league_id"=NULL WHERE "user"."id"=$1`;
// const deleteQuery = `DELETE FROM "league" WHERE "league"."id"=$1`;
// await client.query(updateQuery, [req.query.user_id]);
// await client.query(deleteQuery, [req.query.league_id]);
// await client.query('COMMIT');
// res.sendStatus(200);
// } catch (error) {
// await client.query('ROLLBACK');
// throw error;
// } finally {
// client.release();
// }
// });
module.exports = router;<file_sep>/src/components/TeamPage/TeamPage.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './TeamPage.css';
// material ui
import {
AppBar, Button, Card, IconButton,
Table, TableHead, TableBody,
TableRow, TableCell, Tooltip, Typography
} from '@material-ui/core';
class TeamPage extends Component {
componentDidMount() {
this.fetchUserTeam();
}
fetchUserTeam = () => {
this.props.dispatch({ type: 'FETCH_USER' });
this.props.dispatch({ type: 'GET_USER_TEAM' });
this.props.dispatch({ type: 'GET_USER_PLAYERS' });
}
handleClickStart = (e) => {
if (this.props.reduxState.userTeamStart[`${e.currentTarget.name}`].player_id) {
alert('There is already a player in that starting position!');
} else {
this.props.dispatch({ type: 'START_PLAYER', payload: e.currentTarget.value });
}
}
handleClickBench = (e) => {
this.props.dispatch({ type: 'BENCH_PLAYER', payload: e.currentTarget.value });
}
handleClickRelease = (e) => {
this.props.dispatch({ type: 'RELEASE_PLAYER', payload: e.currentTarget.value });
}
render() {
let startTeam = this.props.reduxState.userTeamStart;
let benchTeam = this.props.reduxState.userTeamBench;
let testArray = [
{ pos: 'QB' }, { pos: 'RB' },
{ pos: 'RB' }, { pos: 'WR' },
{ pos: 'TE' }, { pos: 'K' },
];
if (this.props.reduxState.user.team_id === null) {
return (
<div className="no-players">
<Typography>
You don't have a team!
<br/>
In order to play you must create a team.
<br/>
Click the button below to get started.
</Typography>
<br/>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/CreateTeam')}}
>
Create Team
</Button>
</div>
)
}
// FIX: show if start team exists
else if (benchTeam.length !== 0 || (startTeam.QB && startTeam.QB.player_id) ||
(startTeam.RB && startTeam.RB.player_id) || (startTeam.WR && startTeam.WR.player_id) ||
(startTeam.TE && startTeam.TE.player_id ) || (startTeam.K && startTeam.K.player_id)) {
return (
<>
<AppBar position="relative" color="secondary" style={{boxShadow: 'none', fontSize: '16pt'}}>Team</AppBar>
<br />
<div className="container-one">
<Card style={{ width: '600px' }}>
<Typography className="login-label">STARTERS</Typography>
<Table>
<TableHead>
<TableRow style={{height: '10px'}}>
<TableCell>Position</TableCell>
<TableCell>Player Name</TableCell>
<TableCell style={{textAlign: 'center'}} colSpan={2}>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
startTeam.QB && startTeam.QB.player_id
?
<TableRow>
<TableCell>{startTeam.QB.player_position}</TableCell>
<TableCell>{startTeam.QB.player_first_name} {startTeam.QB.player_last_name}</TableCell>
<TableCell><Button size="small" color="secondary" variant='contained' onClick={this.handleClickBench} value={startTeam.QB.player_id}>Bench</Button></TableCell>
<TableCell><Button size="small" color="secondary" variant='contained' onClick={this.handleClickRelease} value={startTeam.QB.player_id} >Release</Button></TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>QB</div></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.RB && startTeam.RB.player_id
?
<TableRow>
<TableCell>{startTeam.RB.player_position}</TableCell>
<TableCell>{startTeam.RB.player_first_name} {startTeam.RB.player_last_name}</TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickBench} value={startTeam.RB.player_id}>Bench</Button> </TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickRelease} value={startTeam.RB.player_id} >Release</Button> </TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>RB</div></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.WR && startTeam.WR.player_id
?
<TableRow>
<TableCell>{startTeam.WR.player_position}</TableCell>
<TableCell>{startTeam.WR.player_first_name} {startTeam.WR.player_last_name}</TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickBench} value={startTeam.WR.player_id}>Bench</Button> </TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickRelease} value={startTeam.WR.player_id} >Release</Button> </TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>WR</div></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.TE && startTeam.TE.player_id
?
<TableRow>
<TableCell>{startTeam.TE.player_position}</TableCell>
<TableCell>{startTeam.TE.player_first_name} {startTeam.TE.player_last_name}</TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickBench} value={startTeam.TE.player_id}>Bench</Button> </TableCell>
<TableCell> <Button size="small" color="secondary" variant='contained' onClick={this.handleClickRelease} value={startTeam.TE.player_id} >Release</Button> </TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>TE</div></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.K && startTeam.K.player_id
?
<TableRow>
<TableCell>{startTeam.K.player_position}</TableCell>
<TableCell>{startTeam.K.player_first_name} {startTeam.K.player_last_name}</TableCell>
<TableCell> <Button variant='contained' color="secondary" size="small" onClick={this.handleClickBench} value={startTeam.K.player_id}>Bench</Button> </TableCell>
<TableCell> <Button variant='contained' color="secondary" size="small" onClick={this.handleClickRelease} value={startTeam.K.player_id} >Release</Button> </TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>K</div></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
</TableRow>
}
</TableBody>
</Table>
</Card>
</div>
<br />
<div className="container-two">
<Card style={{ width: '600px' }}>
<Typography className="login-label">BENCH</Typography>
<Table>
<TableHead style={{backgroundColor: '#6e2db5'}}>
{/* <TableRow>
<TableCell style={{color: 'white'}}>Position</TableCell>
<TableCell style={{color: 'white'}} colSpan={3}>Player Name</TableCell>
</TableRow> */}
</TableHead>
<TableBody>
{
testArray.map((player, i = 9) => (
< TableRow key={i}>
<TableCell>{benchTeam[i] ? benchTeam[i].player_position : <div style={{ opacity: '0.5' }}>Bench</div>}</TableCell>
<TableCell>{benchTeam[i] ? benchTeam[i].player_first_name : <div style={{ opacity: '0.5' }}>Empty</div>} {benchTeam[i] ? benchTeam[i].player_last_name : <></>}</TableCell>
<TableCell>{benchTeam[i] ? <Button size="small" color="secondary" variant='contained' onClick={this.handleClickStart} name={benchTeam[i].player_position} value={benchTeam[i].player_id}>Start</Button> : <></>}</TableCell>
<TableCell>{benchTeam[i] ? <Button size="small" color="secondary" variant='contained' onClick={this.handleClickRelease} value={benchTeam[i].player_id}>Release</Button> : <></>}</TableCell>
</TableRow>
))
}
</TableBody>
</Table>
</Card>
</div>
</>
)
}
else {
return (
<>
<div className="no-players">
<Typography>
You don't have any players!
<br/>
Click the button below to head over to Free Agency
</Typography>
<br/>
<Tooltip
title="Free Agency is where you can add players
to your team. There are no duplicate players.
First come first serve!"
placement="left-start"
>
<IconButton>
<i className="material-icons">info</i>
</IconButton>
</Tooltip>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/Players')}}
>
Free Agency
</Button>
</div>
</>
)
}
}
}
const mapStateToRedux = reduxState => ({
reduxState,
});
export default connect(mapStateToRedux)(TeamPage);<file_sep>/server/routes/update.data.js
const router = require('express').Router();
const pool = require('../modules/pool');
router.put('/', (req, res)=>{
try {
const {
leagueName,
leagueNumbers,
leagueType,
teamName,
league_id,
team_id
} = req.body;
const updateQuery = `UPDATE "league" SET "league_name"=$1,
"league_numbers"=$2, "league_type"=$3 WHERE "id"=$4`;
const updateQueryTwo = `UPDATE "user_team" SET "team_name"=$1 WHERE "id"=$2`;
pool.query(updateQuery, [leagueName, leagueNumbers, leagueType, league_id]);
pool.query(updateQueryTwo, [teamName, team_id]);
res.sendStatus(201);
} catch (error) {
console.log(`Error with server put route: ${error}`);
res.sendStatus(500);
}
});
router.put('/start-player', (req, res)=>{
try {
const updateQuery = `UPDATE "user_players" SET "player_start"=TRUE
WHERE "user_players"."player_id"=$1`;
pool.query(updateQuery, [req.query.player_id]);
res.sendStatus(200);
} catch (error) {
console.log('Error with server put route:', error);
res.sendStatus(500);
}
});
router.put('/bench-player', (req, res)=>{
try {
const updateQuery = `UPDATE "user_players" SET "player_start"=FALSE
WHERE "user_players"."player_id"=$1`;
pool.query(updateQuery, [req.query.player_id]);
res.sendStatus(200);
} catch (error) {
console.log('Error with server put route:', error);
res.sendStatus(500);
}
});
module.exports = router;<file_sep>/src/redux/sagas/bench-player.js
import {takeEvery, put as dispatch} from 'redux-saga/effects';
import axios from 'axios';
function* benchPlayer(action) {
try {
yield axios.put(`/update/bench-player?player_id=${action.payload}`);
yield dispatch({type: 'GET_USER_PLAYERS'});
} catch (error) {
console.log(`Error with start player saga: ${error}`);
}
}
function* benchPlayerSaga() {
yield takeEvery('BENCH_PLAYER', benchPlayer);
}
export default benchPlayerSaga;<file_sep>/src/components/CreateLeague/CreateLeague.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './CreateLeague.css'
// Material UI
import { Button, FormLabel, IconButton, Input, Paper, Select, MenuItem, Tooltip, Typography } from '@material-ui/core';
class CreateLeague extends Component {
state = {
userID: '',
leagueName: '',
leagueNumber: '8',
leagueType: 'Standard',
}
handleChange = (propertyName) => (e) => {
this.setState({
[propertyName]: e.target.value,
});
}
handleSubmit = (e) => {
e.preventDefault();
if (this.state.leagueName === '') {
// FIX: change this to something less annoying
alert('Please fill in all the blanks!');
} else if (this.props.user.league_id === null) {
this.setState({
userID: this.props.user.id,
}, () => {
this.props.dispatch({ type: 'CREATE_LEAGUE', payload: this.state });
this.props.history.push('/CreateTeam');
});
} else {
alert('You already have a league!');
}
}
render() {
return (
<>
<div className="league-form-container">
<Paper>
<Typography
className="login-label"
>
Create a League
</Typography>
<br/>
<form onSubmit={this.handleSubmit}>
<FormLabel>League Name: </FormLabel>
<Input re="true" placeholder="Name Your League!" onChange={this.handleChange('leagueName')} />
<br />
<Tooltip
title="Number of users who can play in your league"
placement="left-start"
>
<IconButton>
<i className="material-icons">info</i>
</IconButton>
</Tooltip>
<FormLabel>Number of Teams: </FormLabel>
<Select onChange={this.handleChange('leagueNumber')} value={this.state.leagueNumber}>
<MenuItem value="4">4</MenuItem>
<MenuItem value="6">6</MenuItem>
<MenuItem value="8">8</MenuItem>
<MenuItem value="10">10</MenuItem>
<MenuItem value="12">12</MenuItem>
</Select>
<br />
{
this.state.leagueType === 'Standard'
?
<Tooltip
title="Your League will use the standard scoring rules"
placement="left-start"
>
<IconButton>
<i className="material-icons">info</i>
</IconButton>
</Tooltip>
:
<Tooltip
title="Your league will use a PPR (Points Per Reception)
scoring system, this means that
fractional or full points are awarded
for every reception tallied by a player."
placement="left-start"
>
<IconButton>
<i className="material-icons">info</i>
</IconButton>
</Tooltip>
}
<FormLabel>Scoring Type: </FormLabel>
<Select onChange={this.handleChange('leagueType')} value={this.state.leagueType}>
<MenuItem value="Standard">Standard</MenuItem>
<MenuItem value="PPR">PPR</MenuItem>
</Select>
<br />
<br/>
<Button
type="submit"
variant="contained"
size="small"
color="secondary"
>Create
</Button>
</form>
</Paper>
</div>
</>
)
}
}
const mapStateToProps = reduxState => ({
user: reduxState.user,
});
export default connect(mapStateToProps)(CreateLeague);<file_sep>/src/components/Prime/Nav/Nav.js
import React from 'react';
import { Link as Active, Route, Switch } from 'react-router-dom';
import { connect } from 'react-redux';
import LogOutButton from '../LogOutButton/LogOutButton';
import './Nav.css';
// Koua's Components
import PlayerList from '../../player-list/player-list';
import CreateLeague from '../../CreateLeague/CreateLeague';
import CreateTeam from '../../CreateTeam/CreateTeam';
import TeamPage from '../../TeamPage/TeamPage';
import Settings from '../../Settings/Settings';
import UserPage from '../../UserPage/UserPage';
// Dummy page
import Dummy from '../../Dummy/Dummy';
// Sidebar and css
import { slide as Menu } from 'react-burger-menu';
import styles from './styles';
// Material ui
import Link from '@material-ui/core/Link';
const Nav = (props) => (
<>
<Menu className="menu" width={200} disableAutoFocus styles={styles} noOverlay disableCloseOnEsc isOpen customCrossIcon={false} customBurgerIcon={false} pageWrapId={"page-wrap"} outerContainerId={"outer-container"}>
<Link className="active-link" component={Active} to="/home">
<i className="material-icons">home</i>
Home
</Link>
<br />
<Link className="active-link" component={Active} to="/UserTeamPage">
<i className="material-icons">group</i>
Team
</Link>
<br />
<Link className="active-link" component={Active} to="/Players">
<i className="material-icons">person_add</i>
Free Agency
</Link>
<br />
<Link className="active-link" component={Active} to="/Settings">
<i className="material-icons">settings</i>
Settings
</Link>
<br />
<LogOutButton />
</Menu>
<div className="views">
<Switch>
<Route
exact
path="/home"
render={(props) => <UserPage {...props} />}
/>
<Route
exact
path="/CreateLeague"
component={CreateLeague}
/>
<Route
exact
path="/CreateTeam"
component={CreateTeam}
/>
<Route
exact
path="/UserTeamPage"
component={TeamPage}
/>
<Route
exact
path="/Players"
component={PlayerList}
/>
<Route
exact
path="/Settings"
component={Settings}
/>
<Route
exact
path="/Dummy"
component={Dummy}
/>
</Switch>
</div>
</>
);
// Instead of taking everything from state, we just want the user
// object to determine if they are logged in
// if they are logged in, we show them a few more links
// if you wanted you could write this code like this:
// const mapStateToProps = ({ user }) => ({ user });
const mapStateToProps = state => ({
user: state.user,
});
export default connect(mapStateToProps)(Nav);
<file_sep>/src/redux/sagas/player-list.js
import { takeLatest, put as dispatch } from 'redux-saga/effects';
import axios from 'axios';
function* fetchData(action) {
try {
const axiosResponse = yield axios.get(`/data?player_position=${action.payload}`);
yield dispatch({ type: 'SET_PLAYER_LIST', payload: axiosResponse.data });
} catch (error) {
console.log(`Error with axios call ${error}`);
}
}
function* updateData(action) {
try {
const axiosResponse = yield axios.put('/data/player-position', action);
yield dispatch({ type: 'SET_PLAYER_LIST', payload: axiosResponse.data });
} catch (error) {
console.log(`Error with axios call ${error}`);
}
}
function* playerListSaga() {
yield takeLatest('FETCH_PLAYERLIST_DATA', fetchData);
yield takeLatest('UPDATE_PLAYERLIST_DATA', updateData);
}
export default playerListSaga;<file_sep>/src/components/UserPage/UserPage.js
import React from 'react';
import { connect } from 'react-redux';
import UserData from '../User-data/User-data';
import { AppBar } from '@material-ui/core';
// this could also be written with destructuring parameters as:
// const UserPage = ({ user }) => (
// and then instead of `props.user.username` you could use `user.username`
const UserPage = (props) => (
<>
<AppBar position="relative" color="secondary" style={{boxShadow: 'none', fontSize: '16pt'}}>
Home
</AppBar>
<UserData history={props.history}/>
</>
);
export default connect()(UserPage);
<file_sep>/src/redux/sagas/create-league.js
import { takeLatest, put as dispatch } from 'redux-saga/effects';
import axios from 'axios';
function* createLeagueSaga(action) {
try {
yield axios.post('/league/new', action.payload);
yield dispatch({ type: 'GET_USER_LEAGUE' });
} catch (error) {
console.log(`Error with create league saga ${error}`);
}
}
function* getUserLeagues() {
try {
const leagueData = yield axios.get('/league/user');
yield dispatch({type: 'SET_LEAGUES', payload: leagueData.data});
} catch (error) {
console.log(`Error with user league saga ${error}`);
}
}
function* createLeague() {
yield takeLatest('GET_USER_LEAGUE', getUserLeagues);
yield takeLatest('CREATE_LEAGUE', createLeagueSaga);
}
export default createLeague;<file_sep>/src/components/Settings/Settings.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './Settings.css';
// Material UI
import { AppBar, Button, FormLabel, Input, Paper, Select, MenuItem, Typography } from '@material-ui/core';
class Settings extends Component {
state = {
inEditMode: false,
editObject: {
leagueName: '',
leagueNumbers: '8',
leagueType: 'Standard',
teamName: '',
}
}
componentDidMount() {
this.fetchUserData();
}
fetchUserData = () => {
this.props.dispatch({ type: 'GET_USER_LEAGUE' });
this.props.dispatch({ type: 'GET_USER_TEAM' });
this.props.dispatch({ type: 'FETCH_USER' });
}
handleSubmit = (e) => {
e.preventDefault();
const league = this.props.reduxState.createdLeague[0];
const team = this.props.reduxState.createdTeam[0];
if (this.state.editObject.leagueName === '' && this.state.editObject.teamName === '') {
this.setState({
inEditMode: !this.state.inEditMode,
editObject: {
...this.state.editObject,
leagueName: league.league_name,
teamName: team.team_name,
}
}, () => {
this.props.dispatch({
type: 'UPDATE_LEAGUE_AND_TEAM',
payload: { ...this.state.editObject, league_id: league.id, team_id: team.id }
});
});
} else if (this.state.editObject.teamName === '') {
this.setState({
inEditMode: !this.state.inEditMode,
editObject: {
...this.state.editObject,
teamName: team.team_name,
}
}, () => {
this.props.dispatch({
type: 'UPDATE_LEAGUE_AND_TEAM',
payload: { ...this.state.editObject, league_id: league.id, team_id: team.id }
});
});
} else if (this.state.editObject.leagueName === '') {
this.setState({
inEditMode: !this.state.inEditMode,
editObject: {
...this.state.editObject,
leagueName: league.league_name,
}
}, () => {
this.props.dispatch({
type: 'UPDATE_LEAGUE_AND_TEAM',
payload: { ...this.state.editObject, league_id: league.id, team_id: team.id }
});
});
} else {
this.setState({
inEditMode: !this.state.inEditMode,
}, () => {
this.props.dispatch({
type: 'UPDATE_LEAGUE_AND_TEAM',
payload: { ...this.state.editObject, league_id: league.id, team_id: team.id }
});
});
}
}
handleChange = (propertyName) => (e) => {
this.setState({
editObject: {
...this.state.editObject,
[propertyName]: e.target.value,
}
});
}
handleDeleteTeam = (e) => {
this.setState({
inEditMode: !this.state.inEditMode,
}, () => {
this.props.dispatch({ type: 'DELETE_USER_TEAM', payload: this.props.reduxState.user });
});
}
// FIX: Add ability to delete league
// handleDeleteLeague = (e) => {
// this.props.dispatch({ type: 'DELETE_USER_LEAGUE', payload: this.props.reduxState.user });
// }
render() {
let reduxState = this.props.reduxState;
if (this.state.inEditMode) {
return (
<>
<AppBar position="relative" color="secondary" style={{boxShadow: 'none', fontSize: '16pt'}}>Settings</AppBar>
{
this.props.reduxState.user.league_id === null
?
<>
<Typography>
You must have a league in order to change setting!
<br />
Click the button below to get started.
<br />
</Typography>
<br/>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/CreateLeague')}}
>Create</Button>
</>
:
<div className="settings-form-container">
<form onSubmit={reduxState.createdTeam.length >= 1 ? this.handleSubmit : () => { this.setState({ inEditMode: !this.state.inEditMode }) }}
onReset={() => { this.setState({ inEditMode: !this.state.inEditMode }) }}>
{
reduxState.createdLeague.length >= 1
?
<>
<Paper style={{ width: '500px' }}>
<Typography
className="login-label"
>
{
this.props.reduxState.createdLeague && this.props.reduxState.createdLeague[0]
?
this.props.reduxState.createdLeague[0].league_name
:
<>{JSON.stringify(this.props, null, 2)}</>
}
</Typography>
<FormLabel>League Name: </FormLabel>
<Input onChange={this.handleChange('leagueName')} placeholder={reduxState.createdLeague[0].league_name} />
<br />
<FormLabel>League Numbers: </FormLabel>
<Select value={this.state.editObject.leagueNumbers} onChange={this.handleChange('leagueNumbers')}>
<MenuItem value="4">4</MenuItem>
<MenuItem value="6">6</MenuItem>
<MenuItem value="8">8</MenuItem>
<MenuItem value="10">10</MenuItem>
<MenuItem value="12">12</MenuItem>
</Select>
<br />
<FormLabel>League Type: </FormLabel>
<Select value={this.state.editObject.leagueType} onChange={this.handleChange('leagueType')}>
<MenuItem value="Standard">Standard</MenuItem>
<MenuItem value="PPR">PPR</MenuItem>
</Select>
</Paper>
{/* FIX: add ability to delete league
<button onClick={this.handleDeleteLeague}>Delete League</button> */}
</>
:
<></>
}
<br />
{
reduxState.createdTeam.length >= 1
?
<Paper style={{ width: '500px' }}>
<Typography
className="login-label"
>
{
this.props.reduxState.createdTeam && this.props.reduxState.createdTeam[0]
?
this.props.reduxState.createdTeam[0].team_name
:
<>{JSON.stringify(this.props, null, 2)}</>
}
</Typography>
<FormLabel>Team Name: </FormLabel>
<Input onChange={this.handleChange('teamName')} placeholder={reduxState.createdTeam[0].team_name} />
<Button
size="small"
color="secondary"
variant="contained"
onClick={this.handleDeleteTeam}>
Delete Team
</Button>
</Paper>
:
<></>
}
<br />
<Button
size="small"
color="secondary"
variant="contained"
type="reset">
Cancel
</Button>
<div className="divider" />
<Button
size="small"
color="secondary"
variant="contained"
type="submit"
>
Save
</Button>
</form>
</div>
}
</>
)
} else {
return (
<>
<AppBar position="relative" color="secondary" style={{boxShadow: 'none', fontSize: '16pt'}}>Settings</AppBar>
{
this.props.reduxState.user.league_id === null
?
<>
<Typography>
You must have a league in order to change setting!
<br />
Click the button below to get started.
<br />
</Typography>
<br/>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/CreateLeague')}}
>Create</Button>
</>
:
<>
<div className="settings-form-container">
<form>
{reduxState.createdLeague.map((league, i) => (
<Paper style={{ width: '500px' }} key={i}>
<Typography
className="login-label"
>
{
this.props.reduxState.createdLeague && this.props.reduxState.createdLeague[0]
?
this.props.reduxState.createdLeague[0].league_name
:
<>{JSON.stringify(this.props, null, 2)}</>
}
</Typography>
<FormLabel>League Name: </FormLabel>
<Input value={league.league_name} readOnly />
<br />
<FormLabel>League Numbers: </FormLabel>
<Input value={league.league_numbers} readOnly />
<br />
<FormLabel>League Type: </FormLabel>
<Input value={league.league_type} readOnly />
</Paper>
))}
<br />
<>
{
reduxState.createdTeam.length >= 1
?
<Paper style={{ width: '500px' }}>
<Typography
className="login-label"
>
{
this.props.reduxState.createdTeam && this.props.reduxState.createdTeam[0]
?
this.props.reduxState.createdTeam[0].team_name
:
<>{JSON.stringify(this.props, null, 2)}</>
}
</Typography>
<FormLabel>Team Name: </FormLabel>
<Input value={reduxState.createdTeam[0].team_name} readOnly />
</Paper>
:
<></>
}
</>
<br />
</form>
</div>
<div>
<Button
size="small"
color="secondary"
variant="contained"
onClick={() => { this.setState({ inEditMode: !this.state.inEditMode }) }}
>
Edit
</Button>
</div>
</>
}
</>
)
}
}
}
const mapStateToRedux = reduxState => ({
reduxState,
});
export default connect(mapStateToRedux)(Settings);<file_sep>/server/routes/league.data.js
const router = require('express').Router();
const pool = require('../modules/pool');
// Route is hit whenever user goes to their league
router.get('/user', async (req, res) => {
// FIX: grabbing ALL leagues, want to
// make it so i grab only user leagues
try {
const querySelect = `SELECT * FROM "league"`;
const queryResult = await pool.query(querySelect);
res.send(queryResult.rows);
} catch (error) {
console.log(`Error with league get route ${error}`);
}
});
// Route is hit whenever use creates a new league
router.post('/new', async (req, res) => {
const client = await pool.connect();
try {
await client.query('BEGIN');
const queryInsert = `INSERT INTO "league" ("league_name", "league_numbers", "league_type")
VALUES ($1, $2, $3) RETURNING "league"."id"`;
const queryBody = [req.body.leagueName, req.body.leagueNumber, req.body.leagueType];
const queryResult = await client.query(queryInsert, queryBody);
const queryUpdate = `UPDATE "user" SET "league_id"=$1 WHERE "user"."id"=$2`;
const queryBodyTwo = [queryResult.rows[0].id, req.body.userID];
await client.query(queryUpdate, queryBodyTwo);
await client.query('COMMIT');
res.sendStatus(201);
} catch (error) {
await client.query('ROLLBACK');
console.log(`Error with post route ${error}`);
res.sendStatus(500);
} finally {
client.release();
}
});
module.exports = router;<file_sep>/src/components/App/App.js
import React, { Component } from 'react';
import {
HashRouter as Router,
Switch,
Route
} from 'react-router-dom';
import { connect } from 'react-redux';
import './App.css';
// Prime Components
import Nav from '../Prime/Nav/Nav';
import ProtectedRoute from '../Prime/ProtectedRoute/ProtectedRoute'
class App extends Component {
componentDidMount() {
this.props.dispatch({ type: 'FETCH_USER' });
}
render() {
return (
<Router>
<div id="outer-container">
<Switch>
<ProtectedRoute
path="/"
component={Nav}
/>
<Route render={() => <h1>404</h1>} />
</Switch>
</div>
</Router>
)
}
}
export default connect()(App);
<file_sep>/src/components/Prime/Nav/styles.js
import Background from '../../../images/bg.jpg';
let styles = {
bmBurgerBars: {
background: '#373a47'
},
/* Color/shape of burger icon bars on hover*/
bmBurgerBarsHover: {
background: '#a90000'
},
bmMenuWrap: {
position: 'fixed',
top: '0',
left: '0',
backgroundImage: `linear-gradient(to top, rgba(118, 76, 214, 0.18), rgba(110, 45, 181, 0.83)), url(${Background})`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right',
},
/* General sidebar styles */
bmMenu: {
padding: '2.5em 1.5em 0',
fontSize: '1.15em',
},
/* Morph shape necessary with bubble or elastic */
bmMorphShape: {
fill: '#373a47'
},
/* Wrapper for item list */
bmItemList: {
position: 'fixed',
color: '#b8b7ad',
padding: '0.8em',
},
/* Individual item */
bmItem: {
display: 'inline-block',
},
}
export default styles;<file_sep>/src/redux/sagas/start-player.js
import {takeEvery, put as dispatch} from 'redux-saga/effects';
import axios from 'axios';
function* startPlayer(action) {
try {
yield axios.put(`/update/start-player?player_id=${action.payload}`);
yield dispatch({type: 'GET_USER_PLAYERS'});
} catch (error) {
console.log(`Error with start player saga: ${error}`);
}
}
function* startPlayerSaga() {
yield takeEvery('START_PLAYER', startPlayer);
}
export default startPlayerSaga;<file_sep>/src/redux/sagas/add-player.js
import {takeEvery, put as dispatch} from 'redux-saga/effects';
import axios from 'axios';
function* addPlayerToUserTeam(action) {
try {
const axiosResponse = yield axios.post(`/add-player?player_id=${action.payload.player_id}&team_id=${action.payload.team_id}`);
yield dispatch({type: 'FETCH_PLAYERLIST_DATA', payload: axiosResponse.data.player_position});
} catch (error) {
console.log(`Error with add player saga ${error}`);
}
}
function* addPlayerSaga() {
yield takeEvery('ADD_PLAYER', addPlayerToUserTeam);
}
export default addPlayerSaga;<file_sep>/server/routes/team.data.js
const router = require('express').Router();
const pool = require('../modules/pool');
// Route hit when getting data for user team
router.get('/user-team', async (req, res) => {
// FIX: grabbing ALL leagues, want to
// make it so i grab only user leagues
try {
const querySelect = `SELECT * FROM "user_team"`;
const queryResult = await pool.query(querySelect);
res.send(queryResult.rows);
} catch (error) {
console.log(`Error with team get route ${error}`);
res.sendStatus(500);
}
});
router.get('/user-team/players', async(req, res)=>{
try {
const querySelect = `SELECT "player_id","player_first_name", "player_last_name",
"player_position", "player_start" FROM "user_players"
JOIN "user_team" ON "user_team"."id"="user_players"."user_team"
ORDER BY "player_position"='K',"player_position"='TE',"player_position"='WR',
"player_position"='RB',"player_position"='QB';`;
const queryResult = await pool.query(querySelect);
res.send(queryResult.rows);
} catch (error) {
console.log(`Error with user players get route ${error}`);
res.sendStatus(500);
}
});
// Route hit when creating a new user team
router.post('/new', async (req, res) => {
const client = await pool.connect();
try {
await client.query('BEGIN');
const queryInsert = `INSERT INTO "user_team" (team_name) VALUES ($1) RETURNING "user_team"."id";`;
const { teamName, userID } = req.body;
const queryResult = await client.query(queryInsert, [teamName]);
const queryUpdate = `UPDATE "user" SET "team_id"=$1 WHERE "user"."id"=$2 RETURNING "user"."league_id", "user"."team_id";`;
const queryResultTwo = await client.query(queryUpdate, [queryResult.rows[0].id, userID]);
const queryUpdateTwo = `UPDATE "user_team" SET "league_id"=$1 WHERE "user_team"."id"=$2;`;
await client.query(queryUpdateTwo, [queryResultTwo.rows[0].league_id, queryResultTwo.rows[0].team_id]);
await client.query('COMMIT');
res.sendStatus(201);
} catch (error) {
await client.query('ROLLBACK');
console.log(`Error with team post route ${error}`);
res.sendStatus(500);
} finally {
client.release();
}
});
module.exports = router;<file_sep>/src/components/User-data/User-data.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './user-data.css';
// Material UI
import {
Button, Card, ExpansionPanel, ExpansionPanelSummary,
ExpansionPanelDetails, Grid, Typography,
Table, TableHead, TableBody, TableRow, TableCell
}
from '@material-ui/core';
class UserData extends Component {
componentDidMount() {
this.fetchUserData();
}
fetchUserData = () => {
this.props.dispatch({ type: 'GET_USER_LEAGUE' });
this.props.dispatch({ type: 'GET_USER_TEAM' });
this.props.dispatch({ type: 'GET_USER_PLAYERS' });
this.props.dispatch({ type: 'FETCH_USER' });
}
render() {
let startTeam = this.props.reduxState.userTeamStart;
if (this.props.reduxState.user.league_id === null) {
return (
<>
<div className="user-grid">
<Grid container spacing={3}>
<Grid item xs={12}>
<Card style={{width: '800px', margin: 'auto'}}>
<ExpansionPanel>
<ExpansionPanelSummary
style={{backgroundColor: '#6e2db5', color: 'white'}}
expandIcon={<i style={{color: 'white'}} className="material-icons">keyboard_arrow_down</i>}
>
<Typography>
What is Fantasy Football?
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>
Fantasy football is a game
in which participants assemble an imaginary team of
real life footballers and score points based on those
players' actual statistical performance or their perceived
contribution on the field of play. Usually players are
selected from one specific division in a particular country,
although there are many variations. The original game was created
in England by <NAME> on Saturday 14 August 1971 and is
still going strong 45 years later. Fantasy football has evolved
in recent years from a simple recreational activity into a significant
business due to exposure via the internet.
</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
</Card>
</Grid>
<Grid item xs={12}>
<Card style={{width: '800px', margin: 'auto'}}>
<ExpansionPanel>
<ExpansionPanelSummary
style={{backgroundColor: '#6e2db5', color: 'white'}}
expandIcon={<i style={{color: 'white'}} className="material-icons">keyboard_arrow_down</i>}
>
<Typography>
How does Fantasy Football work?
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>
Your team competes against another team every week. During the NFL season,
the real teams face each other and so do the fantasy teams in your league.
The players' real-time stats are converted into fantasy points by your league
provider, and the fantasy team that scores the most points wins the game for the week.
</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
</Card>
</Grid>
<Grid item xs={12}>
<Card style={{width: '800px', margin: 'auto'}}>
<ExpansionPanel>
<ExpansionPanelSummary
style={{backgroundColor: '#6e2db5', color: 'white'}}
expandIcon={<i style={{color: 'white'}} className="material-icons">keyboard_arrow_down</i>}
>
<Typography>
Is there anything else I should know?
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>
The two most popular scoring formats are standard and P.P.R.
(points per reception).
Standard draft leagues are the most popular fantasy football leagues
and generally begin with teams selecting all their players in a serpentine
style draft. Owners then set their lineups each week based on the number of
players per position allowed by league rules.
In P.P.R. leagues, as the name implies,
players who tend to catch more passes than others at their position
are of greater value. This means that players will receive point value
for every catch they make in P.P.R., even if they gain no yards.
</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
</Card>
</Grid>
</Grid>
</div>
<br />
<Typography>
Click the button to start playing!
</Typography>
<Button
size="small"
color="secondary"
variant="contained"
onClick={() => { this.props.history.push('/CreateLeague') }}
>
Create League
</Button>
<br />
</>
)
} else if (this.props.reduxState.user.team_id === null) {
return (
<>
<div className="paper-table">
<Card style={{width:'600px'}}>
<Table>
<TableHead style={{ backgroundColor: '#6e2db5' }}>
<TableRow>
<TableCell style={{ color: 'white' }}>League Name</TableCell>
<TableCell style={{ color: 'white' }}>League Type</TableCell>
<TableCell style={{ color: 'white' }}>League Numbers</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.props.reduxState.createdLeague.map((league, i) => (
<TableRow key={i}>
<TableCell>{league.league_name}</TableCell>
<TableCell>{league.league_type}</TableCell>
<TableCell>{league.league_numbers}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
</div>
<br/>
<Typography>
You don't have a team!
<br/>
In order to play you must create a team.
<br/>
Click the button below to get started.
</Typography>
<br/>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/CreateTeam')}}
>
Create Team
</Button>
</>
)
} else if (this.props.reduxState.user.league_id && this.props.reduxState.user.team_id) {
return (
<div className="paper-table">
<button className="dummy" onClick={()=>{this.props.history.push('/Dummy')}}></button>
<Card style={{width:'600px'}}>
<Table>
<TableHead style={{ backgroundColor: '#6e2db5' }}>
<TableRow>
<TableCell style={{ color: 'white' }}>League Name</TableCell>
<TableCell style={{ color: 'white' }}>League Type</TableCell>
<TableCell style={{ color: 'white' }}>League Numbers</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.props.reduxState.createdLeague.map((league, i) => (
<TableRow key={i}>
<TableCell>{league.league_name}</TableCell>
<TableCell>{league.league_type}</TableCell>
<TableCell>{league.league_numbers}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Card>
<br />
{
(startTeam.QB && startTeam.QB.player_id) || (startTeam.RB && startTeam.RB.player_id) ||
(startTeam.WR && startTeam.WR.player_id) || (startTeam.TE && startTeam.TE.player_id) ||
(startTeam.K && startTeam.K.player_id)
?
<Card style={{ width: '600px' }}>
<Typography className="login-label">STARTERS</Typography>
<Table>
<TableHead style={{backgroundColor: '#6e2db5'}}>
{/* <TableRow>
<TableCell style={{color: 'white'}}>Position</TableCell>
<TableCell style={{color: 'white'}} colSpan={2}>Player Name</TableCell>
</TableRow> */}
</TableHead>
<TableBody>
{
startTeam.QB && startTeam.QB.player_id
?
<TableRow>
<TableCell>{startTeam.QB.player_position}</TableCell>
<TableCell>{startTeam.QB.player_first_name} {startTeam.QB.player_last_name}</TableCell>
<TableCell></TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>QB</div></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.RB && startTeam.RB.player_id
?
<TableRow>
<TableCell>{startTeam.RB.player_position}</TableCell>
<TableCell>{startTeam.RB.player_first_name} {startTeam.RB.player_last_name}</TableCell>
<TableCell></TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>RB</div></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.WR && startTeam.WR.player_id
?
<TableRow>
<TableCell>{startTeam.WR.player_position}</TableCell>
<TableCell>{startTeam.WR.player_first_name} {startTeam.WR.player_last_name}</TableCell>
<TableCell></TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>WR</div></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.TE && startTeam.TE.player_id
?
<TableRow>
<TableCell>{startTeam.TE.player_position}</TableCell>
<TableCell>{startTeam.TE.player_first_name} {startTeam.TE.player_last_name}</TableCell>
<TableCell></TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>TE</div></TableCell>
<TableCell></TableCell>
</TableRow>
}
{
startTeam.K && startTeam.K.player_id
?
<TableRow>
<TableCell>{startTeam.K.player_position}</TableCell>
<TableCell>{startTeam.K.player_first_name} {startTeam.K.player_last_name}</TableCell>
</TableRow>
:
<TableRow>
<TableCell><div style={{ opacity: '0.5' }}>K</div></TableCell>
<TableCell></TableCell>
</TableRow>
}
</TableBody>
</Table>
</Card>
:
<>
<Typography>
You don't have anyone on your starting team!
<br/>
Click the button below to head to your team page.
</Typography>
<Button
color="secondary"
size="small"
variant="contained"
onClick={()=>{this.props.history.push('/UserTeamPage')}}
>
Team
</Button>
</>
}
</div>
)
}
}
}
const mapStateToProps = reduxState => ({
reduxState,
});
export default connect(mapStateToProps)(UserData);<file_sep>/server/routes/player.data.js
const router = require('express').Router();
const pool = require('../modules/pool');
// initial route hit when page loads
router.get('/', async (req, res) => {
try {
const queryCall = `SELECT "player"."id","position", "first_name", "last_name", "name" FROM ffdb.player
JOIN ffdb.player_team_map ON ffdb.player.id=ffdb.player_team_map.player_id
JOIN ffdb.team ON ffdb.team.id=ffdb.player_team_map.team_id
WHERE "position"=$1 AND "status"='ACT' LIMIT 40;`
const queryResponse = await pool.query(queryCall, [req.query.player_position]);
res.send(queryResponse.rows);
} catch (error) {
console.log(`Error with data query call ${error}`);
res.sendStatus(500);
}
});
// route hit when user clicks player position button
router.put('/player-position', async (req, res) => {
try {
const queryCall = `SELECT "player"."id","position", "first_name", "last_name", "name" FROM ffdb.player
JOIN ffdb.player_team_map ON ffdb.player.id=ffdb.player_team_map.player_id
JOIN ffdb.team ON ffdb.team.id=ffdb.player_team_map.team_id
WHERE "position"=$1 AND "status"='ACT' LIMIT 40;`
const queryData = [req.body.payload];
const queryResponse = await pool.query(queryCall, queryData);
res.send(queryResponse.rows);
} catch (error) {
console.log(`Error with data query call ${error}`);
res.sendStatus(500);
}
});
module.exports = router; | 760d3695ccf9648ee77d25ac5935424f17496107 | [
"Markdown",
"JavaScript"
] | 21 | Markdown | amfgkzz/my-solo-project | 59fd44cb6379ee6cdf3fa2105265c4d2e3d1df75 | 670389702c7d6aa8c7b5b877a7b170b7becbe315 |
refs/heads/master | <file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $fillable = [
'category_id','course_id','section_id','video_link','video_length','video_title','thambnail'
];
public function course(){
return $this->belongsTo('App\Models\Course','course_id');
}
public function category(){
return $this->belongsTo('App\Models\Category','category_id');
}
public function section(){
return $this->belongsTo('App\Models\Section','section_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Message;
use Illuminate\Http\Request;
class MessageController extends Controller
{
//index
public function index(){
$messages = Message::where('status',1)->orderBy('id','DESC')->get();
return view('admin.message.index',compact('messages'));
}
//view smg
public function viewMsg($id){
$message = Message::findOrFail($id);
Message::findOrFail($id)->update([
'status' => 1,
]);
return view('admin.message.view',compact('message'));
}
//delete
public function destroy($id){
Message::findOrFail($id)->delete();
$notification=array(
'message'=>'Message Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Course;
use Illuminate\Http\Request;
class CourseController extends Controller
{
public function index(){
$categories = Category::latest()->get();
$courses = Course::orderBy('id','DESC')->get();
return view('fontend.course-page',compact('courses','categories'));
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AdditionalInfo extends Model
{
protected $fillable = [
'institute', 'address','zipcode','country','city','gender',
];
public function users(){
return $this->belongsTo('App\User');
}
}
<file_sep><?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\AdditionalInfo;
use App\Models\Billing;
use App\Models\Course;
use App\Models\Enroll;
use App\Models\Order;
use App\Models\Orderdetail;
use App\Models\Section;
use App\Models\Video;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Intervention\Image\Facades\Image;
use Torann\GeoIP\Facades\GeoIP;
class UserController extends Controller
{
public function index(){
$enroll = Enroll::where('user_id',Auth::id())->get();
return view('user.home',compact('enroll'));
}
// ------------------- orders -----------------
public function myOrders(){
$orders = Order::where('user_id',Auth::id())->latest()->get();
return view('user.orders',compact('orders'));
}
// view orders
public function orderView($payemnt_id){
$order = Order::where('user_id',Auth::id())->where('payment_id',$payemnt_id)->first();
$courses = Orderdetail::where('order_id',$order->id)->latest()->get();
$billing = Billing::where('order_id',$order->id)->first();
return view('user.order-view',compact('order','courses','billing'));
}
// ===================== my course ==============
public function myCourse(){
$courses = Enroll::with('course')->where('user_id',Auth::id())->orderBy('id','DESC')->get();
return view('user.course',compact('courses'));
}
//single course or enroll course details
public function singleCourse($course_id,$course){
$exist = Enroll::where('course_id',$course_id)->where('user_id',Auth::id())->first();
if ($exist) {
$videos = Video::where('course_id',$course_id)->get();
$course = Course::findOrFail($course_id);
$require = $course->requirements;
$requirements = explode(',',$require);
$learn = $course->what_learn;
$learns = explode(',',$learn);
$orverview= Video::where('course_id',$course_id)->first();
$sections = Section::where('course_id',$course_id)->get();
return view('user.single-course',compact('videos','course','requirements','learns','orverview','sections'));
}else{
return redirect()->route('user.dashboard');
}
}
// ---------------- edit profile -------------------
public function editProfile(){
return view('user.edit-profile');
}
// ================ update profile ===============
public function updateProfile(Request $request){
$request->validate([
'name' => 'required|min:4|max:255',
'email' => 'required',
'phone' => 'required|numeric|min:11',
]);
if (User::findOrFail(Auth::id())->email == $request->email) {
User::findOrFail(Auth::id())->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
]);
$notification=array(
'message'=>'Profile Updated',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}else{
$request->validate([
'email' => 'required|unique:users,email|max:255',
]);
User::findOrFail(Auth::id())->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
]);
$notification=array(
'message'=>'Profile Updated',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
// -------------------- change profile picture ---------------
public function updateImage(Request $request){
$request->validate([
'image' => 'required|mimes:png,jpg,jpeg',
]);
if (User::findOrFail(Auth::id())->image == 'media/user/profile/1.jpg') {
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(580,610)->save('media/user/profile/'.$name_gen);
$save_url = 'media/user/profile/'.$name_gen;
User::findOrFail(Auth::id())->update([
'image' => $save_url
]);
$notification=array(
'message'=>'Image Upload Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}else{
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(580,610)->save('media/user/profile/'.$name_gen);
$save_url = 'media/user/profile/'.$name_gen;
unlink(Auth::user()->image);
User::findOrFail(Auth::id())->update([
'image' => $save_url
]);
$notification=array(
'message'=>'Image Upload Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
// ------------------- additional information ------------
public function addtionalInfo(){
$exist = AdditionalInfo::where('user_id',Auth::id())->first();
$info = AdditionalInfo::with('users')->where('user_id',Auth::id())->first();
return view('user.additional-info',compact('exist','info'));
}
// --------------------- addditional information addd ---------
public function addInAdd(){
$ip = GeoIP::getLocation(request()->ip());
return view('user.additional-info-add',compact('ip'));
}
// ---------- addditional information store --------------
public function infStore(Request $request){
AdditionalInfo::insert([
'user_id' => Auth::id(),
'institute' => $request->institute,
'address' => $request->address,
'zipcode' => $request->zipcode,
'country' => $request->country,
'city' => $request->city,
'gender' => $request->gender,
]);
$notification=array(
'message'=>'insert Success',
'alert-type'=>'success'
);
return Redirect()->route('additional-info')->with($notification);
}
// ---------------- edit additional info ------------
public function addInEdit(){
$info = AdditionalInfo::with('users')->where('user_id',Auth::id())->first();
return view('user.additional-info-edit',compact('info'));
}
public function addInUpdate(Request $request){
AdditionalInfo::where('user_id',Auth::id())->update([
'institute' => $request->institute,
'address' => $request->address,
'zipcode' => $request->zipcode,
'country' => $request->country,
'city' => $request->city,
'gender' => $request->gender,
]);
$notification=array(
'message'=>'Updated Success',
'alert-type'=>'success'
);
return Redirect()->route('additional-info')->with($notification);
}
//user password page
public function passwordPage(){
return view('user.password');
}
//update password
public function updatePassword(Request $request){
$request->validate([
'old_password' =>'<PASSWORD>',
'new_password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>|'
]);
$db_pass = Auth::user()->password;
$current_pass = $request->old_password;
$new_password = $request->new_password;
$confirm_pass = $request->confirm_password;
if (Hash::check($current_pass,$db_pass)) {
if ($new_password === $confirm_pass) {
User::findOrFail(Auth::id())->update([
'password' => <PASSWORD>($new_<PASSWORD>)
]);
Auth::logout();
$notification=array(
'message'=>'Password Changed Success,Now Login With Your New Password',
'alert-type'=>'success'
);
return Redirect()->route('login')->with($notification);
}else {
$notification=array(
'message'=>'New Password And Re-Type Password Not Match',
'alert-type'=>'error'
);
return Redirect()->back()->with($notification);
}
}else {
$notification=array(
'message'=>'Old Password Not Match',
'alert-type'=>'error'
);
return Redirect()->back()->with($notification);
}
}
}
<file_sep> function readURL1(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#two')
.attr('src', e.target.result)
.width(116)
.height(122);
};
reader.readAsDataURL(input.files[0]);
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Coupon extends Model
{
protected $fillable = [
'coupon_name','discount','validity'
];
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','Fontend\IndexController@index');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
//-------------------------------admin routes--------------------------------------
Route::group(['prefix'=>'admin','middleware' =>['admin','auth'],'namespace'=>'Admin'], function(){
Route::get('dashboard','AdminController@index')->name('admin.dashboard');
//category
Route::get('category','CategoryController@index');
Route::post('category-store','CategoryController@store')->name('category-store');
Route::get('category-edit/{id}','CategoryController@edit');
Route::post('category-update','CategoryController@update')->name('category-update');
Route::get('category-delete/{id}','CategoryController@delete');
//course
Route::get('course','CourseController@index');
Route::post('course-store','CourseController@store')->name('course-store');
Route::get('course-edit/{id}','CourseController@edit');
Route::post('course-update','CourseController@update')->name('course-update');
Route::get('course-delete/{id}','CourseController@delete');
//course video section
Route::get('course/section','SectionController@index');
Route::get('course/section-all/{id}/{slug}','SectionController@couseWiseSection');
Route::post('section-store','SectionController@store')->name('section-store');
Route::get('section-edit/{id}','SectionController@edit');
Route::post('section-update','SectionController@update')->name('section-update');
Route::get('section-delete/{id}','SectionController@delete');
Route::get('section/get/ajax/{course_id}','SectionController@ajaxSection');
//upload course video
Route::get('course/add-video','VideoController@create');
Route::post('course/video-store','VideoController@store')->name('course-video-store');
Route::get('course/manage-video','VideoController@index');
Route::get('course/wise-videos/{id}/{slug}','VideoController@courseWiseVideo');
Route::get('course/video-edit/{id}','VideoController@edit');
Route::post('course/video-update','VideoController@update')->name('course-video-update');
Route::get('course/video-delete/{id}','VideoController@delete');
//coupon
Route::get('coupon','CouponController@index');
Route::post('coupon-store','CouponController@store')->name('coupon-store');
Route::get('coupon-edit/{id}','CouponController@edit');
Route::post('coupon-update','CouponController@update')->name('coupon-update');
Route::get('coupon-delete/{id}','CouponController@delete');
//pending orders
Route::get('orders-pending','OrderController@pendingOrders');
Route::get('pending/order-view/{id}','OrderController@orderView');
Route::get('enroll-accept/{order_id}','OrderController@enrollAccept');
Route::get('pending/order-delete/{id}','OrderController@pendingDelete');
//confirmed orders
Route::get('orders-confirm','OrderController@confirmOrders');
Route::get('confirm/order-delete/{id}','OrderController@confirmDelete');
//enroll
Route::get('enroll/student','EnrollController@index');
Route::get('enroll/course-details/{id}','EnrollController@enrollDetails');
//subsriber
Route::get('subscriber/all','SubscriberController@index');
Route::get('subscriber-delete/{id}','SubscriberController@destroy');
//message
Route::get('messages/all','MessageController@index');
Route::get('message-view/{id}','MessageController@viewMsg');
Route::get('message-delete/{id}','MessageController@destroy');
//profile
Route::get('settings/profile-edit','ProfileController@editProfile');
Route::post('profile-update','ProfileController@updateProfile');
Route::get('password/change','ProfileController@passPage');
Route::post('password-update','ProfileController@updatePass');
});
// ---------------------------------- user Routes ---------------------------------
Route::group(['prefix'=>'user','middleware' =>['user','auth'],'namespace'=>'User'], function(){
Route::get('dashboard','UserController@index')->name('user.dashboard');
Route::get('orders','UserController@myOrders')->name('user-orders');
Route::get('order-view/{payment_id}','UserController@orderView');
Route::get('enroll-courses','UserController@myCourse')->name('user-course');
Route::get('single-course/{course_id}/{course}','UserController@singleCourse');
Route::get('profile/edit','UserController@editProfile')->name('edit-profile');
Route::post('profile/update','UserController@updateProfile')->name('user-update-profile');
Route::post('profile/image','UserController@updateImage')->name('user-profile-image');
Route::get('additional-info','UserController@addtionalInfo')->name('additional-info');
Route::get('additional-info-add','UserController@addInAdd')->name('additional-info-add');
Route::post('additional-info-store','UserController@infStore')->name('additional-info-store');
Route::get('additional-info-edit','UserController@addInEdit')->name('additional-info-edit');
Route::post('additional-update','UserController@addInUpdate')->name('additional-info-update');
Route::get('password','UserController@passwordPage')->name('user-password');
Route::post('password/update','UserController@updatePassword')->name('user-update-password');
//course enroll for free
Route::post('enroll/for-free','AccountController@enrollFree')->name('enroll-free');
// write review
Route::post('course/review-store','AccountController@storeCourseReview')->name('course-review-store');
});
// ================ fontend routes ===============
Route::get('course','Fontend\CourseController@index');
Route::get('blog','Fontend\BlogController@index');
Route::get('contact','Fontend\ContactController@index');
Route::get('course/details/{id}/{slug}','Fontend\CoursedetailsController@detailsPage');
//add to cart
Route::get('/add-to/cart/{id}','Fontend\CartController@addToCart');
Route::get('/cart/qty','Fontend\CartController@countQty');
//buy now
Route::get('buy-now/{id}','Fontend\CartController@buyNow');
// cart page
Route::get('cart','Fontend\CartController@cartPage');
Route::get('/cart/all','Fontend\CartController@cartAll');
Route::get('/remove/cart/item/{id}','Fontend\CartController@removeCartItem');
// coupon
Route::post('/coupon/apply','Fontend\CouponController@applyCoupon');
Route::get('/coupon/calculation','Fontend\CouponController@couponCal');
Route::get('/coupon/remove','Fontend\CouponController@removeCoupon');
//chekout
Route::get('checkout','Fontend\CheckoutController@checkoutPage');
//
Route::post('payment/process','Fontend\PaymentController@paymentPage');
Route::post('order/store','Fontend\PaymentController@oderStore');
//review
Route::get('review','Fontend\ReviewController@reviewPage');
//send message
Route::post('send/message','Fontend\MessageController@sendMessage');
Route::post('subscirbe/newsletter','Fontend\MessageController@subscribeNewsletter');
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Section;
use Carbon\Carbon;
use Illuminate\Http\Request;
class SectionController extends Controller
{
//index
public function index(){
// $sections = Section::with('course')->get();
// $courses = Course::latest()->get();
$courses = Course::latest()->get();
return view('admin.section.index',compact('courses'));
}
//course wise section
public function couseWiseSection($course_id,$slug){
$sections = Section::with('course')->where('course_id',$course_id)->latest()->get();
$courses = Course::latest()->get();
return view('admin.section.all-section',compact('courses','sections'));
}
//store Section
public function store(Request $request){
$request->validate([
'course_id' => 'required',
'section_name' => 'required',
]);
Section::insert([
'course_id' => $request->course_id,
'section_name' => ucwords($request->section_name),
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Section insert Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
//edit section
public function edit($id){
$section = Section::findOrFail($id);
$courses = Course::latest()->get();
return view('admin.section.edit',compact('section','courses'));
}
//update data
public function update(Request $request){
$id = $request->id;
$request->validate([
'course_id' => 'required',
'section_name' => 'required',
]);
Section::findOrFail($id)->update([
'course_id' => $request->course_id,
'section_name' => ucwords($request->section_name),
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Section Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course/section')->with($notification);
}
//delete data
public function delete($id){
Section::findOrFail($id)->delete();
$notification=array(
'message'=>'Section Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
// get section by ajax
public function ajaxSection($course_id){
$section = Section::where('course_id',$course_id)->latest()->get();
return json_encode($section);
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Newsletter;
use Illuminate\Http\Request;
class SubscriberController extends Controller
{
public function index(){
$subscribers = Newsletter::orderBy('id','DESC')->get();
return view('admin.subsriber.index',compact('subscribers'));
}
//delete
public function destroy($id){
Newsletter::findOrFail($id)->delete();
$notification=array(
'message'=>'Deleted Done',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Course;
use App\Models\Review;
use App\User;
use Illuminate\Http\Request;
class IndexController extends Controller
{
// ============== index pages =========
public function index(){
$categories = Category::latest()->get();
$course = Course::orderBy('id','DESC')->get();
$students = User::all();
$reviews = Review::with('user')->latest()->get();
return view('fontend.index-page',compact('categories','course','students','reviews'));
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'user_id','payment_type','tnx_id','payment_no','order_total','subtotal','discount','coupon_name','order_notes','status','order_date'
];
}
<file_sep>(function ($) {
"use strict";
/*--------------------------
venobox
---------------------------- */
$(document).ready(function(){
$('.venobox').venobox();
});
/*--------------------------
mobile-menu
---------------------------- */
$('#mobile-menu').mmenu();
/*---------------------
menu-stick
--------------------- */
var s = $("#sticker");
var pos = s.position();
$(window).on('scroll',function() {
var windowpos = $(window).scrollTop();
if (windowpos > pos.top) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
});
/*--------------------------
cart dropdown
---------------------------- */
$(".minicart-icon").on('click', function(){
$(".minicart-icon").toggleClass("active");
$(".cart-dropdown").slideToggle();
});
/*--------------------------
scrollUp
---------------------------- */
$.scrollUp({
scrollText: '<i class="fa fa-angle-up"></i>',
easingType: 'linear',
scrollSpeed: 900,
animation: 'slide'
});
/*-------------------------------------
Hero Slider
----------------------------------------*/
var mainSlider = $('.main-slider');
mainSlider.slick({
arrows: false,
prevArrow:"<button type='button' class='slick-prev'><i class='fa fa-angle-left'></i></button>",
nextArrow:"<button type='button' class='slick-next'><i class='fa fa-angle-right'></i></button>",
autoplay: true,
autoplaySpeed: 5000,
dots: true,
pauseOnFocus: false,
pauseOnHover: false,
fade: true,
infinite: true,
slidesToShow: 1,
responsive: [
{
breakpoint: 767,
settings: {
arrows: false
}
},
{
breakpoint: 479,
settings: {
arrows: false
}
}
]
});
mainSlider.on('beforeChange', function(event, slick, currentSlide, nextSlide){
var sliderTitle = $('.main-slider h1');
var currentTitle = $('.slick-current h1');
sliderTitle.removeClass('cssanimation leDoorCloseLeft sequence');
currentTitle.addClass('cssanimation leDoorCloseLeft sequence');
});
mainSlider.on('afterChange', function(event, slick, currentSlide, nextSlide){
var sliderTitle = $('.main-slider h1');
var currentTitle = $('.slick-current h1');
sliderTitle.removeClass('cssanimation leDoorCloseLeft sequence');
currentTitle.addClass('cssanimation leDoorCloseLeft sequence');
});
/*--------------------------
course-carousel
---------------------------- */
$(".course-carousel").slick({
dots: true,
arrows:true,
infinite: true,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
autoPlay: true,
adaptiveHeight: true,
prevArrow: '<i class="fa fa-angle-left"></i>',
nextArrow: '<i class="fa fa-angle-right"></i>',
responsive: [
{
breakpoint: 1169,
settings: {
slidesToShow: 3,
slidesToScroll: 3
}
},
{
breakpoint: 769,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
}
},
{
breakpoint: 481,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
}
},
]
});
/*--------------------------
Three Items
---------------------------- */
$(".three-items").slick({
dots: false,
arrows:true,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
autoPlay: true,
adaptiveHeight: true,
prevArrow: '<i class="fa fa-angle-left"></i>',
nextArrow: '<i class="fa fa-angle-right"></i>',
responsive: [
{
breakpoint: 992,
settings: {
slidesToShow: 3,
slidesToScroll: 3
}
},
{
breakpoint: 769,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
}
},
{
breakpoint: 361,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
}
},
]
});
/*--------------------------
testimonial-carousel
---------------------------- */
$(".testimonial-carousel").slick({
dots: true,
arrows:false,
infinite: true,
speed: 300,
slidesToShow: 2,
slidesToScroll: 2,
autoPlay: true,
adaptiveHeight: true,
prevArrow: '<i class="fa fa-angle-left"></i>',
nextArrow: '<i class="fa fa-angle-right"></i>',
responsive: [
{
breakpoint: 768,
settings: {
arrows: false,
slidesToShow: 1
}
}
]
});
/*--------------------------
testimonial-carousel 2
----------------------------*/
$(".testimonial-carousel-center").slick({
centerMode: true,
centerPadding: '100px',
slidesToShow: 2,
dots:true,
arrows:false,
responsive: [
{
breakpoint: 992,
settings: {
arrows: false,
centerMode: false,
centerPadding: '0',
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
/*--------------------------
team-carousel
---------------------------- */
$(".team-carousel").slick({
dots: false,
arrow:true,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 3,
autoPlay: true,
adaptiveHeight: true,
prevArrow: '<i class="fa fa-angle-left"></i>',
nextArrow: '<i class="fa fa-angle-right"></i>',
responsive: [
{
breakpoint: 992,
settings: {
slidesToShow: 3,
slidesToScroll: 3
}
},
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
}
},
{
breakpoint: 361,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
}
},
]
});
/*--------------------------
counterUp
---------------------------- */
$('.count1').counterUp({
delay: 10,
time: 1000
});
$('.count2').counterUp({
delay: 15,
time: 2000
});
$('.count3').counterUp({
delay: 20,
time: 3000
});
$('.count4').counterUp({
delay: 10,
time: 4000
});
/*---------------------
countdown
--------------------- */
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('<span class="cdown days"><span class="time-count">%-D</span><p>/Days</p></span> <span class="cdown hour"><span class="time-count">%-H</span> <p>/Hour</p></span> <span class="cdown minutes"><span class="time-count">%M</span> <p>/Min</p></span> <span class="cdown second"> <span><span class="time-count">%S</span> <p>/Sec</p></span>'));
});
});
/*----------------------------
price-slider
------------------------------ */
$( "#slider-range" ).slider({
range: true,
min: 40,
max: 600,
values: [ 60, 570 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" - $" + $( "#slider-range" ).slider( "values", 1 ) );
/*--------------------------
isotop
---------------------------- */
$(window).on('load',function() {
var layoutMode = 'fitRows';
if($(window).width() < 992) {
layoutMode = 'masonry';
}
$('.gallery-items').isotope({
layoutMode: layoutMode,
});
});
$('.gallery-nav li').on('click', function() {
$(".gallery-nav li").removeClass("active");
$(this).addClass("active");
var selector = $(this).attr('data-filter');
$(".gallery-items").isotope({
filter: selector,
animationOptions: {
duration: 750,
easing: 'linear',
queue: false
}
});
return false;
});
/*----------------------------
cart-plus-minus-button
------------------------------ */
$(".qtybutton").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
})(jQuery); <file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Course;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use response;
class CartController extends Controller
{
public function addToCart($id){
$course = Course::where('id',$id)->first();
$exist = Cart::content()->where('id',$id)->first();
if ($exist) {
return response()->json(['error' => 'Course Already Has On Your Cart']);
}else{
if (Session::has('coupon')) {
session()->forget('coupon');
}
$data = array();
$data['id'] = $id;
$data['name'] = $course->course_name;
$data['price'] = $course->course_fee;
$data['weight'] = 1;
$data['qty'] = 1;
$data['options']['image'] = $course->image;
Cart::add($data);
return response()->json(['success' => 'Course Added on your Cart']);
}
}
//---------------- Buy Now-------------------
public function buyNow($id){
$course = Course::where('id',$id)->first();
$exist = Cart::content()->where('id',$id)->first();
if ($exist) {
return redirect()->to('cart');
}else{
if (Session::has('coupon')) {
session()->forget('coupon');
}
$data = array();
$data['id'] = $id;
$data['name'] = $course->course_name;
$data['price'] = $course->course_fee;
$data['weight'] = 1;
$data['qty'] = 1;
$data['options']['image'] = $course->image;
Cart::add($data);
return redirect()->to('cart');
}
}
public function countQty(){
$qty = Cart::count();
return response()->json($qty);
}
// cart page
public function cartPage(){
$qty = Cart::count();
if ($qty == 0) {
$notification=array(
'message'=>'Cart Is Empty',
'alert-type'=>'error'
);
return Redirect()->to('/')->with($notification);
}else{
$carts = Cart::content();
return view('fontend.cart-page',compact('carts'));
}
}
// -------------------- cart page function will be go here ---------------
public function cartAll(){
$cart = Cart::content();
$countQty = Cart::count();
$total = Cart::total();
return response()->json(array(
'cart' => $cart,
// 'countqty' => $countQty,
'total' => $total,
));
}
//remove cart item
public function removeCartItem($id){
// Cart::destroy();
Cart::remove($id);
if (Session::has('coupon')) {
session()->forget('coupon');
}
return response()->json(['success' => 'Course Remove From Your Cart']);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Review;
use Illuminate\Http\Request;
class ReviewController extends Controller
{
public function reviewPage(){
$reviews = Review::with('user')->orderBy('id','DESC')->get();
$reviews2 = Review::with('user')->get();
return view('fontend.review-page',compact('reviews','reviews2'));
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Orderdetail extends Model
{
protected $fillable = [
'order_id','course_id','course_name','price'
];
public function course(){
return $this->belongsTo('App\Models\Course','course_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
//edit profile pagge
public function editProfile(){
return view('admin.profile.edit');
}
//update profile
public function updateProfile(Request $request){
$request->validate([
'name' => 'required|min:4',
'email' => 'required|email',
]);
$id = Auth::user()->id;
if ($request->file('image')) {
$request->validate([
'image' => 'required|mimes:jpg,jpeg,png,gif'
]);
if (User::findOrFail(Auth::id())->image == 'media/user/profile/1.jpg') {
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(580,610)->save('media/user/profile/'.$name_gen);
$save_url = 'media/user/profile/'.$name_gen;
User::find($id)->update([
'name' => $request->name,
'email' => $request->email,
'image' => $save_url,
]);
$notification=array(
'message'=>'Profile Update Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}else{
$old_img = $request->old_image;
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(580,610)->save('media/user/profile/'.$name_gen);
$save_url = 'media/user/profile/'.$name_gen;
unlink($old_img);
User::find($id)->update([
'name' => $request->name,
'email' => $request->email,
'image' => $save_url,
]);
$notification=array(
'message'=>'Profile Update Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}else{
User::findOrFail($id)->update([
'name' => $request->name,
'email' => $request->email,
]);
$notification=array(
'message'=>'Profile Update Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
//password page
public function passPage(){
return view('admin.profile.password');
}
// update password
public function updatePass(Request $request){
$id = Auth::id();
$db_pass = Auth::user()->password;
$old_pass = $request->old_password;
$new_pass = $request->new_password;
$confirm_pass = $request->confirm_password;
if(Hash::check($old_pass, $db_pass)){
if($new_pass === $confirm_pass){
User::findOrFail($id)->update([
'password' => <PASSWORD>($request->new_password)
]);
Auth::logout();
$notification=array(
'message'=>'Password Change Successfully.! Now login With New Password',
'alert-type'=>'success'
);
return redirect()->route('login')->with($notification);
}else{
return redirect()->back()->with('danger','new password and confirm passoword not same');
}
}else{
$notification=array(
'message'=>'Old Password Not Match',
'alert-type'=>'error'
);
return redirect()->back()->with($notification);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Enroll;
use App\User;
use Illuminate\Http\Request;
class EnrollController extends Controller
{
public function index(){
$enrolls = Enroll::with('course')->groupBy('course_id')->select('course_id')->latest()->get();
return view('admin.enroll.index',compact('enrolls'));
}
//enroll details
public function enrollDetails($course_id){
$enrolls = Enroll::with('user')->where('course_id',$course_id)->latest()->get();
return view('admin.enroll.details',compact('enrolls'));
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Billing;
use App\Models\Enroll;
use App\Models\Order;
use App\Models\Orderdetail;
use Carbon\Carbon;
use Illuminate\Http\Request;
use PhpParser\Node\Expr\FuncCall;
class OrderController extends Controller
{
//---------------------------------pending orders--------------------------------
public function pendingOrders(){
$orders = Order::where('status',0)->latest()->get();
return view('admin.order.pending',compact('orders'));
}
//order view
public function orderView($order_id){
$order = Order::findOrFail($order_id);
$billing = Billing::where('order_id',$order_id)->first();
$orderdetails = Orderdetail::with('course')->where('order_id',$order_id)->latest()->get();
return view('admin.order.view-order',compact('order','billing','orderdetails'));
}
//accept enrolll now
public function enrollAccept($order_id){
$user = Order::findOrFail($order_id);
$user_id = $user->user_id;
$orderdetails = Orderdetail::where('order_id',$order_id)->latest()->get();
foreach ($orderdetails as $course) {
Enroll::insert([
'course_id' => $course->course_id,
'user_id' => $user_id,
'order_id' => $course->order_id,
'created_at' => Carbon::now(),
]);
}
Order::findOrFail($order_id)->update([
'status' => '1',
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Order Accepted Done',
'alert-type'=>'success'
);
return Redirect()->to('admin/orders-pending')->with($notification);
}
//delete
public function pendingDelete($order_id){
Order::where('id',$order_id)->where('status',0)->delete();
Billing::where('order_id',$order_id)->delete();
Orderdetail::where('order_id',$order_id)->delete();
$notification=array(
'message'=>'Order Deleted Done',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
//---------------------------------confirm orders-----------------------------------
public function confirmOrders(){
$orders = Order::where('status',1)->latest()->get();
return view('admin.order.confirmed',compact('orders'));
}
//delete
public function confirmDelete($order_id){
Order::where('id',$order_id)->where('status',1)->delete();
Billing::where('order_id',$order_id)->delete();
Orderdetail::where('order_id',$order_id)->delete();
$notification=array(
'message'=>'Order Deleted Done',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Message;
use App\Models\Newsletter;
use App\Models\Review;
use Carbon\Carbon;
use Illuminate\Http\Request;
class MessageController extends Controller
{
public function sendMessage(Request $request){
$request->validate([
'name' => 'required|string',
'email' => 'required|email',
'phone' => 'required',
'subject' => 'required',
'message' => 'required',
]);
Message::insert([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'subject' => $request->subject,
'message' => $request->message,
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Successfully Message Send',
'alert-type'=>'success'
);
return redirect()->back()->with($notification);
}
// -------------------------------- Newsletter ----------------------
public function subscribeNewsletter(Request $request){
$request->validate([
'email' => 'required'
]);
$exist = Newsletter::where('email',$request->email)->first();
if ($request->email === $exist->email) {
$notification=array(
'message'=>'You Are Already Subscribed',
'alert-type'=>'error'
);
return redirect()->back()->with($notification);
}else{
Newsletter::insert([
'email' => $request->email,
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Successfully Subscribe',
'alert-type'=>'success'
);
return redirect()->back()->with($notification);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BlogController extends Controller
{
public function index(){
return view('fontend.blog-page');
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Course;
use App\Models\Review;
use App\Models\Section;
use App\Models\Video;
use Illuminate\Http\Request;
class CoursedetailsController extends Controller
{
public function detailsPage($id,$slug){
$course = Course::findOrFail($id);
$require = $course->requirements;
$requirements = explode(',',$require);
$learn = $course->what_learn;
$learns = explode(',',$learn);
$videos= Video::where('course_id',$id)->latest()->get();
$orverview= Video::where('course_id',$id)->first();
$sections = Section::where('course_id',$id)->get();
$reviews = Review::with('user')->where('course_id',$id)->latest()->get();
return view('fontend.course-details',compact('course','videos','sections','requirements','learns','orverview','reviews'));
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Billing extends Model
{
protected $fillable = [
'order_id','first_name','last_name','email','phone','institute_name','address','state','post_code','order_notes',
];
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CheckoutController extends Controller
{
public function checkoutPage(){
if (Auth::check()) {
if (Cart::count() == 0) {
return redirect()->to('/');
}else{
$carts = Cart::content();
$subtotal = Cart::total();
return view('fontend.checkout-page',compact('carts','subtotal'));
}
}else{
$notification=array(
'message'=>'You Need To Login First',
'alert-type'=>'error'
);
return redirect()->route('login')->with($notification);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Course;
use App\Models\Section;
use App\Models\Video;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class VideoController extends Controller
{
public function create(){
$courses = Course::latest()->get();
$categories = Category::latest()->get();
$sections = Section::all();
return view('admin.video.create',compact('courses','categories','sections'));
}
//store video
public function store(Request $request){
$request->validate([
'category_id' => 'required',
'course_id' => 'required',
'section_id' => 'required',
'video_title' => 'required',
'video_link' => 'required',
'video_length' => 'required',
]);
$image = $request->file('thambnail');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(1280,720)->save('media/course/playlist/'.$name_gen);
$save_url = 'media/course/playlist/'.$name_gen;
Video::insert([
'category_id' => $request->category_id,
'course_id' => $request->course_id,
'section_id' => $request->section_id,
'video_title' => $request->video_title,
'video_link' => $request->video_link,
'thambnail' => $save_url,
'video_length' => $request->video_length,
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Video insert Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course/manage-video')->with($notification);
}
// all course section
public function index(){
// $videos = Video::with('course','category','section')->latest()->get();
$courses = Course::latest()->get();
return view('admin.video.index',compact('courses'));
}
///course wise videos
public function courseWiseVideo($course_id,$slug){
$videos = Video::with('course','category','section')->where('course_id',$course_id)->latest()->get();
return view('admin.video.manage-video',compact('videos'));
}
//edit video
public function edit($id){
$video = Video::findOrFail($id);
$courses = Course::latest()->get();
$categories = Category::latest()->get();
$sections = Section::all();
return view('admin.video.edit',compact('courses','categories','sections','video'));
}
//update video
public function update(Request $request){
$id = $request->id;
$old_thamb = $request->old_img;
$request->validate([
'category_id' => 'required',
'course_id' => 'required',
'section_id' => 'required',
'video_title' => 'required',
'video_link' => 'required',
'video_length' => 'required',
]);
if($request->thambnail){
unlink($old_thamb);
$image = $request->file('thambnail');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(1280,720)->save('media/course/playlist/'.$name_gen);
$save_url = 'media/course/playlist/'.$name_gen;
Video::findOrFail($id)->update([
'category_id' => $request->category_id,
'course_id' => $request->course_id,
'section_id' => $request->section_id,
'video_title' => $request->video_title,
'video_link' => $request->video_link,
'thambnail' => $save_url,
'video_length' => $request->video_length,
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Video Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course/manage-video')->with($notification);
}else{
Video::findOrFail($id)->update([
'category_id' => $request->category_id,
'course_id' => $request->course_id,
'section_id' => $request->section_id,
'video_title' => $request->video_title,
'video_link' => $request->video_link,
'thambnail' => $old_thamb,
'video_length' => $request->video_length,
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Video Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course/manage-video')->with($notification);
}
}
//delete
public function delete($id){
Video::findOrFail($id)->delete();
$notification=array(
'message'=>'Video Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Course;
use App\Models\Enroll;
use App\Models\Section;
use App\Models\Video;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class CourseController extends Controller
{
//index
public function index(){
$categories = Category::latest()->get();
$courses = Course::latest()->get();
return view('admin.course.index',compact('courses','categories'));
}
//store course
public function store(Request $request){
$request->validate([
'category_id' => 'required',
'course_name' => 'required',
// 'course_fee' => 'required',
'requirements' => 'required',
'what_learn' => 'required',
]);
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(600,485)->save('media/course/'.$name_gen);
$save_url = 'media/course/'.$name_gen;
Course::insert([
'category_id' => $request->category_id,
'course_fee' => $request->course_fee,
'course_name' => ucwords($request->course_name),
'course_slug' => strtolower(str_replace(' ','-', $request->course_name)),
'requirements' => $request->requirements,
'what_learn' => $request->what_learn,
'image' => $save_url,
'course_files' => $request->course_files,
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Course insert Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
//edit course
public function edit($id){
$course = Course::findOrFail($id);
$categories = Category::latest()->get();
return view('admin.course.edit',compact('course','categories'));
}
//update
public function update(Request $request){
$id = $request->id;
$old_img = $request->old_image;
$request->validate([
'category_id' => 'required',
'course_name' => 'required',
// 'course_fee' => 'required',
'requirements' => 'required',
'what_learn' => 'required',
]);
if ($request->file('image')) {
unlink($old_img);
$image = $request->file('image');
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(600,485)->save('media/course/'.$name_gen);
$save_url = 'media/course/'.$name_gen;
Course::findOrFail($id)->update([
'category_id' => $request->category_id,
'course_name' => ucwords($request->course_name),
'course_slug' => strtolower(str_replace(' ','-', $request->course_name)),
'course_fee' => $request->course_fee,
'requirements' => $request->requirements,
'what_learn' => $request->what_learn,
'image' => $save_url,
'course_files' => $request->course_files,
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Course Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course')->with($notification);
}else {
Course::findOrFail($id)->update([
'category_id' => $request->category_id,
'course_name' => ucwords($request->course_name),
'course_slug' => strtolower(str_replace(' ','-', $request->course_name)),
'course_fee' => $request->course_fee,
'requirements' => $request->requirements,
'what_learn' => $request->what_learn,
'image' => $old_img,
'course_files' => $request->course_files,
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Course Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/course')->with($notification);
}
}
//delete Course
public function delete($id){
$img = Course::findOrFail($id);
$old_img = $img->image;
unlink($old_img);
Course::findOrFail($id)->delete();
Section::where('course_id',$id)->delete();
Video::where('course_id',$id)->delete();
$enroll = Enroll::where('course_id',$id)->first();
if ($enroll) {
$enroll = Enroll::where('course_id',$id)->delete();
}
$notification=array(
'message'=>'Course Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BillingController extends Controller
{
//
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
class CouponController extends Controller
{
public function index(){
$coupons = Coupon::latest()->get();
return view('admin.coupon.index',compact('coupons'));
}
//store coupon
public function store(Request $request){
$request->validate([
'coupon_name' => 'required',
'discount' => 'min:1|max:99',
'validity' => 'required'
]);
Coupon::insert([
'coupon_name' => strtoupper($request->coupon_name),
'discount' => $request->discount,
'validity' => $request->validity,
'created_at' => Carbon::now(),
]);
$notification=array(
'message'=>'Coupon insert Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
//edit coupon
public function edit($id){
$coupon = Coupon::findOrFail($id);
return view('admin.coupon.edit',compact('coupon'));
}
//update coupon
public function update(Request $request){
$id = $request->id;
$request->validate([
'coupon_name' => 'required',
'discount' => 'min:1|max:99',
'validity' => 'required'
]);
Coupon::findOrFail($id)->update([
'coupon_name' => strtoupper($request->coupon_name),
'discount' => $request->discount,
'validity' => $request->validity,
'updated_at' => Carbon::now(),
]);
$notification=array(
'message'=>'Coupon Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/coupon')->with($notification);
}
//delete
public function delete($id){
Coupon::findOrFail($id)->delete();
$notification=array(
'message'=>'Coupon Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $fillable = [
'category_id','course_name','course_slug','requirements','what_learn','image','course_fee','course_files',
];
public function category(){
return $this->belongsTo('App\Models\Category','category_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Coupon;
use Carbon\Carbon;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class CouponController extends Controller
{
public function applyCoupon(Request $request){
$check = Coupon::where('coupon_name',$request->coupon_name)->first();
$total = Cart::total();
if ($check) {
$coupon_validity = $check->validity >= Carbon::now()->format('Y-m-d');
if ($coupon_validity) {
Session::put('coupon',[
'coupon_name' => $check->coupon_name,
'discount' => $check->discount,
'discount_amount' => round($total * ($check->discount/100)),
]);
return response()->json(array(
'coupon_validity' => $coupon_validity,
'success' => 'Successfully Coupon Applied'
));
}else{
return response()->json(['error' => 'Your Coupon Is Not Valid']);
// date expire coupon
}
}else{
return response()->json(['error' => 'Your Coupon Is Not Valid']);
}
}
//after apply coupon & calculate Carts total
public function couponCal(){
if (Session::has('coupon')) {
$subtotal = Cart::total();
$coupon_name = session()->get('coupon')['coupon_name'];
$discount = session()->get('coupon')['discount'];
$discount_amount = session()->get('coupon')['discount_amount'];
return response()->json(array(
'subtotal' => $subtotal,
'coupon_name' => $coupon_name,
'discount' => $discount,
'discount_amount' => $discount_amount,
));
}else {
$total = Cart::total();
return response()->json(array(
'total' => $total
));
}
}
//remove coupon
public function removeCoupon(){
if (Session::has('coupon')) {
session()->forget('coupon');
return response()->json(['success' => 'Coupon Removed Success']);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Enroll;
use App\Models\Review;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class AccountController extends Controller
{
// enroll course for free
public function enrollFree(Request $request){
$course_id = $request->id;
if (Auth::check()) {
$exist = Enroll::Where('course_id',$course_id)->where('user_id',Auth::id())->first();
if (!$exist) {
$course = Course::findOrFail($course_id);
if ($course->course_fee == NULL) {
Enroll::insert([
'course_id' => $course_id,
'user_id' => Auth::id()
]);
$notification=array(
'message'=>'Successfully Enroll Done',
'alert-type'=>'success'
);
return Redirect()->route('user-course')->with($notification);
}else {
return Redirect()->to('/');
}
}else{
$notification=array(
'message'=>'Course Already Enroll You',
'alert-type'=>'error'
);
return redirect()->back()->with($notification);
}
}else {
$notification=array(
'message'=>'You Need to Login First',
'alert-type'=>'success'
);
return redirect()->route('login')->with($notification);
}
}
//course Review
public function storeCourseReview(Request $request){
$course_id = $request->course_id;
$request->validate([
'comment' => 'required'
],[
'comment.required' => 'the review field is required'
]);
Review::insert([
'course_id'=> $course_id,
'user_id'=> Auth::id(),
'comment'=> $request->comment,
'created_at'=> Carbon::now(),
]);
$notification=array(
'message'=>'Your Review Added Our Site',
'alert-type'=>'success'
);
return redirect()->back()->with($notification);
}
}
<file_sep><?php
namespace App\Http\Controllers\Fontend;
use App\Http\Controllers\Controller;
use App\Models\Billing;
use App\Models\Order;
use App\Models\Orderdetail;
use Carbon\Carbon;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PaymentController extends Controller
{
// data from checkout page and get payment page
public function paymentPage(Request $request){
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
'phone' => 'required',
'institute_name' => 'required',
'address' => 'required',
'state' => 'required',
'post_code' => 'required|numeric',
'order_notes' => 'required',
'payment_method' => 'required',
],[
'payment_method.required' => 'select any payment method',
]);
$data = array();
$data['first_name'] = $request->first_name;
$data['last_name'] = $request->last_name;
$data['email'] = $request->email;
$data['phone'] = $request->phone;
$data['institute_name'] = $request->institute_name;
$data['address'] = $request->address;
$data['state'] = $request->state;
$data['post_code'] = $request->post_code;
$data['order_notes'] = $request->order_notes;
$carts = Cart::content();
$subtotal = Cart::total();
if ($request->payment_method == 'bkash') {
return view('fontend.payment.bkash',compact('data','carts','subtotal'));
}elseif($request->payment_method == 'rocket'){
return view('fontend.payment.rocket',compact('data','carts','subtotal'));
}else{
return view('fontend.payment.shurecash',compact('data','carts','subtotal'));
}
}
// ----------------------- Order Store ----------------------
public function oderStore(Request $request){
$request->validate([
'tnx_id' => 'required',
'payment_no' => 'required',
]);
$order_id = Order::insertGetId([
'user_id' => Auth::id(),
'payment_id' => mt_rand(100000,999999),
'payment_type' => $request->payment_type,
'tnx_id' => $request->tnx_id,
'payment_no' => $request->payment_no,
'order_total' => $request->order_total,
'subtotal' => $request->subtotal,
'discount' => $request->discount,
'discount_amount' => $request->discount_amount,
'coupon_name' => $request->coupon_name,
'order_notes' => $request->order_notes,
'status' => 0,
'order_date' => Carbon::now()->format('d F Y'),
'created_at' => Carbon::now(),
]);
Billing::insert([
'order_id' => $order_id,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'phone' => $request->phone,
'institute_name' => $request->institute_name,
'address' => $request->address,
'state' => $request->state,
'post_code' => $request->post_code,
'order_notes' => $request->order_notes,
'created_at' => Carbon::now(),
]);
$carts = Cart::content();
foreach ($carts as $cart) {
Orderdetail::insert([
'order_id' => $order_id,
'course_id' => $cart->id,
'course_name' => $cart->name,
'price' => $cart->price,
'created_at' => Carbon::now(),
]);
}
if (session()->has('coupon')) {
session()->forget('coupon');
}
Cart::destroy();
$notification=array(
'message'=>'Order Completed',
'alert-type'=>'success'
);
return Redirect()->route('user-orders')->with($notification);
}
}
<file_sep>$(document).on("click", "#delete", function(e){
e.preventDefault();
var link = $(this).attr("href");
swal({
title: "Are you sure To Delete?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location.href = link;
} else {
swal("Your imaginary file is safe!");
}
});
});
$(document).on("click", "#enroll", function(e){
e.preventDefault();
var link = $(this).attr("href");
swal({
title: "Are you sure To Enroll Accept?",
text: "Once Accept, you will not be able to return from course!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location.href = link;
} else {
swal("Not Accepted!");
}
});
});
<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Carbon\Carbon;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function index(){
$categories = Category::latest()->get();
return view('admin.category.index',compact('categories'));
}
//store category
public function store(Request $request){
$request->validate([
'category_name' => 'required',
]);
Category::insert([
'category_name' => ucwords($request->category_name),
'created_at' => Carbon::now()
]);
$notification=array(
'message'=>'Category insert Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
//edit category
public function edit($id){
$category = Category::findOrFail($id);
return view('admin.category.edit',compact('category'));
}
//updat data
public function update(Request $request){
$id = $request->id;
$request->validate([
'category_name' => 'required',
]);
Category::findOrFail($id)->update([
'category_name' => ucwords($request->category_name),
'updated_at' => Carbon::now()
]);
$notification=array(
'message'=>'Category Update Success',
'alert-type'=>'success'
);
return Redirect()->to('admin/category')->with($notification);
}
//delete data
public function delete($id){
Category::findOrFail($id)->delete();
$notification=array(
'message'=>'Category Delete Success',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}
}
| 1ceb70faaca5d5657da2766c03cd4555c7e7df69 | [
"JavaScript",
"PHP"
] | 34 | PHP | sarjid/coders | 4926ad5bc28ed5219813252be0ed569fb96b871a | 96eef50fcd66001baff0cef5907673e8fe25ed26 |
refs/heads/master | <file_sep>#include "cMessenger.h"
#include <stdio.h> /* for printf() */
#include <stdlib.h> /* for malloc(), exit() */
#include <unistd.h> /* for close() */
#include <string.h> /* for strcopy(), strlen(), memset() */
#include <arpa/inet.h> /* for struct sockaddr_in, SOCK_STREAM */
#define PORT 8080
#define MAXSIZE 1024
/* Max participants waiting for a connection */
#define MAXPENDING 1
char buffer[MAXSIZE];
int SendMsg(int);
int ReceiveMsg(int);
/**/
/*FUNCTIONS*/
/* Create a listening host using a socket */
/* Source code:
https://www.geeksforgeeks.org/socket-programming-cc/
https://codereview.stackexchange.com/questions/13461/two-way-communication-in-tcp-server-client-implementation?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
http://www.csd.uoc.gr/~hy556/material/tutorials/cs556-3rd-tutorial.pdf */
int CreateServer()
{
/* Socket descriptor for serverAddress */
int serverSocket;
/* Socket descriptor for client */
int clientSocket;
/* Local address:
struct sockaddr_in - data type specific to TCP/IP addresses */
struct sockaddr_in serverAddress;
/* Client address */
struct sockaddr_in clientAddress;
unsigned int size = sizeof(clientAddress);
int messageSize;
/**/
/* SOCKET: Create socket for incoming connections.
AF_INET - IPv4 protocols family,
SOCK_STREAM - TCP socket type,
0 - default protocol */
if (-1 == (serverSocket = socket(AF_INET, SOCK_STREAM, 0)))
{
AddMessage(SYSTEMUSER, "Socket failure!", 0);
}
/* Construct local address structure */
serverAddress.sin_family = AF_INET; /* Internet address family */
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
serverAddress.sin_port = htons(PORT); /* Local port */
/* BIND: Assign address to socket.
serverSocket - socket descriptor,
serverAddress - the address and port,
size - size of sockaddr_in structure */
if (-1 == (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress))))
{
AddMessage(SYSTEMUSER, "Binding Failure!", 0);
close(serverSocket);
return -1;
}
/* LISTEN: Mark the socket to listen for incoming connections */
if (-1 == listen(serverSocket, MAXPENDING))
{
AddMessage(SYSTEMUSER, "Listening Failure!", 0);
close(serverSocket);
return -1;
}
PrintMessage(SYSTEMUSER, "Waiting for a connection...", 0);
/* Allow multiple consecutive connections to a listening socket */
for(;;)
{
/* ACCEPT: Dequeue the net connection on the socket (blocking).
clientSocket - socket used for data transfer,
serverSocket - being listened to socket,
&clientAddress - address of the active participant (filled in upon return),
size - size of sockaddr_in structure */
if (-1 == (clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &size)))
{
AddMessage(SYSTEMUSER, "Accept error!", 0);
close(serverSocket);
return -1;
}
{
AddMessage(SYSTEMUSER, "Connection established! Say hello;)", 0);
}
/* Allow multiple send/receives */
while(1)
{
/* Send a message */
if (-1 == SendMsg(clientSocket))
break;
/* Receive a message */
if (-1 == ReceiveMsg(clientSocket))
break;
AddMessage(SYSTEMUSER, buffer, 0);
}
/* CLOSE: Close connection, free port used */
close(clientSocket);
AddMessage(SYSTEMUSER, "Connection closed!", 0);
}
return 0;
}
/* Create a client by connecting to a listening socket at a specified IP address */
/* Source code: https://www.geeksforgeeks.org/socket-programming-cc/
https://codereview.stackexchange.com/questions/13461/two-way-communication-in-tcp-server-client-implementation?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
http://www.csd.uoc.gr/~hy556/material/tutorials/cs556-3rd-tutorial.pdf */
int CreateClient()
{
/* Socket data */
int clientSocket;
struct sockaddr_in serverAddress;
char ipServer[64];
/* To print Enter IP only once */
int mem = 0;
int messageSize;
/**/
/* SOCKET: Create an active TCP socket */
if (-1 == (clientSocket = socket(AF_INET, SOCK_STREAM, 0)))
{
AddMessage(SYSTEMUSER, "Socket creation error!", 0);
return -1;
}
serverAddress.sin_family = AF_INET; /* Internet address family */
serverAddress.sin_port = htons(PORT); /* Server port */
/* Receive a server IP address from a user.
Convert IPv4 and IPv6 addresses from text to binary form */
while (0 >= inet_pton(AF_INET, ipServer, &serverAddress.sin_addr))
{
/* Receive an IP address from the user */
if (0 == mem++)
AddMessage(SYSTEMUSER, "Enter IP", 0);
{
printf("%s\n", SYSTEMACTION);
PrintMessage(SYSTEMUSER, "Type 'x' to connect to localhost (127.0.0.1)", 1);
strncpy(ipServer, ProcessMessage(64, 0), 64);
if ('x' == ipServer[0])
strncpy(ipServer, "127.0.0.1", 64);
}
AddMessage(CUSER, ipServer, 0);
if(0 >= inet_pton(AF_INET, ipServer, &serverAddress.sin_addr))
{
PrintMessage(SYSTEMUSER, "Invalid address", 0);
}
printf("%s\n", SYSTEMACTION);
}
/* CONNECT: Establish a connection with the server.
clientSocket - socket to be used in connection,
serverAddress - address of the server,
size - size of sockaddr_in structure */
if (-1 == connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)))
{
AddMessage(SYSTEMUSER, "Connection failed", 0);
close(clientSocket);
return -1;
}
/* Send and receive user information */
/*{
char userInfo[20];
char* tempColor = (char*)malloc(sizeof(char[1]));
strncpy(userInfo, CUSER->userName, 20);
sprintf(tempColor, "%d", (CUSER->userColor - 40));
userInfo[17] = *tempColor;
send(clientSocket, userInfo, MAXSIZE-1, MAXSIZE-1);
if (0 > (num = recv(clientSocket, buffer, MAXSIZE, 0)))
{
perror("recv");
return -1;
}
else if (0 == num)
{
AddMessage(SYSTEMUSER, "Connection closed", 0);
return -1;
}
PrintMessage(CUSER, buffer, 0);
}*/
{
AddMessage(SYSTEMUSER, "Connection established! Say hello;)", 0);
}
/* Allow to send/receive multiple times */
while (1)
{
/* Send a message */
if (-1 == SendMsg(clientSocket))
break;
/* Receive a message */
if (-1 == ReceiveMsg(clientSocket))
break;
AddMessage(SYSTEMUSER, buffer, 0);
}
close(clientSocket);
return 0;
}
int SendMsg(int xSocket)
{
/* Input and save a message */
strncpy(buffer, ProcessMessage(MAXSIZE, 1), MAXSIZE);
/* Display it in the message history */
AddMessage(CUSER, buffer, 0);
/* SEND: Send data (blocking).
buffer - message to send,
SENDBUFFERSIZE - size of the message,
0 - no flags */
if (MAXSIZE != (send(xSocket, buffer, MAXSIZE, 0)))
{
AddMessage(SYSTEMUSER, "Failure Sending Message", 0);
return -1;
}
return 0;
}
int ReceiveMsg(int xSocket)
{
int msgSize = -1;
USER* connectionUser = &(USER){ .userName = "connectionUser", .userColor = 46 };
if (-1 == (msgSize = recv(xSocket, buffer, MAXSIZE, 0)))
{
AddMessage(SYSTEMUSER, "Connection Closed", 0);
return -1;
}
/* Display a received message */
AddMessage(SYSTEMUSER, buffer, 0);
/**/
return msgSize;
}
<file_sep>/* GLOBAL SYMBOLIC CONSTANTS */
#define USERNAMESIZE 16
/* STRUCTURES DEFINITIONS */
/* Structure that is used to store data about a user:
Includes a username (16 characters max) and a color, saved as an int */
struct User
{
char userName[USERNAMESIZE];
/* Color Reference: https://misc.flogisoft.com/bash/tip_colors_and_formatting */
int userColor;
} typedef USER;
/* Message structure is a linked-list node that is used to store data about a single message:
Includes data of the sender (in the User structure's pointer),
message string's pointer,
indentation that tells the printing function whether the sender name should be printed
and an address of the next message */
struct Message
{
USER* sender;
char* message;
int indentation;
struct Message* next;
} typedef MESSAGE;
/* Message History is a linked-list consisting of Message nodes. As such, it contains an address of the first Message structure */
struct MessageHistory
{
MESSAGE* top;
} typedef MESSAGEHISTORY;
/**/
/* GLOBAL DECLARATION */
/* System user (cMessenger). Defined at cMessenger.c */
extern USER* SYSTEMUSER;
/* Current User. Defined at cMessenger.c
The pointer cannot be changed, but the values pointed to can be */
extern USER* const CUSER;
/* Message thread of the session. Defined at cMessenger.c */
extern MESSAGEHISTORY* MESSAGEHIST;
/* Standard encapsulation of a system action. Defined at messageIO.c */
extern const char* SYSTEMACTION;
/**/
/* FUNCTIONS PROTOTYPES */
/* Create a user structure
defined at dataStructures.c */
void CreateUser();
/* Add a new node to the dynamic structure
defined at dataStructures.c */
void AddMessage(USER*, char*, int);
/* Create a listening host using a socket
defined at connection.c */
int CreateServer();
/* Create a client by connecting to a listening socket at a specified IP address
defined at connection.c */
int CreateClient();
/* A universal string processing method that includes systems calls.
Allocates memory for a string with the size specified.
By default, returns the pointer to the string.
defined at printMessages.c */
char* ProcessMessage(int, int);
/* Print a message
defined at printMessages.c */
void PrintMessage(USER*, char*, int);
/* Print a passed profile's information
defined at printMessages.c */
void PrintProfile(USER*);
/* Traverse the dynamic strucre of messages
defined at printMessages.c */
void PrintHistory(MESSAGE*);
<file_sep>#include "cMessenger.h"
#include <stdio.h> /* for printf() */
#include <stdlib.h> /* for malloc() */
#include <string.h> /* for strcopy() */
/*FUNCTIONS*/
/* A complete procedure that lets a user to create a USER structure and returns it */
void CreateUser()
{
char userColorInput[1];
AddMessage(SYSTEMUSER, "To create/modify a user profile", 1);
/* Create name */
{
AddMessage(SYSTEMUSER, "Type in your nickname", 1);
strncpy(CUSER->userName, ProcessMessage(USERNAMESIZE, 0), USERNAMESIZE);
AddMessage(CUSER, CUSER->userName, 0);
}
/* Choose color */
{
int i;
char* tempColor = (char*)malloc(sizeof(char[64]));
/* Print various colors */
AddMessage(SYSTEMUSER, "Choose color", 0);
/* Print system action */
{
printf("%s\n", SYSTEMACTION);
for (i = 1; i < 6; i++)
{
printf("\x1b[97;%dm %d - %s \x1b[0m ", i + 40, i, "message");
}
printf("\n%s\n", SYSTEMACTION);
}
while (userColorInput[0] < 49 || userColorInput[0] > 53)
{
strncpy(userColorInput, ProcessMessage(1, 0), 1);
}
CUSER->userColor = atoi(userColorInput) + 40;
/* Reference: http://forums.codeguru.com/showthread.php?347081-itoa-error */
sprintf(tempColor, "%d", CUSER->userColor - 40);
AddMessage(CUSER, tempColor, 0);
}
}
/* Add a new node to the dynamic structure */
void AddMessage(USER* userPtr, char* messageStr, int indentation)
{
struct Message* iMessage;
struct Message* tempMessage;
iMessage = MESSAGEHIST->top;
/* Fill out the new message */
{
tempMessage = (struct Message*)malloc(sizeof(struct Message));
tempMessage->sender = userPtr;
tempMessage->message = messageStr;
tempMessage->indentation = indentation;
tempMessage->next = NULL;
}
if (NULL == iMessage)
{
MESSAGEHIST->top = tempMessage;
}
else
{
while (NULL != iMessage->next)
{
iMessage = iMessage->next;
}
iMessage->next = tempMessage;
}
PrintHistory(MESSAGEHIST->top);
}
| 176ff177faa8f4e5aac50db0119a8e67e0c61402 | [
"C"
] | 3 | C | Ilyumzhinov/cMessenger | 9a54c75ede29e9a7a9fb0b3fd23df07d50060d12 | 665a3ed7cb465e287b07c4d06e83ce1b632acf7b |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (C) 2016 <NAME> (<http://www.marlonfalcon.cl>).
# contact: <EMAIL>
######################################################################
from openerp.osv import fields, osv , orm
from datetime import time, datetime
from openerp.tools.translate import _
class rio2016_modelo(osv.osv):
_name = 'rio2016.modelo'
_description = 'Formulario atletas'
_columns = {
# Campo oblidatorio para buscar , readonly = True
'name' : fields.char('Nombre' , size=256, required=True, help='Este es el nombre'),
'pais' : fields.char('Pais' , size=256, required=True),
'oro' : fields.integer('Oro' , required=True),
'plata' : fields.integer('Plata', required=True),
'active': fields.boolean('Activo'),
}
_defaults = {
'active' : 'true',
}
rio2016_modelo()
<file_sep># ihceRep1
primer repositorio
<file_sep>from openerp.osv import fields, osv
from openerp import models, fields, api, exceptions, tools, SUPERUSER_ID
from openerp.tools.translate import _
from openerp import http
from datetime import datetime
#import pdb
#pdb.set_trace()
class Register(http.Controller):
@http.route('/user/', auth='public', website=True, methods=['GET'])
def index(self, **kw):
Atentionareas = http.request.env['atention.area']
atentionareas = Atentionareas.search([('name','!=','')])
i = []
for x in atentionareas:
i.append(x.name)
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona fisica','Persona moral'],
'areas': i,
})
@http.route('/user/', auth='public', website=True, methods=['POST'])
def reg(self, **kw):
print "INSIDE" + str(http.request.params)
Companies = http.request.env['companies.ihce']
Login = http.request.env['login.ihce']
#------------------------------Aqui va el listado de areas de atencion-------------#
Atentionareas = http.request.env['atention.area']
atentionareas = Atentionareas.search([('name','!=','')])
i = []
for x in atentionareas:
i.append(x.name)
#------------------------------Consulta si el user_login existe-------------#
responseL = http.request.params
responsel = str(responseL['user_login'])
usuarioActivo = Companies.search([('user_login','=',responsel)])
var = len(usuarioActivo)
if var == 0 :
com = Companies.create(http.request.params)
com.write({'company': True, 'diagnostico': True, 'state': 'draft', 'date': datetime.now()})
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona Fisica','Persona Moral'],
'message': 'Gracias por registrarte.',
'areas': i
})
else :
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona Fisica','Persona Moral'],
'message': 'Usuario ya Registrado',
'areas': i
})
@app.route('/stanford')
def stanford_page():
return """<h1>Hello stanford!</h1>"""
<file_sep>from openerp.osv import fields, osv
from openerp import models, fields, api, exceptions, tools, SUPERUSER_ID
from openerp.tools.translate import _
from openerp import http
from datetime import datetime
import locale
import sys
import pdb
reload(sys)
sys.setdefaultencoding('utf-8')
#pdb.set_trace()
class Register(http.Controller):
@http.route('/signup/', auth='public', website=True, methods=['GET'])
def index(self, **kw):
Atentionareas = http.request.env['atention.area']
atentionareas = Atentionareas.search([('name','!=','')])
i = []
for x in atentionareas:
i.append(x.name)
emprered = http.request.env['emprereds']
emprereD = emprered.search([('name','!=','')])
ie = []
for x in emprereD:
ie.append(x.name)
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona Fisica','Persona Moral'],
'areas': i,
'empr': ie,
})
@http.route('/signup/', auth='public', website=True, methods=['POST'])
def reg(self, **kw):
print "INSIDE" + str(http.request.params)
Companies = http.request.env['companies.ihce']
Login = http.request.env['login.ihce']
Res = http.request.env['res.users']
emprered = http.request.env['emprereds']
#------------------------------Aqui va el listado de areas de atencion-------------#
Atentionareas = http.request.env['atention.area']
atentionareas = Atentionareas.search([('name','!=','')])
i = []
for x in atentionareas:
i.append(x.name)
#------------------------------Consulta si el user_login existe-------------#
responseL = http.request.params
responsel = str(responseL['user_l'])
empreredname = str(responseL['empr'])
usuarioActivo = Companies.search([('user_login','=',responsel)])
emprereId = emprered.search([('name','=',empreredname)])
iemp = []
for x in emprereId:
iemp.append(x.id)
nombre = str(responseL['name_people']) + " " + str(responseL['apaterno']) + " " + str(responseL['amaterno'])
emprereD = emprered.search([('name','!=','')])
ie = []
for x in emprereD:
ie.append(x.name)
types = str(responseL['types'])
if types == "Emprendedor":
types = "emprendedor"
if types == "Persona Fisica":
types = "fisica"
if types == "Persona Moral":
types = "moral"
var = len(usuarioActivo)
if var == 0 :
#pdb.set_trace()
http.request.params.update({'name_commercial':nombre, 'company': True, 'diagnostico': True,'state': 'draft','date': datetime.now(),'name': nombre,'emprered': iemp[0], 'user_login':responsel, 'atention_area':Atentionareas, 'type':types})
com = Companies.create2(http.request.params)
#com.write({})
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona Fisica','Persona Moral'],
'message': 'Gracias por registrarte.',
'areas': i,
'empr': ie,
})
else :
return http.request.render('company_ihce.form', {
'types': ['Emprendedor','Persona Fisica','Persona Moral'],
'message': 'Usuario ya Registrado',
'areas': i,
'empr': ie,
})
class seguimiento(http.Controller):
@http.route('/seguimiento/signup/', auth='public', website=True, methods=['GET'])
def index(self, **kw):
return http.request.render('company_ihce.forms_user', {
})
@http.route('/seguimiento/signup/', auth='public', website=True, methods=['POST'])
def a_log(self, **kw):
print "INSIDE" + str(http.request.params)
Companies = http.request.env['companies.ihce']
Login = http.request.env['login.ihce']
responseL = http.request.params
responsel = str(responseL['user_l'])
responseP = str(responseL['password_login'])
usuarioActivo = Companies.search([('user_login','=',responsel), ('password_login','=',responseP)])
var = len(usuarioActivo)
if var == 1 :
return http.request.render('company_ihce.forms', {
'message': 'Gracias puedes continuar para agendar una asesoria',
'id': usuarioActivo.id,
'name': usuarioActivo.name,
})
else :
return http.request.render('company_ihce.forms_user', {
'message': 'Usuario no registrado, registrate para crear una aseosria',
})
@http.route('/seguimiento/asesoria/', auth='public', website=True, methods=['POST'])
def reg_ase(self, **kw):
Asesorias = http.request.env['asesorias.ihce']
#http.request.params.update({'name_commercial':nombre, 'rfc':nombre})
com = Asesorias.create2(http.request.params)
return http.request.render('company_ihce.forms_user',{
'message': 'Gracias, tu asesoria esta registrada',
})
| 99ed0b789b13884d6c15891d553e793ebdc4a0e9 | [
"Markdown",
"Python"
] | 4 | Python | aaronSid1/ihceRep1 | 1530ed1ea441c63f2764f4e371ce7ec688ab990b | c801d0c7bb7ad15f71e6844e85ad788d7e2c121e |
refs/heads/master | <repo_name>dor29494/Snooker-Table<file_sep>/src/Home/PopUpMenu/PopUpMenu.js
import React,{useEffect,useState} from "react";
import PopupState, { bindTrigger, bindMenu } from "material-ui-popup-state";
import { Avatar, Box, Button, Container, Fab ,IconButton} from "@material-ui/core";
import { ballColors, ballAddObj, foulsList } from "../../services/exportsFile";
import RestoreIcon from "@material-ui/icons/Restore";
import {pointDeciderState,scoreState,activeState,lastAction,alertState,accountState} from "../../stateManager/atoms"
import {
useRecoilState,
useRecoilValue,
} from 'recoil';
function PopUpMenu({ classes ,socket}) {
const [active,setActive] = useRecoilState(activeState)
const [alertObj,setAlert] = useRecoilState(alertState)
const [score,setScore] = useRecoilState(scoreState)
const [account, setAccount] = useRecoilState(accountState);
const [action, setLastAction] = useRecoilState(lastAction)
const pointDecider = useRecoilValue(pointDeciderState)
const [messageData,setMessageData] = useState({
state: { score:'', alert:'' },
secret: '16151260696166542610',
socketId: '3fbc77dac0c245be'
});
useEffect(()=>{
// console.log('step 2 , emiting alert...')
let newMsgData = {...messageData}
newMsgData.state.alert = alertObj
setMessageData(newMsgData)
socket.emit('multiplex-statechanged', newMsgData);
},[score])
useEffect(() => {
// console.log('emiting score...')
let newMsgData = {...messageData}
newMsgData.state.score = score;
setMessageData(newMsgData)
// console.log(newMsgData)
socket.emit('multiplex-statechanged', newMsgData);
}, [score]);
const returnHandler = () => {
const { ...data } = score;
let actionObjClone = {...action}
if(active === 1){
if(data.player1 > 0){
const newArray = [...action.player1];
const lastPoint = newArray[newArray.length - 1];
if (isNaN(lastPoint) === false) {
newArray.pop();
setLastAction({...actionObjClone,player1: newArray});
const thingtoAdd = data.player1 + lastPoint;
setScore({ ...data, player1: thingtoAdd });
}
}
}
if(active === 2){
if(data.player2 > 0){
const newArray = [...action.player2];
const lastPoint = newArray[newArray.length - 1];
if (isNaN(lastPoint) === false) {
newArray.pop();
setLastAction({...actionObjClone,player1: newArray});
const thingtoAdd = data.player2 + lastPoint;
setScore({ ...data, player2: thingtoAdd });
}
}
}
};
const ballAdder = (point, popupState,sourceOfAction) => {
// console.log('step 1 , setting alertObj')
let objHolder = {...alertObj}
const { ...data } = score;
if (pointDecider) {
const pointsToAdd = ballAddObj[point];
if (active === 1 && sourceOfAction === 'add') {
data.player1 = score.player1 + pointsToAdd;
let actionObjClone = {...action}
let actionClone = [...action.player1]
setLastAction({...actionObjClone, player1:[...actionClone, -pointsToAdd]});
setScore(data);
objHolder.alert = true
objHolder.alertMsg = `${account.username} just score a ${pointsToAdd} points!`
setAlert(objHolder)
return;
}
if (active === 2 && sourceOfAction === 'add') {
let actionObjClone = {...action}
let actionClone = [...action.player1]
data.player2 = score.player2 + pointsToAdd;
setLastAction({...actionObjClone, player2:[...actionClone, -pointsToAdd]});
setScore(data);
setAlert({
alert: true,
alertMsg: `Opponent just score a ${pointsToAdd} points!`
})
return;
}
if (active === 0) {
alert("Please choose a Player!");
return;
}
}
//// ------ fouls --------- /////
if (active === 1 && sourceOfAction === 'foul') {
let actionObjClone = {...action}
let actionClone = [...action.player1]
data.player2 = score.player2 + point;
setLastAction({...actionObjClone, player2:[...actionClone, -point]});
setScore(data);
setAlert({
alert: true,
alertMsg: `${account.username} got fouled by ${point} points!`
})
return;
}
if (active === 2 && sourceOfAction === 'foul') {
let actionObjClone = {...action}
let actionClone = [...action.player1]
data.player1 = score.player1 + point;
setLastAction({...actionObjClone, player1:[...actionClone, -point]});
setScore(data);
setAlert({
alert: true,
alertMsg: `Opponent got fouled by ${point} points!`
})
return;
}
};
return (
<PopupState variant="popover" popupId="demo-popup-menu">
{(popupState) => (
<>
<Container justify="center" className={classes.ballWrapper}>
{pointDecider
? ballColors.map((color, idx) => (
<Avatar
key={idx}
onClick={(e) => {
ballAdder(color, popupState,'add');
}}
style={{
background: color,
cursor: "pointer",
margin: "0.2vw",
padding: "0.5vw",
}}
>
{idx + 1}
</Avatar>
))
: foulsList.map((foul, idx) => (
<Avatar
style={{
background: "red",
cursor: "pointer",
margin: "0.5vw",
padding: "1vw",
}}
key={idx}
onClick={(e) => {
ballAdder(foul, popupState,'foul');
}}
>
{foul}
</Avatar>
))}
<IconButton
aria-label="delete"
className={classes.margin}
onClick={returnHandler}
>
<RestoreIcon fontSize="large" />
</IconButton>
</Container>
</>
)}
</PopupState>
);
}
export default PopUpMenu;
<file_sep>/src/BotNav/BottomNav.js
import React, { useState, useContext } from "react";
import { SnookerContext } from "../stateManager/stateManager";
import {
BottomNavigationAction,
BottomNavigation,
Box,
} from "@material-ui/core";
import FitnessCenter from "@material-ui/icons/FitnessCenter";
import GameIcon from "@material-ui/icons/SportsEsports";
import Person from "@material-ui/icons/Person";
import HomeIcon from "@material-ui/icons/Home";
function BotNav({ classes }) {
const [checked, setChecked] = React.useState([0]);
const { bottomNavValue, setBottomNavValue } = useContext(SnookerContext);
return (
<Box
position="fixed"
bottom="0"
left="0"
right="0"
textAlign="center"
margin="auto"
>
<BottomNavigation
value={bottomNavValue}
onChange={(event, newValue) => {
setBottomNavValue(newValue);
}}
showLabels
className={classes.bottomMenu}
>
<BottomNavigationAction label="Home" icon={<HomeIcon />} />
<BottomNavigationAction label="Single-Play" icon={<FitnessCenter />} />
<BottomNavigationAction label="Online" icon={<GameIcon />} />
<BottomNavigationAction label="Profile" icon={<Person />} />
</BottomNavigation>
</Box>
);
}
export default BotNav;
<file_sep>/src/stateManager/stateManager.js
import React, {useState, useEffect,useRef} from "react";
const SnookerContext = React.createContext();
const { Provider } = SnookerContext;
const StateManager = ({ children }) => {
const [bottomNavValue, setBottomNavValue] = useState(0)
const [playersLogin,setPlayersLogin] = useState(false)
const [active, setActive] = useState(0);
const [lastAction,setLastAction] = useState([])
const [account,setAccount] = useState({
email: '',
password: '',
username: ''
})
const [pointDecider,setPointDecider] = useState(true)
const [playersScore,setPlayersScore] = useState({
player1: 0,
player2: 0,
})
const [lastScore,setLastScore] = useState({
player1: 0,
player2: 0,
})
const [action,setAction] = useState('')
// state = values to display
const state = {
bottomNavValue,
active,
account,
playersScore,
playersLogin,
pointDecider,
lastScore,
action,
lastAction,
};
// actions = callbacks to invoke
const actions = {
setBottomNavValue,
setActive,
setAccount,
setPlayersScore,
setPlayersLogin,
setPointDecider,
setLastScore,
setAction,
setLastAction,
};
return <Provider value={{ ...state, ...actions }}>{children}</Provider>;
};
export { StateManager, SnookerContext };
<file_sep>/src/Home/ReturnButton/ReturnButton.js
import React, { useState, useContext, useEffect, useRef } from "react";
import { SnookerContext } from "../../stateManager/stateManager";
import { IconButton } from "@material-ui/core";
import RestoreIcon from "@material-ui/icons/Restore";
function ReturnButton({ classes }) {
// const [lastScore,setLastScore] = useState(null)
const { playersScore,setPlayersScore,lastScore,active} = useContext(SnookerContext);
const [renderToggle,setRenderToggle] = useState(false)
const returnHandler = () => {
};
return (
<>
<IconButton aria-label="delete" className={classes.margin}>
<RestoreIcon fontSize="large" onClick={returnHandler} />
</IconButton>
</>
);
}
export default ReturnButton;
<file_sep>/src/services/exportsFile.js
import clsx from "clsx";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import Divider from "@material-ui/core/Divider";
import { makeStyles } from "@material-ui/core/styles";
import { Box, createMuiTheme } from "@material-ui/core";
import { orange, blueGrey, green, red } from "@material-ui/core/colors";
import styled, { keyframes } from "styled-components";
export const rotate = keyframes`
50%,
75% {
transform: scale(2.5);
}
80%,
100% {
opacity: 0;
}
`;
export const drawerWidth = 240;
export const useStyles = makeStyles((theme) => ({
root: {
background: 'lightgrey',
width: "100%",
height: "100vh",
position: "relative",
fontFamily: "RocknRoll One, sans-serif",
},
topBar:{
zIndex: '10',
},
showWrapper:{
border: "5px solid #8B4513",
justifyContent: "space-between",
maxWidth: "50%",
minHeight: "70%",
position: "relative",
top: "2vw",
boxShadow: "0px 5px 15px 5px #000000",
borderRadius: "2vw",},
appWrapper: {
display: 'flex',
background: "#0a6c03",
border: "5px solid #8B4513",
justifyContent: "center",
maxWidth: "50%",
minHeight: "70%",
position: "relative",
top: "2vw",
boxShadow: "0px 5px 15px 5px #000000",
borderRadius: "2vw",
},
ballsGrid: {
flexDirection: "column",
maxWidth: '100%',
},
ballWrapper: {
display: "flex",
flexDirection: "row",
flexWrap: 'wrap',
boxShadow: '1px 8px 15px -4px #000000',
border: '3px solid saddlebrown',
padding: '1.5vw',
borderRadius: '1vw',
marginBottom: '1vw',
},
LoginTitle:{
fontSize: '25vw',
},
homeWrapper: {
display: 'flex',
padding: "0",
margin: "0",
},
playersBar: {
marginLeft: "0",
marginTop: "0.5vw",
border: "2px solid black",
minWidth: "100%",
},
ballList: {
width: "100%",
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
scoreHolder: {
flexGrow: "1",
color: "white",
border: "2px solid black",
marginTop: "1vw",
},
scoreDisplay: {
display: 'flex',
marginBottom: '5vw',
},
showScoreBoard: {
minHeight: '80vh'
},
loginWrapper:{
fontSize: 'RocknRoll One',
display: 'flex',
justifyContent: 'center',
position: 'relative',
right: '0',
left: '0',
background: 'darkgrey',
zIndex: '1',
margin: '0',
minWidth: '100%',
minHeight: '100%',
},
paragraph: {
color: 'red',
fontFamily: 'Yanone Kaffeesatz',
},
loginFloater:{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginTop: '10vw',
background: 'deeppink',
height: '30vw',
width: '30vw'
},
loginInputs:{
marginBottom: '1vw'
},
btn: {
background: "linear-gradient(45deg, #8B4513 30%, #D2691E 90%)",
borderRadius: 3,
border: 0,
color: "white",
height: "4vw",
padding: "0 30px",
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
fontFamily: "RocknRoll One",
margin: '1vw',
},
buttonBlue: {
background: "linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)",
boxShadow: "0 3px 5px 2px rgba(33, 203, 243, .3)",
},
paper: {
alignSelf: "center",
},
active: {
border: "2px solid white",
},
fab: {
margin: theme.spacing(2),
},
drawer: {
[theme.breakpoints.up("sm")]: {
width: drawerWidth,
flexShrink: 0,
},
},
bottomMenu: {
width: 500,
margin: "auto",
},
appBar: {
[theme.breakpoints.up("sm")]: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
},
menuButton: {
marginRight: theme.spacing(2),
[theme.breakpoints.up("sm")]: {
display: "none",
},
},
// necessary for content to be below app bar
toolbar: theme.mixins.toolbar,
drawerPaper: {
width: drawerWidth,
},
content: {
flexGrow: 1,
padding: theme.spacing(6),
},
}));
export const theme = createMuiTheme({
direction: "rtl",
palette: {
},
typography: {
h3: {
fontSize: 36,
marginBottom: 15,
},
h4: { fontSize: 26,marginBottom: "10vw" ,color: "black",fontFamily:'RocknRoll One' },
h6: { fontSize: 26, marginRight: "20px", color: "black",fontFamily:'RocknRoll One' },
},
});
export const ballAddObj = {
red: 1,
yellow: 2,
green: 3,
brown: 4,
blue: 5,
pink: 6,
black: 7,
};
export const ballColors = [
"red",
"yellow",
"green",
"brown",
"blue",
"pink",
"black",
];
export const foulsObject = {
foul: 4,
yellow: 2,
green: 3,
brown: 4,
blue: 5,
pink: 6,
black: 7,
};
export const foulsList = [4, 5, 6, 7];
<file_sep>/src/Home/PointSwitcher/PointSwitcher.js
import React from "react";
import {
FormControlLabel,
Switch
} from "@material-ui/core";
import {
useRecoilState,
useRecoilValue,
} from 'recoil';
import {pointDeciderState} from "../../stateManager/atoms"
function PointSwitcher({ classes}) {
const [pointHandler,setpointHandler] = useRecoilState(pointDeciderState)
return (
<>
<FormControlLabel
control={<Switch checked={pointHandler} onChange={()=>
setpointHandler(!pointHandler)
} name="checkedA" />}
label="Change"
/>
</>
)
}
export default PointSwitcher;
<file_sep>/src/Show/Show.js
import React, { useEffect, useState } from "react";
import {
useRecoilState,
} from "recoil";
import {
Container,
Box,
Paper,
Grid,
Typography,
Snackbar,
} from "@material-ui/core";
import { flash, __esModule } from "react-animations";
import MuiAlert from "@material-ui/lab/Alert";
import {
displayState,
socketAlertState,
alertState,
} from "../stateManager/atoms";
import "fontsource-roboto";
import styled, { keyframes } from "styled-components";
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const flashAnimation = keyframes`${flash}`;
function Show({ classes }) {
const [display, setDisplay] = useRecoilState(displayState);
const [socketAlerts, setSocketAlerts] = useRecoilState(socketAlertState);
const [alertObj, setAlert] = useRecoilState(alertState);
const [open, setOpen] = useState(false);
if (!display) return <Box>No Online Game</Box>;
// const [display,setDisplay] = useState({
// player1: 23,
// player2: 24
// })
console.log(`step 4 show display socketAlertObj = ${socketAlerts} ${display.player1} and alertObj ${alertObj}`)
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
let prevAlertObj = alertObj;
let prevSocketsAlert = socketAlerts;
setSocketAlerts({ ...prevAlertObj, alert: false ,alertMsg: "",});
setAlert({ ...prevSocketsAlert, alert: false, alertMsg: "" });
if (reason === "clickaway") {
return;
}
};
return (
<Container className={classes.showWrapper}>
<Snackbar
open={socketAlerts.alert}
autoHideDuration={6000}
onClose={handleClose}
style={{marginTop: '3.2vw'}}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
>
<Alert onClose={handleClose} severity="success">
{socketAlerts.alertMsg}{" "}
</Alert>
</Snackbar>
<Grid container className={classes.showScoreBoard} direction="column" justify="center" alignItems="center">
<Grid item>
<Typography>
<Flash>
{socketAlerts.alertMsg}{" "}
</Flash>
</Typography>
</Grid>
<Grid item className={classes.scoreDisplay}>
<Grid item xs={6} spacing={3}>
<Paper
elevation={5}
style={{
background: "red",
minHeight: "90%",
fontSize: "90px",
textAlign: "center",
minWidth: "20vw",
border: '1px solid black',
marginRight: '2vw',
}}
>
{display.player1}
</Paper>
</Grid>
<Grid item xs={6} spacing={3}>
<Paper
elevation={5}
style={{
background: "blue",
minHeight: "90%",
fontSize: "90px",
textAlign: "center",
border: '1px solid black',
minWidth: "20vw",
}}
>
{display.player2}
</Paper>
</Grid>
</Grid>
</Grid>
</Container>
);
}
export default Show;
const Flash = styled.h1`
animation: 4s ${flashAnimation};
margin: 1vw;
animation-iteration-count: infinite;
font-size: 2vw;
color: black;
`;<file_sep>/src/stateManager/atoms.js
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
export const socketAlertState = atom({
key: 'socketAlertState',
default: {
alert: false,
alertMsg: '',
},
});
export const alertState = atom({
key: 'alertState',
default: {
alert: false,
alertMsg: '',
},
});
export const appLoading = atom({
key: 'appLoading',
default: true,
});
export const displayState = atom({
key: 'displayState',
default: null,
});
export const loginRemover = atom({
key: 'loginRemover',
default: false,
});
export const playersLogin = atom({
key: 'playersLogin',
default: false,
});
export const activeState = atom({
key: 'activeState',
default: 0,
});
export const lastAction = atom({
key: 'lastAction',
default: {player1: [],
player2: []},
});
export const accountState = atom({
key: 'accountState',
default: {
email: '',
password: '',
username: ''
},
});
export const pointDeciderState = atom({
key: 'pointDeciderState',
default: true,
});
export const scoreState = atom({
key: 'scoreState',
default: {
player1: 0,
player2: 0,
},
});
export const actionState = atom({
key: 'actionState',
default: '',
});
| 0800bea4ce7e60e86f7776486269ca285cb19d3a | [
"JavaScript"
] | 8 | JavaScript | dor29494/Snooker-Table | 2d381156d13ed6838b7c45405f5aabaeb6fbdc4d | 08c540bd66e003f67c526c0a1a8def79d87adf5c |
refs/heads/master | <repo_name>heyqule/slackhive<file_sep>/README.md
Slack Hive
------------------
Export Slack Pins and view them in a **nice** format.
Dependency
------------------
Saywut <https://github.com/heyqule/saywut>
<file_sep>/index.php
<?php
/**
* Created by PhpStorm.
* User: heyqule
* Date: 09/01/16
* Time: 10:32 PM
*/
ini_set('display_error',1);
include 'saywut/config.php';
include 'saywut/bots/Slack_Bot.php';
$bot = new \Saywut\Slack_Bot(\Saywut\Core::getBotKey($GLOBALS['BOT_CONFIG'][1]),$GLOBALS['BOT_CONFIG'][1]);
if(!empty($_GET['run']))
{
$bot->run();
}
$postCollection = new \Saywut\Post_Collection();
$limit = 50;
$offset = 0;
$anchorUrl = '?';
$query = '';
if(!empty($_GET['query']))
{
$postCollection->addFullText($_GET['query']);
$anchorUrl = '?query='.urlencode($_GET['query']);
$query = htmlentities($_GET['query'],ENT_HTML5);
}
$page = 0;
if(isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $page * $limit;
}
$posts = $postCollection->loadByQuery($offset,$limit);
$size = $postCollection->getSize();
?>
<!DOCTYPE html>
<html lang="en">
<head profile="http://www.w3.org/1999/xhtml/vocab">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<link href="main.css" rel="stylesheet">
<title>ʕつ ͡◔ ᴥ ͡◔ʔつ Bindom</title>
<meta name="Description" content="wut deescrippteion da ryu wanta?">
</head>
<body>
<h1>ʕつ ͡◔ ᴥ ͡◔ʔつ Bindom</h1>
<section class="controller">
<form id="search" method="get" action="/">
Searchere: <input type="text" name="query" value="<?php echo $query ?>" /> <input type="submit" />
</form>
<menu>
Page:
<?php
for($i = 0; $i*$limit < $size; $i++) {
if($i == $page)
echo ($i+1).' | ';
else
echo '<a href="' . $anchorUrl . '&page='.$i.'">'.($i+1).'</a> | ';
}
?>
</menu>
</section>
<section class="container">
<?php foreach($posts as $post):
$htmlObjects = json_decode($post->contents); ?>
<article class="pin-block">
<?php foreach($htmlObjects as $htmlObj): ?>
<div class="msg-block <?php echo $htmlObj->additionalClass; ?>">
<div class="msg-meta">
<span class="name"><?php echo $htmlObj->name; ?></span>
<span class="date"><?php echo $htmlObj->date; ?></span>
</div>
<div class="msg-content">
<?php echo $htmlObj->text; ?>
<?php if(property_exists($htmlObj,'attachment')): ?>
<div class="attachement">
<?php echo $htmlObj->attachment; ?>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<div class="msg-close">◟ʕ´∀`ʔ◞ CLOSE ◟ʕ´∀`ʔ ◞</div>
</article>
<?php
endforeach;
?>
</section>
<section class="controller">
<form id="search" method="get" action="/">
Searchere: <input type="text" name="query" value="<?php echo $query ?>" /> <input type="submit" />
</form>
<menu>
Page:
<?php
for($i = 0; $i*$limit < $size; $i++) {
if($i == $page)
echo ($i+1).' | ';
else
echo '<a href="' . $anchorUrl . '&page='.$i.'">'.($i+1).'</a> | ';
}
?>
</menu>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
</body>
<file_sep>/saywut/bots/Slack_Bot.php
<?php
/**
* Created by PhpStorm.
* User: heyqule
* Date: 09/01/16
* Time: 10:30 PM
*
* Bot Config:
* $GLOBALS['BOT_CONFIG'][1] = array(
* 'class'=>'Slack_Bot',
* 'name' => 'SlackHive',
* 'interval'=>60,
* );
*/
namespace Saywut;
use Slackbot;
require_once SAYWUT_ROOT_PATH.DS.'includes'.DS.'Bot.php';
require_once SAYWUT_SERVER_ROOT.DS.'slack/SlackUserCollection.php';
class Slack_Bot extends Bot
{
protected $pinBeforeMsgs = array();
protected $pinAfterMsgs = array();
protected $hasTop = false;
protected $slackUser;
protected $api;
protected $rawPinList;
public function __construct($id,$config)
{
parent::__construct($id);
$this->interval = $config['interval'];
$this->slackUser = new Slackbot\SlackUserCollection();
$this->api = new Slackbot\Api();
}
protected function fetch() {
$this->slackUser->update();
$request = array(
'token' => Slackbot\Setting::API_AUTH_TOKEN,
'channel' => Slackbot\Setting::THE_B_CHANNEL,
);
//Fetch All Pins
$this->rawPinList = $this->api->getPins($request);
$pinIds = array();
//Fetch all saved pins based on ID
foreach($this->rawPinList->items as $pin)
{
switch ($pin->type)
{
case 'file':
$pid = 'file-'.$pin->file->id;
break;
case 'message':
$pid = 'msg-'.$pin->message->ts;
break;
default:
break;
}
$pinIds[] = $pid;
$this->data[$pid] = $pin;
}
unset($pin,$pid);
//Remove it if there are match pins in saywut
$postCollection = new Post_Collection();
$postCollection->addWhere('provider_pid','in',$pinIds);
foreach($postCollection as $post)
{
unset($this->data[$post->getProviderCid()]);
}
//Fetch B20 A5 Messages for each new pin
foreach($this->data as $providerId => $pin)
{
if($pin->type == 'message')
{
$this->_getMessageBefore($providerId,$pin,$request);
$this->_getMessageAfter($providerId,$pin,$request);
}
}
}
protected function _getMessageBefore($providerId,$pin,$request)
{
$this->hasTop = false;
$msgRequest = $request;
$msgRequest['latest'] = $pin->message->ts;
$msgRequest['count'] = 20;
$oldMessages = $this->api->getChannelMessages($msgRequest);
if($oldMessages->ok && sizeof($oldMessages->messages))
{
$this->hasTop = true;
$oldMessages->messages = array_reverse($oldMessages->messages);
$this->pinBeforeMsgs[$providerId] = $oldMessages->messages;
}
}
protected function _getMessageAfter($providerId,$pin,$request)
{
if($this->hasTop)
{
$msgRequest = $request;
$msgRequest['oldest'] = $pin->message->ts;
$msgRequest['count'] = 5;
$oldMessages = $this->api->getChannelMessages($msgRequest);
if($oldMessages->ok && sizeof($oldMessages->messages))
{
$oldMessages->messages = array_reverse($oldMessages->messages);
$this->pinAfterMsgs[$providerId] = $oldMessages->messages;
}
}
}
/*
* Manipulating and storing data
*/
protected function store()
{
foreach($this->data as $providerCid => $pin)
{
try
{
if ($pin->type == 'message')
{
$message = $pin->message;
$htmlObj = $this->_processBeforeMsg($providerCid);
$htmlObj[] = $this->_processMessage($message, 'is-pin');
$afterMsgHtmlObj = $this->_processAfterMsg($providerCid);
foreach($afterMsgHtmlObj as $obj)
{
$htmlObj[] = $obj;
}
$postData['title'] = str_replace(array('<', '>'), '', $message->text);
$postData['content'] = json_encode($htmlObj);
$postData['timestamp'] = date(DT_FORMAT, $message->ts);
}
if ($pin->type == 'file')
{
$file = $pin->file;
$htmlObj = array($this->_processFile($file,'is-pin'));
$postData['title'] = str_replace(array('<', '>'), '', $file->title);
$postData['content'] = json_encode($htmlObj);
$postData['timestamp'] = date(DT_FORMAT, $file->timestamp);
}
$post = new Post();
$post->loadByProdviderId($this->provider_id,$providerCid);
if($post->id)
{
continue;
}
$post->id = null;
$post->title = $postData['title'];
$post->provider_id = $this->provider_id;
$post->provider_cid = $providerCid;
$post->contents = $postData['content'];
$post->create_time = $postData['timestamp'];
$post->update_time = $postData['timestamp'];
$post->save();
$this->numberChanged++;
}
catch(Exception $e)
{
Event::write($this->provider_id,Event::E_ERROR,$e->getMessage());
}
}
$postCollection = new Post_Collection();
$postCollection->reindexAll();
//Remove saved pin from slack (TO BE DISCUSS) when success
$this->_removePins();
}
protected function _processBeforeMsg($key)
{
$beforeMessages = array();
$htmlObjects = array();
if(!empty($this->pinBeforeMsgs[$key]))
{
$beforeMessages = $this->pinBeforeMsgs[$key];
}
foreach($beforeMessages as $msg)
{
if($msg->type == 'message')
{
$htmlObjects[] = $this->_processMessage($msg, 'before-pin');
}
elseif($msg->type == 'file')
{
$htmlObjects[] = $this->_processFile($msg,'before-pin');
}
}
return $htmlObjects;
}
protected function _processAfterMsg($key)
{
$afterMessages = array();
$htmlObjects = array();
if(!empty($this->pinAfterMsgs[$key]))
{
$afterMessages = $this->pinAfterMsgs[$key];
}
foreach($afterMessages as $msg)
{
if($msg->type == 'message')
{
$htmlObjects[] = $this->_processMessage($msg, 'after-pin');
}
elseif($msg->type == 'file')
{
$htmlObjects[] = $this->_processFile($msg,'after-pin');
}
}
return $htmlObjects;
}
protected function _processMessage($message,$additionalClass = '')
{
$htmlObj = new \stdClass();
$htmlObj->additionalClass = $additionalClass;
$htmlObj->name = $this->_getUser($message,true);
$htmlObj->date = date(DT_FORMAT, $message->ts);
if(property_exists($message, 'subtype') && $message->subtype == 'pinned_item')
{
$attachment = $message->attachments[0];
$attachment->text = $this->_processText($attachment->text);
if(property_exists($attachment,'author_icon'))
{
$htmlObj->text = "pinned <img src=\"{$attachment->author_icon}\"/> {$attachment->author_name}: {$attachment->text}";
}
elseif(property_exists($attachment,'author_subname'))
{
$htmlObj->text = "pinned {$attachment->author_subname}: {$attachment->text}";
}
}
else
{
$htmlObj->text = $this->_processText($message->text);
if (!empty($message->attachments))
{
$attachment = $message->attachments[0];
if (property_exists($attachment, 'video_html'))
{
$videoUrl = str_replace(array('autoplay=1'), '', $attachment->video_html);
$videoUrl = str_replace(array('autoplay'), '', $videoUrl);
$htmlObj->attachment = $videoUrl;
} else if (property_exists($attachment, 'audio_html'))
{
$htmlObj->attachment = $attachment->audio_html;
} else if (property_exists($attachment, 'image_url'))
{
$htmlObj->attachment = "<img src=\"{$attachment->image_url}\" />";
} else if (property_exists($attachment, 'thumb_url'))
{
$htmlObj->attachment = "<img src=\"{$attachment->thumb_url}\" />";
}
else if (property_exists($attachment, 'service_name')
&& $attachment->service_name == 'twitter')
{
$htmlObj->attachment = "<a href=\"{$attachment->author_link}\" ><img src=\"{$attachment->author_icon}\">@";
$htmlObj->attachment .= "{$attachment->author_name} </a>: {$attachment->text}";
}
}
}
return $htmlObj;
}
protected function _processFile($file,$additionalClass = '')
{
$htmlObj = new \stdClass();
$htmlObj->additionalClass = $additionalClass;
$htmlObj->name = $this->_getUser($file,true);
$htmlObj->date = date(DT_FORMAT, $file->timestamp);
$htmlObj->text = "<a href=\"{$file->permalink}\">A Slack {$file->pretty_type} File</a>";
/* Should I link the pic?
if($file->mimetype == 'image/jpeg' ||
$file->mimetype == 'image/gif' ||
$file->mimetype == 'image/webp' ||
$file->mimetype == 'image/png'
)
{
$htmlObj->attachment .= <img src="'.$file->thumb_480.'"/>;
}
*/
return $htmlObj;
}
protected function _removePins()
{
$removeThreadhold = 50;
$dataSize = sizeof($this->data);
if($dataSize <= $removeThreadhold)
{
return;
}
$this->data = array_reverse($this->data);
$recToRemove = $dataSize - $removeThreadhold;
$i = 0;
foreach($this->data as $pin)
{
if($i == $recToRemove)
{
break;
}
$i++;
$request = array(
'token' => Slackbot\Setting::API_AUTH_TOKEN,
'channel' => Slackbot\Setting::THE_B_CHANNEL,
);
$removeId = '';
if($pin->type == 'message')
{
$request['timestamp'] = $pin->message->ts;
$removeId = $request['timestamp'];
}
elseif($pin->type == 'file')
{
$request['file'] = $pin->file->id;
$removeId = $request['file'];
}
if(Slackbot\Setting::TEST)
{
Event::write($this->provider_id,Event::E_INFO,"Test Mode: Remove pin {$removeId}");
}
else
{
Event::write($this->provider_id,Event::E_INFO,"Remove pin {$removeId}");
$this->api->unPin($request);
}
}
Event::write($this->provider_id,Event::E_INFO,"Removed {$i} pins");
}
/**
* pull user from msg or file object
* @param $message
* @param bool $withPic
* @return string
*/
protected function _getUser($message,$withPic = false)
{
$rcName = '';
if(property_exists($message,'user'))
{
$member = $this->slackUser->getMemberById($message->user);
if($withPic && property_exists($member,'profile') && property_exists($member->profile,'image_72'))
{
$rcName .= "<img src=\"{$member->profile->image_72}\" /><br />";
}
$rcName .= $this->slackUser->getName($member);
}
elseif(property_exists($message,'username'))
{
$rcName = $message->username;
}
return $rcName;
}
protected function _processText($text)
{
$text = $this->_processLinks($text);
$text = $this->_processUserText($text);
return $text;
}
/**
* <http link> => <a> link
* @param $text
* @return string
*/
protected function _processLinks($text)
{
if(strpos($text,'<http') === false)
{
return $text;
}
$tokens = explode(' ',$text);
foreach($tokens as $key => $token)
{
if(strpos($token,'<http') !== false)
{
$token = str_replace(array('<', '>'), '', $token);
$token = "<a href=\"{$token}\">{$token}</a>";
}
$tokens[$key] = $token;
}
$text = implode(' ',$tokens);
return $text;
}
/**
* Process <@U0CKTLCKA|something> => <img> name
* @param $text
* @return string
*/
protected function _processUserText($text)
{
if(strpos($text,'<@') === false)
{
return $text;
}
$tokens = explode(' ',$text);
foreach($tokens as $key => $token)
{
if(!empty($token) && strpos($token,'<@') !== false)
{
$userString = substr($token,0,strpos($token,'>')+1);
$endPart = substr($token,strpos($token,'>')+1);
$user = str_replace(array('<@','>'),'',$userString);
$userToken = array();
if(strpos('|',$userString) !== false)
{
$userToken = explode('|',$userString);
$user = $userToken[0];
}
$member = $this->slackUser->getMemberById($user);
$name = $this->slackUser->getName($member);
//pick stored user id
if(empty($name) && sizeof($userToken))
{
$name = $userToken[1];
}
if(empty($name))
{
$name = 'A rage quited loser';
}
$token = '';
if(property_exists($member,'profile') && property_exists($member->profile,'image_72'))
{
$token .= "<img src=\"{$member->profile->image_72}\" /> ";
}
$token .= $name.$endPart;
}
$tokens[$key] = $token;
}
$text = implode(' ',$tokens);
return $text;
}
} | 92a080799864d73e9b379da5338aa88be3822239 | [
"Markdown",
"PHP"
] | 3 | Markdown | heyqule/slackhive | 1a8cfc40a58d46cff45d382d3bfe149a411ffa87 | aaacefed4d0e63fe36fa36735e929308f72f6477 |
refs/heads/main | <file_sep># calculator-with-JS
the good calc
<file_sep>const number = document.querySelectorAll(".btn");
const screen = document.getElementById("screen");
const sign = document.querySelectorAll(".sign");
let number1 = 0;
let operation = "";
let number2 = 0;
let content = '';
// start new fun
number.forEach(btn => {
btn.addEventListener("click", (e) => {
if (btn.innerText !== "=") {
if (number1 === 0 && btn.classList.contains('num')) {
screen.value += btn.innerText;
} else if (btn.classList.contains('sign')) {
number1 = screen.value;
screen.value += btn.innerText;
operation = btn.innerText;
} else if (operation !== '' && btn.classList.contains('num')) {
screen.innerText = '';
content += btn.innerText;
screen.value = content;
number2 = content;
console.log(number1, operation, number2);
}
} else {
show();
reset();
}
});
});
// end new fun
function calculation() {
if (operation === "+") {
return parseInt(number1) + parseInt(number2);
} else if (operation === "-") {
return parseInt(number1) - parseInt(number2);
} else if (operation === "*") {
return parseInt(number1) * parseInt(number2);
} else if (operation === "/") {
return parseInt(number1) / parseInt(number2);
}
}
function reset() {
number1 = 0;
number2 = 0;
operation = "";
content = '';
}
function show() {
screen.value = calculation();
}
const clear_btn = document.querySelector(".clear");
clear_btn.addEventListener("click", () => {
screen.value = "";
}); | bb6239dbf707f29f9200ae972d35c04ae4a93036 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | AhmadMKIlani/calculator-with-JS | 72a7d904b1d1d1d26861731c4d21647e4b6cc368 | be51a5c3f24fe3bd2fc8eb0bc95eaa8b9bab8bf5 |
refs/heads/main | <file_sep>from transformers import BertJapaneseTokenizer, BertForMaskedLM, BertModel
import numpy as np
import torch
import argparse
from typing import List, Optional
def_n_generate = 10
def_n_max_try = 100
def_mask_frac = 0.15
def_cos_thre = 0.9
def_n_cand = 10
def_seed = 0
def_batch_size = 8
class SentenceBertJapanese:
def __init__(
self,
model_name_or_path:str,
device:Optional[str] = None,
):
self.tokenizer = BertJapaneseTokenizer.from_pretrained(
model_name_or_path,
)
self.model = BertModel.from_pretrained(model_name_or_path)
self.model.eval()
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
self.device = torch.device(device)
self.model.to(device)
def _mean_pooling(
self,
model_output:str,
attention_mask:torch.Tensor,
):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(
token_embeddings.size()
).float()
return (
torch.sum(token_embeddings * input_mask_expanded, 1)
/ torch.clamp(input_mask_expanded.sum(1), min=1e-9)
)
@torch.no_grad()
def encode(
self,
sentences:List[str],
batch_size:int = def_batch_size,
as_numpy:bool = False,
):
all_embeddings = []
iterator = range(0, len(sentences), batch_size)
for batch_idx in iterator:
batch = sentences[batch_idx:batch_idx + batch_size]
encoded_input = self.tokenizer.batch_encode_plus(
batch,
padding="longest",
truncation=True,
return_tensors="pt",
).to(self.device)
model_output = self.model(**encoded_input)
sentence_embeddings = self._mean_pooling(
model_output,
encoded_input["attention_mask"],
).to('cpu')
all_embeddings.extend(sentence_embeddings)
return (torch.stack(all_embeddings).numpy()
if as_numpy else torch.stack(all_embeddings))
def main(
input_sentence:str,
n_generate:int = def_n_generate,
n_max_try:int = def_n_max_try,
mask_frac:float = def_mask_frac,
n_cand:int = def_n_cand,
cos_thre:float = def_cos_thre,
seed:int = def_seed,
verbose:bool = False,
) -> List[str]:
base_model_path = "cl-tohoku/bert-base-japanese"
sbert_model_path = "sonoisa/sentence-bert-base-ja-mean-tokens"
device = "cpu"
tokenizer = BertJapaneseTokenizer.from_pretrained(base_model_path)
masked_lang_model = BertForMaskedLM.from_pretrained(
base_model_path
).to(device)
#sbert_model = BertModel.from_pretrained(sbert_model_path)
sbert_model = SentenceBertJapanese(sbert_model_path)
input_tokenized = tokenizer.tokenize(input_sentence)
if verbose:
print(f"{input_tokenized}")
print("----------")
n_token = len(input_tokenized)
input_encoded = sbert_model.encode([input_sentence],as_numpy=True)[0]
input_norm = np.sqrt(np.sum(input_encoded*input_encoded))
rng = np.random.default_rng(seed=seed)
generated_list = []
cos_list = []
segment_ids = [0]*(2+n_token)+[1]*(1+n_token)
segments_tensor = torch.tensor([segment_ids]).to(device)
for i_try in range(n_max_try):
if verbose:
print(f"i_try = {i_try} : n_generated = {len(generated_list)}")
while True:
n_mask = rng.poisson( mask_frac*n_token )
if n_mask>0:
break
mask_indices = np.random.choice(
n_token,
n_mask,
replace=False,
)
if verbose:
print(f" mask_indices = {mask_indices}")
modified = [token for token in input_tokenized]
for mask_index in mask_indices:
masked_token = input_tokenized[mask_index]
i_masked = n_token+2+mask_index
double_modified = [token for token in (["[CLS]"]
+modified+["[SEP]"]
+modified+["[SEP]"])]
double_modified[i_masked] = "[MASK]"
token_ids = tokenizer.convert_tokens_to_ids(double_modified)
tokens_tensor = torch.tensor([token_ids]).to(device)
with torch.no_grad():
prediction = masked_lang_model(
tokens_tensor,
token_type_ids=segments_tensor,
)[0]
topk_score, topk_index = torch.topk(
prediction[0, i_masked],
n_cand,
)
topk_index = topk_index.tolist()
while True:
i_cand = rng.choice(topk_index)
cand_token = tokenizer.convert_ids_to_tokens([i_cand])[0]
if cand_token!=masked_token:
modified[i_masked-2-n_token] = cand_token
break
if verbose:
print(modified)
detokenized = tokenizer.convert_tokens_to_string(
modified
).replace(" ", "")
modified_encoded = sbert_model.encode(
[detokenized],
as_numpy=True,
)[0]
modified_norm = np.sqrt(np.sum(modified_encoded*modified_encoded))
cos = np.sum(modified_encoded*input_encoded)/modified_norm/input_norm
if verbose:
print(f"{i_try} : {detokenized} (cos={cos})")
if cos>cos_thre:
generated_list.append(detokenized)
cos_list.append(cos)
if len(generated_list)>=n_generate:
break
if verbose:
print()
for cos, sentence in zip(cos_list, generated_list):
print(cos, sentence)
return generated_list
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Japanese text generation with similar meaning "
"to the input sentence using masked language model"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"input_sentence",
nargs="+",
type=str,
help="input sentence",
)
parser.add_argument(
"-n", "--n_generate",
type=int,
default=def_n_generate,
help="the number of sentences to be generated",
)
parser.add_argument(
"-t", "--n_max_try",
type=int,
default=def_n_max_try,
help="the number of maximum trials",
)
parser.add_argument(
"-f", "--mask_frac",
type=int,
default=def_mask_frac,
help="fraction of the number of masked words",
)
parser.add_argument(
"-c", "--cos_thre",
type=float,
default=def_cos_thre,
help=(
"threshold of cosine similarity to qualify the same meaning "
"of generated sentences with the input one"
),
)
parser.add_argument(
"-s", "--seed",
type=int,
help="random number seed for numpy random number generator",
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
default=False,
help="show messages during processes",
)
args = parser.parse_args()
main(
input_sentence=" ".join(args.input_sentence),
n_generate=args.n_generate,
n_max_try=args.n_max_try,
mask_frac=args.mask_frac,
cos_thre=args.cos_thre,
seed=args.seed,
verbose=args.verbose,
)
<file_sep># Japanese text augmentation with BERT masked language model
## overview
You can generate sentences with a similar meaning to the input sentence.
Candidate sentences are created
by replacing several tokens with masked language model
and only sentences with high cosine similarity are filtered out.
## reference
- https://arxiv.org/pdf/1907.06226.pdf
- https://huggingface.co/cl-tohoku/bert-base-japanese
- https://huggingface.co/sonoisa/sentence-bert-base-ja-mean-tokens
| 192cefc4cc83df6ddf06e3955445585c9f077a9b | [
"Markdown",
"Python"
] | 2 | Python | maedamaeday/text_aug | 5ec4e43d0076e1a01b38087c696762b41c62ec06 | 720bab935087c25abb914fef6475f408abc2bf23 |
refs/heads/master | <repo_name>paulacandido/ExerciciosPOO-Semana2<file_sep>/CalculadoraCientifica/CalculadoraCientifica.java
import java.lang.Math;
public class CalculadoraCientifica{
public double raiz(int numero) {
return Math.sqrt(numero);
}
public double raiz(double numero) {
return Math.sqrt(numero);
}
public double raiz(String palavra) {
double numero = Double.parseDouble(palavra);
return Math.sqrt(numero);
}
public double potencia(byte a, byte b) {
return Math.pow(a,b);
}
public double potencia(String s1, String s2) {
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
return Math.pow(a,b);
}
public double potencia(int a, double b) {
return Math.pow(a,b);
}
} | 598d26ed7dc3dd87c870e507f5a527044b569c3d | [
"Java"
] | 1 | Java | paulacandido/ExerciciosPOO-Semana2 | 36e442384c9c5c23035f99846f34074ef82f7221 | 5cd21ee7df387cda56ee9e4afd9867f5e4299813 |
refs/heads/master | <repo_name>parry2403/R2N2<file_sep>/RSTParser/adds.py
import os
# Read in the file
from nltk.tokenize import word_tokenize, sent_tokenize
import nltk
for fname in os.listdir('../aclImdb/test/pos'):
fullp=os.path.join('../aclImdb/test/pos/', fname)
fullo=os.path.join('../aclImdbo/test/pos/', fname)
inf = open(fullp,'r').read()
inf = inf.decode('ascii', 'ignore')
s = sent_tokenize(inf)
out = open(fullo, 'w')
# print fname
for line in s:
if line[-1]=="." :
out.write(line +"<s>")
else:
out.write(line +"<s>")
# out.close
<file_sep>/RSTParser/feature.py
## feature.py
## Author: <NAME>
## Date: 08-29-2014
## Time-stamp: <yangfeng 11/06/2014 14:35:59>
from nltk.tokenize import word_tokenize, sent_tokenize
import nltk
from nltk.stem import WordNetLemmatizer
class FeatureGenerator(object):
def __init__(self, stack, queue, doclen=None):
""" Initialization of feature generator
:type stack: list
:param stack: list of SpanNode instance
:type queue: list
:param queue: list of SpanNode instance
:type doclen: int
:param doclen: document length wrt EDUs
"""
# Stack
if len(stack) >= 2:
self.stackspan1 = stack[-1] # Top-1st on stack
self.stackspan2 = stack[-2] # Top-2rd on stack
elif len(stack) == 1:
self.stackspan1 = stack[-1]
self.stackspan2 = None
else:
self.stackspan1, self.stackspan2 = None, None
# Queue
if len(queue) > 0:
self.queuespan1 = queue[0] # First in queue
else:
self.queuespan1 = None
# Document length
self.doclen = doclen
def features(self):
""" Main function to generate features
1, if you add any argument to this function, remember
to give it a default value
2, if you add any sub-function for feature generation,
remember to call the sub-function here
"""
features = []
# Status features
for feat in self.status_features():
features.append(feat)
# Structural features
for feat in self.structural_features():
features.append(feat)
# Lexical features
for feat in self.lexical_features():
features.append(feat)
return features
def structural_features(self):
""" Structural features
"""
features = []
if self.stackspan1 is not None:
# Span Length wrt EDUs
features.append(('StackSpan1','Length-EDU',self.stackspan1.eduspan[1]-self.stackspan1.eduspan[0]+1))
# Distance to the beginning of the document wrt EDUs
features.append(('StackSpan1','Distance-To-Begin',self.stackspan1.eduspan[0]))
# Distance to the end of the document wrt EDUs
if self.doclen is not None:
features.append(('StackSpan1','Distance-To-End',self.doclen-self.stackspan1.eduspan[1]))
if self.stackspan2 is not None:
features.append(('StackSpan2','Length-EDU',self.stackspan2.eduspan[1]-self.stackspan2.eduspan[0]+1))
features.append(('StackSpan2','Distance-To-Begin',self.stackspan2.eduspan[0]))
if self.doclen is not None:
features.append(('StackSpan2','Distance-To-End',self.doclen-self.stackspan2.eduspan[1]))
if self.queuespan1 is not None:
features.append(('QueueSpan1','Distance-To-Begin',self.queuespan1.eduspan[0]))
# Should include some features about the nucleus EDU
for feat in features:
yield feat
def status_features(self):
""" Features related to stack/queue status
"""
features = []
if (self.stackspan1 is None) and (self.stackspan2 is None):
features.append(('Empty-Stack'))
elif (self.stackspan1 is not None) and (self.stackspan2 is None):
features.append(('One-Elem-Stack'))
elif (self.stackspan1 is not None) and (self.stackspan2 is not None):
features.append(('More-Elem-Stack'))
else:
raise ValueError("Unrecognized status in stack")
if self.queuespan1 is None:
features.append(('Empty-Queue'))
else:
features.append(('NonEmpty-Queue'))
for feat in features:
yield feat
def lexical_features(self):
""" Lexical features
"""
lmtzr = WordNetLemmatizer()
features = []
coreferenceList = ["his","her","it","they","their","he","she","our"]
if self.stackspan1 is not None:
text = self.stackspan1.text
texts1 = word_tokenize(text)
sent_tokenize_list =sent_tokenize(text)
wordb = word_tokenize(sent_tokenize_list[0] )
worde = word_tokenize(sent_tokenize_list[-1] )
features.append(('StackSpan1','BEGIN-WORD-STACK1',wordb[0].lower()))
features.append(('StackSpan1','BEGIN-END-STACK1',worde[-1].lower()))
features.append(('StackSpan1','BEGIN-END-WORD-STACK1',wordb[0].lower(),worde[-1].lower()))
for words in texts1:
if words.lower() in coreferenceList:
features.append(('StackSpan1','COREFERNCE',True))
break
if self.stackspan1.dep is not None:
for deps in self.stackspan1.dep:
if deps[2]=='R':
features.append(('StackSpan1','DEPENDENCY-BEGIN-END-WORD-STACK1',deps[0]))
break
if deps[2]=="U":
features.append(('StackSpan1','DEPENDENCY-BEGIN-OTHER-WORD-STACK1',deps[0]))
break
if self.stackspan1.pos is not None:
poss = self.stackspan1.pos.split("\t")
features.append(('StackSpan1','BEGIN-POS-WORD-STACK1',poss[0]))
# features.append(('StackSpan1','END-POS-WORD-STACK1',poss[-1]))
else:
# print text
tagged_text = nltk.pos_tag(wordb)
begins1 =tagged_text[0][1]
features.append(('StackSpan1','BEGIN-POS-WORD-STACK1',begins1))
tagged_text = nltk.pos_tag(worde)
ends =tagged_text[-1][1]
# features.append(('StackSpan1','END-POS-WORD-STACK1',ends))
self.stackspan1.pos = begins1 + "\t" + ends
if self.stackspan2 is not None:
text = self.stackspan2.text
texts2 = word_tokenize(text)
sent_tokenize_list =sent_tokenize(text)
wordb = word_tokenize(sent_tokenize_list[0] )
worde = word_tokenize(sent_tokenize_list[-1] )
features.append(('StackSpan2','BEGIN-WORD-STACK2',wordb[0].lower()))
features.append(('StackSpan2','BEGIN-END-STACK2',worde[-1].lower()))
if self.stackspan2.pos is not None:
poss = self.stackspan2.pos.split("\t")
# features.append(('StackSpan2','BEGIN-POS-WORD-STACK1',poss[0]))
# features.append(('StackSpan1','END-POS-WORD-STACK1',poss[-1]))
else:
# print text
tagged_text = nltk.pos_tag(wordb)
begins1 =tagged_text[0][1]
# features.append(('StackSpan2','BEGIN-POS-WORD-STACK1',begins1))
tagged_text = nltk.pos_tag(worde)
ends =tagged_text[-1][1]
# features.append(('StackSpan1','END-POS-WORD-STACK1',ends))
self.stackspan2.pos = begins1 + "\t" + ends
if self.queuespan1 is not None:
text = self.queuespan1.text
textq1 = word_tokenize(text)
sent_tokenize_list =sent_tokenize(text)
wordb = word_tokenize(sent_tokenize_list[0] )
worde = word_tokenize(sent_tokenize_list[-1] )
features.append(('QueueSpan1','BEGIN-WORD-QUEUE1',wordb[0].lower()))
features.append(('QueueSpan1','BEGIN-END-QUEUE',worde[-1].lower()))
features.append(('QueueSpan1','BEGIN-END-WORD-QUEUE1',wordb[0].lower(),worde[-1].lower()))
for words in textq1:
if words.lower() in coreferenceList:
features.append(('StackSpan1','COREFERNCE',True))
break
if self.queuespan1.pos is not None:
posq = self.queuespan1.pos.split("\t")
features.append(('QueueSpan1','BEGIN-POS-WORD-QUEUE1',posq[0]))
else:
tagged_text = nltk.pos_tag(wordb)
beginq1 =tagged_text[0][1]
features.append(('QueueSpan1','BEGIN-POS-WORD-QUEUE1',beginq1))
tagged_text = nltk.pos_tag(worde)
ends =tagged_text[-1][1]
self.queuespan1.pos = beginq1 + "\t" + ends
if self.queuespan1.dep is not None:
for deps in self.queuespan1.dep:
if deps[2]=='R':
features.append(('QueueSpan1','DEPENDENCY-BEGIN-END-WORD-QUEUE1',deps[0]))
break
if self.stackspan2 is not None and self.stackspan1 is not None:
features.append(('StackSpan1','LENGTH-STACK1-STACK2',len(texts1),len(texts2)))
if self.stackspan2.line is not None and self.stackspan1.line is not None :
lineq = self.stackspan2.line
lines1 = self.stackspan1.line
for line in lines1:
nex = str(int(line)+1)
if nex in lineq or line in lineq:
features.append(('StackSpan1','SAME-LINE-STACK1-STACK2',True))
break
if self.stackspan2.pos is not None and self.stackspan1.pos is not None :
poss2 = self.stackspan2.pos.split("\t")
poss = self.stackspan1.pos.split("\t")
features.append(('StackSpan1','BEGIN-POS-WORD-STACK1-STACK2',poss[0],poss2[0]))
if self.queuespan1 is not None and self.stackspan1 is not None :
text = self.stackspan1.text
sent_tokenize_list =sent_tokenize(text)
wordsb = word_tokenize(sent_tokenize_list[0] )
wordse = word_tokenize(sent_tokenize_list[-1] )
text = self.queuespan1.text
sent_tokenize_list =sent_tokenize(text)
wordqb = word_tokenize(sent_tokenize_list[0] )
wordqe = word_tokenize(sent_tokenize_list[-1] )
features.append(('StackSpan1','LENGTH-STACK1-QUEUE1',len(texts1),len(textq1)))
# features.append(('StackSpan1','LENGTH-STACK1--QUEUE1',len(texts1),len(textq1)))
if self.queuespan1.line is not None and self.stackspan1.line is not None :
lineq = self.queuespan1.line
lines1 = self.stackspan1.line
for line in lines1:
nex = str(int(line)+1)
if nex in lineq or line in lineq:
features.append(('StackSpan1','SAME-LINE-STACK1-QUEUE1',True))
break
if self.queuespan1.pos is not None and self.stackspan1.pos is not None :
posq = self.queuespan1.pos.split("\t")
poss = self.stackspan1.pos.split("\t")
features.append(('StackSpan1','BEGIN-POS-WORD-STACK1-QUEUE1',poss[0],posq[0]))
for feat in features:
yield feat
<file_sep>/README.md
# R2N2
RhetoricalRecursiveNeuralNetwork(R2N2) is recursive neural network using RST for NLP Tasks such as Sentiment Analysis
http://www.cc.gatech.edu/~jeisenst/papers/bhatia-ji-sentiment-emnlp-2015.pdf
To run RST Parser
run RSTParser/R2N2/tan.py for pre - training of weights using Max-Margin
run RSTParser/R2N2/mainst.py using weights from the pre trained system as initialisation for joint modeling
<file_sep>/RSTParser/R2N2/tan.py
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
import nltk
import os
from collections import defaultdict, Counter
from sets import Set
import sklearn
from sklearn import svm
from sklearn import linear_model
import numpy as np
import scipy as sci
import timeit
import sys
sys.path.append('../')
from nltk.stem import WordNetLemmatizer
from buildtree import *
from datastructure import *
from util import *
from model import ParsingModel
from evalparser import *
from math import pow
from numpy import linalg as LA
from math import fabs
from scipy import sparse
import numpy, sys
import numpy, gzip, sys
from numpy.linalg import norm
from util import *
from cPickle import load, dump
rng = numpy.random.RandomState(1234)
class LR():
def __init__(self, alpha,lmbda,maxiter,size):
self.alpha = float(alpha) # learning rate for gradient ascent
self.lmbda = float(lmbda) # regularization constant
self.epsilon = 0.00001 # convergence measure
self.maxiter = int(maxiter) # the maximum number of iterations through the data before stopping
self.threshold = 0.5 # the class prediction threshold
self.theta = np.zeros(size, dtype='float')
def tanh(self,X):
return np.tanh(X)
def tanh_grad(self,X):
return 1. / np.square(np.cosh(X))
def sigmoid(self,x):
x= 1. / (1. + np.exp(-x))
return x
def get_theta(self):
return self.theta
def getDataFiles(self,files,train, vocab , vocab_no,rev_vocab):
rows = []
cols = []
data = []
pol = []
review_sum = count = tp = fp = fn = 0
folds = ['neg','pos']
# path = "../../Movies/edu-input-final/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.edus')]
for filename in files:
# filename = (filename.split(".edus"))[0]
f = open(filename, 'r')
content = f.read()
# print content
content = content.decode('utf-8').encode('ascii','ignore')
content = content.replace('<br />','').lower()
words = word_tokenize(content)
words2 = [w for w in words if not w in stopwords.words('english')]
cnt = Counter(words2)
for word in cnt:
if word not in vocab and train:
vocab[word] = vocab_no[0]
rev_vocab[vocab_no[0]] = word
vocab_no[0] = vocab_no[0] + 1
if word in vocab:
rows.append(count)
cols.append(vocab[word])
data.append(cnt[word])
fname = str(filename.split("/")[-1])
rating = int(fname.split(".")[0].split("_")[1])
if rating <6:
pol.append(-1)
if rating >6 :
pol.append(1)
count = count + 1
f.close()
mat = sci.sparse.csr_matrix((data,(rows,cols)), shape=(count,vocab_no[0])).todense()
return mat, pol
def fit(self, X, y,test_mat,test_pol):
"""
This function optimizes the parameters for the logistic regression classification model from training
data using learning rate alpha and regularization constant lmbda
@post: parameter(theta) optimized by gradient descent
"""
# X = self.add_ones(X_) # prepend ones to training set for theta_0 calculations
# initialize optimization arrays
self.n = X.shape[1] # the number of features
self.m = X.shape[0] # the number of instances
self.probas = np.zeros(self.m, dtype='float') # stores probabilities generated by the logistic function
# stores the model theta
self.lw = np.zeros(self.m, dtype='float')
self.theta = np.zeros(self.n, dtype='float')
# iterate through the data at most maxiter times, updating the theta for each feature
# also stop iterating if error is less than epsilon (convergence tolerance constant)
print "iter | magnitude of the gradient"
for iteration in xrange(self.maxiter):
# calc probabilities
self.lw = self.get_der(X,y)
# self.probas = self.get_proba(X)
print iteration
# print self.lw.shape
# print X.T.shape
# print self.probas
# # calculate the gradient and update theta
# c= self.probas -y
c= self.lw
# print "Cshape",c.shape
# print c
# print self.lw
# if y < 0:
# y=0
k = (1.0/self.m) * np.dot(X.T,c.T)
k=k.T
# print k.shape
gw = np.zeros(k.shape[1], dtype='float')
for i in range(k.shape[1]):
# print k[i,0]
gw[i]=k[0,i]
# print "GW",gw.shape
# print gw[0:10]
# print self.theta[0:10]
# print gw
# g0 = gw[0] # save the theta_0 gradient calc before regularization
gw =gw + (self.lmbda * self.theta)/self.m # regularize using the lmbda term
# gw[0] = g0 # restore regularization independent theta_0 gradient calc
self.theta -= self.alpha * gw # update parameters
# calculate the magnitude of the gradient and check for convergence
loss = np.linalg.norm(gw)
if self.epsilon > loss:
break
print "Accuracy" , ":", self.compute_accuracy(test_pol,self.predict(test_mat))
print iteration, ":", loss
def get_der(self,X,label):
iscore = np.dot(X, self.theta)
# print iscore
score = self.tanh(iscore)
# score= iscore
score =score.T
# score = iscore.T
# print "Score******"
# print iscore
# print score
fscore = np.zeros(score.shape[0], dtype='float')
for i in range(score.shape[0]):
# print k[i,0]
fscore[i]=score[i,0]
# print "fscore" ,fscore.shape
# print fscore
check = 1.0- label*fscore
# print "Check" , check.shape
# print check
check[check<0] = 0
check[check>0] = 1
# print "heck"
# print check
gradscore = self.tanh_grad(score).T
# # print gradscore
gscore = np.zeros(gradscore.shape[1], dtype='float')
for i in range(gradscore.shape[1]):
# print k[i,0]
gscore[i]=gradscore[0,i]
# print "Gscore" , gscore.shape
# print gscore
fcore= gscore*label
der = -check*fcore
# print der.shape
fder = np.zeros((1,der.shape[0]), dtype='float')
for i in range(der.shape[0]):
# print k[i,0]
fder[0,i]=der[i]
# *gscore
# print der
# print "Der",der.shape
# print fder.shape
return fder
def get_proba(self, X):
return 1.0 / (1 + np.exp(- np.dot(X, self.theta)))
def predict_proba(self, X):
"""
Returns the set of classification probabilities based on the model theta.
@parameters: X - array-like of shape = [n_samples, n_features]
The input samples.
@returns: y_pred - list of shape = [n_samples]
The probabilities that the class label for each instance is 1 to standard output.
"""
# X_ = self.add_ones(X)
return self.get_proba(X)
def score(self,X):
return self.tanh(np.dot(X, self.theta))
def predict(self, X):
"""
Classifies a set of data instances X based on the set of trained feature theta.
@parameters: X - array-like of shape = [n_samples, n_features]
The input samples.
@returns: y_pred - list of shape = [n_samples]
The predicted class label for each instance.
"""
y_pred =[]
pred = self.predict_proba(X)
for i in range(pred.shape[1]):
proba =pred[0,i]
if proba >self.threshold:
y_pred.append(1)
else:
y_pred.append(-1)
# y_pred = [proba > self.threshold for proba in self.predict_proba(X)]
return y_pred
def add_ones(self, X):
# prepend a column of 1's to dataset X to enable theta_0 calculations
# print X.shape[0]
return np.hstack((np.zeros(shape=(X.shape[0],1), dtype='float') + 1, X))
def sigmoid_grad(self,f):
sig = sigmoid(f)
return sig * (1 - sig)
def compute_accuracy(self,y_test, y_pred):
"""
@returns: The precision of the classifier, (correct labels / instance count)
"""
correct = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
correct += 1
return float(correct) / len(y_test)
def savemodel(fname,D):
""" Save model into fname
"""
if not fname.endswith('.pickle.gz'):
fname = fname + '.pickle.gz'
# D = self.getparams()
with gzip.open(fname, 'w') as fout:
dump(D, fout)
print 'Save model into file {}'.format(fname)
def loadmodel( fname):
""" Load model from fname
"""
with gzip.open(fname, 'r') as fin:
D = load(fin)
return D
print 'Load model from file: {}'.format(fname)
if __name__ == '__main__':
path = "../../../Movies//sf/out/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
tfiles = files
# [0:5000]
print len(tfiles)
# vfiles = files[0:50] + files[950:]
path = "../../../Movies//sf/outtest/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# tfiles = tfiles + files[50:950]
vfiles = files[0:5000]
print len(vfiles)
# path = "../../../Movies//start/train/pos/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# tfiles = files[0:10000]
# # vfiles = files[950:1000]
# path = "../../../Movies//start/train/neg/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# tfiles = tfiles + files[0:10000]
# # vfiles = vfiles + files[950:1000]
# path = "../../../Movies//start/test/pos/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# # tfiles = files[0:500]
# vfiles = files[0:10000]
# path = "../../../Movies//start/test/neg/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# # tfiles = tfiles + files[0:500]
# vfiles = vfiles + files[0:10000]
print len(tfiles)
print len(vfiles)
# path = "../../../Movies/Bigger-set//"
# tfiles = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
# path = "../../../Movies/edu-input-final/"
# vfiles = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
print "start"
alpha=1.0
lmbda=.1
maxiter=500
lr = LR(alpha,lmbda,maxiter,0)
# theta = defaultdict(int)
vocab = defaultdict()
vocab_no = Counter()
rev_vocab = defaultdict()
train_mat,train_pol = lr.getDataFiles(tfiles,True,vocab,vocab_no,rev_vocab)
test_mat,test_pol = lr.getDataFiles(vfiles,False,vocab,vocab_no,rev_vocab)
# print test_pol
# D = {"tdata":train_mat, "tpos":train_pol}
# savemodel("data-sd.pickle.gz",D)
# D={"vdata":test_mat,"vpos":test_pol}
# savemodel("data-sdtest.pickle.gz",D)
# D =loadmodel("data.pickle.gz")
# train_mat,train_pol = D["tdata"] ,D["tpos"]
# prob_train =[]
# for i in range(len(train_pol)):
# if train_pol[i] < 0:
# prob_train.append(0)
# else:
# prob_train.append(1)
# test_mat,test_pol = D["vdata"] , D["vpos"]
print test_pol
# lr = LR(alpha,lmbda,maxiter,train_mat.shape[1])
# for i in range(10):
# print lr.score(train_mat)
lr.fit(train_mat,train_pol,test_mat,test_pol)
y_pred = lr.predict(test_mat)
print lr.compute_accuracy(test_pol,y_pred)
print lr.score(test_mat)
theta = lr.get_theta()
words = defaultdict()
# vocab = D["vocab"]
# vocab_no = D["vocabno"]
# rev_vocab = D["rev_vocab"]
for i in range(len(theta)):
words[rev_vocab[i]] =theta[i]
print words
D = {"words":words,"vocab":vocab,"vocabno":vocab_no,"rev_vocab":rev_vocab}
savemodel("test-weights-sd.pickle.gz",D)
# print len(test_pol)
# print y_pred
# lr.setup(theta,tfiles)
# lr.grad_descent(tfiles,theta,vfiles)
# print lr.predict(vfiles,theta)
<file_sep>/RSTParser/offlinePOS4All.py
# -*-coding:utf-8-*-
import locale
locale.setlocale(locale.LC_ALL, '')
# -*- coding: cp1254 -*-
import os
from nltk.tokenize import word_tokenize, sent_tokenize
import nltk
from nltk.tag.stanford import POSTagger
from nltk.parse.stanford import StanfordParser
from multiprocessing import Pool
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
#coding: utf-8
def _parse_output(output_):
res = []
cur_lines = []
for line in output_.splitlines(False):
if line == '':
# res.append(Tree.fromstring('\n'.join(cur_lines)))
cur_lines = []
else:
root =line.split('(')
if root[0] =='root':
return root[1].split(',')[1].split('-')[0].strip()
return cur_lines
def posgen(fname):
length = 0
if fname.endswith('.edus') :
print fname
f = open(os.path.join(path,fname),'r')
mys1 =os.path.join(path, fname.split(".")[0] +".pos")
print mys1
pos = open(mys1,"w")
data = f.read().splitlines()
for line in data:
if len(line)>length:
length =len(line)
wordb = word_tokenize(line.encode('utf8'))
for i in range(len(wordb)):
wordb[i]= wordb[i].encode('utf8')
tags = english_postagger.tag(wordb)
pos.write(str(line.strip()))
pos.write("@#%^&*")
# print str(line.strip())
# print tags
for tgpair in tags[0]:
# print tgpair
pos.write(str(tgpair[1]))
pos.write("\t")
pos.write("\n") # print i
# i=i+1
# print length
# continue;
mys = "sentencepos2all" + ".txt"
#mys1 = "dep2" + ".txt"
pos = open(mys,"w")
#dep = open(mys1,"w")
english_postagger = POSTagger('../postagger/models/english-bidirectional-distsim.tagger', '../postagger/stanford-postagger.jar', encoding='utf-8')
english_parser = StanfordParser('../postagger/stanford-parser.jar', '../parser/stanford-parser-3.5.0-models.jar', encoding='utf-8')
path = "../../Movies/review_polarity/txt_sentoken/pos/"
p = Pool(25)
p.map(posgen, os.listdir(path))
# for fname in os.listdir(path):
# posgen(fname)
<file_sep>/RSTParser/R2N2/relation.py
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
import nltk
import os
from collections import defaultdict, Counter
from sets import Set
import sklearn
from sklearn import svm
from sklearn import linear_model
import numpy as np
import scipy as sci
import timeit
import sys
sys.path.append('../')
from parsers import SRParser
from nltk.stem import WordNetLemmatizer
from buildtree import *
from datastructure import *
from util import *
from model import ParsingModel
from evalparser import *
from math import pow
from numpy import linalg as LA
from math import fabs
from scipy import sparse
import numpy, sys
import numpy, gzip, sys
from numpy.linalg import norm
from util import *
from cPickle import load, dump
rng = numpy.random.RandomState(1234)
from scipy.special import expit
from rst import *
class RSTRelation():
def __init__(self):
None
def checkEDU(self, edu_span, annotations_range,buffer=2):
start = int(edu_span[0])+ buffer
end =int(edu_span[1])-buffer
for ast,aend in annotations_range:
if (start in range(int(ast), int(aend))) and (end in range(int(ast), int(aend))):
# print "Yes"
# print ast , aend
# print start , end
return True
return False
def addSpan(self,node,edu_span):
if node.lnode == None and node.lnode ==None:
edu_span = edu_map[node.text.strip()]
edu_span = (edu_span.split("\t")[0],edu_span.split("\t")[1])
node.trange = edu_span
return node.trange
lrange = addSpan(node.lnode,edu_span)
rrange = addSpan(node.rnode,edu_span)
node.trange = (lrange[0],rrange[1])
return node.trange;
def treeTraverseSimple(self,node, height = 0):
disFeats = []
if node.lnode != None and node.lnode.prop == 'Nucleus':
# print "Nucleus "
# print height
print node.lnode.trange
# text = word_tokenize(node.lnode.text.lower())
# for word in text:
# nucFeats.append(('Nucleus', word))
elif node.rnode != None and node.rnode.prop == 'Nucleus':
# print "Nucleus "
# print height
print node.rnode.trange
#text = word_tokenize(node.rnode.text.lower())
#for word in text:
# nucFeats.append(('Nucleus', word))
if None != node.lnode and None != node.rnode :
treeTraverse(node.lnode,height+1)
treeTraverse(node.rnode,height+1)
def createHeads(self,node):
if node !=None:
hl= self.createHeads(node.lnode)
hr = self.createHeads(node.rnode)
node.depList=[]
if node.lnode == None:
node.head = node
else:
if node.lnode.prop == 'Nucleus':
node.head = node.lnode.head
else:
node.head = node.rnode.head
return max(hl+1,hr+1)
else:
return 0
def treeTraverseHeads(self,node, height = 0):
if node!=None:
print node.head.text
if None != node.lnode and None != node.rnode :
self.treeTraverseHeads(node.lnode,height+1)
self.treeTraverseHeads(node.rnode,height+1)
def getNucleusParent(self,node,head):
anc = node.pnode
while(anc!=None and anc.prop == 'Nucleus'):
anc = anc.pnode
anc = anc.pnode
if anc!=None:
anc.head.depList.append(node)
else:
if head !=node:
head.depList.append(node)
def getSatelliteParent(self,node):
anc = node.pnode
if anc!=None and anc.head!=node:
anc.head.depList.append(node)
def treeTraverseTerminal(self,node,head, height = 0):
if None != node.lnode and None != node.rnode :
self.treeTraverseTerminal(node.lnode,head,height+1)
self.treeTraverseTerminal(node.rnode,head,height+1)
else:
if node.prop == 'Nucleus':
self.getNucleusParent(node,head)
else:
self.getSatelliteParent(node)
def checkEDU(edu_span, annotations_range,annotations_map,primary,height,buffer=2):
start = int(edu_span[0])+ buffer
end =int(edu_span[1])-buffer
for ast,aend in annotations_range:
if (start in range(int(ast), int(aend))) and (end in range(int(ast), int(aend))):
if annotations_map[(ast,aend)] in primary:
height_freq[height+1]= height_freq[height+1]+1
node_freq[height+1]= node_freq[height+1]+1
return True
else:
node_freq[height+1]= node_freq[height+1]+1
return False
def treeTraverseDep(self,node,depth_parameter,height=0):
local_score = 0.0
text = word_tokenize(node.text.lower())
for word in text:
if word in sa_dict:
# print word
if height <3:
local_score=local_score+sa_dict[word]*(1-depth_parameter*height)
# local_score=local_score+sa_dict[word]*pow(.89, height)
# tcnt[word] = tcnt[word]+ local_score
# data.append(local_score)
else:
local_score =local_score + .5*sa_dict[word]
# local_score=local_score+ sa_dict[word]*(1-depth_parameter*height)
score = local_score
# /(height+1)
# print height , "****---"
# print node.text
for nodes in node.depList:
score = score+ self.treeTraverseDep(self,nodes,depth_parameter,height+1)
return score
def neval(self,x,alpha = 1e-5):
x = (2.0/3) * x
exp2x = np.exp(-2*x)
val = (1.7159 * (1 - exp2x) / (1 + exp2x)) + (alpha * x.sum())
return val
def grad(self,x,alpha = 1e-5):
val = self.neval(x)
g = (1.7159 * (2.0 / 3) * (1 - (val ** 2))) + (np.ones(x.shape) * alpha)
return g
def bft(self,root):
""" Breadth-first traversal on the tree (starting
from root note!)
"""
nodelist = []
if root is not None:
queue = [root]
while queue:
node = queue.pop(0)
if node.lnode is not None:
queue.append(node.lnode)
if node.rnode is not None:
queue.append(node.rnode)
nodelist.append(node)
return nodelist
def is_leaf(self,node):
""" Whether this node is a leaf node
"""
if (node.lnode is None) and (node.rnode is None):
return True
else:
return False
def treeCompositionSimple(self,node,param):
if node !=None:
self.treeCompositionSimple(node.lnode,param)
self.treeCompositionSimple(node.rnode,param)
comp(node,param)
def comp(self,node, param):
""" Composition function
For internal node, compute the composition function
For leaf node, return the value directly
:type param: instance of Param class or dict of instances
:param param: composition matrices and bias
"""
imp_rel = ['Constrast','Comparison','antithesis','antithesis-e','consequence-s','concession','Problem-Solution']#'circumstance-e']#'concession']
tparam = param
if (node.lnode is None) and (node.rnode is None):
# If both children nodes are None
return node.value
elif (node.lnode is not None) and (node.rnode is not None):
try:
# print tparam.S , tparam.N
if node.rnode.prop=="Nucleus":
if node.relation in imp_rel :
u = tparam.S.T[1]*(node.lnode.value) + tparam.N.T[1]*(node.rnode.value)
else:
u = tparam.S.T[0]*(node.lnode.value) + tparam.N.T[0]*(node.rnode.value)
# u += tparam.N.dot(node.rnode.value)
else:
if node.relation in imp_rel :
u = tparam.S.T[1]*(node.rnode.value) + tparam.N.T[1]*(node.lnode.value)
else:
u = tparam.S.T[0]*(node.rnode.value) + tparam.N.T[0]*(node.lnode.value)
# u += tparam.N.dot(node.lnode.value)
except TypeError:
print self.lnode.pos, self.lnode.value
print self.rnode.pos, self.rnode.value
import sys
sys.exit()
node.value = self.neval(u)
else:
raise ValueError("Unrecognized situation")
def feedforward(self,nodelist,param,root):
""" Upward semantic composition step ---
Using forward to compute the composition result
of the root node
Find a topological order of all nodes, then follow
the linear order to update the node value one by one
"""
# Reverse the nodelist, without change the original one
nodelist.reverse() # Reverse
for node in nodelist:
if self.is_leaf(node): # Leaf node
pass
else: # Non-leaf node
self.comp(node,param)
# Return the composition result
nodelist.reverse() # Reverse back
return root.value
def cross_feedforward(self,param,root):
llist = self.bft(T.tree.lnode)
scorel = self.feedforward(llist,param, T.tree.lnode)
rlist = bft(T.tree.rnode)
scorer = feedforward(rlist,param, T.tree.rnode)
if T.tree.lnode.prop=="Nucleus":
score = scorel*param.N + scorer*param.S
else:
score = scorel*param.S + scorer*param.N
root.value = self.sigmoid(score)
return root.value
def paramgrad(self,node, param):
""" Compute the param gradient given current param,
which is used to update param
:type param: instance of Param class
:param param: composition metrices and bias
:type grad_parent: 1-d numpy.array
:param grad_parent: gradient information from parent node
"""
# Element-wise multiplication, 1-d numpy.array
imp_rel = ['Constrast','Comparison','antithesis','antithesis-e','consequence-s','concession','Problem-Solution']
gu = self.grad(node.value) * node.grad_parent
if self.is_leaf(node):
gS = np.zeros(param.S.shape)
gN = np.zeros(param.N.shape)
else:
if node.rnode.prop=="Nucleus":
if node.relation in imp_rel :
gS = np.array([0, np.outer(gu, node.lnode.value)])
gN = np.array([0, np.outer(gu, node.rnode.value)])
else:
gS = np.array([np.outer(gu, node.lnode.value),0])
gN = np.array([np.outer(gu, node.rnode.value),0])
else:
if node.relation in imp_rel :
gN = np.array([0 , np.outer(gu, node.lnode.value)])
gS = np.array([0 , np.outer(gu, node.rnode.value)])
else:
gN = np.array([np.outer(gu, node.lnode.value),0])
gS = np.array([np.outer(gu, node.rnode.value),0])
if (node.rnode is None) and (node.lnode is None):
gbias = np.zeros(param.N.shape)
else:
# Without bias term in composition
gbias = np.zeros(param.N.shape)
# print gL.shape, gR.shape, gbias.shape
node.grad_param = Param(gS, gN, gbias)
def grad_input(self,node, param):
""" Compute the gradient wrt input from left child node,
and right child node. If it is a leaf node, return
the gradient information from parent node directly.
This is mainly for back-propagating gradient
information
:type grad_parent: 1-d numpy.array
:param grad_parent: gradient information from parent node
"""
# Compute gradient
imp_rel = ['Constrast','Comparison','antithesis','antithesis-e','consequence-s','concession','Problem-Solution']
if (node.lnode is None) and (node.rnode is None):
try:
node.grad = node.grad_parent[0]
except :
node.grad = node.grad_parent
return node.grad_parent
else:
# Is it safe to use the value directly?
# What if it is not updated with the new param?
gu = self.grad(node.value) * node.grad_parent
# Assign gradient back to children nodes
# For satellite node
grad_s = param.S.T[0]* gu
grad_scont = param.S.T[1]* gu
# For nucleus node
grad_n = param.N.T[0]* gu
grad_ncont = param.N.T[1]* gu
if node.rnode.prop=="Nucleus":
if node.relation in imp_rel :
node.lnode.grad_parent = grad_scont
node.rnode.grad_parent = grad_ncont
else:
node.lnode.grad_parent = grad_s
node.rnode.grad_parent = grad_n
else:
if node.relation in imp_rel :
node.rnode.grad_parent = grad_scont
node.lnode.grad_parent = grad_ncont
else:
node.rnode.grad_parent = grad_s
node.lnode.grad_parent = grad_n
return (grad_s, grad_n)
# raise ValueError("Need double check")
def ngrad(self,root, param, grad_inputs,nodelist):
""" Using back-propagation to compute upward gradients
wrt parameters
:type grad_input: 1-d numpy.array
:param grad_input: gradient information from model
(In other words, this is the gradient of the model
wrt to the composition result)
"""
# Assign the grad_input
root.grad_parent = grad_inputs
# If the node list is empty, do BFT first
imp_rel = ['Constrast','Comparison','antithesis','antithesis-e','consequence-s','concession','Problem-Solution']
# Back propagating the gradient from root to leaf
for node in nodelist:
# For model parameters
self.paramgrad(node,param)
# For back propagation
self.grad_input(node,param)
# Collecting grad information
# Traversing all the interval nodes and adding
# all the grad information wrt param together
gparam = Param(np.zeros(nodelist[0].grad_param.S.shape),
np.zeros(nodelist[0].grad_param.N.shape),
np.zeros(nodelist[0].grad_param.bias.shape))
gword = {}
# print '-----------------------------------'
for node in nodelist:
# What will happen if the node is leaf node?
if len(node.grad_param.S.shape) ==2:
# print node.grad_param.S.shape[1]
gs = np.zeros(node.grad_param.S.shape[1], dtype='float')
for i in range(node.grad_param.S.shape[1]):
gs[i]=node.grad_param.S[0,i]
gn = np.zeros(node.grad_param.N.shape[1], dtype='float')
for i in range(node.grad_param.N.shape[1]):
gn[i]=node.grad_param.N[0,i]
else:
gparam.S += node.grad_param.S
gparam.N += node.grad_param.N
if self.is_leaf(node):
text = word_tokenize(node.text.lower())
for word in text:
if isinstance(node.grad, list):
val = node.grad[0]
else:
val = node.grad
if word in gword:
gword[word] += val
else:
gword[word] = val
# numpy.linalg.norm(gparam.L)
# numpy.linalg.norm(gparam.R)
return gparam , gword
def sigmoid(self,x):
""" Sigmoid function """
###################################################################
# Compute the sigmoid function for the input here. #
###################################################################
x= 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(self,f):
""" Sigmoid gradient function """
###################################################################
# Compute the gradient for the sigmoid function here. Note that #
# for this implementation, the input f should be the sigmoid #
# function value of your original input x. #
###################################################################
sig = sigmoid(f)
return sig * (1 - sig)
return f
def cross_ngrad(self,root, param, grad_inputs,nodelist):
""" Using back-propagation to compute upward gradients
wrt parameters
:type grad_input: 1-d numpy.array
:param grad_input: gradient information from model
(In other words, this is the gradient of the model
wrt to the composition result)
"""
# Assign the grad_input
root.grad_parent = grad_inputs
# If the node list is empty, do BFT first
# Back propagating the gradient from root to leaf
for node in nodelist:
# For model parameters
if root == node :
print"yes"
gu = sigmoid_grad(node.value) * node.grad_parent
if node.rnode.prop=="Nucleus":
gS = np.outer(gu, node.lnode.value)
gN = np.outer(gu, node.rnode.value)
else:
gS = np.outer(gu, node.rnode.value)
gN = np.outer(gu, node.lnode.value)
gbias = np.zeros(param.bias.shape)
node.grad_param = Param(gS, gN, gbias)
grad_s = np.dot(param.S.T, gu)
# For nucleus node
grad_n = np.dot(param.N.T, gu)
if node.rnode.prop=="Nucleus":
node.lnode.grad_parent = grad_s
node.rnode.grad_parent = grad_n
else:
node.rnode.grad_parent = grad_s
node.lnode.grad_parent = grad_n
else:
paramgrad(node,param)
grad_input(node,param)
gparam = Param(np.zeros(nodelist[0].grad_param.S.shape),
np.zeros(nodelist[0].grad_param.N.shape),
np.zeros(nodelist[0].grad_param.bias.shape))
gword = {}
# print '-----------------------------------'
for node in nodelist:
# What will happen if the node is leaf node?
gparam.S += node.grad_param.S
gparam.N += node.grad_param.N
if is_leaf(node):
text = word_tokenize(node.text.lower())
for word in text:
if isinstance(node.grad, list):
val = node.grad[0]
else:
val = node.grad
if word in gword:
gword[word] += val
else:
gword[word] = val
# numpy.linalg.norm(gparam.L)
# numpy.linalg.norm(gparam.R)
return gparam , gword
def addScoreDep(self,node,depth_parameter,sa_dict,height=0):
local_score = 0.0
text = word_tokenize(node.text.lower())
for word in text:
if word in sa_dict:
local_score=local_score+sa_dict[word]
score = local_score
node.value = np.array([score])
for nodes in node.depList:
score=score+self.addScoreDep(nodes,depth_parameter,sa_dict,height+1)
return score
def addLearnedScoreDepL(self,node,sa_dict,height=0):
local_score = 0.0
text = node.text
# score = getEDUData(text,vocab,vocab_no,lr)
text = word_tokenize(node.text.lower())
for word in text:
if word in sa_dict:
local_score=local_score+sa_dict[word]
score = local_score
node.value = np.array([score])
for nodes in node.depList:
score=score+self.addLearnedScoreDepL(nodes,sa_dict,height+1)
return score
def learn_word_weights(gword,sa_dict, learning = .05):
for word in gword:
if word in sa_dict:
sa_dict[word] = sa_dict[word] - learning*gword[word]
# else:
# sa_dict[word] = - learning*gword[word]
def miniHingeJointTopSGD(pm,files,size,sa_dict,iterations=100):
alpha = .05
learning = 1.0
i=0
batches =0
param = Param(np.ones(1),np.ones(1),np.zeros(1))
# param = Param(np.array([.82]),np.array([1.2]),np.zeros(1))
gparams =[]
gwords =defaultdict(int)
for it in range(iterations):
batches=0
print "Iteration " , it
for fname in files:
T = parse(pm, fname )
nlist = bft(T.tree)
max_height = createHeads( T.tree)
treeTraverseTerminal(T.tree,T.tree.head)
depth_parameter = .95/max_height
addScoreDep(T.tree.head,depth_parameter,sa_dict)
if batches< size:
batches=batches+1
else:
batches=0
N = sum([gparam.N for gparam in gparams])/size
S = sum([gparam.S for gparam in gparams])/size
param.N = param.N - alpha*N
param.S = param.S - alpha*S
# else:
# sa_dict[word] = - learning*gwords[word]/size
for word in gwords:
if word in sa_dict:
sa_dict[word] = sa_dict[word] - (learning*(gwords[word]) /size)
print param.N
print param.S
if LA.norm( [param.S,param.N]) >1.8:
param.S =(param.S /LA.norm( [param.S,param.N]))
param.N =(param.N /LA.norm( [param.S,param.N]))
gparams=[]
gwords =defaultdict(int)
break
scorel = 0
scorer= 0
if T.tree.lnode !=None and T.tree.lnode !=None:
score = feedforward(nlist,param, T.tree)
fname = str(fname.split("/")[-1])
rating = int(fname.split(".")[0].split("_")[1])
true_pos = 1.6
true_neg = -1.6
y_i=0
if rating <6 :
y_i = -1
else:
y_i=1
margin = (1-y_i*score)
if margin <0:
margin=0
if margin==0:
grad_inputs=margin
else:
grad_inputs=-y_i
gpram , gword = ngrad(T.tree, param, grad_inputs,nlist)
gparams.append(gpram)
for word in gword:
try:
val = gword[word]
gwords[word] += val
except KeyError:
gwords[word] = val
return param
def savemodel(fname,D):
""" Save model into fname
"""
if not fname.endswith('.pickle.gz'):
fname = fname + '.pickle.gz'
# D = self.getparams()
with gzip.open(fname, 'w') as fout:
dump(D, fout)
print 'Save model into file {}'.format(fname)
def loadmodel( fname):
""" Load model from fname
"""
with gzip.open(fname, 'r') as fin:
D = load(fin)
return D
print 'Load model from file: {}'.format(fname)
class Param(object):
def __init__(self, S, N, bias):
""" Parameters for composition
:type L: 2-d numpy.array
:param L: composition matrix for left node
:type R: 2-d numpy.array
:param R: composition matrix for right node
:type bias: 1-d numpy.array
:param bias: composition bias
"""
self.S = S
self.N = N
self.bias = bias
if __name__ == '__main__':
D =loadmodel("weights.pickle.gz")
weights = D["words"]
vocab = D["vocab"]
vocab_no = D["vocabno"]
pm = ParsingModel()
pm.loadmodel("../parsing-model.pickle.gz")
path = "../../../Movies/edu-input-final/"
path = "../../../Movies/Bigger-set/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.edus')]
# param = miniKJointSGD(files,400,sa_dict,iterations=40)
param = miniHingeJointTopSGD(pm,files,1500,weights,iterations=100)
print param.N
print param.S<file_sep>/RSTParser/R2N2/mainstrel.py
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
import nltk
import os
from collections import defaultdict, Counter
from sets import Set
import sklearn
from sklearn import svm
from sklearn import linear_model
import numpy as np
import scipy as sci
import timeit
import sys
sys.path.append('../')
from nltk.stem import WordNetLemmatizer
from buildtree import *
from datastructure import *
from util import *
from model import ParsingModel
from evalparser import *
from math import pow
from numpy import linalg as LA
from math import fabs
from scipy import sparse
import numpy, sys
import numpy, gzip, sys
from numpy.linalg import norm
from util import *
from cPickle import load, dump
from ltan import *
# from joint import *
from relation import *
rng = numpy.random.RandomState(1234)
if __name__ == '__main__':
# path = "../../../Movies/edu-input-final/"
# vfiles = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.edus')]
alpha=1.0
lmbda=.1
maxiter=100
rel = .05
joint =.1
lr = MaxMargin(alpha,lmbda,maxiter)
D =loadmodel("weights-pang.pickle.gz")
weights_bow = D["words"]
vocab = D["vocab"]
vocab_no = D["vocabno"]
P =loadmodel("weights-pang.pickle.gz")
weights_rst = P["words"]
vocab = D["vocab"]
vocab_no = D["vocabno"]
pm = ParsingModel()
pm.loadmodel("../parsing-model.pickle.gz")
# path = "../../../Movies/Bigger-set/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.edus')]
path = "../../../Movies//review_polarity/txt_sentoken/pos/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
tfiles = files[50:950]
vfiles = files[0:50] + files[950:]
path = "../../../Movies//review_polarity/txt_sentoken/neg/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
tfiles = tfiles + files[50:950]
vfiles = vfiles + files[0:50] + files[950:]
rst =RSTRelation()
i=0
batches =0
# param = Param(np.ones(1),np.ones(1),np.zeros(1))
param = Param(np.ones(2),np.ones(2),np.zeros(2))
# param = Param(np.array([.82]),np.array([1.2]),np.zeros(1))
gparams =[]
Kb = 1.0
Kr = 1.0
size = len(tfiles)
for it in range(maxiter):
print "Iteration everythng *** " , it
gwords_bow =defaultdict(int)
gwords_rst =defaultdict()
gkbs =[]
gkrs =[]
gparams=[]
# correct_pred = 0.0
# total_pred = 0.0
# for fname in vfiles:
# tfile = fname
# fname = tfile+".edus"
# score_bow = lr.getScore(tfile,weights_bow)
# T = parse(pm, fname )
# nlist = rst.bft(T.tree)
# max_height = rst.createHeads( T.tree)
# rst.treeTraverseTerminal(T.tree,T.tree.head)
# depth_parameter = .95/max_height
# rst.addLearnedScoreDepL(T.tree.head,weights_rst)
# score_rst = rst.feedforward(nlist,param, T.tree)/1.71
# # Combined score
# fscore = Kb*score_bow + Kr*score_rst
# fname = str(fname.split("/")[-1])
# rating = int(fname.split(".")[0].split("_")[1])
# if rating <6 and fscore <0:
# correct_pred = correct_pred+1
# if rating >6 and fscore >0:
# # print "Here "
# correct_pred = correct_pred+1
# total_pred = total_pred+1
# print correct_pred/total_pred
for fname in tfiles:
# BOW Grad Start
fn = str(fname.split("/")[-1])
rating = int(fn.split(".")[0].split("_")[1])
y_i=0
if rating <6 :
y_i = -1
else:
y_i = 1
textfile = fname
fname = textfile+".edus"
# textfile = fname.split(".edus")[0]
score_bow = lr.getScore(textfile,weights_bow)
T = parse(pm, fname )
nlist = rst.bft(T.tree)
max_height = rst.createHeads( T.tree)
rst.treeTraverseTerminal(T.tree,T.tree.head)
depth_parameter = .95/max_height
rst.addScoreDep(T.tree.head,depth_parameter,weights_rst)
score_rst = rst.feedforward(nlist,param, T.tree)/1.71
# Combined score
fscore = Kb*score_bow + Kr*score_rst
# fscore =score_bow
margin = (1.0-y_i*fscore)
if margin <0:
margin=0
gradkb = -margin*y_i*score_bow
gradkr = -margin*y_i*score_rst
gkbs.append(gradkb)
gkrs.append(gradkr)
gradsb = -margin*y_i*Kb
gradsr = -margin*y_i*Kr
gpram , gword = rst.ngrad(T.tree, param, gradsr,nlist)
gparams.append(gpram)
for word in gword:
try:
val = gword[word]
gwords_rst[word] += val
except KeyError:
gwords_rst[word] = val
gscore = lr.tanh_grad(score_bow)
der = -margin*gscore*y_i*Kb
lr.cal_grad(textfile,gwords_bow,der)
# Update Parameters
bowweight = sum([gparam for gparam in gkbs])/size
rstweight = sum([gparam for gparam in gkrs])/size
Kb = Kb - joint*bowweight
Kr = Kr - joint*rstweight
# BOW
for word in gwords_bow:
# if word in weights_bow:
reg = (lmbda*weights_bow[word])/size
weights_bow[word] = weights_bow[word] - alpha*( (gwords_bow[word] /size) +reg)
# RST Update
N = sum([gparam.N for gparam in gparams])/size
S = sum([gparam.S for gparam in gparams])/size
param.N = param.N - rel*N
param.S = param.S - rel*S
for word in gwords_rst:
if word in weights_rst:
reg = (lmbda*weights_rst[word])/size
weights_rst[word] = weights_rst[word] - alpha*((gwords_rst[word]) /size)
# print param.N
# print param.S
if LA.norm( [param.S,param.N]) >1.8 or LA.norm( [param.S,param.N]) < -1.8:
param.S =(param.S /LA.norm( [param.S,param.N]))
param.N =(param.N /LA.norm( [param.S,param.N]))
# print param.N
# print param.S
# print Kb
# print Kr
gwords_bow =defaultdict(int)
gwords_rst =defaultdict()
gkbs =[]
gkrs =[]
gparams=[]
# Predictions
correct_pred = 0.0
total_pred = 0.0
for fname in vfiles:
# tfile = (fname.split(".edus"))[0]
tfile = fname
fname = tfile+".edus"
score_bow = lr.getScore(tfile,weights_bow)
T = parse(pm, fname )
nlist = rst.bft(T.tree)
max_height = rst.createHeads( T.tree)
rst.treeTraverseTerminal(T.tree,T.tree.head)
depth_parameter = .95/max_height
rst.addLearnedScoreDepL(T.tree.head,weights_rst)
score_rst = rst.feedforward(nlist,param, T.tree)/1.71
# Combined score
fscore = Kb*score_bow + Kr*score_rst
fname = str(fname.split("/")[-1])
rating = int(fname.split(".")[0].split("_")[1])
if rating <6 and fscore <0:
correct_pred = correct_pred+1
if rating >6 and fscore >0:
# print "Here "
correct_pred = correct_pred+1
total_pred = total_pred+1
print correct_pred/total_pred
# RST Grad Done
# BOW Model Begin
<file_sep>/RSTParser/R2N2/lin.py
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
import nltk
import os
from collections import defaultdict, Counter
from sets import Set
import sklearn
from sklearn import svm
from sklearn import linear_model
import numpy as np
import scipy as sci
import timeit
import sys
sys.path.append('../')
from nltk.stem import WordNetLemmatizer
from buildtree import *
from datastructure import *
from util import *
from model import ParsingModel
from evalparser import *
from math import pow
from numpy import linalg as LA
from math import fabs
from scipy import sparse
import numpy, sys
import numpy, gzip, sys
from numpy.linalg import norm
from util import *
from cPickle import load, dump
rng = numpy.random.RandomState(1234)
class LR():
def __init__(self, alpha,lmbda,maxiter):
self.alpha = float(alpha) # learning rate for gradient ascent
self.lmbda = float(lmbda) # regularization constant
self.epsilon = 0.00001 # convergence measure
self.maxiter = int(maxiter) # the maximum number of iterations through the data before stopping
self.threshold = 0.5 # the class prediction threshold
# def getScore(self,fname,theta):
# f = open(fname, 'r')
# content = f.read()
# content = content.decode('utf-8').encode('ascii','ignore')
# content = content.replace('<br />','').lower()
# words = word_tokenize(content)
# words2 = [w for w in words if not w in stopwords.words('english')]
# score=0
# for word in words2:
# if word in theta:
# # print score
# score= score+theta[word]
# return score
# def cal_grad(self,fname,gwords,grad_input):
# f = open(fname, 'r')
# content = f.read()
# content = content.decode('utf-8').encode('ascii','ignore')
# content = content.replace('<br />','').lower()
# words = word_tokenize(content)
# words2 = [w for w in words if not w in stopwords.words('english')]
# score=0
# for word in words2:
# if word in gwords:
# gwords[word]= gwords[word]+grad_input
# else:
# gwords[word]=grad_input
# def grad_descent(self,files,theta,vfiles,iterations =30):
# size = len(files)
# learning = 0.01
# lamb = 0.1
# # print files
# gwords =defaultdict(int)
# for i in range(iterations):
# print "Iteration " , i
# for f in files:
# # print f
# score = self.getScore(f,theta)
# # print score
# prob = self.sigmoid(score)
# fname = str(f.split("/")[-1])
# rating = int(fname.split(".")[0].split("_")[1])
# y_i=0
# if rating <6 :
# y_i = 0
# else:
# y_i=1
# # print y_i
# grad_input = (prob - y_i)
# # print grad_input
# self.cal_grad(f,gwords,grad_input)
# # Update of parameters
# for word in gwords:
# if word in theta:
# theta[word] = theta[word] - ((learning*gwords[word]) /size) + lamb*theta[word]
# # else:
# # theta[word] = rng.uniform(high=1, low=-1) - (learning*(gwords[word]) /size)
# gwords.clear()
# # print theta
# print self.predict(vfiles,theta)
# def predicts(self,files,theta):
# correct_pred = 0.0
# total_pred = 0.0
# for fname in files:
# score = self.getScore(fname,theta)
# # print score
# fname = str(fname.split("/")[-1])
# rating = int(fname.split(".")[0].split("_")[1])
# if rating <6 and score <0:
# correct_pred = correct_pred+1
# if rating >6 and score >0:
# correct_pred = correct_pred+1
# total_pred = total_pred+1
# return correct_pred/total_pred
# def setup(self,theta,files):
# for fname in files:
# f = open(fname, 'r')
# content = f.read()
# content = content.decode('utf-8').encode('ascii','ignore')
# content = content.replace('<br />','').lower()
# words = word_tokenize(content)
# words2 = [w for w in words if not w in stopwords.words('english')]
# score=0
# for word in words2:
# if word not in theta:
# theta[word] = rng.uniform(high=1, low=0)
def sigmoid(self,x):
x= 1. / (1. + np.exp(-x))
return x
def getDataFiles(self,files,train, vocab , vocab_no):
rows = []
cols = []
data = []
pol = []
review_sum = count = tp = fp = fn = 0
folds = ['neg','pos']
# path = "../../Movies/edu-input-final/"
# files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.edus')]
for filename in files:
# fname = (filename.split(".edus"))[0]
f = open(filename, 'r')
content = f.read()
content = content.decode('utf-8').encode('ascii','ignore')
content = content.replace('<br />','').lower()
words = word_tokenize(content)
words2 = [w for w in words if not w in stopwords.words('english')]
cnt = Counter(words2)
for word in cnt:
if word not in vocab and train:
vocab[word] = vocab_no[0]
vocab_no[0] = vocab_no[0] + 1
if word in vocab:
rows.append(count)
cols.append(vocab[word])
data.append(cnt[word])
fname = str(filename.split("/")[-1])
rating = int(fname.split(".")[0].split("_")[1])
if rating <6:
pol.append(-1)
if rating >6 :
pol.append(1)
count = count + 1
mat = sci.sparse.csr_matrix((data,(rows,cols)), shape=(count,vocab_no[0])).todense()
return mat, pol
def fit(self, X, y,test_mat,test_pol):
"""
This function optimizes the parameters for the logistic regression classification model from training
data using learning rate alpha and regularization constant lmbda
@post: parameter(theta) optimized by gradient descent
"""
# X = self.add_ones(X_) # prepend ones to training set for theta_0 calculations
# initialize optimization arrays
self.n = X.shape[1] # the number of features
self.m = X.shape[0] # the number of instances
self.probas = np.zeros(self.m, dtype='float') # stores probabilities generated by the logistic function
self.theta = np.zeros(self.n, dtype='float') # stores the model theta
# iterate through the data at most maxiter times, updating the theta for each feature
# also stop iterating if error is less than epsilon (convergence tolerance constant)
print "iter | magnitude of the gradient"
for iteration in xrange(self.maxiter):
# calc probabilities
self.probas = self.get_proba(X)
print iteration
# calculate the gradient and update theta
print X.shape
gw = np.zeros(self.n, dtype='float')
# if y < 0:
# y=0
k = (1.0/self.m) * np.dot(X.T,(self.probas - y).T)
# print k.shape[0]
for i in range(k.shape[0]):
# print k[i,0]
gw[i]=k[i,0]
# g0 = gw[0] # save the theta_0 gradient calc before regularization
gw =gw + (self.lmbda * self.theta)/self.m # regularize using the lmbda term
# gw[0] = g0 # restore regularization independent theta_0 gradient calc
self.theta -= self.alpha * gw # update parameters
# calculate the magnitude of the gradient and check for convergence
loss = np.linalg.norm(gw)
if self.epsilon > loss:
break
print "Accuracy" , ":", self.compute_accuracy(test_pol,self.predict(test_mat))
print iteration, ":", loss
def get_proba(self, X):
return 1.0 / (1 + np.exp(- np.dot(X, self.theta)))
def predict_proba(self, X):
"""
Returns the set of classification probabilities based on the model theta.
@parameters: X - array-like of shape = [n_samples, n_features]
The input samples.
@returns: y_pred - list of shape = [n_samples]
The probabilities that the class label for each instance is 1 to standard output.
"""
# X_ = self.add_ones(X)
return self.get_proba(X)
def predict(self, X):
"""
Classifies a set of data instances X based on the set of trained feature theta.
@parameters: X - array-like of shape = [n_samples, n_features]
The input samples.
@returns: y_pred - list of shape = [n_samples]
The predicted class label for each instance.
"""
y_pred =[]
pred = self.predict_proba(X)
for i in range(pred.shape[1]):
proba =pred[0,i]
if proba >self.threshold:
y_pred.append(1)
else:
y_pred.append(-1)
# y_pred = [proba > self.threshold for proba in self.predict_proba(X)]
return y_pred
def add_ones(self, X):
# prepend a column of 1's to dataset X to enable theta_0 calculations
# print X.shape[0]
return np.hstack((np.zeros(shape=(X.shape[0],1), dtype='float') + 1, X))
def sigmoid_grad(self,f):
sig = sigmoid(f)
return sig * (1 - sig)
def compute_accuracy(self,y_test, y_pred):
"""
@returns: The precision of the classifier, (correct labels / instance count)
"""
correct = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
correct += 1
return float(correct) / len(y_test)
def savemodel(fname,D):
""" Save model into fname
"""
if not fname.endswith('.pickle.gz'):
fname = fname + '.pickle.gz'
# D = self.getparams()
with gzip.open(fname, 'w') as fout:
dump(D, fout)
print 'Save model into file {}'.format(fname)
def loadmodel( fname):
""" Load model from fname
"""
with gzip.open(fname, 'r') as fin:
D = load(fin)
return D
print 'Load model from file: {}'.format(fname)
if __name__ == '__main__':
path = "../../../Movies//review_polarity/txt_sentoken/pos/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
tfiles = files[0:300]
vfiles = files[950:]
path = "../../../Movies//review_polarity/txt_sentoken/neg/"
files = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
tfiles = tfiles + files[0:300]
vfiles = vfiles + files[950:]
path = "../../../Movies/Bigger-set//"
tfiles = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
path = "../../../Movies/edu-input-final/"
vfiles = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('.txt')]
alpha=1
lmbda=.1
maxiter=200
lr = LR(alpha,lmbda,maxiter)
theta = defaultdict(int)
vocab = defaultdict()
vocab_no = Counter()
train_mat,train_pol = lr.getDataFiles(tfiles,True,vocab,vocab_no)
test_mat,test_pol = lr.getDataFiles(vfiles,False,vocab,vocab_no)
# D = {"tdata":train_mat, "tpos":train_pol, "vdata":test_mat,"vpos":test_pol}
# savemodel("data.pickle.gz",D)
D =loadmodel("data.pickle.gz")
# train_mat,train_pol = D["tdata"] ,D["tpos"]
prob_train =[]
for i in range(len(train_pol)):
if train_pol[i] < 0:
prob_train.append(0)
else:
prob_train.append(1)
test_mat,test_pol = D["vdata"] , D["vpos"]
lr.fit(train_mat[0:50],prob_train[0:50],test_mat,test_pol)
y_pred = lr.predict(test_mat)
print lr.compute_accuracy(test_pol,y_pred)
# print len(test_pol)
# print y_pred
# lr.setup(theta,tfiles)
# lr.grad_descent(tfiles,theta,vfiles)
# print lr.predict(vfiles,theta)
| dd09af2d476ad23880f0354dff822f869eb5ff34 | [
"Markdown",
"Python"
] | 8 | Python | parry2403/R2N2 | c01253cf9bde553ed54ceca08be1dfe6db3a9578 | 1ea8c839ee4daa68f6ccd038ba0687a4cc010d69 |
refs/heads/master | <file_sep>require('rspec')
require('parcels') #requires lib file that is .rb
describe() do
it("calculates shipping cost for a simple percel") do #doesnt matter english explination
parcel = Parcel.new(1,2,3,4)
expect(parcel.ship()).to(eq(16))
end
end
<file_sep># this is where you put the code
class Parcel
define_method(:initialize) do |height, width, depth, weight, speed|
height = height
width = width
depth = depth
@weight = weight
@volume = height * width * depth
@speed = speed
end
define_method(:ship) do
shipping_cost= (@weight * (@volume-2))
if (@speed == 1 || @speed == 2)
shipping_cost += 10
else
shipping_cost += 5
end
end
end
<file_sep>require('rspec')
require('./lib/parcels')
require('sinatra')
require('sinatra/reloader')
also_reload('lib/**/*.rb')
get('/') do
erb(:index)
end
get('/ship') do#place form 'action' in the get parentheses
@weight = params.fetch('weight').to_i
@height = params.fetch('height').to_i
@width = params.fetch('width').to_i
@depth = params.fetch('depth').to_i
@speed = params.fetch('speed').to_i
parcel = Parcel.new(@height,@width,@depth,@weight,@speed)
@result = parcel.ship()
erb(:result)#this is the page where you want your method to display
end
| fd4456cbc8ea6fd04f17d3fad4a2a8b914a13b50 | [
"Ruby"
] | 3 | Ruby | n-powell/shippingRuby | 9744abf20ebc3204b77848eccd021c49b7be6aa2 | 2b912a5b5c1933cd2acc83659dbede5e45211ac9 |
refs/heads/master | <repo_name>prasad-joshi/data-verification<file_sep>/main.cc
#include <iostream>
#include <cassert>
#include <gflags/gflags.h>
#include "io_generator.h"
#include "disk_io.h"
using std::vector;
using std::pair;
using std::string;
using std::cout;
using std::endl;
DEFINE_string(disk, "/dev/null", "Comma seperated list of block devices for IO verification");
DEFINE_int32(iodepth, 32, "Number of concurrent IOs");
DEFINE_int32(percent, 100, "Percent of block device to use for IOs");
DEFINE_string(blocksize, "4096:40,8192:40", "Typical block sizes for IO.");
DEFINE_string(runtime, "1h", "runtime in (s)seconds/(m)minutes/(h)hours/(d)days");
DEFINE_string(logpath, "/tmp/", "Log directory path");
vector<string> split(const string &str, char delim) {
std::vector<string> tokens;
size_t s = 0;
size_t e = 0;
while ((e = str.find(delim, s)) != string::npos) {
if (e != s) {
tokens.push_back(str.substr(s, e - s));
s = e + 1;
}
}
if (e != s) {
tokens.push_back(str.substr(s));
}
return tokens;
}
void bytesToHumanReadable(uint64_t nbytes, uint64_t &valp, string &unitp) {
vector<string> units = {
"B",
"KB",
"MB",
"GB",
"TB",
};
for (auto i = 0; i < 4; i++) {
auto t = nbytes;
nbytes >>= 10;
if (nbytes == 0) {
valp = t;
unitp = units[i];
return;
}
}
valp = nbytes;
unitp = "TB";
}
int main(int argc, char *argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
/* check block sizes */
auto tokens = split(FLAGS_blocksize, ',');
if (!tokens.size()) {
throw std::invalid_argument("Block sizes not given.");
}
auto tp = 0;
vector<pair<uint32_t, uint8_t>> sizes;
for (auto &t : tokens) {
auto e = t.find(':');
if (e == string::npos) {
cout << "Invalid block size " << t << endl;
continue;
}
auto bs = std::stoul(t.substr(0, e));
auto p = std::stoul(t.substr(e+1));
if (!bs || !p || bs % 512 != 0 || p > 100) {
cout << "Invalid block size " << t << endl;
continue;
}
sizes.push_back(std::make_pair(bs>>9, p));
tp += p;
}
if (!sizes.size()) {
throw std::invalid_argument("Block sizes not given.");
} else if (tp > 100) {
throw std::invalid_argument("Invalid Blocksizes.\n");
}
/* check IO Depth */
if (FLAGS_iodepth <= 0 || FLAGS_iodepth > 512) {
throw std::invalid_argument("iodepth > 0 and iodepth < 512");
}
/* check percentage */
if (FLAGS_percent <= 0 || FLAGS_percent > 100) {
throw std::invalid_argument("percent > 0 and percent < 100");
}
/* check runtime */
auto m = 1ull;
auto &c = FLAGS_runtime.back();
switch (c) {
case 'd':
case 'D':
m *= 24;
case 'h': /* fall through */
case 'H':
m *= 60;
case 'm': /* fall through */
case 'M':
m *= 60;
case 's': /* fall through */
case 'S':
m *= 1;
break;
default:
auto d = '9' - c;
if (d < 0 || d > 9) {
throw std::invalid_argument("Invalid Runtime");
}
m *= 1;
}
double runtime;
try {
runtime = std::stod(FLAGS_runtime);
if (errno == ERANGE || runtime == 0.0) {
throw std::invalid_argument("stoul");
}
} catch (std::exception &e) {
throw std::invalid_argument("Invalid Runtime");
}
runtime *= m;
/* constuct disk object */
disk d1(FLAGS_disk, FLAGS_percent, sizes, FLAGS_iodepth, (uint64_t)runtime);
/* print some information */
cout << "Disk " << FLAGS_disk << endl;
cout << "Disk size in sectors " << d1.nsectors() << endl;
cout << "Number of sectors for IOs " << d1.ioNSectors() << endl;
for (auto &s : sizes) {
cout << "Block Size = " << (s.first << 9) << " " << (int) s.second << "%\n";
}
cout << "IODepth " << FLAGS_iodepth << endl;
cout << "Runtime " << runtime << " seconds\n";
d1.verify();
uint64_t nr, nw, nbr, nbw;
d1.getStats(&nr, &nw, &nbr, &nbw);
uint64_t r;
string ur;
bytesToHumanReadable(nbr, r, ur);
uint64_t w;
string uw;
bytesToHumanReadable(nbw, w, uw);
cout << endl;
cout << "Total IOs " << nr + nw << endl;
cout << "Read (Verification) IOs " << nr << " Read (Verified) Bytes " << nbr << " (" << r << ur << ")" << endl;
cout << "Write IOs " << nw << " Wrote Bytes " << nbw << " (" << w << uw << ")" << endl;
return 0;
}
<file_sep>/disk_io.h
#ifndef __DISK_IO_H__
#define __DISK_IO_H__
#include <cstdint>
#include <string>
#include <memory>
#include <set>
#include <vector>
#include <atomic>
#include <utility>
#include <mutex>
#include <libaio.h>
#include <event.h>
#include <folly/init/Init.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/AsyncTimeout.h>
#include "io_generator.h"
#include "zipf.h"
#include "AsyncIO.h"
#include "block_trace.h"
#define MIN_TO_SEC(min) ((min) * 60)
#define SEC_TO_MILLI(sec) ((sec) * 1000)
#define MIN_TO_MILLI(min) (SEC_TO_MILLI(MIN_TO_SEC((min))))
#define MIN(n1, n2) ((n1) <= (n2) ? (n1) : (n2))
using std::string;
using std::set;
using std::vector;
using std::shared_ptr;
using std::pair;
using std::unique_ptr;
using namespace folly;
using TimeOutCB = std::function<void(void *cbdata)>;
struct Corruption: public std::runtime_error {
uint64_t sector;
uint16_t nsectors;
string readLine;
string pattern;
Corruption(uint64_t sector_, uint16_t nsectors_, const string &readline_, const string &pattern_) :
sector(sector_), nsectors(nsectors_), readLine(readline_), pattern(pattern_),
std::runtime_error("Corruption") {
}
};
enum class IOMode {
WRITE,
VERIFY,
};
class range {
public:
uint64_t sector;
uint32_t nsectors;
range(uint64_t sect, uint32_t nsect) {
sector = sect;
nsectors = nsect;
}
range(const range &r) {
this->sector = r.sector;
this->nsectors = r.nsectors;
}
void operator = (const range &r) {
this->sector = r.sector;
this->nsectors = r.nsectors;
}
range(): range(0, 0) {}
uint64_t end_sector(void) const {
return this->sector + this->nsectors - 1;
}
uint64_t start_sector(void) const {
return this->sector;
}
bool operator< (const range &rhs) const {
uint64_t le = this->end_sector();
// std::cout << le << "<" << rhs.sector << " " << (le < rhs.sector) << std::endl;
return le < rhs.sector;
}
};
class IO {
public:
range r;
string pattern;
int16_t pattern_start;
public:
IO(uint64_t sect, uint32_t nsec, const string &pattern, int16_t pattern_start);
size_t size();
uint64_t offset();
};
typedef std::shared_ptr<IO> IOPtr;
struct IOCompare {
using is_transparent = void;
bool operator() (const IOPtr &a, const IOPtr &b) const {
return a->r < b->r;
}
bool operator() (const IOPtr &a, const range &b) const {
return a->r < b;
}
bool operator() (const range &a, const IOPtr &b) const {
return a < b->r;
}
};
class disk {
private:
string path_;
uint64_t size;
uint64_t sectors_;
int fd;
uint16_t iodepth_;
uint16_t percent_;
unique_ptr<io_generator> iogen;
TraceLog trace_;
private:
folly::EventBase base;
AsyncIO asyncio;
std::mutex lock;
set<IOPtr, IOCompare> ios;
vector<pair<range, bool>> writeIOsSubmitted;
protected:
void setIOMode(IOMode mode);
int writesSubmit(uint64_t nreads);
int readsSubmit(uint64_t nreads);
void setRuntimeTimer();
ManagedBuffer getIOBuffer(size_t size);
ManagedBuffer prepareIOBuffer(size_t size, const string &pattern);
bool patternCompare(uint64_t s, uint16_t ns, const char *const bufp,
size_t size, const string &pattern, int16_t start);
bool readDataVerify(const char *const data, uint64_t sector, uint16_t nsectors);
void patternCreate(uint64_t sector, uint16_t nsectors, string &pattern);
void writeDone(uint64_t sector, uint16_t nsectors, const string &pattern, const int16_t pattern_start);
void addWriteIORange(uint64_t sector, uint16_t nsectors);
pair<range, bool> removeWriteIORange(uint64_t sector, uint16_t nsectors);
public:
class TimeoutWrapper : public AsyncTimeout {
private:
void *cbdatap_;
TimeOutCB cb_;
public:
TimeoutWrapper(TimeoutManager *mp, TimeOutCB cb, void *cbdatap) :
AsyncTimeout(mp), cb_(cb), cbdatap_(cbdatap) {
}
void timeoutExpired() noexcept {
cb_(cbdatap_);
}
};
disk(string path, uint16_t percent, vector<pair<uint32_t, uint8_t>> sizes,
uint16_t iodepth, uint64_t runtime);
~disk();
void switchIOMode();
int verify();
void writeDone(uint64_t sector, uint16_t nsectors);
void readDone(const char *const bufp, uint64_t sector, uint16_t nsectors);
int iosSubmit(uint64_t nios);
// void print_ios(void);
uint64_t getStats(uint64_t *nreadsp, uint64_t *nwritesp, uint64_t *nreadBytesp, uint64_t *nwroteBytes) {
*nreadsp = asyncio.getNReads();
*nwritesp = asyncio.getNWrites();
*nreadBytesp = asyncio.getBytesRead();
*nwroteBytes = asyncio.getBytesWrote();
}
uint64_t nsectors() {
return sectors_;
}
uint64_t ioNSectors() {
return sectors_ * percent_ / 100;
}
int disk_fd(void) {
return fd;
}
void runtimeExpired();
bool runInEventBaseThread(folly::Function<void()>);
private:
IOMode mode_;
unique_ptr<TimeoutWrapper> ioModeSwitchTimer_;
bool modeSwitched_;
uint64_t runtime_;
unique_ptr<TimeoutWrapper> runtimeTimer_;
bool runtimeComplete_ = false;
public: /* some test APIs */
void cleanupEverything();
void testReadSubmit(uint64_t s, uint16_t ns);
void testWriteSubmit(uint64_t s, uint16_t ns);
void testWriteOnceReadMany();
void testOverWrite();
void testBlockTrace(const string &file);
void testNO1();
void testNO2();
void testNoOverlap();
void testExactOverwrite();
void testTailExactOverwrite();
void testHeadExactOverwrite();
void testDoubleSplit();
void testTailOverwrite();
void testHeadOverwrite();
void testCompleteOverwrite();
void testHeadSideSplit();
void testMid();
void testTailSideSplit();
void testSectorReads();
void _testSectorReads(uint64_t sector, uint16_t nsectors);
void test();
};
#endif
<file_sep>/block_trace.h
#ifndef __BLOCK_TRACE_LOG_H__
#define __BLOCK_TRACE_LOG_H__
#include <fstream>
#include <ctime>
using std::string;
using std::time_t;
using std::fstream;
struct block_trace {
time_t timestamp_;
uint64_t sector_;
uint16_t nsectors_;
uint8_t read_:1;
uint8_t pad_[5];
block_trace() {
}
block_trace(time_t &t, uint64_t sector, uint16_t nsectors, bool read) :
timestamp_(t), sector_(sector), nsectors_(nsectors), read_(read) {
}
};
class TraceLog {
private:
string logPrefix_;
uint32_t current_;
string curLogFile_;
int curLogFD_;
fstream curFS_;
private:
#if 0
void open();
void close();
void compress();
#endif
public:
TraceLog(string logPrefix);
~TraceLog();
void addTraceLog(uint64_t sector, uint16_t nsectors, bool read);
// std::vector<block_trace> searchTraceLog(uint64_t sector, uint16_t nsectors);
void dumpTraceLog(uint64_t sector, uint16_t nsectors);
};
#endif
<file_sep>/disk_io.cc
#include <iostream>
#include <string>
#include <memory>
#include <future>
#include <set>
#include <vector>
#include <atomic>
#include <utility>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <unistd.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <event.h>
#include <sys/eventfd.h>
#include <libaio.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventHandler.h>
#include <folly/io/async/AsyncTimeout.h>
#include "disk_io.h"
using std::string;
using std::unique_ptr;
using std::shared_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using std::runtime_error;
using namespace folly;
static inline uint64_t sector_to_byte(uint64_t sector) {
return sector << 9;
}
static inline uint64_t bytes_to_sector(uint64_t bytes) {
return bytes >> 9;
}
IO::IO(uint64_t sect, uint32_t nsec, const string &pattern, int16_t pattern_start):
r(sect, nsec) {
this->pattern = pattern;
this->pattern_start = pattern_start;
}
size_t IO::size() {
return sector_to_byte(r.nsectors);
}
uint64_t IO::offset() {
return sector_to_byte(r.sector);
}
disk::disk(string path, uint16_t percent, vector<pair<uint32_t, uint8_t>> sizes,
uint16_t iodepth, uint64_t runtime) :
asyncio(iodepth), path_(path), percent_(percent), iodepth_(iodepth),
runtime_(runtime), modeSwitched_(false), fd(-1),
trace_("/tmp/log.dat") {
fd = open(path.c_str(), O_RDWR | O_DIRECT);
if (fd < 0) {
throw runtime_error("Could not open file " + path);
}
struct stat sb;
auto rc = fstat(fd, &sb);
if (rc < 0 || !S_ISBLK(sb.st_mode)) {\
throw runtime_error(path + " is not a block device.");
}
assert(rc >= 0 && S_ISBLK(sb.st_mode));
uint64_t sz;
rc = ioctl(fd, BLKGETSIZE64, &sz);
if (rc < 0 || sz == 0) {
throw runtime_error("unable to find size of device " + path);
}
assert(sz != 0);
this->size = sz;
this->sectors_ = bytes_to_sector(sz);
auto ns = this->sectors_ * percent / 100;
this->iogen = std::make_unique<io_generator>(0, ns, sizes);
}
disk::~disk() {
if (this->fd > 0) {
close(this->fd);
}
}
void disk::patternCreate(uint64_t sect, uint16_t nsec, string &pattern) {
pattern = "<" + std::to_string(sect) + "," + std::to_string(nsec) + ">";
}
ManagedBuffer disk::prepareIOBuffer(size_t size, const string &pattern) {
auto bufp = asyncio.getIOBuffer(size);
assert(bufp);
char *bp = bufp.get();
/* fill pattern in the buffer */
const char *const p = pattern.c_str();
auto len = pattern.length();
auto i = size / len;
assert(i > 0);
while (i--) {
std::memcpy(bp, p, len);
bp += len;
}
i = size - ((size/len) * len);
std::memcpy(bp, p, i);
return std::move(bufp);
}
ManagedBuffer disk::getIOBuffer(size_t size) {
return asyncio.getIOBuffer(size);
}
void disk::addWriteIORange(uint64_t sector, uint16_t nsectors) {
range nr(sector, nsectors);
bool c = true;
for (auto &it : writeIOsSubmitted) {
if (nr < it.first || it.first < nr) {
/* not equal */
continue;
}
c = false;
it.second = false;
}
pair<range, bool> p(nr, c);
writeIOsSubmitted.push_back(p);
}
pair<range, bool> disk::removeWriteIORange(uint64_t sector, uint16_t nsectors) {
range nr(sector, nsectors);
pair<range, bool> res;
bool found = false;
auto it = writeIOsSubmitted.begin();
while (it != writeIOsSubmitted.end()) {
if (it->first.sector == sector && it->first.nsectors == nsectors) {
res = *it;
writeIOsSubmitted.erase(it);
found = true;
break;
}
it++;
}
assert(found == true);
return res;
}
int disk::writesSubmit(uint64_t nwrites) {
struct iocb *ios[nwrites];
struct iocb cbs[nwrites];
struct iocb *cbp;
uint64_t s;
uint64_t ns;
size_t sz;
uint64_t o;
for (auto i = 0; i < nwrites; i++) {
iogen->next_io(&s, &ns);
assert(ns >= 1 && s <= sectors_ && s+ns <= sectors_);
// cout << "W " << s << " " << ns << endl;
string p;
patternCreate(s, ns, p);
sz = sector_to_byte(ns);
o = sector_to_byte(s);
auto bufp = prepareIOBuffer(sz, p);
cbp = &cbs[i];
ios[i] = cbp;
asyncio.pwritePrepare(cbp, fd, std::move(bufp), sz, o);
addWriteIORange(s, ns);
trace_.addTraceLog(s, ns, false);
}
auto rc = asyncio.pwrite(ios, nwrites);
assert(rc == nwrites);
if (rc < 0) {
throw runtime_error("io_submit failed " + string(strerror(-rc)));
}
return 0;
}
int disk::readsSubmit(uint64_t nreads) {
struct iocb *ios[nreads];
struct iocb cbs[nreads];
struct iocb *cbp;
uint64_t s;
uint64_t ns;
size_t sz;
uint64_t o;
for (auto i = 0; i < nreads; i++) {
iogen->next_io(&s, &ns);
assert(ns >= 1 && s <= sectors_ && s+ns <= sectors_);
// cout << "R " << s << " " << ns << endl;
sz = sector_to_byte(ns);
o = sector_to_byte(s);
auto bufp = getIOBuffer(sz);
cbp = &cbs[i];
ios[i] = cbp;
asyncio.preadPrepare(cbp, fd, std::move(bufp), sz, o);
trace_.addTraceLog(s, ns, true);
}
auto rc = asyncio.pread(ios, nreads);
assert(rc == nreads);
if (rc < 0) {
throw runtime_error("io_submit failed " + string(strerror(-rc)));
}
return 0;
}
int disk::iosSubmit(uint64_t nios) {
int rc;
if (modeSwitched_ == true) {
/* wait till all submitted IOs are complete */
if (asyncio.getPending() != 0) {
return 0;
}
nios = iodepth_;
modeSwitched_ = false;
}
if (runtimeComplete_ == true) {
if (asyncio.getPending() == 0) {
base.terminateLoopSoon();
}
return 0;
}
assert(modeSwitched_ == false);
switch (mode_) {
case IOMode::WRITE:
rc = writesSubmit(nios);
break;
case IOMode::VERIFY:
rc = readsSubmit(nios);
break;
}
return rc;
}
bool disk::patternCompare(uint64_t sector, uint16_t nsectors,
const char *const bufp, size_t size, const string &pattern,
int16_t start) {
assert(bufp && pattern.length() && pattern.length() >= start &&
size > pattern.length() && size >= 512 && pattern.length() < 512);
const char *const p = pattern.c_str();
const char *bp = bufp;
auto len = pattern.length();
auto i = size / len;
assert(i > 0);
while (i--) {
/* fast path */
auto cl = len - start;
auto rc = std::memcmp(bp, p + start, cl);
if (rc != 0) {
/* corruption */
string r;
for (auto x = 0; x < cl; x++) {
r += *(bp + x);
}
throw Corruption(sector, nsectors, r, pattern);
return true;
}
bp += cl;
start = 0;
}
i = size - ((size/len) * len);
auto rc = std::memcmp(bp, p, i);
if (rc != 0) {
/* corruption */
string r(bp);
throw Corruption(sector, nsectors, r, pattern);
return true;
}
return false;
}
bool disk::readDataVerify(const char *const data, uint64_t sector, uint16_t nsectors) {
range r(sector, nsectors);
auto io = ios.find(r);
if (io == ios.end()) {
/* case 0: <sector, nsector> are never written before */
return false;
}
auto rios = r.start_sector();
auto rioe = r.end_sector();
auto oios = (*io)->r.start_sector();
auto oioe = (*io)->r.end_sector();
const char *vbufp = data; /* verification buffer pointer */
auto vssec = sector; /* verfification start sector */
auto vnsec = nsectors; /* number of sectors to verify */
if (rios < oios) {
/*
* CASE 1:
*
* Read IOs start sector is before found IOs start sector. Since this
* part is not part of IOS set, it should never have data corruption.
*/
auto s = rios;
auto ns = oios - s;
auto c = readDataVerify(vbufp, s, ns);
if (c == true) {
/* corruption */
assert(0);
}
assert(vnsec > ns);
vbufp += sector_to_byte(ns);
vssec = oios;
vnsec = vnsec - ns;
}
assert(vnsec > 0);
/*
* CASE 2:
*
*/
auto s = vssec;
auto vend = MIN(oioe, rioe);
auto ns = vend - s + 1;
assert(ns <= vnsec);
auto d = vssec - oios;
auto ps = (sector_to_byte(d) + (*io)->pattern_start) % (*io)->pattern.length();
auto c = patternCompare(s, ns, vbufp, sector_to_byte(ns), (*io)->pattern, ps);
if (c == true) {
/* corruption */
assert(0);
} else if (vnsec <= ns) {
/* data has been verified - no corruption */
assert(vnsec - ns == 0);
return false;
}
/* CASE 3: */
vssec = vend + 1;
vnsec -= ns;
vbufp += sector_to_byte(ns);
return readDataVerify(vbufp, vssec, vnsec);
}
void disk::readDone(const char *const bufp, uint64_t sector, uint16_t nsectors) {
try {
auto corruption = readDataVerify(bufp, sector, nsectors);
if (corruption) {
assert(0);
}
} catch(Corruption &c) {
cout << "Data Corruption\n";
cout << "Read(sector = " << c.sector << ", nsectors=" << c.nsectors << ")\n";
cout << "Expected Pattern = " << c.pattern << endl;
cout << "Read Pattern = " << c.readLine << endl;
trace_.dumpTraceLog(c.sector, c.nsectors);
base.terminateLoopSoon();
}
}
void disk::writeDone(uint64_t sector, uint16_t nsectors) {
auto pr = removeWriteIORange(sector, nsectors);
if (pr.second == false) {
/*
* TODO: improve this
*
* IO on same range of sectors was submitted simultaneously. There is
* no simple way to verify data. At the moment, we remove all traces
* of the related IOs.
*/
while (1) {
auto io = ios.find(pr.first);
if (io == ios.end()) {
break;
}
ios.erase(io);
}
assert(ios.find(pr.first) == ios.end());
return;
}
string p;
patternCreate(sector, nsectors, p);
writeDone(sector, nsectors, p, 0);
}
void disk::writeDone(uint64_t sector, uint16_t nsectors, const string &pattern, const int16_t pattern_start) {
range r(sector, nsectors);
auto nios = r.start_sector(); /* new IO start sector */
auto nioe = r.end_sector(); /* new IO end sector */
do {
auto io = ios.find(r);
if (io == ios.end()) {
auto newiop = make_shared<IO>(sector, nsectors, pattern, pattern_start);
ios.insert(newiop);
break;
}
/* overlapping IO range found */
/*
std::cout << "Trying to insert " << sector << " " << nsectors << " ";
std::cout << "preset " << (*io)->r.sector << " " << (*io)->r.nsectors << std::endl;
*/
auto oios = (*io)->r.start_sector(); /* old IO start sector */
auto oions = (*io)->r.nsectors; /* old IO nsectors */
auto oioe = (*io)->r.end_sector(); /* old IO end sector */
auto opattern = (*io)->pattern;
auto ops = (*io)->pattern_start;
if (oios == nios && oioe == nioe) {
/* exact match - only update pattern */
(*io)->pattern = pattern;
(*io)->pattern_start = 0;
break;
}
ios.erase(io);
if (nios <= oios && nioe >= oioe) {
/*
* old is too small - only delete it
*
* For example:
* New IO --> sector 100, nsectors 8
* Old IO --> sector 101, nsectors 2
*
* The new IO completely overrides old IO
* */
continue;
}
if (oios <= nios) {
if (oioe <= nioe) {
/*
* old IO sector < new IO sector and old IO end <= new IO end
*
* for example:
* CASE1: OLD IO (16, 16) and NEW IO(24, 16)
* 16 31
* OLD IO |--------|
* 24 39
* NEW IO |---------|
*
* CASE2: OLD IO (32, 32) and NEW IO (56, 8)
* 32 63
* OLD IO |----------------|
* 56 63
* NEW IO |-----|
*
* In both the case old io's end is modified and new io is inserted
*/
oioe = nios - 1;
auto ons = oioe - oios + 1;
assert(ons != 0);
writeDone(oios, ons, opattern, ops);
} else {
if (oios != nios) {
auto o1s = oios;
auto o1ns = nios - o1s;
auto o1b = opattern;
assert(o1s + o1ns == nios);
writeDone(o1s, o1ns, opattern, ops);
}
auto o2s = nioe + 1;
auto d = o2s - oios;
auto o2ns = oions - d;
int16_t ps = (sector_to_byte(d) + ops) % opattern.size();
writeDone(o2s, o2ns, opattern, ps);
}
} else {
/*
* old IO ==> sector 32, nsectors 16 i.e. sectors 32 to 47
* new IO ==> sector 24, nsectors 16 i.e. sectors 24 to 39
*
* change old IO's start to 40 and nsectors to 8
* old IO's pattern remains as it is, however pattern start may change
*/
auto d = r.end_sector() - oios + 1;
assert(d != 0);
auto ns = oions - d; /* calculate nsectors */
auto ss = oios + d; /* start sector number */
assert(r.sector + r.nsectors == ss);
int16_t ps = (sector_to_byte(d) + ops) % opattern.size(); /* pattern start */
writeDone(ss, ns, opattern, ps);
}
} while (1);
}
void ioCompleted(void *cbdata, ManagedBuffer bufp, size_t size, uint64_t offset, ssize_t result, bool read) {
assert(cbdata && bufp && result == size && size >= sector_to_byte(1));
disk *diskp = reinterpret_cast<disk *>(cbdata);
uint64_t sector = bytes_to_sector(offset);
uint16_t nsectors = bytes_to_sector(size);
assert(nsectors >= 1);
if (read == true) {
char *bp = bufp.get();
diskp->readDone(bp, sector, nsectors);
} else {
diskp->writeDone(sector, nsectors);
}
}
void nioCompleted(void *cbdata, uint16_t nios) {
assert(cbdata);
disk *diskp = reinterpret_cast<disk *>(cbdata);
diskp->iosSubmit(nios);
}
bool disk::runInEventBaseThread(folly::Function<void()> func) {
return base.runInEventBaseThread(std::move(func));
}
/* IO mode and it's timer */
static void switchIOModeTCB(void *cbdp) {
disk *dp = reinterpret_cast<disk *>(cbdp);
dp->switchIOMode();
}
void disk::setIOMode(IOMode mode) {
this->mode_ = mode;
this->ioModeSwitchTimer_ = std::make_unique<TimeoutWrapper>(&base, switchIOModeTCB, this);
this->ioModeSwitchTimer_->scheduleTimeout(MIN_TO_MILLI(1));
}
void disk::switchIOMode() {
assert(modeSwitched_ == false);
IOMode m;
switch (this->mode_) {
case IOMode::WRITE:
m = IOMode::VERIFY;
cout << "Setting IO Mode to VERIFY\n";
break;
case IOMode::VERIFY:
m = IOMode::WRITE;
cout << "Setting IO Mode to WRITE\n";
break;
}
modeSwitched_ = true;
base.runInEventBaseThread([dpCap = this, mode = m] () {
dpCap->setIOMode(mode);
});
}
/* runtime and it's timer handling */
static void runtimeExpiredTCB(void *cbdp) {
disk *dp = reinterpret_cast<disk *>(cbdp);
dp->runtimeExpired();
}
void disk::runtimeExpired() {
runtimeComplete_ = true;
if (asyncio.getPending() == 0) {
base.terminateLoopSoon();
}
}
void disk::setRuntimeTimer() {
assert(runtimeComplete_ == false);
runtimeTimer_ = std::make_unique<TimeoutWrapper>(&base, runtimeExpiredTCB, this);
runtimeTimer_->scheduleTimeout(SEC_TO_MILLI(runtime_));
}
int disk::verify() {
asyncio.init(&base);
asyncio.registerCallback(ioCompleted, nioCompleted, this);
setIOMode(IOMode::WRITE);
setRuntimeTimer();
auto rc = iosSubmit(iodepth_);
assert(rc == 0);
base.loopForever();
// rc = event_base_dispatch(ebp);
}
void disk::cleanupEverything() {
ios.erase(ios.begin(), ios.end());
}
void disk::testReadSubmit(uint64_t s, uint16_t ns) {
struct iocb *ios[1];
struct iocb cb;
size_t sz;
uint64_t o;
sz = sector_to_byte(ns);
o = sector_to_byte(s);
auto bufp = getIOBuffer(sz);
ios[0] = &cb;
asyncio.preadPrepare(&cb, fd, std::move(bufp), sz, o);
auto rc = asyncio.pread(ios, 1);
assert(rc == 1);
}
void disk::testWriteSubmit(uint64_t s, uint16_t ns) {
struct iocb *ios[1];
struct iocb cb;
size_t sz;
uint64_t o;
string p;
patternCreate(s, ns, p);
sz = sector_to_byte(ns);
o = sector_to_byte(s);
auto bufp = prepareIOBuffer(sz, p);
ios[0] = &cb;
asyncio.pwritePrepare(&cb, fd, std::move(bufp), sz, o);
auto rc = asyncio.pwrite(ios, 1);
assert(rc == 1);
}
void disk::testWriteOnceReadMany() {
testWriteSubmit(512, 16);
base.loopOnce();
for (auto ns = 50; ns != 0; ns--) {
testReadSubmit(500, ns);
base.loopOnce();
}
testWriteSubmit(100, 9);
base.loopOnce();
for (auto ns = 50; ns != 0; ns--) {
testReadSubmit(100, ns);
base.loopOnce();
}
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testOverWrite() {
cleanupEverything();
assert(ios.size() == 0);
for (auto step = 1; step < 16; step++) {
for (int16_t ns = 16, c = 0; ns > 0; ns-=step, c++) {
testWriteSubmit(512, ns);
base.loopOnce();
assert(ios.size() == c+1);
testReadSubmit(500, 50);
base.loopOnce();
}
cleanupEverything();
assert(ios.size() == 0);
}
assert(ios.size() == 0);
for (auto step = 1; step < 160; step++) {
for (int16_t ns = 160, c = 0; ns > 0; ns-=step, c++) {
testWriteSubmit(100, ns);
base.loopOnce();
assert(ios.size() == c+1);
testReadSubmit(98, 200);
base.loopOnce();
}
cleanupEverything();
assert(ios.size() == 0);
}
assert(ios.size() == 0);
}
void disk::testNO2() {
/*
W 8081398 1404
W 8081398 909
W 8081398 1093
R 8082135 8
*/
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(8081398, 1404);
base.loopOnce();
assert(ios.size() == 1);
#if 0
cout << "1\n";
for (auto &io : ios) {
cout << io->r.sector << " " << io->r.nsectors << " " << io->pattern << " " << io->pattern_start << endl;
}
#endif
testWriteSubmit(8081398, 909);
base.loopOnce();
assert(ios.size() == 2);
testWriteSubmit(8081398, 1093);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(8082135, 8);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testNO1() {
cleanupEverything();
assert(ios.size() == 0);
const uint64_t SECTOR = 1783797;
testWriteSubmit(SECTOR, 1207);
base.loopOnce();
assert(ios.size() == 1);
for (auto &io : ios) {
string p;
patternCreate(SECTOR, 1207, p);
assert(io->r.sector == SECTOR && io->r.nsectors == 1207 &&
io->pattern == p && io->pattern_start == 0);
}
auto ns = 8;
auto sz = sector_to_byte(ns);
testWriteSubmit(SECTOR, ns);
base.loopOnce();
assert(ios.size() == 2);
int c = 0;
for (auto &io : ios) {
if (c == 0) {
string p;
patternCreate(SECTOR, ns, p);
assert(io->r.sector == SECTOR && io->r.nsectors == ns &&
io->pattern == p && io->pattern_start == 0);
} else {
string p;
patternCreate(SECTOR, 1207, p);
auto ps = sz % p.length();
assert(io->r.sector == SECTOR+ns && io->r.nsectors == 1207-ns &&
io->pattern == p && io->pattern_start == ps);
}
c++;
}
auto ns1 = 16;
auto sz1 = sector_to_byte(ns1);
testWriteSubmit(SECTOR, 16);
base.loopOnce();
assert(ios.size() == 2);
c = 0;
for (auto &io : ios) {
if (c == 0) {
string p;
patternCreate(SECTOR, ns1, p);
assert(io->r.sector == SECTOR && io->r.nsectors == ns1 &&
io->pattern == p && io->pattern_start == 0);
} else {
string p;
patternCreate(SECTOR, 1207, p);
auto ps = sz1 % p.length();
assert(io->r.sector == SECTOR+ns1 && io->r.nsectors == 1207-ns1 &&
io->pattern == p && io->pattern_start == ps);
}
c++;
}
testReadSubmit(1783797, 64);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testNoOverlap() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 3000);
base.loopOnce();
testWriteSubmit(2000, 500);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(1000, 3000);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testExactOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testTailExactOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1300, 200);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(1000, 500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testHeadExactOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1000, 100);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(1000, 500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testDoubleSplit() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1200, 100);
base.loopOnce();
assert(ios.size() == 3);
testReadSubmit(1000, 500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testTailOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1300, 500);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(1000, 1000);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testHeadOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(800, 500);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(500, 2000);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testCompleteOverwrite() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 100);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
testWriteSubmit(1000, 500);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(1000, 500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testHeadSideSplit() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 2000);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1000, 100);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1000, 200);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1300, 200);
base.loopOnce();
assert(ios.size() == 4);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1600, 600);
base.loopOnce();
assert(ios.size() == 6);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1400, 600);
base.loopOnce();
assert(ios.size() == 6);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1100, 20);
base.loopOnce();
assert(ios.size() == 8);
testReadSubmit(800, 2500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testMid() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 2000);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1500, 50);
base.loopOnce();
assert(ios.size() == 3);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1300, 350);
base.loopOnce();
assert(ios.size() == 3);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1200, 500);
base.loopOnce();
assert(ios.size() == 3);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1600, 10);
base.loopOnce();
assert(ios.size() == 5);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1350, 300);
base.loopOnce();
assert(ios.size() == 5);
testReadSubmit(800, 2500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::testTailSideSplit() {
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(1000, 2000);
base.loopOnce();
assert(ios.size() == 1);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(2500, 500);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(2000, 1000);
base.loopOnce();
assert(ios.size() == 2);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(2200, 500);
base.loopOnce();
assert(ios.size() == 4);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(2200, 600);
base.loopOnce();
assert(ios.size() == 4);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(2100, 300);
base.loopOnce();
assert(ios.size() == 5);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1500, 300);
base.loopOnce();
assert(ios.size() == 7);
testReadSubmit(800, 2500);
base.loopOnce();
testWriteSubmit(1700, 500);
base.loopOnce();
assert(ios.size() == 6);
testReadSubmit(800, 2500);
base.loopOnce();
cleanupEverything();
assert(ios.size() == 0);
}
void disk::_testSectorReads(uint64_t sector, uint16_t nsectors) {
uint64_t s;
uint16_t ns;
for (s = sector, ns = 0; ns < nsectors; ns++, s++) {
testReadSubmit(s, 1);
base.loopOnce();
}
}
void disk::testSectorReads() {
const uint64_t SECTOR = 1000;
const uint16_t NSECTORS = 500;
cleanupEverything();
assert(ios.size() == 0);
testWriteSubmit(SECTOR, NSECTORS);
base.loopOnce();
assert(ios.size() == 1);
_testSectorReads(SECTOR, NSECTORS);
for (auto s = SECTOR; s < (SECTOR + NSECTORS); s += 2) {
testWriteSubmit(s, 1);
base.loopOnce();
_testSectorReads(SECTOR, NSECTORS);
}
cleanupEverything();
assert(ios.size() == 0);
}
void disk::test() {
asyncio.init(&base);
asyncio.registerCallback(ioCompleted, nullptr, this);
testWriteOnceReadMany();
testOverWrite();
testNO1();
testNO2();
testNoOverlap();
testNoOverlap();
testExactOverwrite();
testTailExactOverwrite();
testHeadExactOverwrite();
testDoubleSplit();
testTailOverwrite();
testHeadOverwrite();
testCompleteOverwrite();
testHeadSideSplit();
testMid();
testTailSideSplit();
testSectorReads();
}
void lineSplit(const string &line, const char delim, vector<string> &result) {
std::stringstream ss;
ss.str(line);
string item;
while (std::getline(ss, item, delim)) {
result.emplace_back(item);
}
}
#include <fstream>
void disk::testBlockTrace(const string &file) {
asyncio.init(&base);
asyncio.registerCallback(ioCompleted, nullptr, this);
std::ifstream ifs(file);
if (!ifs.is_open()) {
return;
}
range tr(8082135, 8);
string line;
while (std::getline(ifs, line)) {
std::vector<string> l;
lineSplit(line, ' ', l);
if (l.size() != 3) {
cout << "Unabled to parse trace " << line << endl;
continue;
}
uint64_t s = std::stoul(l[1]);
uint16_t ns = std::stoul(l[2]);
range r(s, ns);
if ((tr.sector >= s && tr.sector <= r.end_sector()) || (tr.end_sector() >= s && tr.end_sector() <= r.end_sector())) {
if (l[0] == "W") {
cout << "W " << s << " " << ns << endl;
testWriteSubmit(s, ns);
} else if (l[0] == "R") {
cout << "R " << s << " " << ns << endl;
testReadSubmit(s, ns);
} else {
cout << "Unrecognized operation " << l[0] << endl;
continue;
}
base.loopOnce();
}
}
}
#if 0
void disk::print_ios(void)
{
bool first = false;
range r;
for (auto &w: ios) {
// std::cout << w->r.sector << " " << w->r.nsectors << " " << w->buffer << std::endl;
if (first == false) {
first = true;
r = w->r;
} else {
auto e = r.end_sector();
assert(e < w->r.sector);
r = w->r;
}
}
}
#endif<file_sep>/AsyncIO.h
#ifndef __ASYNCIO_H__
#define __ASYNCIO_H__
#include <libaio.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventHandler.h>
using namespace folly;
using std::unique_ptr;
using std::shared_ptr;
typedef unique_ptr<char, void(*)(void*)> ManagedBuffer;
typedef std::function<void(void *cbdata, ManagedBuffer bufp, size_t size, uint64_t offset, ssize_t result, bool read)> IOCompleteCB;
typedef std::function<void(void *cbdata, uint16_t nios)> NIOSCompleteCB;
class AsyncIO {
private:
io_context_t context_;
int eventfd_;
uint16_t capacity_;
bool initialized_;
uint64_t nsubmitted;
uint64_t ncompleted;
uint64_t nwrites;
uint64_t nreads;
uint64_t nbytesRead;
uint64_t nbytesWrote;
private:
NIOSCompleteCB niocbp_;
IOCompleteCB iocbp_;
void *cbdatap_;
private:
ssize_t ioResult(struct io_event *ep);
public:
class EventFDHandler : public EventHandler {
private:
int fd_;
EventBase *basep_;
AsyncIO *asynciop_;
public:
EventFDHandler(AsyncIO *asynciop, EventBase *basep, int fd) :
fd_(fd), basep_(basep), asynciop_(asynciop), EventHandler(basep, fd) {
assert(fd >= 0 && basep);
}
void handlerReady(uint16_t events) noexcept {
assert(events & EventHandler::READ);
if (events & EventHandler::READ) {
asynciop_->iosCompleted();
}
}
};
AsyncIO(uint16_t capcity);
~AsyncIO();
void init(EventBase *basep);
void registerCallback(IOCompleteCB iocb, NIOSCompleteCB niocb, void *cbdata);
void iosCompleted();
void pwritePrepare(struct iocb *cbp, int fd, ManagedBuffer bufp, size_t size, uint64_t offset);
int pwrite(struct iocb **iocbpp, int nwrites);
void preadPrepare(struct iocb *cbp, int fd, ManagedBuffer bufp, size_t size, uint64_t offset);
int pread(struct iocb **iocbpp, int nwrites);
ManagedBuffer getIOBuffer(size_t size);
uint64_t getPending();
uint64_t getNWrites() const {
return nwrites ;
}
uint64_t getNReads() const {
return nreads;
}
uint64_t getBytesRead() const {
return nbytesRead;
}
uint64_t getBytesWrote() const {
return nbytesWrote;
}
private:
EventFDHandler *handlerp_;
};
#endif<file_sep>/zipf.h
#ifndef __ZIP_F_H__
#define __ZIP_F_H__
/*
* MOST OF THE SOURCE CODE IS COPIED FROM fio SOURCE CODE
* */
#include <random>
#include <cstdint>
#include <cmath>
class frand {
private:
uint32_t s1;
uint32_t s2;
uint32_t s3;
private:
uint32_t __seed(uint32_t x, uint32_t m) {
return (x < m) ? x + m : x;
}
public:
static const uint32_t FRAND_MAX = -1U;
frand(uint32_t seed) {
auto LCG = [] (uint64_t x, uint32_t seed) {
return ((x) * 69069 ^ (seed));
};
s1 = __seed(LCG((2^31) + (2^17) + (2^7), seed), 1);
s2 = __seed(LCG(s1, seed), 7);
s3 = __seed(LCG(s2, seed), 15);
}
frand() : frand(1) {}
unsigned int rand() {
auto TAUSWORTHE = [] (uint32_t s, int a, int b, uint32_t c, int d) {
return ((s&c)<<d) ^ (((s <<a) ^ s)>>b);
};
s1 = TAUSWORTHE(s1, 13, 19, 4294967294UL, 12);
s2 = TAUSWORTHE(s2, 2, 25, 4294967288UL, 4);
s3 = TAUSWORTHE(s3, 3, 11, 4294967280UL, 17);
return (s1 ^ s2 ^ s3);
}
};
class zipf {
private:
const uint64_t MAX_GEN = 10000000ul;
const uint64_t GR_PRIME_64 = 0x9e37fffffffc0001ULL;
frand rand;
double theta;
uint64_t nitems; /* number of items to choose from */
double zetan; /* precalculated ZetaN, based on nitems */
double zeta2; /* precalculated Zeta2, based on theta */
uint64_t rand_off;
uint32_t seed;
private:
/* aux function to calculate zeta */
double zetan_calculate(void) {
auto MIN = [] (uint64_t a, uint64_t b) {
return (a < b ? a : b);
};
double ans = 0.0;
auto n = MIN(this->nitems, MAX_GEN);
for (uint64_t i = 1; i <= n; i++)
ans += pow(1.0 / (double)i, theta);
return ans;
}
public:
zipf(double theta, double nitems, uint32_t seed) : rand(seed) {
this->theta = theta;
this->nitems = nitems;
this->seed = seed;
zetan = zetan_calculate();
zeta2 = pow(1.0, theta) + pow(0.5, theta);
rand_off = rand.rand();
}
uint64_t next() {
auto hash_u64 = [=] (uint64_t v) {
return v * GR_PRIME_64;
};
double alpha, eta, rand_uni, rand_z;
uint64_t n = nitems;
uint64_t val;
alpha = 1.0 / (1.0 - theta);
eta = (1.0 - pow(2.0 / n, 1.0 - theta)) / (1.0 - zeta2 / zetan);
rand_uni = (double) rand.rand() / (double) frand::FRAND_MAX;
rand_z = rand_uni * zetan;
if (rand_z < 1.0) {
val = 1;
} else if (rand_z < (1.0 + pow(0.5, theta))) {
val = 2;
} else {
val = 1 + (uint64_t)(n * pow(eta*rand_uni - eta + 1.0, alpha));
}
return (hash_u64(val - 1) + rand_off) % nitems;
}
uint32_t get_seed() {
return seed;
}
};
class uniform {
private:
std::mt19937 eng{std::random_device{}()};
uint64_t min;
uint64_t max;
uint32_t seed;
public:
uniform() = default;
uniform(uint32_t seed, uint64_t min = 1, uint64_t max = 100000000ull) :
eng(seed)
{
this->min = min;
this->max = max;
this->seed = seed;
}
uint64_t next() {
return std::uniform_int_distribution<uint64_t>{min, max}(eng);
}
uint64_t get_min() { return min; }
uint64_t get_max() { return max; }
uint64_t get_seed() { return seed; }
};
#endif
<file_sep>/io_generator.h
#ifndef __IO_GEN_H__
#define __IO_GEN_H__
#include <vector>
#include <utility>
#include <algorithm>
#include <cstdint>
#include <cassert>
#include "zipf.h"
using std::vector;
using std::pair;
class block_stats {
public:
uint64_t nios;
uint32_t nsectors;
uint8_t percent;
block_stats(uint8_t nsectors, uint8_t percent) {
this->nsectors = nsectors;
this->percent = percent;
this->nios = 0;
}
void dump(void) {
std::cout << "# Sectors: " << nsectors << " Percentage " <<
+percent << " IOs " << nios << std::endl;
}
};
class io_generator {
private:
const uint64_t MAX_IO_SIZE = 1ull << 20;
const uint64_t SECTOR_SHIFT = 9;
const uint64_t MAX_SECTORS = MAX_IO_SIZE >> SECTOR_SHIFT;
private:
uint64_t sector; /* start sector */
uint64_t nsectors; /* number of sectors */
uint64_t seed;
uniform size_rand;
zipf sector_rand;
uint64_t total_ios;
vector<block_stats> bstat;
public:
io_generator(uint64_t sector, uint64_t nsectors,
vector<pair<uint32_t, uint8_t>> &sizes) :
size_rand(1, 1, MAX_SECTORS),
sector_rand(0.9, nsectors - MAX_SECTORS, 1)
{
uint32_t seed = 1;
nsectors -= MAX_SECTORS;
this->sector = sector;
this->nsectors = nsectors;
this->seed = seed;
this->total_ios = 0;
for (auto &it : sizes) {
auto s = it.first;
auto p = it.second;
block_stats b(s, p);
bstat.push_back(b);
}
std::sort(bstat.begin(), bstat.end(),
[] (const block_stats &a, const block_stats &b) {
return a.percent > b.percent;
});
}
void next_io(uint64_t *sectorp, uint64_t *nsectorsp) {
total_ios++;
uint32_t ns = 0;
for (auto &it : bstat) {
auto n = it.nios;
auto p = it.percent;
if ((100 * n / total_ios) < p) {
ns = it.nsectors;
it.nios++;
break;
}
}
if (ns == 0) {
ns = size_rand.next();
assert(ns >= 1 && ns <= MAX_SECTORS);
for (auto &it : bstat) {
if (it.nsectors == ns) {
it.nios++;
break;
}
}
}
auto s = sector_rand.next();
assert(s >= 0 && s <= this->nsectors);
s += this->sector;
assert(s < this->sector + this->nsectors);
*nsectorsp = ns;
*sectorp = s;
}
void dump_stats(void) {
for (auto &it : bstat) {
it.dump();
}
std::cout << "Total IOs " << total_ios << std::endl;
}
};
#endif
<file_sep>/block_trace.cc
#include <iostream>
#include <ios>
#include <vector>
#include <fstream>
#include <chrono>
#include <ctime>
#include <cassert>
#include <string>
#include "block_trace.h"
using std::string;
using std::vector;
using std::fstream;
using std::cout;
using std::endl;
using std::ios;
using std::time_t;
TraceLog::TraceLog(string logPrefix) : logPrefix_(logPrefix),
curFS_(logPrefix, ios::out | ios::binary | ios::app) {
}
TraceLog::~TraceLog() {
if (curFS_.is_open()) {
curFS_.flush();
curFS_.sync();
curFS_.close();
}
}
void TraceLog::addTraceLog(uint64_t sector, uint16_t nsectors, bool read) {
auto ct = std::chrono::system_clock::now();
auto st = std::chrono::system_clock::to_time_t(ct);
block_trace trace{st, sector, nsectors, read};
curFS_.write((char *) &trace, sizeof(trace));
}
void TraceLog::dumpTraceLog(uint64_t sector, uint16_t nsectors) {
curFS_.flush();
curFS_.sync();
fstream is(logPrefix_, ios::in | ios::binary);
assert(is && is.is_open());
is.seekg(0, is.beg);
auto r1_low = sector;
auto r1_high = sector + nsectors - 1;
auto f = true;
auto nreads = 0ul;
auto nwrites = 0ul;
auto nbytesRead = 0ull;
auto nbytesWrote = 0ull;
while (!is.eof()) {
block_trace t;
is.read((char *)&t, sizeof(t));
auto r2_low = t.sector_;
auto r2_high = t.sector_ + t.nsectors_ - 1;
if (r2_low < r1_high && r2_high > r1_low) {
/* Intercepting IO */
if (f == false) {
if (nreads) {
cout << nbytesRead << " bytes Read in " << nreads << " Reads " << endl;
}
if (nwrites) {
cout << nbytesWrote << " bytes Wrote in " << nwrites << " Writes " << endl;
}
nreads = 0;
nbytesRead = 0;
nwrites = 0;
nbytesWrote = 0;
}
auto ioc = t.read_ ? 'R' : 'W';
string time(ctime(&t.timestamp_));
time.pop_back();
cout << time << " ===> " << ioc << " " << t.sector_ << " " << t.nsectors_ << endl;
f = false;
continue;
}
if (f == true) {
string time(ctime(&t.timestamp_));
time.pop_back();
cout << "====== Start Time " << time << " =====\n";
f = false;
}
if (t.read_) {
nreads++;
nbytesRead += (t.nsectors_ << 9);
} else {
nwrites++;
nbytesWrote += (t.nsectors_ << 9);
}
}
}<file_sep>/AsyncIO.cpp
#include <cassert>
#include <cstdlib>
#include <sys/eventfd.h>
#include <libaio.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventHandler.h>
#include "AsyncIO.h"
using namespace folly;
enum class IOType {
READ,
WRITE,
};
class io {
public:
uint64_t offset_;
size_t size_;
int fd_;
ManagedBuffer bufp_;
IOType type_;
private:
AsyncIO *asynciop_;
public:
io(AsyncIO *asynciop, int fd, ManagedBuffer bufp, size_t size, uint64_t offset, IOType type) : bufp_(std::move(bufp)) {
offset_ = offset;
size_ = size;
fd_ = fd;
asynciop_ = asynciop;
type_ = type;
}
};
AsyncIO::AsyncIO(uint16_t capacity) :
capacity_(capacity), eventfd_(-1), handlerp_(nullptr), initialized_(false) {
std::memset(&context_, 0, sizeof(context_));
auto rc = io_setup(capacity_, &context_);
assert(rc == 0);
nsubmitted = 0;
ncompleted = 0;
nreads = 0;
nwrites = 0;
nbytesRead = 0;
nbytesWrote = 0;
}
AsyncIO::~AsyncIO() {
if (eventfd_ >= 0) {
close(eventfd_);
}
if (handlerp_) {
delete(handlerp_);
}
io_destroy(context_);
}
void AsyncIO::init(EventBase *basep) {
eventfd_ = eventfd(0, EFD_NONBLOCK);
assert(eventfd_ >= 0);
handlerp_ = new EventFDHandler(this, basep, eventfd_);
assert(handlerp_);
handlerp_->registerHandler(EventHandler::READ | EventHandler::PERSIST);
initialized_ = true;
}
void AsyncIO::registerCallback(IOCompleteCB iocb, NIOSCompleteCB niocb, void *cbdata) {
iocbp_ = iocb;
cbdatap_ = cbdata;
niocbp_ = niocb;
}
ssize_t AsyncIO::ioResult(struct io_event *ep) {
return ((ssize_t)(((uint64_t)ep->res2 << 32) | ep->res));
}
void AsyncIO::iosCompleted() {
assert(iocbp_ && eventfd_ >= 0);
eventfd_t nevents;
uint16_t completed = 0;
while (1) {
nevents = 0;
int rc = eventfd_read(eventfd_, &nevents);
if (rc < 0 || nevents == 0) {
if (rc < 0 && errno != EAGAIN) {
assert(0);
}
assert(errno == EAGAIN);
/* no more events to process */
break;
}
assert(nevents > 0);
struct io_event events[nevents];
rc = io_getevents(context_, nevents, nevents, events, NULL);
assert(rc == nevents);
for (auto ep = events; ep < events + nevents; ep++) {
auto *iop = reinterpret_cast<io*>(ep->data);
auto result = ioResult(ep);
bool read = iop->type_ == IOType::READ;
if (read) {
this->nbytesRead += iop->size_;
} else {
this->nbytesWrote += iop->size_;
}
iocbp_(cbdatap_, std::move(iop->bufp_), iop->size_, iop->offset_, result, read);
delete iop;
}
completed += nevents;
}
this->ncompleted += completed;
if (niocbp_) {
niocbp_(cbdatap_, completed);
}
}
uint64_t AsyncIO::getPending() {
return this->nsubmitted - this->ncompleted;
}
void AsyncIO::pwritePrepare(struct iocb *iocbp, int fd, ManagedBuffer bufp, size_t size, uint64_t offset) {
assert(initialized_ && iocbp && bufp && fd >= 0);
std::memset(iocbp, 0, sizeof(*iocbp));
char *b = bufp.get();
io_prep_pwrite(iocbp, fd, b, size, offset);
io_set_eventfd(iocbp, eventfd_);
auto iop = new io(this, fd, std::move(bufp), size, offset, IOType::WRITE);
iocbp->data = reinterpret_cast<void *>(iop);
assert(iop);
}
int AsyncIO::pwrite(struct iocb **iocbpp, int nwrites) {
assert(initialized_ && iocbpp && nwrites);
this->nwrites += nwrites;
this->nsubmitted += nwrites;
return io_submit(context_, nwrites, iocbpp);
}
void AsyncIO::preadPrepare(struct iocb *iocbp, int fd, ManagedBuffer bufp, size_t size, uint64_t offset) {
assert(initialized_ && iocbp && bufp && fd >= 0);
std::memset(iocbp, 0, sizeof(*iocbp));
char *b = bufp.get();
io_prep_pread(iocbp, fd, b, size, offset);
io_set_eventfd(iocbp, eventfd_);
auto iop = new io(this, fd, std::move(bufp), size, offset, IOType::READ);
iocbp->data = reinterpret_cast<void *>(iop);
assert(iop);
}
int AsyncIO::pread(struct iocb **iocbpp, int nreads) {
assert(initialized_ && iocbpp && nreads);
this->nreads += nreads;
this->nsubmitted += nreads;
return io_submit(context_, nreads, iocbpp);
}
#define PAGE_SIZE 4096
#define DEFAULT_ALIGNMENT PAGE_SIZE
ManagedBuffer AsyncIO::getIOBuffer(size_t size) {
void *bufp{};
auto rc = posix_memalign(&bufp, DEFAULT_ALIGNMENT, size);
assert(rc == 0 && bufp);
return ManagedBuffer(reinterpret_cast<char *>(bufp), free);
}<file_sep>/Makefile
INC := -I.
LIBS := -levent -laio -lpthread -lfolly -lgflags
CPPCLAGS := -g -ggdb -O0
all: main
main: disk_io.cc main.cc AsyncIO.cpp block_trace.cc
g++ -std=c++14 $(CPPCLAGS) $(INC) -o $@ $^ $(LIBS)
clean:
rm -rf main
| 793a491de5bc53a4befe421f7a3d279bf5a337bb | [
"Makefile",
"C++"
] | 10 | C++ | prasad-joshi/data-verification | 51a318cca26d8e1a91b99a0896206627c94bed87 | fd65eaec121e16cdc98d2f1f96620716232a64e3 |
refs/heads/master | <repo_name>Build-Week-DevDesk-Queue2/frontend<file_sep>/front-end/src/components/index.js
// pages
import Dashboard from "./pages/Dashboard";
// que
import Card from "./que/Card";
import ClosedCard from "./que/ClosedCard";
import ClosedTickets from "./que/ClosedTickets";
import TicketList from "./que/TicketList";
import StudentQueue from "./que/StudentQueue";
import TicketForm from "./que/TicketForm";
// users
import CreateUserForm from "./users/CreateUserForm";
import LoginForm from "./users/LoginForm";
export {
Dashboard,
Card,
ClosedCard,
ClosedTickets,
TicketList,
StudentQueue,
TicketForm,
CreateUserForm,
LoginForm,
};
<file_sep>/front-end/src/components/que/TicketList.js
import React, { useState, useEffect } from "react";
import styled from "styled-components";
import Card from "./Card";
import axios from "axios";
import tickets from "../../tickets";
import { connect } from 'react-redux';
import { getTickets, getHelperTickets } from '../../actions/actions';
const mapStateToPtops = state => {
return {
tickets: state.tickets
}
}
const OpenTickets = (props) => {
useEffect(() => {
if (props.role === 'student') {
props.getTickets()
} else {
props.getHelperTickets()
}
}, [])
const [ticket, setTicket] = useState(tickets);
//console.log("Ticket List", ticket);
return (
<ListCard>
{props.tickets.filter(ticket => !ticket.completed).map(ticket => {
return <Card role={props.role} ticket={ticket} key={ticket.id} />;
})}
</ListCard>
);
};
const ListCard = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const BackgroundWrap = styled.div`
background: #fff;
border-radius: 10px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -430px;
margin-left: -600px;
width: 960px;
padding: 30px 130px 0px 120px;
`;
export default connect(mapStateToPtops, {getTickets, getHelperTickets})(OpenTickets);
<file_sep>/front-end/src/components/que/ClosedCard.js
import React from "react";
import styled from "styled-components";
import css from "../users/createuser.css";
const ClosedCard = () => {
return (
<ClosedTicketWrap>
<div className="closed-ticket-box-style">
<ClosedTicketTitle>Laptop stopped working</ClosedTicketTitle>
<TicketStatus>Closed</TicketStatus>
</div>
</ClosedTicketWrap>
);
};
const ClosedTicketWrap = styled.div`
background: #fff;
border-radius: 10px;
width: 343px;
margin-top: 30px;
`;
const ClosedTicketTitle = styled.h3`
padding-left: 5px;
text-align: left;
`;
const TicketStatus = styled.p`
text-align: right;
padding-right: 5px;
font-size: 16px;
line-height: 20px;
width: 50px;
margin: 0;
`;
export default ClosedCard;
<file_sep>/front-end/src/components/que/StudentDropdown.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
const StudentDropdown = () => {
const [dropdownOpen, setDropdownOpen] = useState(false);
const toggle = () => setDropdownOpen((prevState) => !prevState);
return (
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret>Manage</DropdownToggle>
<DropdownMenu>
<DropdownItem>Edit Ticket</DropdownItem>
<DropdownItem>Delete Ticket</DropdownItem>
<DropdownItem>Mark Resolved</DropdownItem>
</DropdownMenu>
</Dropdown>
);
};
export default StudentDropdown;
<file_sep>/front-end/src/actions/actions.js
import { axiosWithAuth } from '../auth/axiosWithAuth';
export const USER_LOGIN_START = 'USER_LOGIN_START';
export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS';
export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL';
export const REGISTER_USER_START = 'REGISTER_USER_START';
export const REGISTER_USER_SUCCESS = 'REGISTER_USER_SUCCESS';
export const REGISTER_USER_FAIL = 'REGISTER_USER_FAIL';
export const FETCH_TICKETS_START = 'FETCH_TICKETS_START';
export const FETCH_TICKETS_SUCCESS = 'FETCH_TICKETS_SUCCESS';
export const FETCH_TICKETS_FAIL = 'FETCH_TICKETS_FAIL';
export const POST_TICKET_START = 'POST_TICKET_START';
export const POST_TICKET_SUCCESS = 'POST_TICKET_SUCCESS';
export const POST_TICKET_FAIL = 'POST_TICKET_FAIL';
export const LOG_OUT = 'LOG_OUT';
export const registerUser = credentials => dispatch => {
dispatch({type: REGISTER_USER_START});
axiosWithAuth()
.post('/auth/register', credentials)
.then(res => {
console.log(res);
dispatch({type: REGISTER_USER_SUCCESS});
})
.catch(err => {
console.log(err);
dispatch({type: REGISTER_USER_FAIL});
})
}
export const login = credentials => dispatch => {
dispatch({type: USER_LOGIN_START});
axiosWithAuth()
.post('/auth/login', credentials)
.then(res => {
console.log(res);
dispatch({ type: USER_LOGIN_SUCCESS, payload: res.data });
})
.catch(err => {
console.log(err);
dispatch({ type: USER_LOGIN_FAIL, payload: err })
});
}
export const logOut = () => dispatch => {
dispatch({type: LOG_OUT});
}
export const getTickets = () => dispatch => {
dispatch({ type: FETCH_TICKETS_START });
axiosWithAuth()
.get('/students/tickets')
.then(res => {
console.log(res);
dispatch({ type: FETCH_TICKETS_SUCCESS, payload: res.data });
})
.catch(err => {
console.log(err);
dispatch({ type: FETCH_TICKETS_FAIL, payload: err });
});
}
export const getHelperTickets = () => dispatch => {
dispatch({ type: FETCH_TICKETS_START});
axiosWithAuth()
.get('/helpers/tickets')
.then(res => {
console.log(res);
dispatch({ type: FETCH_TICKETS_SUCCESS, payload: res.data })
})
.catch(err => {
console.log(err);
dispatch({ type: FETCH_TICKETS_FAIL, payload: err })
});
}
export const postTicket = ticket => dispatch => {
dispatch({ type: POST_TICKET_START });
axiosWithAuth()
.post('/students/tickets', ticket)
.then(res => {
console.log(res);
dispatch({ type: POST_TICKET_SUCCESS, payload: res });
})
.catch(err => {
console.log(err);
dispatch({ type: POST_TICKET_FAIL, payload: err });
});
}<file_sep>/front-end/src/App.js
import React from "react";
import "./App.css";
import { LoginForm, CreateUserForm, Dashboard } from "./components";
import { Route, Redirect } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) =>
localStorage.getItem("token") ? (
<Component {...props} />
) : (
<Redirect to="/" />
)
}
/>
);
function App() {
return (
<div className="App">
<Route exact path="/" component={LoginForm} />
<Route path="/sign-up" component={CreateUserForm} />
<PrivateRoute path="/dashboard" component={Dashboard} />
</div>
);
}
export default App;<file_sep>/README.md
# frontend
DevDesk Queue - React Frontend
<file_sep>/front-end/src/components/que/HelperNav.js
import React, { useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import TicketList from "./TicketList";
import ClosedTickets from "./ClosedTickets";
import TicketForm from "./TicketForm";
import MyTicketsList from "./MyTicketsList";
import SuccessMessage from "./SuccessMessage";
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Switch,
Redirect,
} from "react-router-dom";
const HelperNav = (props) => {
console.log("Helper Nav", props);
let role = props.role;
return (
<div>
<SuccessMessage />
<Router>
<nav>
<NavLink to="/dashboard/open-tickets">All Tickets</NavLink>
<NavLink to="/dashboard/my-tickets">My Tickets</NavLink>
</nav>
<Switch>
<Route
exact
path="/dashboard"
render={() => {
return <Redirect to="/dashboard/open-tickets" />;
}}
/>
<Route
path="/dashboard/open-tickets"
render={(props) => <TicketList {...props} role={role} />}
/>
<Route
path="/dashboard/my-tickets"
render={(props) => <MyTicketsList {...props} role={role} />}
/>
<Route path="/dashboard/open-tickets" component={TicketList} />
<Route path="/dashboard/my-tickets" component={MyTicketsList} />
</Switch>
</Router>
</div>
);
};
export default HelperNav;
<file_sep>/front-end/src/components/que/StudentNav.js
import React, { useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import TicketList from "./TicketList";
import ClosedTickets from "./ClosedTickets";
import TicketForm from "./TicketForm";
import SuccessMessage from "./SuccessMessage";
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Switch,
Redirect,
} from "react-router-dom";
import OpenTickets from "./TicketList";
const StudentNav = (props) => {
//console.log("Student Nav", props);
let role = props.role;
return (
<div className="student-nav-container">
<SuccessMessage timeout="5000" />
<Router>
<NavLink className="create-ticket-icon" to="/dashboard/create-ticket">
<i className="fas fa-notes-medical" id="notes-medical"></i>
</NavLink>
<nav>
<NavLink to="/dashboard/open-tickets">Open Tickets</NavLink>
<NavLink to="/dashboard/closed-tickets">Closed Tickets</NavLink>
</nav>
<Switch>
<Route
exact
path="/dashboard"
render={() => {
return <Redirect to="/dashboard/open-tickets" />;
}}
/>
<Route
path="/dashboard/open-tickets"
render={(props) => <TicketList {...props} role={role} />}
/>
<Route path="/dashboard/closed-tickets" component={ClosedTickets} />
<Route path="/dashboard/create-ticket" component={TicketForm} />
</Switch>
</Router>
</div>
);
};
export default StudentNav;
<file_sep>/front-end/src/components/que/HelperDropdown.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
const HelperDropdown = () => {
const [dropdownOpen, setDropdownOpen] = useState(false);
const toggle = () => setDropdownOpen((prevState) => !prevState);
return (
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret>Assign</DropdownToggle>
<DropdownMenu>
<DropdownItem>Assign to me</DropdownItem>
<DropdownItem>Section Lead</DropdownItem>
<DropdownItem>Student Success</DropdownItem>
<DropdownItem>Human Resources</DropdownItem>
</DropdownMenu>
</Dropdown>
);
};
export default HelperDropdown;
<file_sep>/front-end/src/components/que/StudentCard.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
const StudentCard = (props) => {
let ticket = props.ticket;
//console.log("StudentCardTicket", ticket);
let role = props.role;
//console.log("StudentCard", props);
return (
<div>
<StyledCardTitle>{ticket.title}</StyledCardTitle>
<StyledParagraphTitle>{ticket.issue}</StyledParagraphTitle>
<div className="open-ticket-tried-section">
<h4>Effort</h4>
<ul>
<li>{ticket.effort}</li>
</ul>
</div>
<div className="open-ticket-info-section">
<h4>More Info</h4>
<p>{ticket.info}</p>
</div>
</div>
);
};
const StyledCardTitle = styled.span`
font-size: 13px;
line-height: 16px;
`;
const StyledParagraphTitle = styled.p`
font-weight: 600;
font-size: 21px;
line-height: 26px;
margin-top: 0;
`;
export default StudentCard;
<file_sep>/front-end/src/components/que/HelperCard.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
const HelperCard = (props) => {
return (
<div>
<StyledCardTitle>Equipment Issue</StyledCardTitle>
<StyledParagraphTitle>Laptop stopped working</StyledParagraphTitle>
</div>
);
};
const StyledCardTitle = styled.span`
font-size: 13px;
line-height: 16px;
`;
const StyledParagraphTitle = styled.p`
font-weight: 600;
font-size: 21px;
line-height: 26px;
margin-top: 0;
`;
export default HelperCard;
<file_sep>/front-end/src/components/users/CreateUserForm.js
import React, { useState, useEffect } from "react";
import * as yup from "yup";
import styled from "styled-components";
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Switch,
} from "react-router-dom";
import "./createuser.css";
import { axiosWithAuth } from "../../auth/axiosWithAuth";
import { connect } from 'react-redux';
import { registerUser } from '../../actions/actions';
const mapStateToProps = state => {
return {
success: state.success
}
}
/////////////////////////
/// FORM ///
/////////////////////////
const CreateUserForm = (props) => {
useEffect(() => {
if (props.success) {
props.history.push('dashboard');
}
}, [props.success])
////////////////////////
/// STATE ///
///////////////////////
// Initial state for the Create User Form
const initialFormState = {
username: "",
password: "",
role: "",
};
// State for inputs
const [formState, setFormState] = useState(initialFormState);
// State for errors
const [errors, setErrors] = useState(initialFormState);
////////////////////////
/// VALIDATION ///
////////////////////////
// FORM SCHEMA Validation for Login Page
const formSchema = yup.object().shape({
username: yup.string().required("Username is a required field"),
password: yup.string().required("<PASSWORD>"),
role: yup.string().required("Role is a required field"),
});
// Validation for each input
const validateChange = (e) => {
yup
// Read the value of schema key using name of input
.reach(formSchema, e.target.name)
// Validate the value of input
.validate(e.target.value)
// If the validation passes, clear all errors
.then((valid) => {
setErrors({ ...errors, [e.target.name]: "" });
})
.catch((err) => {
setErrors({ ...errors, [e.target.name]: err.errors[0] });
});
};
////////////////////////
/// INPUT ONCHANGE ///
////////////////////////
const inputChange = (e) => {
e.persist();
const newFormData = {
...formState,
[e.target.name]: e.target.value,
};
validateChange(e); // Validates every change in every input
setFormState(newFormData); // Update state with new data
};
////////////////////////
/// ROLE ONCHANGE ///
////////////////////////
// const inputChangeRole = (e) => {
// let roles = formState.roles;
// let role = e.target.name;
// let selected = e.target.checked;
// if (selected) {
// roles.push(role);
// } else {
// let index = roles.indexOf(role);
// roles.splice(index, 1);
// }
// e.persist();
// const newFormData = {
// ...formState,
// roles: roles,
// };
// console.log(roles);
// setFormState(newFormData);
// };
////////////////////////
/// ON SUBMIT ///
////////////////////////
const registerUser = (e) => {
e.preventDefault();
props.registerUser(formState);
};
return (
<div className="create-account-form">
<BackgroundWrap>
<CreateAccountHeading>We're Here to help.</CreateAccountHeading>
<CreateAccountSubHeading>
Create an account to start receiving help!
</CreateAccountSubHeading>
<form onSubmit={registerUser}>
<label htmlFor="username">
{/* NAME */}
<input
className="input"
id="username"
type="text"
name="username"
placeholder="Username"
onChange={inputChange}
value={formSchema.username}
/>
{errors.username.length > 0 ? (
<p className="error">{errors.username}</p>
) : null}
</label>
<label htmlFor="password">
{/* PASSWORD */}
<input
className="input"
id="password"
type="password"
name="password"
placeholder="<PASSWORD>"
onChange={inputChange}
value={formSchema.password}
/>
{errors.password.length > 0 ? (
<p className="error">{errors.password}</p>
) : null}
</label>
<label htmlFor="role" className="role">
My Role:
<input
type="radio"
id="student"
name="role"
value="student"
checked={formState.role === "student"}
onChange={inputChange}
/>
<label htmlFor="student">Student</label>
<input
type="radio"
id="helper"
name="role"
value="helper"
checked={formState.role === "helper"}
onChange={inputChange}
/>
<label htmlFor="helper">Helper</label>
{errors.roles === [] ? (
<p className="error">{errors.roles}</p>
) : null}
</label>
<button type="submit">Create Account</button>
<h2>
<span>or</span>
</h2>
<StyledLink to="/">Sign In</StyledLink>
</form>
</BackgroundWrap>
</div>
);
};
/////////////////////////
/// STYLED COMPONENTS ///
/////////////////////////
const CreateAccountHeading = styled.span`
color: #333333;
font-weight: 800;
font-size: 24px;
line-height: 1.2;
text-align: center;
display: block;
padding-bottom: 25px;
margin: 0 0 0 5%;
`;
const CreateAccountSubHeading = styled.span`
color: #333333;
font-weight: 300;
font-size: 18px;
line-height: 1.2;
text-align: center;
display: block;
width: 330px;
margin: 0 35%;
padding-bottom: 25px;
`;
const BackgroundWrap = styled.div`
background: #fff;
border-radius: 10px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -600px;
width: 960px;
padding: 30px 130px 130px 95px;
`;
const StyledLink = styled(Link)`
margin: 5% 4%;
width: 100%;
display: inline-block;
padding: 15px 0px;
font-size: 1.2rem;
text-transform: uppercase;
border: 0;
border-radius: 25px;
letter-spacing: 2px;
line-height: 16px;
outline: none;
background-color: #efefef;
color: #3b394e;
cursor: pointer;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
text-decoration: none;
`;
export default connect(mapStateToProps, {registerUser})(CreateUserForm);
<file_sep>/front-end/src/components/que/MyTicketsHelperDropdown.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
const MyTicketsHelperDropdown = () => {
const [dropdownOpen, setDropdownOpen] = useState(false);
const toggle = () => setDropdownOpen((prevState) => !prevState);
return (
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret>Assigned</DropdownToggle>
<DropdownMenu>
<DropdownItem>Unassign</DropdownItem>
</DropdownMenu>
</Dropdown>
);
};
export default MyTicketsHelperDropdown;
<file_sep>/front-end/src/reducers/reducer.js
import {
USER_LOGIN_START,
USER_LOGIN_SUCCESS,
USER_LOGIN_FAIL,
LOG_OUT,
REGISTER_USER_START,
REGISTER_USER_SUCCESS,
REGISTER_USER_FAIL,
FETCH_TICKETS_START,
FETCH_TICKETS_SUCCESS,
FETCH_TICKETS_FAIL,
POST_TICKET_START,
POST_TICKET_SUCCESS,
POST_TICKET_FAIL
} from '../actions/actions';
const initialState = {
tickets: [],
user: {
id: '',
username: '',
role: ''
},
logging_in: false,
registering: false,
fetching_tickets: false,
posting_ticket: false,
error: '',
logged_in: false,
success: '',
update_tickets: true
}
export const reducer = (state = initialState, action) => {
switch(action.type) {
case USER_LOGIN_START:
return {
...state,
logging_in: true,
error: '',
success: ''
};
case USER_LOGIN_SUCCESS:
localStorage.setItem('token', action.payload.token);
return {
...state,
user: {
id: action.payload.id,
username: action.payload.username,
role: action.payload.role
},
logging_in: false,
logged_in: true
};
case USER_LOGIN_FAIL:
return {
...state,
logging_in: false,
error: 'Username or Password incorrect'
};
case LOG_OUT:
localStorage.removeItem('token');
return {
...initialState
};
case REGISTER_USER_START:
return {
...state,
registering: true,
error: ''
};
case REGISTER_USER_SUCCESS:
return {
...state,
registering: false,
success: 'You have successfully registered please log in'
};
case REGISTER_USER_FAIL:
return {
...state,
registering: false,
error: 'Sorry something went wrong'
}
case FETCH_TICKETS_START:
return {
...state,
fetching_tickets: true,
error: ''
}
case FETCH_TICKETS_SUCCESS:
return {
...state,
fetching_tickets: false,
tickets: action.payload,
}
case FETCH_TICKETS_FAIL:
return {
...state,
fetching_tickets: false,
error: 'Failed to fetch tickets'
}
case POST_TICKET_START:
return {
...state,
posting_ticket: true,
error: ''
}
case POST_TICKET_SUCCESS:
return {
...state,
posting_ticket: false,
error: ''
}
case POST_TICKET_FAIL:
return {
...state,
posting_ticket: false,
error: 'Ticket Failed to post'
}
default:
return state;
}
}<file_sep>/front-end/src/components/que/MyTicketsList.js
import React from "react";
import ClosedCard from "./ClosedCard";
import styled from "styled-components";
import MyTicketsCard from "./MyTicketsCard";
import { connect } from 'react-redux';
const mapStateToProps = state => {
return {
tickets: state.tickets,
user: {
id: state.user.id
}
}
}
const MyTicketsList = (props) => {
let role = props.role;
console.log("MyTicketsList", role);
return (
<ListCard>
{props.tickets.filter(ticket => ticket.created_by === props.user.id).map(ticket => {
console.log(ticket);
// return(
// <MyTicketsCard role={role} ticket={ticket} />
// )
})}
<MyTicketsCard role={role} />
</ListCard>
);
};
const ListCard = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
export default connect(mapStateToProps, {})(MyTicketsList);
<file_sep>/front-end/src/components/que/TicketForm.js
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import * as yup from "yup";
import "../users/createuser.css";
import StudentSuccessPage from "../pages/Dashboard";
import { connect } from 'react-redux';
import { postTicket } from '../../actions/actions';
const TicketForm = props => {
let history = useHistory();
////////////////////////
/// STATE ///
///////////////////////
// Initial state for the Create User Form
const initialFormState = {
title: "",
category: "",
tried: "",
additional_info: "",
};
// State for inputs
const [formState, setFormState] = useState(initialFormState);
// State for errors
const [errors, setErrors] = useState(initialFormState);
////////////////////////
/// VALIDATION ///
////////////////////////
// FORM SCHEMA Validation for Ticket Form
const formSchema = yup.object().shape({
title: yup.string().required("This is a required field"),
category: yup.string().required("This is a required field"),
tried: yup.string().required("This is a required field"),
additional_info: yup.string().required("This is a required field"),
});
// Validation for each input
const validateChange = (e) => {
yup
// Read the value of schema key using name of input
.reach(formSchema, e.target.name)
// Validate the value of input
.validate(e.target.value)
// If the validation passes, clear all errors
.then((valid) => {
setErrors({ ...errors, [e.target.name]: "" });
})
.catch((err) => {
setErrors({ ...errors, [e.target.name]: err.errors[0] });
});
};
// onsubmit functino
const submitTicket = e => {
e.preventDefault();
props.postTicket(formState);
toSuccessPage();
}
////////////////////////
/// INPUT ONCHANGE ///
////////////////////////
const inputChange = (e) => {
e.persist();
const newFormData = {
...formState,
[e.target.name]: e.target.value,
};
validateChange(e); // Validates every change in every input
setFormState(newFormData); // Update state with new data
};
///////////////////////////////////////
/// Close Ticket -> Success Page ///
/////////////////////////////////////
const toSuccessPage = () => {
history.push("/dashboard");
};
return (
<BackgroundWrap>
<form onSubmit={submitTicket}>
<CloseButton
onClick={toSuccessPage}
className="far fa-times-circle"
></CloseButton>
<HeadingContainer>
<TicketHeading>Let's submit a help ticket.</TicketHeading>
<RequiredSpan>* Required Fields</RequiredSpan>
</HeadingContainer>
<label htmlFor="title" className="required">
Title
<input
className="input"
id="title"
type="title"
name="title"
placeholder="Add a Title..."
onChange={inputChange}
value={formSchema.name}
/>
{errors.title.length > 0 ? (
<p className="error">{errors.title}</p>
) : null}
</label>
<label htmlFor="category" className="required">
Topic
<select id="category" name="category">
<option>Select Category</option>
<option value="equipment">Equipment</option>
<option value="people">People</option>
<option value="track">Track</option>
<option value="finances">Finances</option>
<option value="Other">Other</option>
</select>
{errors.category.length > 0 ? (
<p className="error">{errors.category}</p>
) : null}
</label>
<label htmlFor="tried">
What have you tried?
<textarea
className="input"
id="tried"
name="tried"
rows="5"
cols="40"
onChange={inputChange}
value={formSchema.effort}
/>
{errors.tried.length > 0 ? (
<p className="error">{errors.tried}</p>
) : null}
</label>
<label htmlFor="additional_info">
Anything else we should know?
<textarea
className="input"
id="additional_info"
name="additional_info"
rows="5"
cols="40"
onChange={inputChange}
value={formSchema.info}
/>
{errors.additional_info.length > 0 ? (
<p className="error">{errors.info}</p>
) : null}
</label>
<button type="submit">SUBMIT TICKET</button>
</form>
</BackgroundWrap>
);
};
const BackgroundWrap = styled.div`
background: #f9fafb;
border-radius: 10px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -430px;
margin-left: -610px;
width: 960px;
height: 100vh;
padding: 30px 130px 0px 120px;
`;
const RequiredSpan = styled.span`
position: absolute;
left: 37.5%;
`;
const TicketHeading = styled.h1`
text-align: start;
`;
const HeadingContainer = styled.div`
margin-bottom: 10%;
`;
const CloseButton = styled.i`
position: absolute;
top: 5%;
left: 63%;
font-size: 18px;
`;
export default connect(null, {postTicket})(TicketForm);
<file_sep>/front-end/src/components/que/MyTicketsCard.js
import React, { useState } from "react";
import styled from "styled-components";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from "reactstrap";
import css from "../users/createuser.css";
import MyTicketsHelperDropdown from "./MyTicketsHelperDropdown";
const MyTicketsCard = (props) => {
let role = props.role;
console.log("MyTicketsCard", props);
return (
<CardWrap>
<div className="ticket-card">
<MyTicketsHelperDropdown role={role} />
<StyledCardTitle>Equipment Issue</StyledCardTitle>
<StyledParagraphTitle>Laptop stopped working</StyledParagraphTitle>
</div>
</CardWrap>
);
};
const StyledCardTitle = styled.span`
font-size: 13px;
line-height: 16px;
`;
const StyledParagraphTitle = styled.p`
font-weight: 600;
font-size: 21px;
line-height: 26px;
margin-top: 0;
`;
const CardWrap = styled.div`
text-align: left;
width: 350px;
height: auto;
background: #ffffff;
box-shadow: 2px 4px 10px rgba(0, 0, 0, 0.02), 2px 3px 8px rgba(0, 0, 0, 0.02);
border-radius: 5px;
border-left: 8px solid #007aff;
margin-top: 30px;
`;
export default MyTicketsCard;
<file_sep>/front-end/src/components/users/LoginForm.js
import React, { useState } from "react";
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Switch,
} from "react-router-dom";
import * as yup from "yup";
import styled from "styled-components";
import CreateUserForm from "./CreateUserForm";
import "./createuser.css";
import { connect } from 'react-redux';
import { login } from '../../actions/actions';
const mapStateToProps = state => {
return {
error: state.error,
logged_in: state.logged_in,
success: state.success
}
}
/////////////////////////
/// FORM ///
/////////////////////////
const Login = props => {
if (props.logged_in) {
props.history.push('/dashboard');
}
////////////////////////
/// STATE ///
///////////////////////
// Initial state for the Login form
const initialFormState = {
username: "",
password: "",
};
// State for inputs
const [formState, setFormState] = useState(initialFormState);
// State for errors
const [errors, setErrors] = useState(initialFormState);
////////////////////////
/// VALIDATION ///
////////////////////////
// FORM SCHEMA Validation for Login Page
const formSchema = yup.object().shape({
username: yup.string().required("Username is a required field"),
password: yup.string().required("Password is a required field"),
});
// Validation for each input
const validateChange = (e) => {
yup
// Read the value of schema key using name of input
.reach(formSchema, e.target.name)
// Validate the value of input
.validate(e.target.value)
// If the validation passes, clear all errors
.then((valid) => {
setErrors({ ...errors, [e.target.name]: "" });
})
.catch((err) => {
setErrors({ ...errors, [e.target.name]: err.errors[0] });
});
};
////////////////////////
/// INPUT ONCHANGE ///
////////////////////////
const inputChange = (e) => {
e.persist();
const newFormData = {
...formState,
[e.target.name]: e.target.value,
};
validateChange(e); // Validates every change in every input
setFormState(newFormData); // Update state with new data
};
////////////////////////
/// ON SUBMIT ///
////////////////////////
const loginRequest = e => {
e.preventDefault();
props.login(formState);
}
return (
<div className="create-account-form">
<BackgroundWrap>
<LoginHeading>LOGIN</LoginHeading>
<form onSubmit={loginRequest}>
<label htmlFor="username">
{/* USERNAME */}
<input
className="input"
id="username"
type="text"
name="username"
placeholder="Username"
onChange={inputChange}
value={formState.username}
/>
{errors.username.length > 0 ? (
<p className="error">{errors.username}</p>
) : null}
</label>
<label htmlFor="password">
{/* PASSWORD */}
<input
className="input"
id="password"
type="<PASSWORD>"
name="password"
placeholder="<PASSWORD>"
onChange={inputChange}
value={formState.password}
/>
{errors.password.length > 0 ? (
<p className="error">{errors.password}</p>
) : null}
{props.error.length > 0 && props.success.length < 1 ? <p className="error">{props.error}</p> : null}
{props.success.length > 0 ? <p className="error">{props.success}</p> : null}
</label>
<button type="submit">LOG IN</button>
<h2>
<span>or</span>
</h2>
<Router>
<StyledLink className="signin" to="/sign-up">
Create an Account
</StyledLink>
<Route path="/sign-up" component={CreateUserForm} />
</Router>
</form>
</BackgroundWrap>
</div>
);
};
/////////////////////////
/// STYLED COMPONENTS ///
/////////////////////////
const LoginHeading = styled.span`
color: #333333;
font-weight: 800;
font-size: 24px;
line-height: 1.2;
text-align: center;
display: block;
padding-bottom: 25px;
margin: 0 0 0 5%;
`;
const BackgroundWrap = styled.div`
background: #fff;
border-radius: 10px;
position: fixed;
top: 50%;
left: 50%;
margin-top: -300px;
margin-left: -600px;
width: 960px;
padding: 30px 130px 130px 95px;
`;
const StyledLink = styled(Link)`
margin: 5% 5%;
width: 100%;
display: inline-block;
padding: 15px 0px;
font-size: 1.2rem;
text-transform: uppercase;
border: 0;
border-radius: 25px;
letter-spacing: 2px;
line-height: 16px;
outline: none;
background-color: #efefef;
color: #3b394e;
cursor: pointer;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
text-decoration: none;
`;
export default connect(mapStateToProps, {login})(Login);
// axiosWithAuth()
// .post('/login', formState)
// .then(res => {
// console.log(res);
// localStorage.setItem('token', res.data.token);
// props.history.push('/dashboard');
// }
// )
// .catch(err => console.log(err)) | 76bcbea26a008a53975cf1e2a005814fa6aa3479 | [
"JavaScript",
"Markdown"
] | 19 | JavaScript | Build-Week-DevDesk-Queue2/frontend | 7560073101c47ad2a953a739910b9dfaae91d3a3 | 28036561f76b95b06da9ee8c801477dba5ab2399 |
refs/heads/master | <repo_name>dev4jam/deputy-shifts<file_sep>/Shifts/Shifts/App/AppComponent.swift
//
// AppComponent.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RIBs
import UIKit
import RxSwift
final class AppComponent: Component<EmptyDependency>, RootDependency {
let networkService: NetworkServiceProtocol
let imageService: NetworkServiceProtocol
let state: Variable<AppState>
init(application: UIApplication,
launchOptions: [UIApplication.LaunchOptionsKey : Any]?,
state: Variable<AppState>) {
self.state = state
networkService = NetworkService(baseUrl: Config.serviceBaseUrl,
auth: .token(Config.serviceAccessToken),
headers: [:])
imageService = NetworkService(baseUrl: "", auth: nil, headers: [:])
super.init(dependency: EmptyComponent())
}
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/NetworkiServiceProtocol.swift
//
// NetworkServiceProtocol.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
public enum SessionAuth {
case token(String)
case basic(String, String)
}
public protocol NetworkServiceProtocol: class, AutoMockable {
var headers: HeadersDict { get set }
var auth: SessionAuth? { get set }
var url: String { get }
var cachePolicy: URLRequest.CachePolicy { get set }
init(baseUrl: String, auth: SessionAuth?, headers: HeadersDict)
func execute(_ request: RequestProtocol?) -> Promise<ResponseProtocol>
}
<file_sep>/Shifts/Shifts/Utils/AutoMockable.swift
//
// AutoMockable.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
public protocol AutoMockable { // Protocol for Sourcery
}
<file_sep>/Shifts/Shifts/Models/Config.swift
//
// Config.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
struct Config {
static let storeFilename: String = "shared-store"
static let defaultTimeout: TimeInterval = 60.0
static let preferredStatusBarStyle: UIStatusBarStyle = .lightContent
static let serviceBaseUrl: String = "https://apjoqdqpi3.execute-api.us-west-2.amazonaws.com/dmc"
static let imagesBaseUrl: String = "https://unsplash.it"
static let serviceAccessToken: String = "a8cf97adadec4e1b734a39bc5aea71b5741cfca1"
}
<file_sep>/Shifts/Shifts/RIBs/Common/LoadingPresentable.swift
//
// LoadingPresentable.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import SVProgressHUD
protocol LoadingPresentable: class {
func showLoading(with status: String?)
func showError(with status: String?)
func hideLoading()
}
extension UIViewController: LoadingPresentable {
func showLoading(with status: String?) {
SVProgressHUD.show(withStatus: status)
}
func showError(with status: String?) {
SVProgressHUD.showError(withStatus: status)
}
func hideLoading() {
SVProgressHUD.dismiss()
}
}
<file_sep>/Shifts/Shifts/Services/Remote/ShiftsServiceProtocol.swift
//
// ShiftsServiceProtocol.swift
// Shifts
//
// Created by <NAME> on 26/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
import UIKit
protocol ShiftsServiceProtocol: AutoMockable {
init(networkService: NetworkServiceProtocol, imageService: NetworkServiceProtocol)
func getShifts() -> Promise<[Shift]>
func startShift(latitude: Double, longitude: Double) -> Promise<Bool>
func stopShift(latitude: Double, longitude: Double) -> Promise<Bool>
func getShiftImage(url: String) -> Promise<UIImage>
}
<file_sep>/Shifts/Shifts/RIBs/Shifts/ShiftsRouter.swift
//
// ShiftsRouter.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
protocol ShiftsInteractable: Interactable {
var router: ShiftsRouting? { get set }
var listener: ShiftsListener? { get set }
}
protocol ShiftsViewControllable: ViewControllable {
// TODO: Declare methods the router invokes to manipulate the view hierarchy.
}
final class ShiftsRouter: ViewableRouter<ShiftsInteractable, ShiftsViewControllable>, ShiftsRouting {
// TODO: Constructor inject child builder protocols to allow building children.
override init(interactor: ShiftsInteractable, viewController: ShiftsViewControllable) {
super.init(interactor: interactor, viewController: viewController)
interactor.router = self
}
}
<file_sep>/Shifts/Shifts/Services/Local/LocationServiceProtocol.swift
//
// LocationServiceProtocol.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import CoreLocation
import When
enum LocationError: Error {
case locationDisabled
case locationNotAuthorised
case locationNotFound
case locationError(String)
public var localizedDescription: String {
return message
}
public var message: String {
switch self {
case .locationError(let message): return message
case .locationDisabled: return L10n.locationDisabled
case .locationNotAuthorised: return L10n.locationNotAuthorised
case .locationNotFound: return L10n.locationNotFound
}
}
}
protocol LocationServiceProtocol: AutoMockable {
var lastLocation: CLLocation? { get }
func discover() -> Promise<CLLocation>
}
<file_sep>/Shifts/ShiftsTests/Generated/Interactable.generated.swift
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable line_length
// swiftlint:disable variable_name
import Foundation
import RIBs
import RxSwift
@testable import Shifts
final class RootInteractableMock: RootInteractable {
var router: RootRouting?
var listener: RootListener?
var isActive: Bool = false { didSet { isActiveSetCallCount += 1 } }
private (set) var isActiveSetCallCount = 0
var isActiveStreamSubject: PublishSubject<Bool> = PublishSubject<Bool>() { didSet { isActiveStreamSubjectSetCallCount += 1 } }
private (set) var isActiveStreamSubjectSetCallCount = 0
var isActiveStream: Observable<Bool> { return isActiveStreamSubject }
// Function Handlers
var activateHandler: (() -> ())?
var activateCallCount: Int = 0
var deactivateHandler: (() -> ())?
var deactivateCallCount: Int = 0
func activate() {
activateCallCount += 1
if let activateHandler = activateHandler {
return activateHandler()
}
}
func deactivate() {
deactivateCallCount += 1
if let deactivateHandler = deactivateHandler {
return deactivateHandler()
}
}
}
final class ShiftsInteractableMock: ShiftsInteractable {
var router: ShiftsRouting?
var listener: ShiftsListener?
var isActive: Bool = false { didSet { isActiveSetCallCount += 1 } }
private (set) var isActiveSetCallCount = 0
var isActiveStreamSubject: PublishSubject<Bool> = PublishSubject<Bool>() { didSet { isActiveStreamSubjectSetCallCount += 1 } }
private (set) var isActiveStreamSubjectSetCallCount = 0
var isActiveStream: Observable<Bool> { return isActiveStreamSubject }
// Function Handlers
var activateHandler: (() -> ())?
var activateCallCount: Int = 0
var deactivateHandler: (() -> ())?
var deactivateCallCount: Int = 0
func activate() {
activateCallCount += 1
if let activateHandler = activateHandler {
return activateHandler()
}
}
func deactivate() {
deactivateCallCount += 1
if let deactivateHandler = deactivateHandler {
return deactivateHandler()
}
}
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/ImageOperation.swift
//
// ImageOperation.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
/// Model Operation, return a response as Decodable Model
open class ImageOperation: OperationProtocol {
public typealias DataType = UIImage?
/// Request
public var request: RequestProtocol?
/// Init
public init() { }
/// Execute a request and return your specified model `Output`.
///
/// - Parameters:
/// - service: service to use
/// - Returns: Promise
public func execute(in service: NetworkServiceProtocol) -> Promise<UIImage?> {
return service.execute(request)
.then { response -> UIImage? in
guard let data = response.data else {
throw NetworkError.missingData("response with no data")
}
return UIImage(data: data)
}
}
}
<file_sep>/Shifts/Shifts/Models/StopShiftResponse.swift
//
// StopShiftResponse.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
struct StopShiftResponse: Codable {
let time: String
let latitude: String
let longitude: String
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/OperationProtocol.swift
//
// OperationProtocol.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
public protocol OperationProtocol {
associatedtype T
/// Request
var request: RequestProtocol? { get set }
/// Execute an operation into specified service
///
/// - Parameters:
/// - service: service to use
/// - Returns: Promise
func execute(in service: NetworkServiceProtocol) -> Promise<T>
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/Response.swift
//
// Response.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
public protocol ResponseProtocol {
/// Type of response (success or failure)
var type: Response.Result { get }
/// Request
var request: RequestProtocol { get }
/// Return the http url response
var httpResponse: HTTPURLResponse? { get }
/// Return HTTP status code of the response
var httpStatusCode: Int? { get }
/// Return the raw Data instance response of the request
var data: Data? { get }
/// Attempt to decode Data received from server and return a String object.
/// If it fails it return `nil`.
/// Call is not cached but evaluated at each call.
/// If no encoding is specified, `utf8` is used instead.
///
/// - Parameter encoding: encoding of the data
/// - Returns: String or `nil` if failed
func toString(_ encoding: String.Encoding?) -> String?
}
public class Response: ResponseProtocol {
/// Type of response
///
/// - success: success
/// - error: error
public enum Result {
case success(_: Int)
case error(_: Int)
case noResponse
private static let successCodes: Range<Int> = 200..<299
public static func from(response: HTTPURLResponse?) -> Result {
guard let r = response else {
return .noResponse
}
return (Result.successCodes.contains(r.statusCode) ? .success(r.statusCode) : .error(r.statusCode))
}
public var code: Int? {
switch self {
case .success(let code): return code
case .error(let code): return code
case .noResponse: return nil
}
}
}
/// Type of result
public let type: Response.Result
/// Status code of the response
public var httpStatusCode: Int? {
return self.type.code
}
/// HTTPURLResponse
public let httpResponse: HTTPURLResponse?
/// Raw data of the response
public var data: Data?
/// Request executed
public let request: RequestProtocol
/// Initialize a new response from Alamofire response
///
/// - Parameters:
/// - response: response
/// - request: request
public init(urlResponse response: URLResponse?, data: Data?, request: RequestProtocol) {
let httpResponse = response as? HTTPURLResponse
self.type = Result.from(response: httpResponse)
self.httpResponse = httpResponse
self.data = data
self.request = request
}
public func toString(_ encoding: String.Encoding? = nil) -> String? {
guard let d = self.data else { return nil }
return String(data: d, encoding: encoding ?? .utf8)
}
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/ModelOperation.swift
//
// ModelOperation.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
/// Model Operation, return a response as Decodable Model
open class ModelOperation<Output: Decodable>: OperationProtocol {
public typealias DataType = Output
/// Request
public var request: RequestProtocol?
/// Init
public init() {
}
/// Execute a request and return your specified model `Output`.
///
/// - Parameters:
/// - service: service to use
/// - Returns: Promise
public func execute(in service: NetworkServiceProtocol) -> Promise<Output> {
return service.execute(request)
.then { response -> Output in
guard let data = response.data else {
throw NetworkError.missingData("Response contains no data")
}
do {
let decoder: JSONDecoder = JSONDecoder()
return try decoder.decode(Output.self, from: data)
} catch let error {
throw NetworkError.failedToDecode(error.localizedDescription)
}
}
}
}
<file_sep>/Shifts/Shifts/RIBs/Root/RootBuilder.swift
//
// RootBuilder.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
import RxSwift
protocol RootDependency: Dependency {
// TODO: Declare the set of dependencies required by this RIB, but cannot be
// created by this RIB.
var networkService: NetworkServiceProtocol { get }
var imageService: NetworkServiceProtocol { get }
var state: Variable<AppState> { get }
}
final class RootComponent: Component<RootDependency> {
// TODO: Declare 'fileprivate' dependencies that are only used by this RIB.
var networkService: NetworkServiceProtocol {
return dependency.networkService
}
var imageService: NetworkServiceProtocol {
return dependency.imageService
}
var state: Variable<AppState> {
return dependency.state
}
}
// MARK: - Builder
protocol RootBuildable: Buildable {
func build() -> LaunchRouting
}
final class RootBuilder: Builder<RootDependency>, RootBuildable {
override init(dependency: RootDependency) {
super.init(dependency: dependency)
}
func build() -> LaunchRouting {
let component = RootComponent(dependency: dependency)
let viewController = RootViewController()
let interactor = RootInteractor(presenter: viewController)
let shiftsBuilder = ShiftsBuilder(dependency: component)
return RootRouter(interactor: interactor,
viewController: viewController,
shiftsBuilder: shiftsBuilder)
}
}
<file_sep>/Shifts/Shifts/Services/Remote/ShiftsService.swift
//
// StartShiftOperation.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
private final class StartShiftOperation: PlainTextOperation {
init(time: Date, latitude: Double, longitude: Double) {
super.init()
let body: RequestBody = .json([
"time": time.toServerString(),
"latitude": "\(latitude)",
"longitude": "\(longitude)"
])
request = Request(method: .post, endpoint: "/shift/start",
params: nil, fields: nil, body: body)
}
}
private final class StopShiftOperation: PlainTextOperation {
init(time: Date, latitude: Double, longitude: Double) {
super.init()
let body: RequestBody = .json([
"time": time.toServerString(),
"latitude": "\(latitude)",
"longitude": "\(longitude)"
])
request = Request(method: .post, endpoint: "/shift/end",
params: nil, fields: nil, body: body)
}
}
private final class GetShiftsOperation: ModelOperation<[Shift]?> {
override init() {
super.init()
request = Request(method: .get, endpoint: "/shifts",
params: nil, fields: nil, body: nil)
}
}
private final class GetShiftImageOperation: ImageOperation {
init(url: String) {
super.init()
request = Request(method: .get, endpoint: url,
params: nil, fields: nil, body: nil)
}
}
final class ShiftsService: ShiftsServiceProtocol {
private let networkService: NetworkServiceProtocol
private let imageService: NetworkServiceProtocol
init(networkService: NetworkServiceProtocol, imageService: NetworkServiceProtocol) {
self.networkService = networkService
self.imageService = imageService
}
func getShifts() -> Promise<[Shift]> {
return GetShiftsOperation()
.execute(in: networkService)
.then { response -> [Shift] in
if let shifts = response {
return shifts
}
return []
}
}
func startShift(latitude: Double, longitude: Double) -> Promise<Bool> {
return StartShiftOperation(time: Date(), latitude: latitude, longitude: longitude)
.execute(in: networkService)
.then { response -> Bool in
return response != nil
}
}
func stopShift(latitude: Double, longitude: Double) -> Promise<Bool> {
return StopShiftOperation(time: Date(), latitude: latitude, longitude: longitude)
.execute(in: networkService)
.then { response -> Bool in
return response != nil
}
}
func getShiftImage(url: String) -> Promise<UIImage> {
return GetShiftImageOperation(url: url)
.execute(in: imageService)
.then { response -> UIImage in
if let image = response {
return image
}
throw NetworkError.missingData("Missing image")
}
}
}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/NetworkService.swift
//
// NetworkService.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
/// Service is a concrete implementation of the ServiceProtocol
open class NetworkService: NSObject, NetworkServiceProtocol {
/// Session headers
public var headers: HeadersDict
/// URL session
public let session: URLSession
/// Authentication
public var auth: SessionAuth?
/// Base url
public var url: String
/// Service cache policy
public var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
/// Internal processing queue
private let networkingQueue = DispatchQueue(label: "network-processing-queue")
/// Initialize a new service with given parameters
public required init(baseUrl: String, auth: SessionAuth?, headers: HeadersDict) {
self.url = baseUrl
self.auth = auth
self.headers = headers
self.session = URLSession(configuration: URLSessionConfiguration.default)
}
/// Execute a request and return a promise with the response
///
/// - Parameters:
/// - request: request to execute
/// - Returns: Promise
/// - Throws: throw an exception if operation cannot be executed
public func execute(_ request: RequestProtocol?) -> Promise<ResponseProtocol> {
// Wrap in a promise the request itself
let promise = Promise<ResponseProtocol>()
networkingQueue.async {
guard let rq = request else { // missing request
// yield this thread
promise.reject(NetworkError.missingEndpoint("no request specified"))
return
}
do {
let urlRequest = try rq.urlRequest(in: self)
let task: URLSessionDataTask = self.session.dataTask(with: urlRequest) { data, response, error in
let parsedResponse = Response(urlResponse: response, data: data, request: rq)
if let url = urlRequest.url,
let responseStr = parsedResponse.toString() {
#if DEBUG
print("Response from \(url):")
print(responseStr)
#endif
}
switch parsedResponse.type {
case .success: // success
promise.resolve(parsedResponse)
case .error(let code): // failure
if code == 23 {
promise.reject(NetworkError.authorisationExpired("session expired"))
} else if code == 401 {
promise.reject(NetworkError.notAuthorised("request is not authorized"))
} else if let data = parsedResponse.data, data.isEmpty {
promise.reject(NetworkError.missingData("no data"))
} else if parsedResponse.data != nil {
promise.resolve(parsedResponse)
} else {
promise.reject(NetworkError.genericError("received error code: \(code)"))
}
case .noResponse: // no response
promise.reject(NetworkError.noResponse("no response from server"))
}
}
task.resume()
} catch (let error) {
#if DEBUG
print(error.localizedDescription)
#endif
promise.reject(error)
}
}
return promise
}
}
<file_sep>/Shifts/Shifts/Views/ShiftCell.swift
//
// ShiftCell.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RxSwift
final class ShiftCell: UITableViewCell {
@IBOutlet private weak var iconView: UIImageView!
@IBOutlet private weak var startLabel: UILabel!
@IBOutlet private weak var stopLabel: UILabel!
private var disposeBag = DisposeBag()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func prepareForReuse() {
// Unsubscribe from previous subscription
disposeBag = DisposeBag()
}
func show(shift: ShiftVM) {
startLabel.text = L10n.startedOn(shift.startedAt)
if let endedAt = shift.endedAt {
stopLabel.text = L10n.stoppedOn(endedAt)
} else {
stopLabel.text = nil
}
iconView.image = shift.image.value
shift.image
.asObservable()
.subscribe(onNext: { [weak self] (newImage) in
guard let this = self else { return }
this.iconView.image = newImage
}).disposed(by: disposeBag)
}
}
<file_sep>/Shifts/Shifts/RIBs/Shifts/ShiftsBuilder.swift
//
// ShiftsBuilder.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
import RxSwift
protocol ShiftsDependency: Dependency {
// TODO: Declare the set of dependencies required by this RIB, but cannot be
// created by this RIB.
var networkService: NetworkServiceProtocol { get }
var imageService: NetworkServiceProtocol { get }
var state: Variable<AppState> { get }
}
final class ShiftsComponent: Component<ShiftsDependency> {
// TODO: Declare 'fileprivate' dependencies that are only used by this RIB.
let locationService: LocationServiceProtocol
var networkService: NetworkServiceProtocol {
return dependency.networkService
}
var imageService: NetworkServiceProtocol {
return dependency.imageService
}
var state: Variable<AppState> {
return dependency.state
}
init(dependency: ShiftsDependency, locationService: LocationServiceProtocol) {
self.locationService = locationService
super.init(dependency: dependency)
}
}
// MARK: - Builder
protocol ShiftsBuildable: Buildable {
func build(withListener listener: ShiftsListener) -> ShiftsRouting
}
final class ShiftsBuilder: Builder<ShiftsDependency>, ShiftsBuildable {
override init(dependency: ShiftsDependency) {
super.init(dependency: dependency)
}
func build(withListener listener: ShiftsListener) -> ShiftsRouting {
let locationService = LocationService()
let component = ShiftsComponent(dependency: dependency,
locationService: locationService)
let service = ShiftsService(networkService: component.networkService,
imageService: component.imageService)
let viewController = ShiftsViewController()
let interactor = ShiftsInteractor(presenter: viewController,
service: service,
locationService: component.locationService,
state: component.state)
interactor.listener = listener
return ShiftsRouter(interactor: interactor, viewController: viewController)
}
}
<file_sep>/Shifts/Shifts/Other-Sources/Generated/l10n.swift
// swiftlint:disable all
// Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
// MARK: - Strings
// swiftlint:disable function_parameter_count identifier_name line_length type_body_length
internal enum L10n {
/// Loading...
internal static let loading = L10n.tr("Localizable", "Loading")
/// LocationDisabled
internal static let locationDisabled = L10n.tr("Localizable", "LocationDisabled")
/// Failed to detect your location
internal static let locationFailed = L10n.tr("Localizable", "LocationFailed")
/// Location is not authorised
internal static let locationNotAuthorised = L10n.tr("Localizable", "LocationNotAuthorised")
/// Location not found
internal static let locationNotFound = L10n.tr("Localizable", "LocationNotFound")
/// Waiting for location...
internal static let locationNotReady = L10n.tr("Localizable", "LocationNotReady")
/// N/A
internal static let notAvailable = L10n.tr("Localizable", "NotAvailable")
/// Shift
internal static let shift = L10n.tr("Localizable", "Shift")
/// Shifts
internal static let shifts = L10n.tr("Localizable", "Shifts")
/// Start
internal static let start = L10n.tr("Localizable", "Start")
/// Start: %@
internal static func startedOn(_ p1: String) -> String {
return L10n.tr("Localizable", "StartedOn", p1)
}
/// Starting...
internal static let starting = L10n.tr("Localizable", "Starting")
/// Stop
internal static let stop = L10n.tr("Localizable", "Stop")
/// Stop: %@
internal static func stoppedOn(_ p1: String) -> String {
return L10n.tr("Localizable", "StoppedOn", p1)
}
/// Stopping...
internal static let stopping = L10n.tr("Localizable", "Stopping")
}
// swiftlint:enable function_parameter_count identifier_name line_length type_body_length
// MARK: - Implementation Details
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = NSLocalizedString(key, tableName: table, bundle: Bundle(for: BundleToken.self), comment: "")
return String(format: format, locale: Locale.current, arguments: args)
}
}
private final class BundleToken {}
<file_sep>/Shifts/Shifts/Services/Remote/Networking/NetworkErrors.swift
//
// NetworkErrors.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
/// Possible networking error
///
/// - dataIsNotEncodable: data cannot be encoded in format you have specified
/// - stringFailedToDecode: failed to decode data with given encoding
public enum NetworkError: Error {
case dataIsNotEncodable(String)
case stringFailedToDecode(String)
case invalidURL(String)
case notAuthorised(String)
case authorisationExpired(String)
case noResponse(String)
case missingEndpoint(String)
case failedToParseData(String)
case missingData(String)
case failedToDecode(String)
case genericError(String)
public var localizedDescription: String {
return message
}
public var message: String {
switch self {
case .dataIsNotEncodable(let message),
.stringFailedToDecode(let message),
.invalidURL(let message),
.notAuthorised(let message),
.authorisationExpired(let message),
.noResponse(let message),
.missingEndpoint(let message),
.failedToParseData(let message),
.missingData(let message),
.failedToDecode(let message),
.genericError(let message):
return message
}
}
}
<file_sep>/Shifts/Shifts/Models/ShiftVM.swift
//
// ShiftVM.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
final class ShiftVM {
let model: Shift
init(model: Shift) {
self.model = model
}
var key: Int {
return model.id
}
var startedAt: String {
return model.start.toDateTime()?.toString() ?? Date.distantPast.toString()
}
var endedAt: String? {
return model.end.toDateTime()?.toString()
}
var startLatitude: String {
return model.startLatitude
}
var startLongitude: String {
return model.startLongitude
}
var endLatitude: String {
return model.endLatitude
}
var endLongitude: String {
return model.endLongitude
}
var imageUrl: String {
return model.image
}
var image: Variable<UIImage?> = Variable(nil)
}
<file_sep>/Shifts/Shifts/RIBs/Shifts/ShiftsViewController.swift
//
// ShiftsViewController.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
import RxSwift
import UIKit
protocol ShiftsPresentableListener: class {
func didPrepareView()
func didSelectAction()
func didRequestImage(for shift: ShiftVM)
}
final class ShiftsViewController: UIViewController, ShiftsPresentable, ShiftsViewControllable {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var actionButton: UIButton!
weak var listener: ShiftsPresentableListener?
private var shifts: [ShiftVM] = []
private let cellId: String = "ShiftsViewControllerShiftCellId"
override func viewDidLoad() {
super.viewDidLoad()
actionButton.layer.cornerRadius = actionButton.frame.width / 2.0
actionButton.layer.borderColor = UIColor.black.cgColor
actionButton.layer.borderWidth = 2.0
tableView.register(UINib(nibName: "ShiftCell", bundle: Bundle(for: ShiftCell.self)),
forCellReuseIdentifier: cellId)
listener?.didPrepareView()
}
@IBAction
private func onActionButtonTap() {
listener?.didSelectAction()
}
// MARK: - ShiftsPresentable
func showShifts(_ shifts: [ShiftVM]) {
self.shifts = shifts
tableView.reloadData()
}
func updateActionTitle(to newTitle: String) {
actionButton.setTitle(newTitle, for: UIControl.State())
}
func showAction() {
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
self.actionButton.alpha = 1.0
}) { finished in
self.actionButton.alpha = 1.0
}
}
func hideAction() {
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
self.actionButton.alpha = 0.0
}) { finished in
self.actionButton.alpha = 0.0
}
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension ShiftsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shifts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId) else { fatalError() }
guard let shiftCell = cell as? ShiftCell else { fatalError() }
guard indexPath.row < shifts.count else { fatalError() }
let shift = shifts[indexPath.row]
shiftCell.show(shift: shift)
listener?.didRequestImage(for: shift)
return shiftCell
}
}
<file_sep>/Shifts/Shifts/Models/Shift.swift
//
// Shift.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
struct Shift: Codable {
let id: Int
let start: String
let end: String
let startLatitude: String
let startLongitude: String
let endLatitude: String
let endLongitude: String
let image: String
}
<file_sep>/Shifts/ShiftsTests/Generated/AutoMockable.generated.swift
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable line_length
// swiftlint:disable variable_name
import Foundation
import RIBs
import RxSwift
import CoreLocation
import When
@testable import Shifts
final class LocationServiceProtocolMock: LocationServiceProtocol {
var lastLocation: CLLocation?
//MARK: - discover
var discoverCallsCount = 0
var discoverCalled: Bool {
return discoverCallsCount > 0
}
var discoverReturnValue: Promise<CLLocation>!
var discoverHandler: (() -> Promise<CLLocation>)?
func discover() -> Promise<CLLocation> {
discoverCallsCount += 1
return discoverHandler.map({ $0() }) ?? discoverReturnValue
}
}
final class NetworkServiceProtocolMock: NetworkServiceProtocol {
var headers: HeadersDict = [:]
var auth: SessionAuth?
var url: String {
get { return underlyingUrl }
set(value) { underlyingUrl = value }
}
var underlyingUrl: String!
var cachePolicy: URLRequest.CachePolicy {
get { return underlyingCachePolicy }
set(value) { underlyingCachePolicy = value }
}
var underlyingCachePolicy: URLRequest.CachePolicy!
//MARK: - init
var initBaseUrlAuthHeadersReceivedArguments: (baseUrl: String, auth: SessionAuth?, headers: HeadersDict)?
var initBaseUrlAuthHeadersHandler: ((String, SessionAuth?, HeadersDict) -> Void)?
required init(baseUrl: String, auth: SessionAuth?, headers: HeadersDict) {
initBaseUrlAuthHeadersReceivedArguments = (baseUrl: baseUrl, auth: auth, headers: headers)
initBaseUrlAuthHeadersHandler?(baseUrl, auth, headers)
}
//MARK: - execute
var executeCallsCount = 0
var executeCalled: Bool {
return executeCallsCount > 0
}
var executeReceivedRequest: RequestProtocol?
var executeReturnValue: Promise<ResponseProtocol>!
var executeHandler: ((RequestProtocol?) -> Promise<ResponseProtocol>)?
func execute(_ request: RequestProtocol?) -> Promise<ResponseProtocol> {
executeCallsCount += 1
executeReceivedRequest = request
return executeHandler.map({ $0(request) }) ?? executeReturnValue
}
}
final class ShiftsServiceProtocolMock: ShiftsServiceProtocol {
//MARK: - init
var initNetworkServiceImageServiceReceivedArguments: (networkService: NetworkServiceProtocol, imageService: NetworkServiceProtocol)?
var initNetworkServiceImageServiceHandler: ((NetworkServiceProtocol, NetworkServiceProtocol) -> Void)?
required init(networkService: NetworkServiceProtocol, imageService: NetworkServiceProtocol) {
initNetworkServiceImageServiceReceivedArguments = (networkService: networkService, imageService: imageService)
initNetworkServiceImageServiceHandler?(networkService, imageService)
}
//MARK: - getShifts
var getShiftsCallsCount = 0
var getShiftsCalled: Bool {
return getShiftsCallsCount > 0
}
var getShiftsReturnValue: Promise<[Shift]>!
var getShiftsHandler: (() -> Promise<[Shift]>)?
func getShifts() -> Promise<[Shift]> {
getShiftsCallsCount += 1
return getShiftsHandler.map({ $0() }) ?? getShiftsReturnValue
}
//MARK: - startShift
var startShiftLatitudeLongitudeCallsCount = 0
var startShiftLatitudeLongitudeCalled: Bool {
return startShiftLatitudeLongitudeCallsCount > 0
}
var startShiftLatitudeLongitudeReceivedArguments: (latitude: Double, longitude: Double)?
var startShiftLatitudeLongitudeReturnValue: Promise<Bool>!
var startShiftLatitudeLongitudeHandler: ((Double, Double) -> Promise<Bool>)?
func startShift(latitude: Double, longitude: Double) -> Promise<Bool> {
startShiftLatitudeLongitudeCallsCount += 1
startShiftLatitudeLongitudeReceivedArguments = (latitude: latitude, longitude: longitude)
return startShiftLatitudeLongitudeHandler.map({ $0(latitude, longitude) }) ?? startShiftLatitudeLongitudeReturnValue
}
//MARK: - stopShift
var stopShiftLatitudeLongitudeCallsCount = 0
var stopShiftLatitudeLongitudeCalled: Bool {
return stopShiftLatitudeLongitudeCallsCount > 0
}
var stopShiftLatitudeLongitudeReceivedArguments: (latitude: Double, longitude: Double)?
var stopShiftLatitudeLongitudeReturnValue: Promise<Bool>!
var stopShiftLatitudeLongitudeHandler: ((Double, Double) -> Promise<Bool>)?
func stopShift(latitude: Double, longitude: Double) -> Promise<Bool> {
stopShiftLatitudeLongitudeCallsCount += 1
stopShiftLatitudeLongitudeReceivedArguments = (latitude: latitude, longitude: longitude)
return stopShiftLatitudeLongitudeHandler.map({ $0(latitude, longitude) }) ?? stopShiftLatitudeLongitudeReturnValue
}
//MARK: - getShiftImage
var getShiftImageUrlCallsCount = 0
var getShiftImageUrlCalled: Bool {
return getShiftImageUrlCallsCount > 0
}
var getShiftImageUrlReceivedUrl: String?
var getShiftImageUrlReturnValue: Promise<UIImage>!
var getShiftImageUrlHandler: ((String) -> Promise<UIImage>)?
func getShiftImage(url: String) -> Promise<UIImage> {
getShiftImageUrlCallsCount += 1
getShiftImageUrlReceivedUrl = url
return getShiftImageUrlHandler.map({ $0(url) }) ?? getShiftImageUrlReturnValue
}
}
<file_sep>/Shifts/Shifts/RIBs/Root/RootComponent+Shifts.swift
//
// RootComponent+Shifts.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
/// The dependencies needed from the parent scope of Root to provide for the Shifts scope.
// TODO: Update RootDependency protocol to inherit this protocol.
protocol RootDependencyShifts: Dependency {
// TODO: Declare dependencies needed from the parent scope of Root to provide dependencies
// for the Shifts scope.
}
extension RootComponent: ShiftsDependency {
// TODO: Implement properties to provide for Shifts scope.
}
<file_sep>/Shifts/ShiftsTests/ShiftsTests.swift
//
// ShiftsTests.swift
// ShiftsTests
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import XCTest
import RxSwift
import When
import CoreLocation
@testable import Shifts
final class ShiftsTests: XCTestCase {
private var interactor: ShiftsInteractor!
private var router: ShiftsRoutingMock!
private var view: ShiftsViewControllableMock!
private var presenter: ShiftsPresentableMock!
private var appState: Variable<AppState>!
private var locationService: LocationServiceProtocolMock!
private var service: ShiftsServiceProtocolMock!
private var locationPromise: Promise<CLLocation>!
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
locationPromise = Promise<CLLocation>()
locationService = LocationServiceProtocolMock()
locationService.discoverReturnValue = locationPromise
locationService.lastLocation = CLLocation(latitude: 0.0, longitude: 0.0)
let netService = NetworkServiceProtocolMock(baseUrl: Config.serviceBaseUrl,
auth: .token(Config.serviceAccessToken),
headers: [:])
let imgService = NetworkServiceProtocolMock(baseUrl: "", auth: nil, headers: [:])
service = ShiftsServiceProtocolMock(networkService: netService, imageService: imgService)
appState = Variable<AppState>(.launched)
presenter = ShiftsPresentableMock()
view = ShiftsViewControllableMock()
interactor = ShiftsInteractor(presenter: presenter,
service: service,
locationService: locationService,
state: appState)
router = ShiftsRoutingMock(interactable: interactor, viewController: view)
interactor.router = router
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
// MARK: - Tests
func testLifecycle() {
// This is an example of an interactor test case.
// Test your interactor binds observables and sends messages to router or listener.
service.getShiftsReturnValue = Promise<[Shift]>()
XCTAssertFalse(interactor.isActive)
XCTAssertEqual(router.children.count, 0)
interactor.activate()
XCTAssertTrue(interactor.isActive)
interactor.deactivate()
XCTAssertFalse(interactor.isActive)
}
func testInitialState() {
service.getShiftsReturnValue = Promise<[Shift]>()
XCTAssertEqual(presenter.updateActionTitleToCallsCount, 0)
XCTAssertEqual(presenter.showShiftsCallsCount, 0)
XCTAssertEqual(presenter.showActionCallsCount, 0)
XCTAssertEqual(presenter.hideActionCallsCount, 0)
XCTAssertEqual(presenter.showLoadingWithCallsCount, 0)
XCTAssertEqual(presenter.showErrorWithCallsCount, 0)
XCTAssertEqual(presenter.hideLoadingCallsCount, 0)
interactor.activate()
interactor.didPrepareView()
XCTAssertEqual(presenter.updateActionTitleToCallsCount, 1)
XCTAssertEqual(presenter.updateActionTitleToReceivedNewTitle, L10n.start)
interactor.deactivate()
}
func testInitialLoading() {
let expect = expectation(description: "Service result callback")
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 1)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 2)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 0)
XCTAssertEqual(self.presenter.hideActionCallsCount, 0)
self.interactor.deactivate()
}
}
func testFailedLoading() {
let expect = expectation(description: "Service result callback")
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.reject(NetworkError.genericError("Test"))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 1)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 0)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showActionCallsCount, 0)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 0)
XCTAssertEqual(self.presenter.hideActionCallsCount, 0)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithReceivedStatus, "Test")
self.interactor.deactivate()
}
}
func testShowStartedShift() {
let expect = expectation(description: "Service result callback")
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 1,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "1.0",
startLongitude: "1.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com"),
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 1)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 2)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.stop)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 1)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 2)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.hideActionCallsCount, 0)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 0)
self.interactor.deactivate()
}
}
func testShowStoppedShift() {
let expect = expectation(description: "Service result callback")
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 1,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "1.0",
startLongitude: "1.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com"),
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 1)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 2)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 1)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 2)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.hideActionCallsCount, 0)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 0)
self.interactor.deactivate()
}
}
func testFailedLocation() {
let expect = expectation(description: "Service result callback")
service.startShiftLatitudeLongitudeHandler = { (latitude, longitude) -> Promise<Bool> in
let promise = Promise<Bool>()
DispatchQueue.main.async {
promise.resolve(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
}
return promise
}
interactor.activate()
interactor.didPrepareView()
DispatchQueue.main.async {
self.interactor.didSelectAction()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 1)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 4)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 1)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 1)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.hideActionCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 1)
self.interactor.deactivate()
}
}
func testStartShift() {
let expect = expectation(description: "Service result callback")
service.startShiftLatitudeLongitudeHandler = { (latitude, longitude) -> Promise<Bool> in
let promise = Promise<Bool>()
DispatchQueue.main.async {
promise.resolve(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
DispatchQueue.main.async {
self.interactor.didSelectAction()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 3)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 2)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 4)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 2)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 1)
XCTAssertEqual(self.presenter.showActionCallsCount, 2)
XCTAssertEqual(self.presenter.hideActionCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 0)
self.interactor.deactivate()
}
}
func testFailedStartShift() {
let expect = expectation(description: "Service result callback")
service.startShiftLatitudeLongitudeHandler = { (latitude, longitude) -> Promise<Bool> in
let promise = Promise<Bool>()
DispatchQueue.main.async {
promise.reject(NetworkError.genericError("Test"))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "2018-01-01T02:11:00+00:00",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
DispatchQueue.main.async {
self.interactor.didSelectAction()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 2)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 3)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 1)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 1)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.hideActionCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 1)
self.interactor.deactivate()
}
}
func testStopShift() {
let expect = expectation(description: "Service result callback")
service.stopShiftLatitudeLongitudeHandler = { (latitude, longitude) -> Promise<Bool> in
let promise = Promise<Bool>()
DispatchQueue.main.async {
promise.resolve(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.interactor.didSelectAction()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 3)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 2)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 4)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.stop)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 2)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 1)
XCTAssertEqual(self.presenter.showActionCallsCount, 2)
XCTAssertEqual(self.presenter.hideActionCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 0)
self.interactor.deactivate()
}
}
func testFailedStopShift() {
let expect = expectation(description: "Service result callback")
service.stopShiftLatitudeLongitudeHandler = { (latitude, longitude) -> Promise<Bool> in
let promise = Promise<Bool>()
DispatchQueue.main.async {
promise.reject(NetworkError.genericError("Test"))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
expect.fulfill()
}
}
return promise
}
service.getShiftsHandler = { () -> Promise<[Shift]> in
let promise = Promise<[Shift]>()
DispatchQueue.main.async {
promise.resolve([
Shift(id: 0,
start: "2018-01-01T00:11:00+00:00",
end: "",
startLatitude: "2.0",
startLongitude: "2.0",
endLatitude: "2.0",
endLongitude: "2.0",
image: "www.google.com")
])
}
return promise
}
interactor.activate()
interactor.didPrepareView()
locationPromise.resolve(CLLocation(latitude: 1.0, longitude: 1.0))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.interactor.didSelectAction()
}
waitForExpectations(timeout: 1) { error in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
XCTAssertEqual(self.presenter.showLoadingWithCallsCount, 2)
XCTAssertEqual(self.presenter.hideLoadingCallsCount, 1)
XCTAssertEqual(self.presenter.updateActionTitleToCallsCount, 3)
XCTAssertEqual(self.presenter.updateActionTitleToReceivedNewTitle, L10n.start)
XCTAssertEqual(self.presenter.showShiftsCallsCount, 1)
XCTAssertNotNil(self.presenter.showShiftsReceivedShifts)
XCTAssertEqual(self.presenter.showShiftsReceivedShifts!.count, 1)
XCTAssertEqual(self.presenter.showActionCallsCount, 1)
XCTAssertEqual(self.presenter.hideActionCallsCount, 1)
XCTAssertEqual(self.presenter.showErrorWithCallsCount, 1)
self.interactor.deactivate()
}
}
}
<file_sep>/Shifts/Shifts/RIBs/Common/UIViewController.swift
//
// UIViewController.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import RIBs
extension UIViewController {
func present(view: ViewControllable) {
present(view.uiviewController, animated: true, completion: nil)
}
func dismiss(view: ViewControllable, animated: Bool) {
view.uiviewController.dismiss(animated: animated, completion: nil)
}
func push(view: ViewControllable, animated: Bool) {
navigationController?.pushViewController(view.uiviewController, animated: animated)
}
func pop(view: ViewControllable, animated: Bool) {
navigationController?.popViewController(animated: animated)
}
}
<file_sep>/Shifts/Shifts/Utils/UserDefaults.swift
//
// UserDefaults.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
public extension UserDefaults {
public static var shared: UserDefaults = UserDefaults(suiteName: Config.storeFilename) ?? UserDefaults.standard
public func reset() {
removePersistentDomain(forName: Config.storeFilename)
}
public var lastShiftStartTime: Date? {
get {
let value = double(forKey: #function)
return Date(timeIntervalSince1970: value)
}
set {
self.set(newValue?.timeIntervalSince1970, forKey: #function)
self.synchronize()
}
}
}
<file_sep>/Shifts/ShiftsTests/Generated/Presentable.generated.swift
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable line_length
// swiftlint:disable variable_name
import Foundation
import RIBs
import RxSwift
@testable import Shifts
final class RootPresentableMock: RootPresentable {
var listener: RootPresentableListener?
}
final class ShiftsPresentableMock: ShiftsPresentable {
var listener: ShiftsPresentableListener?
//MARK: - showShifts
var showShiftsCallsCount = 0
var showShiftsCalled: Bool {
return showShiftsCallsCount > 0
}
var showShiftsReceivedShifts: [ShiftVM]?
var showShiftsHandler: (([ShiftVM]) -> Void)?
func showShifts(_ shifts: [ShiftVM]) {
showShiftsCallsCount += 1
showShiftsReceivedShifts = shifts
showShiftsHandler?(shifts)
}
//MARK: - updateActionTitle
var updateActionTitleToCallsCount = 0
var updateActionTitleToCalled: Bool {
return updateActionTitleToCallsCount > 0
}
var updateActionTitleToReceivedNewTitle: String?
var updateActionTitleToHandler: ((String) -> Void)?
func updateActionTitle(to newTitle: String) {
updateActionTitleToCallsCount += 1
updateActionTitleToReceivedNewTitle = newTitle
updateActionTitleToHandler?(newTitle)
}
//MARK: - showAction
var showActionCallsCount = 0
var showActionCalled: Bool {
return showActionCallsCount > 0
}
var showActionHandler: (() -> Void)?
func showAction() {
showActionCallsCount += 1
showActionHandler?()
}
//MARK: - hideAction
var hideActionCallsCount = 0
var hideActionCalled: Bool {
return hideActionCallsCount > 0
}
var hideActionHandler: (() -> Void)?
func hideAction() {
hideActionCallsCount += 1
hideActionHandler?()
}
//MARK: - showLoading
var showLoadingWithCallsCount = 0
var showLoadingWithCalled: Bool {
return showLoadingWithCallsCount > 0
}
var showLoadingWithReceivedStatus: String?
var showLoadingWithHandler: ((String?) -> Void)?
func showLoading(with status: String?) {
showLoadingWithCallsCount += 1
showLoadingWithReceivedStatus = status
showLoadingWithHandler?(status)
}
//MARK: - showError
var showErrorWithCallsCount = 0
var showErrorWithCalled: Bool {
return showErrorWithCallsCount > 0
}
var showErrorWithReceivedStatus: String?
var showErrorWithHandler: ((String?) -> Void)?
func showError(with status: String?) {
showErrorWithCallsCount += 1
showErrorWithReceivedStatus = status
showErrorWithHandler?(status)
}
//MARK: - hideLoading
var hideLoadingCallsCount = 0
var hideLoadingCalled: Bool {
return hideLoadingCallsCount > 0
}
var hideLoadingHandler: (() -> Void)?
func hideLoading() {
hideLoadingCallsCount += 1
hideLoadingHandler?()
}
}
<file_sep>/Shifts/ShiftsTests/ShiftsMocks.swift
//
// ShiftsMocks.swift
// ShiftsTests
//
// Created by <NAME> on 26/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
@testable import Shifts
final class ShiftsViewControllableMock: ShiftsViewControllable {
// Variables
var uiviewController: UIViewController = UIViewController() { didSet { uiviewControllerSetCallCount += 1 } }
var uiviewControllerSetCallCount = 0
}
<file_sep>/Shifts/Shifts/Utils/String.swift
//
// String.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
private let dateFormatter = DateFormatter()
extension String {
public func toDateTime() -> Date? {
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return dateFormatter.date(from: self)
}
}
<file_sep>/Shifts/ShiftsTests/Generated/ViewableRouting.generated.swift
// Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
// swiftlint:disable line_length
// swiftlint:disable variable_name
import Foundation
import RIBs
import RxSwift
@testable import Shifts
final class RootRoutingMock: RootRouting {
var viewControllable: ViewControllable
// Variables
var interactable: Interactable { didSet { interactableSetCallCount += 1 } }
private (set) var interactableSetCallCount = 0
var children: [Routing] = [Routing]() { didSet { childrenSetCallCount += 1 } }
private (set) var childrenSetCallCount = 0
var lifecycleSubject: PublishSubject<RouterLifecycle> = PublishSubject<RouterLifecycle>() { didSet { lifecycleSubjectSetCallCount += 1 } }
private (set) var lifecycleSubjectSetCallCount = 0
var lifecycle: Observable<RouterLifecycle> { return lifecycleSubject }
// Function Handlers
var loadHandler: (() -> ())?
private (set) var loadCallCount: Int = 0
var attachChildHandler: ((_ child: Routing) -> ())?
private (set) var attachChildCallCount: Int = 0
var detachChildHandler: ((_ child: Routing) -> ())?
private (set) var detachChildCallCount: Int = 0
init(interactable: Interactable, viewController: ViewControllable) {
self.interactable = interactable
self.viewControllable = viewController
}
func load() {
loadCallCount += 1
if let handler = loadHandler {
return handler()
}
}
func attachChild(_ child: Routing) {
attachChildCallCount += 1
if let handler = attachChildHandler {
return handler(child)
}
}
func detachChild(_ child: Routing) {
detachChildCallCount += 1
if let handler = detachChildHandler {
return handler(child)
}
}
//MARK: - routeToShifts
var routeToShiftsCallsCount = 0
var routeToShiftsCalled: Bool {
return routeToShiftsCallsCount > 0
}
var routeToShiftsHandler: (() -> Void)?
func routeToShifts() {
routeToShiftsCallsCount += 1
routeToShiftsHandler?()
}
}
final class ShiftsRoutingMock: ShiftsRouting {
var viewControllable: ViewControllable
// Variables
var interactable: Interactable { didSet { interactableSetCallCount += 1 } }
private (set) var interactableSetCallCount = 0
var children: [Routing] = [Routing]() { didSet { childrenSetCallCount += 1 } }
private (set) var childrenSetCallCount = 0
var lifecycleSubject: PublishSubject<RouterLifecycle> = PublishSubject<RouterLifecycle>() { didSet { lifecycleSubjectSetCallCount += 1 } }
private (set) var lifecycleSubjectSetCallCount = 0
var lifecycle: Observable<RouterLifecycle> { return lifecycleSubject }
// Function Handlers
var loadHandler: (() -> ())?
private (set) var loadCallCount: Int = 0
var attachChildHandler: ((_ child: Routing) -> ())?
private (set) var attachChildCallCount: Int = 0
var detachChildHandler: ((_ child: Routing) -> ())?
private (set) var detachChildCallCount: Int = 0
init(interactable: Interactable, viewController: ViewControllable) {
self.interactable = interactable
self.viewControllable = viewController
}
func load() {
loadCallCount += 1
if let handler = loadHandler {
return handler()
}
}
func attachChild(_ child: Routing) {
attachChildCallCount += 1
if let handler = attachChildHandler {
return handler(child)
}
}
func detachChild(_ child: Routing) {
detachChildCallCount += 1
if let handler = detachChildHandler {
return handler(child)
}
}
}
<file_sep>/Shifts/Shifts/RIBs/Shifts/ShiftsInteractor.swift
//
// ShiftsInteractor.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
import RxSwift
import CoreLocation
protocol ShiftsRouting: ViewableRouting {
// TODO: Declare methods the interactor can invoke to manage sub-tree via the router.
}
protocol ShiftsPresentable: Presentable, LoadingPresentable {
var listener: ShiftsPresentableListener? { get set }
// TODO: Declare methods the interactor can invoke the presenter to present data.
func showShifts(_ shifts: [ShiftVM])
func updateActionTitle(to newTitle: String)
func showAction()
func hideAction()
}
protocol ShiftsListener: class {
// TODO: Declare methods the interactor can invoke to communicate with other RIBs.
}
final class ShiftsInteractor: PresentableInteractor<ShiftsPresentable>, ShiftsInteractable, ShiftsPresentableListener {
private let service: ShiftsServiceProtocol
private let locationService: LocationServiceProtocol
private let state: Variable<AppState>
weak var router: ShiftsRouting?
weak var listener: ShiftsListener?
private var isShiftStarted: Bool = false
private var location: CLLocation? = nil
// TODO: Add additional dependencies to constructor. Do not perform any logic
// in constructor.
init(presenter: ShiftsPresentable,
service: ShiftsServiceProtocol,
locationService: LocationServiceProtocol,
state: Variable<AppState>) {
self.service = service
self.locationService = locationService
self.state = state
super.init(presenter: presenter)
presenter.listener = self
}
private func updateLocation() {
locationService.discover()
.done { [weak self] (location) in
guard let this = self else { return }
this.location = location
}
}
private func revertAction() {
isShiftStarted = !isShiftStarted
updateAction()
}
private func parseReloadShiftsNetworkError(_ error: NetworkError) {
switch error {
case .missingData(_):
isShiftStarted = false
updateAction()
presenter.showAction()
presenter.hideLoading()
default:
presenter.showError(with: error.localizedDescription)
}
}
private func parseStartStopShiftNetworkError(_ error: NetworkError) {
switch error {
case .missingData(_):
presenter.hideLoading()
reloadShifts()
default:
presenter.showError(with: error.localizedDescription)
}
}
private func parseShifts(_ shifts: [Shift]) {
if !shifts.isEmpty {
guard let shift = shifts.last else { fatalError() }
isShiftStarted = shift.end.isEmpty
let sortedShifts = shifts
.sorted { $0.id > $1.id }
.map { ShiftVM(model: $0) }
presenter.showShifts(sortedShifts)
} else {
isShiftStarted = false
}
updateAction()
presenter.showAction()
}
private func reloadShifts() {
presenter.showLoading(with: L10n.loading)
service.getShifts()
.done { [weak self] (shifts) in
guard let this = self else { return }
this.parseShifts(shifts)
this.presenter.hideLoading()
}
.fail { [weak self] (error) in
guard let this = self else { return }
if let netError = error as? NetworkError {
this.parseReloadShiftsNetworkError(netError)
} else {
this.presenter.showError(with: error.localizedDescription)
}
}
}
private func updateAction() {
let newActionTitle = isShiftStarted ? L10n.stop : L10n.start
presenter.updateActionTitle(to: newActionTitle)
}
private func startShift() {
guard let location = self.location else {
presenter.showError(with: L10n.locationFailed)
revertAction()
return
}
presenter.showLoading(with: L10n.starting)
service.startShift(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude)
.done { [weak self] (response) in
guard let this = self else { return }
this.reloadShifts()
}
.fail { [weak self] (error) in
guard let this = self else { return }
if let netError = error as? NetworkError {
this.parseStartStopShiftNetworkError(netError)
} else {
this.presenter.showError(with: error.localizedDescription)
}
}
}
private func stopShift() {
guard let location = self.location else {
presenter.showError(with: L10n.locationFailed)
revertAction()
return
}
presenter.showLoading(with: L10n.stopping)
service.stopShift(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude)
.done { [weak self] (response) in
guard let this = self else { return }
this.reloadShifts()
}
.fail { [weak self] (error) in
guard let this = self else { return }
if let netError = error as? NetworkError {
this.parseStartStopShiftNetworkError(netError)
} else {
this.presenter.showError(with: error.localizedDescription)
}
}
}
override func didBecomeActive() {
super.didBecomeActive()
// TODO: Implement business logic here.
state.asObservable()
.subscribe(onNext: { [weak self] (newState) in
guard let this = self else { return }
this.updateLocation()
this.reloadShifts()
}).disposeOnDeactivate(interactor: self)
}
override func willResignActive() {
super.willResignActive()
// TODO: Pause any business logic.
}
// MARK: - ShiftsPresentableListener
func didPrepareView() {
updateAction()
}
func didRequestImage(for shift: ShiftVM) {
guard shift.image.value == nil else { return }
guard !shift.imageUrl.isEmpty else { return }
service.getShiftImage(url: shift.imageUrl)
.done { (image) in
shift.image.value = image
}
}
func didSelectAction() {
presenter.hideAction()
if isShiftStarted {
stopShift()
} else {
startShift()
}
isShiftStarted = !isShiftStarted
updateAction()
}
}
<file_sep>/Shifts/Shifts/Services/Local/LocationService.swift
//
// LocationService.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import When
import CoreLocation
final class LocationService: NSObject, LocationServiceProtocol {
private var promise: Promise<CLLocation>?
private lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyKilometer
return manager
}()
private func authoriseLocation() {
locationManager.requestWhenInUseAuthorization()
}
private func startLocationDiscovery() {
guard CLLocationManager.locationServicesEnabled() else {
promise?.reject(LocationError.locationDisabled)
return
}
guard CLLocationManager.authorizationStatus() == .authorizedAlways ||
CLLocationManager.authorizationStatus() == .authorizedWhenInUse else {
authoriseLocation()
return
}
locationManager.requestLocation()
}
private func findMostRelevantLocation(from locations: [CLLocation]) -> CLLocation? {
let newLocations = locations
.filter { $0.horizontalAccuracy > 0 }
.sorted { $0.horizontalAccuracy < $1.horizontalAccuracy }
return newLocations.first
}
// MARK: - LocationServiceProtocol
var lastLocation: CLLocation? {
return locationManager.location
}
func discover() -> Promise<CLLocation> {
let promise = Promise<CLLocation>()
self.promise = promise
DispatchQueue.main.async {
self.startLocationDiscovery()
}
return promise
}
}
// MARK: - CLLocationManager delegate methods
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: Array <CLLocation>) {
let newLocation = findMostRelevantLocation(from: locations)
if let location = newLocation {
promise?.resolve(location)
} else {
promise?.reject(LocationError.locationNotFound)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
promise?.reject(error)
}
}
<file_sep>/Shifts/Shifts/RIBs/Root/RootViewController.swift
//
// RootViewController.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
import RxSwift
import UIKit
import SVProgressHUD
protocol RootPresentableListener: class {
// TODO: Declare properties and methods that the view controller can invoke to perform
// business logic, such as signIn(). This protocol is implemented by the corresponding
// interactor class.
}
final class RootViewController: UIViewController, RootPresentable, RootViewControllable {
private var targetViewController: ViewControllable?
private var animationInProgress = false
weak var listener: RootPresentableListener?
override var preferredStatusBarStyle: UIStatusBarStyle {
return Config.preferredStatusBarStyle
}
override func viewDidLoad() {
super.viewDidLoad()
configureHUD()
view.backgroundColor = UIColor.white
}
private func configureHUD() {
SVProgressHUD.setDefaultAnimationType(.flat)
SVProgressHUD.setMaximumDismissTimeInterval(2)
SVProgressHUD.setDefaultStyle(.dark)
}
// MARK: - RootViewControllable
func presentInitialView(_ view: ViewControllable) {
targetViewController = view
guard !animationInProgress else { return }
animationInProgress = true
let controller = view.uiviewController
controller.modalPresentationStyle = .overCurrentContext
controller.modalTransitionStyle = .crossDissolve
controller.view.backgroundColor = .clear
present(view.uiviewController, animated: true) { [weak self] in
self?.animationInProgress = false
self?.targetViewController = nil
}
}
}
<file_sep>/Shifts/Shifts/Models/EmptyResponse.swift
//
// EmptyResponse.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
struct EmptyResponse: Codable {
}
<file_sep>/Shifts/Shifts/RIBs/Root/RootRouter.swift
//
// RootRouter.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import RIBs
protocol RootInteractable: Interactable, ShiftsListener {
var router: RootRouting? { get set }
var listener: RootListener? { get set }
}
protocol RootViewControllable: ViewControllable {
func presentInitialView(_ view: ViewControllable)
}
final class RootRouter: LaunchRouter<RootInteractable, RootViewControllable>, RootRouting {
private let shiftsBuilder: ShiftsBuildable
// TODO: Constructor inject child builder protocols to allow building children.
init(interactor: RootInteractable,
viewController: RootViewControllable,
shiftsBuilder: ShiftsBuildable) {
self.shiftsBuilder = shiftsBuilder
super.init(interactor: interactor, viewController: viewController)
interactor.router = self
}
// MARK: - RootRouting
func routeToShifts() {
let rib = shiftsBuilder.build(withListener: interactor)
attachChild(rib)
viewController.presentInitialView(rib.viewControllable)
}
}
<file_sep>/Shifts/Shifts/RIBs/Common/UINavigationController.swift
//
// UINavigationController.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import RIBs
extension UINavigationController: ViewControllable {
public var uiviewController: UIViewController { return self }
public convenience init(root: ViewControllable) {
self.init(rootViewController: root.uiviewController)
}
}
final class NavController: UINavigationController {
override func popViewController(animated: Bool) -> UIViewController? {
return super.popViewController(animated: animated)
}
override func popToRootViewController(animated: Bool) -> [UIViewController]? {
return super.popToRootViewController(animated: animated)
}
}
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? Config.preferredStatusBarStyle
}
}
<file_sep>/Shifts/Shifts/Utils/DateTime.swift
//
// DateTime.swift
// Shifts
//
// Created by <NAME> on 24/11/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
private let dateFormatter = DateFormatter()
public extension Date {
public var timestamp: String {
return String(format: "%.0f", timeIntervalSince1970 * 1000)
}
public var timestampInt: Int {
return Int(round(timeIntervalSince1970 * 1000))
}
public func add(_ component: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: component, value: value, to: self)!
}
public func toString() -> String {
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .medium
return dateFormatter.string(from: self)
}
public func toServerString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
return dateFormatter.string(from: self)
}
}
| 6224de1847ba1c588fa5c6049c39873e986f31e4 | [
"Swift"
] | 40 | Swift | dev4jam/deputy-shifts | fecc0b029c1831ebdbdb49eebc89fca9ac0b5ff6 | 7a49620949f59043d5049340b5933ee8510e2776 |
refs/heads/master | <file_sep>#ifndef HELPER_H
#define HELPER_H
#include "speed.h"
#include <vector>
#include <chrono>
#include <math.h>
#include <numeric>
#include <unistd.h>
#include <stdlib.h>
#include "ros/ros.h"
#include "tf/transform_datatypes.h"
#include "geometry_msgs/Quaternion.h"
using namespace std;
using namespace std::chrono;
template<typename T>
float vectorNorm(T p) {
std::vector<float> v { p.x, p.y };
float res = inner_product(v.begin(), v.end(), v.begin(), 0.0f);
return sqrt(res);
}
float vectorNorm(Speed p);
Speed normaliseSpeed(Speed speed);
float getYaw(geometry_msgs::Quaternion q);
float angDiff(float a, float b);
float wraparound(float th);
float angAdd(float a, float b);
float magSquared(Speed p);
#endif
<file_sep>#ifndef SPEED_H
#define SPEED_H
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <unistd.h>
#include <pthread.h>
#include <sstream>
#include <stdlib.h>
#include <cstdint>
#include <memory>
#include <vector>
#define equals(x, y) (fabs(x-y) < 0.00001)
#define MAX_LIN_VEL 1.3
#define MIN_LIN_VEL 0.88
#define MAX_ANG_VEL 0.785
#define MIN_ANG_VEL 0.785
using namespace std;
struct Speed {
float v;
float w;
Speed(const Speed& speed) :
v(speed.v), w(speed.w) {
}
Speed(float vt, float wt) :
v(vt), w(wt) {
}
Speed() {
w = v = 0;
}
Speed operator*(float s) // copy/move constructor is called to construct arg
{
Speed speed = Speed();
speed.v = this->v * s;
speed.w = this->w * s;
return speed;
}
Speed operator+(Speed rhs) // copy/move constructor is called to construct arg
{
Speed speed = Speed();
speed.v = this->v + rhs.v;
speed.w = this->w + rhs.w;
return speed;
}
Speed operator-(Speed rhs) // copy/move constructor is called to construct arg
{
Speed speed = Speed();
speed.v = this->v - rhs.v;
speed.w = this->w - rhs.w;
return speed;
}
bool operator==(Speed s) // copy/move constructor is called to construct arg
{
if (equals(this->v,s.v) && equals(this->w, s.w)) {
return true;
} else {
return false;
}
}
};
#endif
<file_sep>#ifndef CONCURRENT_VECTOR_H
#define CONCURRENT_VECTOR_H
#include <mutex>
#include <vector>
#include "speed.h"
using namespace std;
template<typename T>
class concurrent_vector: public std::vector<T> {
private:
std::mutex mylock;
public:
concurrent_vector<T>() : vector<T>(){
}
concurrent_vector<T>(const concurrent_vector<T>& x) :
vector<T>(x) {
}
// concurrent_vector<T>(concurrent_vector<T>&& x) :
// vector<T>(x) {
// }
// concurrent_vector<T> (concurrent_vector<T>&& x, const std::allocator<T>& alloc): vector<T>(x,alloc){}
concurrent_vector& operator=(const concurrent_vector<T>&x) {
vector<T>::operator=(x);
return *this;
}
void push_back(T val) {
mylock.lock();
vector < T > ::push_back(val);
mylock.unlock();
}
};
#endif
<file_sep>#include "ros/ros.h"
#include "geometry_msgs/TwistStamped.h"
#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <math.h>
#include <numeric>
#include "concurrent_vector.h"
#include "speed.h"
#include "DeOscillator.h"
using namespace std;
typedef struct {Speed speed;float pval;} Distribution;
class PSC{
public:
PSC(const char * topic, ros::NodeHandle &n_t);
void getInputCandidates(Speed input, vector<Distribution> &candidates);
Speed computePSCVelocity(concurrent_vector<Speed> reactive_candidate);
void usercommandCallback( geometry_msgs::TwistStamped cmd,Pose currentPose);
geometry_msgs::TwistStamped usercmd;
protected:
ros::NodeHandle n;
string topic; // Namespace for yaml variables.
private:
Pose currPose;
Pose goalPose;
Speed chosenSpeed;
float dt;
DeOscillator deOscillator;
float coupling;
}
;
<file_sep>#ifndef POSE_H
#define POSE_H
#include "point.h"
#include "helper.h"
using namespace std;
class Pose: public Point<float> {
public:
float th;
Pose(float xt, float yt, float tht = 0) :
Point(xt, yt), th(tht) {
}
Pose() :
Point() {
th = 0;
}
bool operator==(Pose pose) // copy/move constructor is called to construct arg
{
if (equals(this->x, pose.x) && equals(this->y, pose.y)
&& equals(this->th, pose.th)) {
return true;
} else {
return false;
}
}
Pose& operator=(Pose pose) // copy/move constructor is called to construct arg
{
this->x = pose.x;
this->y = pose.y;
this->th = pose.th;
return *this;
}
Pose operator+(Pose pose) // copy/move constructor is called to construct arg
{
pose.x += this->x;
pose.y += this->y;
pose.th = angAdd(pose.th, this->th);
return pose;
}
float bearingToPose(Pose pose) {
float y = pose.y - this->y;
float x = pose.x - this->x;
float bearing = atan2(y, x);
return bearing;
}
};
#endif
<file_sep>#ifndef POINT_H
#define POINT_H
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <unistd.h>
#include <pthread.h>
#include <sstream>
#include <stdlib.h>
#include <cstdint>
#include <memory>
#include <vector>
#define equals(x, y) (fabs(x-y) < 0.00001)
using namespace std;
template<class T>
class Point {
public:
Point() {
x = y = 0;
}
virtual ~Point() {
}
Point(T x_t, T y_t) :
x(x_t), y(y_t) {
}
virtual Point operator=(const Point& b) {
this->x = b.x;
this->y = b.y;
return *this;
}
virtual Point operator+=(const Point& b) {
this->x += b.x;
this->y += b.y;
return *this;
}
virtual Point operator-(const Point& b) {
T x = this->x - b.x;
T y = this->y - b.y;
return Point(x,y);
}
virtual bool operator==(const Point& b) {
if (equals(this->x, b.x) && equals(this->y, b.y))
return true;
else
return false;
}
T x;
T y;
};
class IntPoint: public Point<int> {
public:
IntPoint() :
Point() {
}
IntPoint(int xt, int yt) :
Point(xt, yt) {
}
bool operator==(const IntPoint& b) {
if (this->x == b.x && this->y == b.y)
return true;
else
return false;
}
};
class RealPoint: public Point<float> {
public:
RealPoint() :
Point() {
}
RealPoint(float xt, float yt) :
Point(xt, yt) {
}
};
#endif
<file_sep>
//PSC node
#include "ros/ros.h"
#include "psc.h"
#include "helper.h"
using namespace std;
using namespace std::chrono;
PSC::PSC(const char * topic, ros::NodeHandle &n_t):topic(topic), n(n_t)
{
this->chosenSpeed = Speed(0,0);
this->dt = 0.1; //delta time
}
void PSC::usercommandCallback(geometry_msgs::TwistStamped cmd,Pose currentPose)
{
//user command callback -- In reality should be used with subscriber
this->usercmd = geometry_msgs::TwistStamped(cmd);
Speed humanInput = Speed(this->usercmd.twist.linear.x,
this->usercmd.twist.angular.z);
this->currPose = currentPose;
// Here, we estimate the goal pose from the user command.
float dx, dy, th;
goalPose = currPose;
if (humanInput.v != 0)
{
if (humanInput.v<0)
{
humanInput.w = -humanInput.w;
}
th = atan2(humanInput.w, humanInput.v); // estimate user desired direction
float length = 2; // Assume the goal is 2 meters ahead in user's desired direction
dx = length * cos(th);
dy = length * sin(th);
// Now dx, dy are in the body frame and will need to be rotated to the global frame.
float xt = cos(currPose.th) * dx - sin(currPose.th) * dy;
float yt = sin(currPose.th) * dx + cos(currPose.th) * dy;
//xt, yt is the delta distance user want to go in global frame
goalPose = goalPose + Pose(xt, yt, th); //set new goal pose
}
else
{
//pure roation, assume target direction is turn left or turn right
if (humanInput.w >0){th = M_PI/2;}
else if (humanInput.w<0){th=-M_PI/2;}
else{th=0;}
float dth = humanInput.w * this->dt;
goalPose.th = angAdd(goalPose.th, dth);
}
this->deOscillator.changeDir(currPose, goalPose);
}
void PSC::getInputCandidates(Speed input, vector<Distribution> &candidates)
{
/*estimate user input
At this stage, we only used a simple assumption -- a normal distribution over candidate velocity pairs centred at the direction user indicated
Interface difference is taken into account by setting different std value */
Distribution p;
float std = 0;
if (this->usercmd.header.frame_id == "DIRECT")
{ //assume user's input as user's intention, no distribution
p.speed = input;
p.pval = 1;
candidates.emplace_back(p);
return;
}
else
{
//assume normal distribution
std = M_PI / 5; //user defined value.
float var = std * std;
p.speed = input;
p.pval = 1/pow(2 * var * M_PI, 0.5);
candidates.emplace_back(p);
//if not going straight forward, add all the input candidate from the normal distribution
if (!(equals(input.w, 0) && input.v > 0))
{
// find magnitude and angle.
float th_0 = atan2(input.w, input.v);
float mag = vectorNorm(input);
int step = 1;
float d = std / step;
for (float dth = d; dth <= std; dth += d)
{
if (equals(dth, 0))
continue;
//left theta
float th = th_0 - dth;
float v = cos(th) * mag;
float w = sin(th) * mag;
float pval = exp(-dth * dth / (2 * var)) / pow(2 * var * M_PI, 0.5); //normal distribution
Distribution p;
p.speed.v = v;
p.speed.w = w;
p.pval = pval;
candidates.emplace_back(p);
//right theta
th = th_0 + dth;
v = cos(th) * mag;
w = sin(th) * mag;
p.speed = Speed(v, w);
candidates.emplace_back(p);
}
}
}
}
Speed PSC::computePSCVelocity(concurrent_vector<Speed> reactive_candidate) {
//Use PSC to find next desired linear velocity & angular velocity pair
Speed chosenSpeed; //desired velocity pair
Speed humanInput = Speed(this->usercmd.twist.linear.x,this->usercmd.twist.angular.z); //user input (v,w pair)
//If user input is (0,0), stop the wheelchair
if (equals(humanInput.v, 0) && equals(humanInput.w, 0)) {
return Speed(0,0);
}
//calculate cost function based on heading, velocity and clearance (or other user defined cost function)
//coupling parameter
float a = 100; // user defined value. agreement factor between user command and resultant velocity.
//For pure rotation, set a =0.1
if (equals(humanInput.v, 0) && !equals(humanInput.w, 0)) {
a = .1; //user defined value
}
float inva = 1 / a;
float alpha = 0.03; // user defined value. weight for heading.
float sigma = 0.1; // user defined value. weight for clearance
float gamma = 0.75; // user defined value. weight for velocity.
float final_clearance = 0;
float max_clearance = 0;
float max_cost = 0;
//get user input distribution
vector<Distribution> inputDistribution;
inputDistribution.clear();
//pure rotation input distribution
if (equals(humanInput.v, 0) && !equals(humanInput.w, 0)) {
Distribution d;
d.speed = humanInput;
d.pval =0.01;
inputDistribution.emplace_back(d);
} else {
getInputCandidates(humanInput, inputDistribution);
}
std::mutex mylock;
if (reactive_candidate.size()==0)
{
ROS_INFO("No candidate error");
return Speed(0,0);
}
else
{
#pragma omp parallel for collapse(2)
//loop through each input distribution & candidate velocity pairs
for (int j = 0; j < inputDistribution.size(); j++) {
for (int i = 0; i < reactive_candidate.size(); i++) {
Distribution d = inputDistribution[j];
Speed input = d.speed;
Speed realspeed = reactive_candidate[i];
float ang = atan2(realspeed.w,realspeed.v);
float global_ang = angAdd(ang,currPose.th);
if (realspeed.v == 0)
{
//pure rotation or stop
global_ang = currPose.th+realspeed.w*dt;
}
float clearance = 1; //computeClearance(realspeed); //define a function that calculate clearance for each candidate vel pair.
//The function we used is related with DWA. In general, this is the distance to the nearest obstacle when the robot moves one step using this candidate velocity.
//TODO: you can use your own function here.
float heading = ((M_PI-fabs(angDiff(atan2(goalPose.y-currPose.y,goalPose.x-currPose.x),global_ang)))/M_PI);
Speed norm_speed = normaliseSpeed(realspeed);
float velocity = abs(norm_speed.v);
float G = alpha * heading + gamma * velocity + sigma*clearance;
//G: probability distribution of candidate safe velocity pairs -- reflected in the cost value
Speed diff = norm_speed - input;
float x = magSquared(diff);
x *= -0.5 * inva;
float coupling = expf(x);
//speed difference between user input and candidate vel
float cost = G * coupling * d.pval *1;
//couping: probability distribution of user input
//can further add an interaction probability with moving obstacles(agents)
mylock.lock();
if (cost>max_cost) {
max_cost = cost;
chosenSpeed = realspeed;
final_clearance = clearance;
}
mylock.unlock();
}
}
geometry_msgs::Vector3Stamped c;
c.header.stamp = ros::Time::now();
c.vector.z = final_clearance;
c.vector.x = chosenSpeed.v;
c.vector.y = chosenSpeed.w;
return chosenSpeed;
}
}
<file_sep>1. test psc node :
roslaunch psc test_psc.launch
2. There are some user defined values such as dt, weights for cost functions. You can change them in PSC.cpp
3. As our function to calculate clearance is related with DWA, you need to use your own function to calculate clearance. Currently this parameter is set to 1 (Please see details in PSC.cpp)
<file_sep>
//Script to test PSC node
#include "ros/ros.h"
#include "geometry_msgs/TwistStamped.h"
#include "geometry_msgs/Twist.h"
#include "geometry_msgs/Pose.h"
#include "nav_msgs/OccupancyGrid.h"
#include "nav_msgs/Odometry.h"
#include "tf/transform_datatypes.h"
#include <tf/transform_broadcaster.h>
#include "../include/psc.h"
using namespace std;
using namespace std::chrono;
Speed test_PSC(PSC psc)
{
//simulate user input. In reality should be subscribed from ROS
geometry_msgs::TwistStamped cmd;
cmd.header.frame_id = 'DIRECT';
cmd.twist.linear.x = 1;
cmd.twist.linear.y=0;
cmd.twist.angular.z = 0;
//simulate current robot pose
Pose currentPose;
currentPose.x = 0;
currentPose.y = 0;
currentPose.th = 0;
psc.usercommandCallback(cmd,currentPose);
//simulate candidate velocity pairs from reactive navigation
concurrent_vector<Speed> reactive_result;
reactive_result.clear();
reactive_result.emplace_back(Speed(0,0));
reactive_result.emplace_back(Speed(1,0));
reactive_result.emplace_back(Speed(1,0.2));
reactive_result.emplace_back(Speed(1,0.6));
reactive_result.emplace_back(Speed(1,1));
Speed chosenSpeed=psc.computePSCVelocity(reactive_result);
return chosenSpeed;
}
int main(int argc, char** argv) {
const char* ns = "PSC";
ros::init(argc, argv, ns);
ros::NodeHandle n;
PSC psc = PSC(ns,n);
Speed psc_result;
while (ros::ok())
{
psc_result = test_PSC(psc);
cout<<"psc_result [v="<<psc_result.v<<",w="<<psc_result.w<<"]"<<endl;
}
}
<file_sep>#include "helper.h"
#include "DeOscillator.h"
using namespace std;
float DeOscillator::lin_dist_thres = .1;
float DeOscillator::ang_dist_thres_lower = M_PI * 10 / 180;
float DeOscillator::ang_dist_thres_upper = M_PI * 110 / 180;
float vectorNorm(Speed p) {
return sqrt(magSquared(p));
}
float magSquared(Speed p) {
std::vector<float> v { p.v, p.w };
float res = inner_product(v.begin(), v.end(), v.begin(), 0.0f);
return res;
}
Speed normaliseSpeed(Speed speed_old) {
Speed speed = Speed(speed_old);
if (speed.v >= 0) {
speed.v /= (MAX_LIN_VEL);
} else {
speed.v /= (MIN_LIN_VEL);
}
if (speed.w >= 0) {
speed.w /= (MAX_ANG_VEL);
} else {
speed.w /= (MIN_ANG_VEL);
}
return speed;
}
float getYaw(geometry_msgs::Quaternion q) {
tf::Quaternion qt;
tf::quaternionMsgToTF(q, qt);
tf::Matrix3x3 m(qt);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
return yaw;
}
float angDiff(float a1, float a2) {
float a = wraparound(a1) - wraparound(a2);
a = fmod((a + M_PI), (2 * M_PI)) - M_PI;
return wraparound(a);
}
float wraparound(float ang) { // [-pi, pi]
if (equals(ang, 0) || equals(fabs(ang), M_PI))
return ang;
if ((ang <= M_PI) && (ang >= -M_PI))
return ang;
if (ang > M_PI) {
ang -= 2 * M_PI;
}
if (ang < -M_PI) {
ang += 2 * M_PI;
}
return wraparound(ang); //again wraparound here?
}
float angAdd(float a, float b) {
float c = wraparound(a + b);
return c;
}
<file_sep>#ifndef DEOSCILLATOR_H
#define DEOSCILLATOR_H
#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <math.h>
#include <numeric>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/TwistStamped.h"
#include "nav_msgs/Odometry.h"
#include "pose.h"
#include "tf/transform_datatypes.h"
#include "helper.h"
#define INVALID_DIR -12
class DeOscillator {
private:
float upperbound, lowerbound;
bool front;
Pose start_pose; // The pose at the start of deoscillation.
float velDir; // instantanouse direction of motion in the body frame.
static float lin_dist_thres, ang_dist_thres_lower, ang_dist_thres_upper;
bool first;
public:
DeOscillator() {
upperbound = M_PI + .01;
lowerbound = -M_PI - .01;
start_pose = Pose();
velDir = 0;
front = true;
first = true;
}
// This function examines if we have travelled far enough to ensure deoscillation.
void updateOdom(const nav_msgs::Odometry& cmd) {
float xt = cmd.pose.pose.position.x;
float yt = cmd.pose.pose.position.y;
float tht = getYaw(cmd.pose.pose.orientation);
if (first) {
start_pose = Pose(xt, yt, tht);
first = false;
return;
}
float lin_dist = sqrt(
pow(start_pose.x - xt, 2) + pow(start_pose.y - yt, 2));
float ang_dist = abs(angDiff(start_pose.th, tht));
if ((lin_dist > lin_dist_thres) || ((ang_dist > ang_dist_thres_lower)
// && (ang_dist < ang_dist_thres_upper)
)) {
start_pose = Pose(xt, yt, tht);
velDir = atan2(cmd.twist.twist.angular.z, cmd.twist.twist.linear.x);
}
}
void getAdmissibleDirection(float& upperbound, float& lowerbound) {
upperbound = velDir + M_PI * 90 / 180;
upperbound = wraparound(upperbound);
lowerbound = velDir - M_PI * 90 / 180;
lowerbound = wraparound(lowerbound);
}
// This is called only once anytime the goal pose changes.
void changeDir(Pose currPose, Pose goalPose, float dir = INVALID_DIR) {
float bearing = currPose.bearingToPose(goalPose);
float trueBearing = angDiff( bearing,currPose.th);
bool front_t = true;
int sign = -1;
if (front) sign = 1;
if (fabs(trueBearing) > (M_PI / 2 +sign*.1) && bearing!=0) {
front_t = false;
}
if (dir != INVALID_DIR) {
velDir = dir;
}
if (front ^ front_t) {
// Useful when DWA is used and complex update of velDir is not required.
// This is because DWA only takes one goal and does not change its goal.
if (dir == INVALID_DIR) {
if (front_t) {
velDir = 0;
} else {
velDir = M_PI;
}
}
front = front_t;
// cout << "CHANGING DIRECTION, isFront= " << front << ". Veldir: "
// << velDir << " !!!" << endl;
} else {
// cout << "New goal but direction Remains the same. isFront= "
// << front << ". Veldir: " << velDir << endl;
}
}
bool isFront() const {
return front;
}
}
;
#endif
| 48f79120eba963928e56b7334b2353df8fe6386e | [
"Markdown",
"C++"
] | 11 | C++ | akaimody123/Crowdbot_sharedControl | f76cf9baf58eaeb607d286d00c2ad38628578ad0 | 7304d00138b3ab795254eef8393d9de3b4816397 |
refs/heads/master | <file_sep>package com.example.dxs.navigation;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by dxs on 3/17/2017.
*/
public class contactAdapter extends ArrayAdapter<String>{
public contactAdapter(@NonNull Context context, String [] contacts) {
super(context, R.layout.contactrow, contacts);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater contactInflater = LayoutInflater.from(getContext());
View customView = contactInflater.inflate(R.layout.contactrow,parent,false);
String contactName = getItem(position);
TextView contactText = (TextView) customView.findViewById(R.id.contactTextView);
ImageView contactImage = (ImageView) customView.findViewById(R.id.contactPicView);
contactText.setText(contactName);
contactImage.setImageResource(R.drawable.contactpic);
return customView;
//return super.getView(position, convertView, parent);
}
}
| 86b90bb25bc6bb388ffd91c318171080eabd5b18 | [
"Java"
] | 1 | Java | ncadsxh/chatAndroid | b10d9cb28700021b08578e0b9dd5373602c30399 | 0927d3579e729b8ca40a17396f6b994739c47ce9 |
refs/heads/master | <file_sep>import { isValidTime, decomposeTime } from '@/components/UtTimePicker/utils';
describe('isValidTime', () => {
it('validates against time regex', () => {
expect(isValidTime('19:54:20')).toBe(true);
expect(isValidTime('109:54:20')).toBe(false);
expect(isValidTime('-1:54:20')).toBe(false);
expect(isValidTime('19;54:20')).toBe(false);
expect(isValidTime('1 9;54:20')).toBe(false);
expect(isValidTime('19: 54:20')).toBe(false);
});
});
describe('decomposeTime', () => {
it('get hours, minutes, seconds', () => {
expect(decomposeTime('19:54:20').hours).toBe('19');
expect(decomposeTime('19:54:20').minutes).toBe('54');
expect(decomposeTime('19:54:20').seconds).toBe('20');
});
});
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VRadio, VRadioGroup } from "vuetify/lib";
<Meta
title="Design System/Composants/Formulaire/Radio"
component={VRadio}
/>
# Radio
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/selection-controls/) complète de Vuetify
## Style
On utilise la classe `ut-input` pour appliquer le style *Ugitech*
<Preview>
<Story name="Basique" inline={true} height="200px">
{{
components: { VRadio, VRadioGroup },
template: `
<v-radio-group>
<v-radio
class="ut-input"
v-for="n in 3"
:key="n"
:label="'Radio ' + n"
:value="n"
></v-radio>
</v-radio-group>
`,
}}
</Story>
</Preview>
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VTextField } from "vuetify/lib";
<Meta
title="Design System/Composants/Formulaire/Texte"
component={VTextField}
decorators={[() => ({
template: '<div class="pa-2"><story/></div>'
})]}
/>
# Champ texte
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/text-fields/#text-fields) complète de Vuetify
## Style
Pour l'apparence, on utilise les propriétés suivantes:
- `filled`
<Preview>
<Story name="Basique" inline={true} height="50">
{{
components: { VTextField },
template: `
<v-text-field label="Label" placeholder="Placeholder" filled></v-text-field>
`,
}}
</Story>
</Preview>
### Texte d'aide
<Preview>
<Story name="Texte d\'aide" inline={true} height="50">
{{
components: { VTextField },
template: `
<v-text-field
label="Url"
hint="www.example.com"
persistent-hint
filled>
</v-text-field>
`,
}}
</Story>
</Preview>
### Erreur de validation
<Preview>
<Story name="Erreur de validation" inline={true} height="50">
{{
components: { VTextField },
template: `
<v-text-field
label="Label"
counter="10"
:rules="[rules.required, rules.min]"
filled
clearable
></v-text-field>
`,
data: () => ({
rules: {
required: value => !!value || 'Champ obligatoire',
min: v => v && v.length >= 5 || '5 caractères minimum',
},
})
}}
</Story>
</Preview><file_sep>import { Component, Vue, Prop } from 'vue-property-decorator';
import {
VCol,
VRow,
VAppBar,
VAppBarNavIcon,
VMenu,
VBtn,
VIcon,
VDialog,
VTooltip,
} from 'vuetify/lib';
import { UtAppMenu, MenuItem } from '../UtAppMenu';
import UtAppBarTitle from './UtAppBarTitle';
import './UtAppBar.scss';
import ugitechLogo from '../../assets/ugitech-original.svg';
@Component({
name: 'ut-app-bar',
components: {
VCol,
VRow,
VAppBar,
VAppBarNavIcon,
VBtn,
VIcon,
VMenu,
VDialog,
VTooltip,
UtAppBarTitle,
UtAppMenu,
},
filters: {
initials(value: string, maxLength: number = 20) {
if (value.length > maxLength) {
const splitUsername = value.split(' ');
if (splitUsername.length === 2) {
return `${splitUsername[0][0].toUpperCase()}${splitUsername[1][0].toUpperCase()}`;
}
}
return value;
},
},
template: `
<v-app-bar
app
class="ut-app-bar"
clipped-left
:dark="dark"
>
<v-row>
<v-col
cols="2"
lg="4"
md="4"
class="d-flex justify-start text-no-wrap ut-no-overflow align-center"
>
<div
v-if="username && $vuetify.breakpoint.mdAndUp"
class="d-flex align-center"
>
<v-btn
icon
@click="logout"
>
<v-icon>mdi-power</v-icon>
</v-btn>
<div
class="ut-app-bar__username ml-2">
<v-tooltip bottom v-if="username.length > maxLength">
<template v-slot:activator="obj">
<div v-on="obj.on" style="cursor: default">{{ username | initials(maxLength) }}</div>
</template>
<span>{{ username }}</span>
</v-tooltip>
<span v-else>
{{ username }}
</span>
</div>
</div>
<img
v-if="$vuetify.breakpoint.smAndDown"
class="ut-app-bar-title__img"
:src="logo"
>
</v-col>
<v-col
cols="8"
md="4"
lg="4"
class="d-flex justify-center text-no-wrap"
>
<img
v-if="$vuetify.breakpoint.mdAndUp"
class="ut-app-bar-title__img"
:src="logo"
>
<ut-app-bar-title
:website="website"
:page="page"
/>
</v-col>
<v-col
lg="4"
md="4"
cols="2"
class="d-flex justify-end text-no-wrap ut-no-overflow"
>
<v-dialog
v-if="items.length > 0 && $vuetify.breakpoint.xsOnly"
v-model="showMenu"
dark
transition="slide-x-reverse-transition"
fullscreen >
<template v-slot:activator="obj">
<v-app-bar-nav-icon v-on="obj.on" />
</template>
<ut-app-menu
:items="items"
title="Menu"
:username="username"
@hide="showMenu = false"
@logout="logout"
@click="navigate"
>
<template v-slot:img>
<slot name="menuImg"></slot>
</template>
</ut-app-menu>
</v-dialog>
<v-menu
v-if="items.length > 0 && $vuetify.breakpoint.smAndUp"
v-model="showMenu"
fixed
nav
:close-on-click="false"
:close-on-content-click="false"
dark
>
<template v-slot:activator="obj">
<v-app-bar-nav-icon v-on="obj.on" />
</template>
<ut-app-menu
:items="items"
title="Menu"
@hide="showMenu = false"
@logout="logout"
@click="navigate"
:username="username"
>
<template v-slot:img>
<slot name="menuImg"></slot>
</template>
</ut-app-menu>
</v-menu>
</v-col>
</v-row>
</v-app-bar>
`,
})
export default class UtAppBar extends Vue {
@Prop({
type: String,
required: false,
default: ugitechLogo,
}) logo!: string;
@Prop({
type: String,
required: false,
default: undefined,
}) username!: string;
@Prop({
type: Array,
required: true,
}) items!: MenuItem[];
@Prop({
type: Boolean,
required: true,
}) dark!: boolean;
@Prop({
type: String,
required: true,
}) website!: string;
@Prop({
type: String,
required: true,
}) page!: string;
logout() {
this.$emit('logout');
}
navigate(item: MenuItem) {
this.$emit('navigate', item);
}
showMenu = false;
maxLength = 20;
}
<file_sep>import { addDecorator, addParameters } from '@storybook/vue';
import Vue from 'vue';
import './stories.scss';
import vuetify from '@/plugins/vuetify';
import '@mdi/font/css/materialdesignicons.css';
import Vuetify, {
VApp,
VAppBar,
VAppBarNavIcon,
VBtn,
VCard,
VCardText,
VCol,
VContainer,
VContent,
VDatePicker,
VDialog,
VDivider,
VIcon,
VImg,
VList,
VListItem,
VListItemAvatar,
VListItemContent,
VListItemIcon,
VListItemTitle,
VListItemAction,
VListGroup,
VNavigationDrawer,
VMenu,
VRow,
VSheet,
VSnackbar,
VSparkline,
VSpacer,
VSubheader,
VTab,
VTabs,
VTabItem,
VToolbar,
VToolbarTitle,
VTooltip,
VLayout,
Resize,
} from 'vuetify/lib';
Vue.use(Vuetify, {
components: {
VApp,
VAppBar,
VAppBarNavIcon,
VBtn,
VCard,
VCardText,
VCol,
VContainer,
VContent,
VDatePicker,
VDialog,
VDivider,
VIcon,
VImg,
VList,
VListItem,
VListItemAvatar,
VListItemContent,
VListItemIcon,
VListItemTitle,
VListItemAction,
VListGroup,
VMenu,
VNavigationDrawer,
VRow,
VSheet,
VSnackbar,
VSparkline,
VSpacer,
VSubheader,
VTab,
VTabs,
VTabItem,
VToolbar,
VToolbarTitle,
VTooltip,
VLayout,
},
directives: {
Resize
}
});
addParameters({
options: {
showRoots: true,
},
docs: {
inlineStories: false,
},
});
addDecorator((decoratedStory, story) => {
let _wrapWithVuetifyApp = true;
let _fullHeight = false;
if (story.parameters.custom) {
const { wrapWithVuetifyApp, fullHeight } = story.parameters.custom;
if (wrapWithVuetifyApp !== undefined) {
_wrapWithVuetifyApp = wrapWithVuetifyApp;
}
if (fullHeight !== undefined) {
_fullHeight = fullHeight;
}
}
if (_wrapWithVuetifyApp) {
return {
vuetify,
components: { VApp },
template: `
<v-app class="${_fullHeight ? '' : 'min-height'}">
<story/>
</v-app>
`,
};
}
return '<story/>';
})
<file_sep>/**
* @see https://jestjs.io/docs/en/configuration#setupfiles-array
*/
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { action } from "@storybook/addon-actions";
import { UtAppBar } from '@/components/UtAppBar';
import appImg from '@/assets/LogoA2iUgitech_FullRes.png';
import LinkTo from "@storybook/addon-links/react";
<Meta
title="Design System/Composants/Layout/UtAppBar"
component={UtAppBar}
/>
# UtAppBar
Un assemblage de plusieurs composants:
- [v-app-bar](https://vuetifyjs.com/en/components/app-bars/)
- <LinkTo kind="design-system-composants-utappbartitle">ut-app-bar-title</LinkTo>
- <LinkTo kind="design-system-composants-utappmenu">ut-app-menu</LinkTo>
## API
#### Props
| Nom | Commentaires | Required |
|---|---|---|
| items | MenuItem[] (voir <LinkTo kind="design-system-composants-utappmenu">UtAppMenu</LinkTo>) | oui (peut être un tableau vide) |
| username | Identifiant de l'utilisateur connecté | oui |
| dark | application de la variante `dark` de Vuetify | oui |
| website | Nom du site actuel (voir UtAppBarTitle) | oui |
| page | Nom de la page actuelle (voir UtAppBarTitle) | oui |
| logo | logo pour remplacer le logo par défaut | non |
#### Slots
| Nom | Commentaires |
| --- | --- |
| menuImg | image apparaissant dans le menu |
#### Events
| Nom | Commentaires |
| --- | --- |
| logout | émis quand on clique sur le bouton de déconnection |
| navigate | émis quand on clique sur un lien de navigation |
## Complet
<Preview>
<Story name="Complet">
{{
components: { UtAppBar },
template: `
<ut-app-bar
:items="menuItems"
:username="username"
dark
@logout="logout"
@navigate="navigate"
website="Nom du site"
page="Titre de page 3"
>
<template v-slot:menuImg>
<img :src="appImg" width="40"/>
</template>
</ut-app-bar>
`,
data: () => ({
appImg,
username: 'Cyril Martinez',
menuItems: [
{ title: 'Titre de page 1', path: 'example.com' },
{ title: 'Titre de page 2' },
{
title: 'Ensemble de pages 1',
items: [
{ title: 'Titre de page 3' },
{ title: 'Titre de page 4' },
],
},
{ title: 'Titre de page 5' },
],
}),
methods: {
logout: action('logout'),
navigate: action('navigate')
},
}}
</Story>
</Preview>
## Sans menu
<Preview>
<Story name="Sans Menu">
{{
components: { UtAppBar },
template: `
<ut-app-bar
:items="[]"
:username="username"
dark
@logout="logout"
website="Nom du site"
page="Titre de page 3"
/>
`,
data: () => ({
username: 'Cyril Martinez',
}),
methods: {
logout: action('logout'),
},
}}
</Story>
</Preview>
## Sans utilisateur connecté
<Preview>
<Story name="Sans connection">
{{
components: { UtAppBar },
template: `
<ut-app-bar :items="[]" dark website="Nom du site" page="Titre de page 3"/>
`,
}}
</Story>
</Preview>
## Long texte
<Preview>
<Story name="Long texte">
{{
components: { UtAppBar },
template: `
<ut-app-bar
:items="[]"
dark
@logout="logout"
username="Gabriel Longnomdefamille"
website="Nom du site à rallonge"
page="Très très long titre de page"/>
`,
methods: {
logout: action('logout'),
},
}}
</Story>
</Preview>
## Changer le logo
<Preview>
<Story name="Changer le logo">
{{
components: { UtAppBar },
template: `
<ut-app-bar
:items="[]"
dark
@logout="logout"
:logo="appImg"
website="Nom du site"
page="Titre de page"/>
`,
methods: {
logout: action('logout'),
},
data: () => ({
appImg,
})
}}
</Story>
</Preview>
<file_sep>import { Prop, Component, Vue } from 'vue-property-decorator';
import {
VTabs,
VTab,
VIcon,
VTabItem,
VDatePicker,
} from 'vuetify/lib';
import moment from 'moment';
import { UtTimePicker } from '../UtTimePicker';
import { decomposeTime } from '../UtTimePicker/utils';
import './UtDatetimePicker.scss';
@Component({
name: 'ut-datetime-picker',
components: {
UtTimePicker,
VTabs,
VTab,
VIcon,
VTabItem,
VDatePicker,
},
template: `
<div class="ut-datetime-picker">
<v-tabs
centered
grow
>
<v-tab
href="#date"
>
<v-icon>mdi-calendar</v-icon>
</v-tab>
<v-tab href="#time">
<v-icon>mdi-clock-outline</v-icon>
</v-tab>
<v-tab-item value="date">
<v-date-picker
:value="date"
no-title
scrollable
show-current="false"
@input="onDateChange"
/>
</v-tab-item>
<v-tab-item value="time">
<ut-time-picker
:value="time"
@input="onTimeChange"
/>
</v-tab-item>
</v-tabs>
<div class="ut-datetime-picker__footer">
<slot />
</div>
</div>
`,
})
export default class UtDatetimePicker extends Vue {
@Prop({
type: Date,
required: true,
}) value!: Date;
get momentObj() {
return moment(this.value);
}
get date(): string {
const { momentObj } = this;
return momentObj.clone().toISOString().substr(0, 10);
}
get time(): string {
const { momentObj } = this;
return `${momentObj.hours()}:${momentObj.minutes()}:${momentObj.seconds()}`;
}
onTimeChange(newValue: string) {
const { hours, seconds, minutes } = decomposeTime(newValue);
const { momentObj } = this;
this.$emit('input', momentObj.hours(parseInt(hours, 10))
.minutes(parseInt(minutes, 10))
.seconds(parseInt(seconds, 10))
.toDate());
}
onDateChange(newValue: string) {
const { momentObj } = this;
this.$emit('input', moment(newValue)
.hours(momentObj.hours())
.minutes(momentObj.minutes())
.seconds(momentObj.seconds())
.toDate());
}
}
<file_sep>
import vuetifyConfig from '@/plugins/vuetify';
import {
VApp, VContent, VContainer, VBtn, VTextField,
} from 'vuetify/lib';
import { UtNavigationBar } from '@/components/UtNavigationBar';
import { UtAppBar } from '@/components/UtAppBar';
import { UtNavigationDrawer } from '@/components/UtNavigationDrawer';
import { UtConnectionLayout } from '@/components/UtConnectionLayout';
const component = {
vuetify: vuetifyConfig,
components: {
UtNavigationBar,
UtAppBar,
UtNavigationDrawer,
UtConnectionLayout,
VBtn,
VApp,
VContainer,
VContent,
VTextField,
},
template: `
<v-app :class="{ 'ut-app--navigation-bar': navigationBar }">
<ut-navigation-bar>
</ut-navigation-bar>
<ut-app-bar
dark
:items="menuItems"
website="Nom du site"
page="Titre de page 3"
:username="username"
@logout="logout"
/>
<ut-navigation-drawer
v-model="drawer"
title="Titre"
:toggle-options="{ icon: 'mdi-filter-variant' }"
>
<div class="pa-4">
REMPLIR AVEC VOTRE CONTENU
</div>
</ut-navigation-drawer>
<v-content>
<v-container
class="fill-height"
fluid
>
<div>REMPLIR AVEC VOTRE CONTENU</div>
<v-btn
fab
v-if="$vuetify.breakpoint.mdAndDown"
@click="drawer = !drawer"
class="ut-navigation-drawer__float-button"
>
<v-icon>mdi-filter-variant</v-icon>
</v-btn>
</v-container>
</v-content>
<ut-connection-layout v-if="showConnection" style="z-index: 300; position: fixed; top: 0; left: 0; right: 0; bottom: 0;">
<form class="px-10 col-12 col-md-6">
<div class="text-left title mb-4">
<span class="text-no-wrap">Bienvenue sur</span>
<span class="text-no-wrap">Nom du site</span>
</div>
<div class="display-2 text-left mb-6">Connexion</div>
<div class="mt-5">
<v-text-field
v-model="email"
label="Email"
filled
type="email"
name="email"
/>
<v-text-field
v-model="password"
label="Mot de passe"
name="password"
hide-details
filled
@click:append="togglePassword"
:type="showPassword ? 'text' : 'password'"
:append-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'" />
</div>
<div class="text-right mt-5">
<v-btn
:ripple="false"
color="primary"
@click="submit"
>Connexion</v-btn>
</div>
</fStoryorm>
</ut-connection-layout>
</v-app>
`,
data: () => ({
showConnection: true,
showPassword: false,
password: '',
email: '',
drawer: true,
username: '<NAME>',
navigationBar: true,
menuItems: [
{
title: 'Applications',
color: '#99CD50',
iStorycon: 'mdi-wrench',
type: 'app',
},
{
title: 'Ged-archive',
color: '#6A969C',
icon: 'mdi-package-down',
type: 'app',
},
{
title: 'Titre de page 1',
},
{
title: 'Titre de page 2',
},
{
title: 'Ensemble de pages 1',
items: [
{
title: 'Titre de page 3',
disabled: true,
},
{
title: 'Titre de page 4',
},
],
},
{
title: 'Titre de page 5',
},
],
}),
methods: {
togglePassword() {
this.showPassword = !this.showPassword;
},
submit() {
this.showConnection = false;
},
logout() {
this.showConnection = true;
},
},
};
export default component;
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VTooltip, VBtn } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
<Meta
title="Design System/Composants/Tooltip"
component={VTooltip}
decorators={[() => ({
template: '<div class="pa-2"><story/></div>'
})]}
/>
# Tooltip
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/tooltips/#tooltips) complète de Vuetify
<Preview>
<Story name="Basique">
{{
components: { VTooltip, VBtn },
template: `
<v-tooltip bottom>
<template v-slot:activator="obj">
<span v-on="obj.on">This text has a tooltip</span>
</template>
<span>Tooltip</span>
</v-tooltip>
`,
}}
</Story>
</Preview>
<file_sep>import './UtTimePickerHeader.scss';
declare const _default: {
name: string;
components: {
VRow: import("vue").Component<import("vue/types/options").DefaultData<never>, import("vue/types/options").DefaultMethods<never>, import("vue/types/options").DefaultComputed, Record<string, any>>;
VCol: import("vue").Component<import("vue/types/options").DefaultData<never>, import("vue/types/options").DefaultMethods<never>, import("vue/types/options").DefaultComputed, Record<string, any>>;
};
template: string;
};
export default _default;
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VDialog, VCard, VCardTitle, VCardActions, VBtn } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
<Meta title="Design System/Composants/Modal" component={VDialog} />
# Modal
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/dialogs/#modal) complète de Vuetify
<Preview>
<Story name="Basique">
{{
components: { VDialog, VCard, VCardTitle, VCardActions, VBtn },
template: `
<div class="text-center">
<v-dialog
v-model="dialog"
width="500"
>
<template v-slot:activator="obj">
<v-btn
color="primary"
dark
v-on="obj.on"
>
Cliquer
</v-btn>
</template>
<v-card>
<v-card-title
class="headline"
primary-title
>
Titre de la modale
</v-card-title>
<v-card-text>
Je présente des informations à l'utilisateur à propos d'une tâche.
Je peux contenir plusieurs tâches, comme des choix à travers une liste,
ou bien présenter une décision à prendre.
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn
color="primary"
text
@click="dialog = false"
>
Accepter
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
`,
data: () => ({ dialog: false })
}}
</Story>
</Preview>
<file_sep>import { Meta, Preview, Story } from "@storybook/addon-docs/blocks";
import logoA2i from "@/assets/LogoA2iUgitech_FullRes.png"
import ugitechLogo from '@/assets/ugitech.png'
import ugitechByline from '@/assets/ugitech+byline.svg'
import ugitechOriginal from '@/assets/ugitech-original.svg'
import ugitechVariation from '@/assets/ugitech-variation.svg'
<Meta title="Design System/Demo/Images"/>
# Images
Les images du package `@ugitech/web-template` présentées ci-dessous sont exploitables dans vos projets.
## LogoA2iUgitech_FullRes.png
```js
import logoA2i from '@ugitech/web-template/src/assets/LogoA2iUgitech_FullRes.png'
```
<Preview>
<Story name="LogoA2iUgitech_FullRes.png" inline={true}>
{{
data: () => ({ src: logoA2i }),
template: `<img :src="src" width="100">`
}}
</Story>
</Preview>
## ugitech.png
```js
import ugitechLogo from '@ugitech/web-template/src/assets/ugitech.png'
```
<Preview>
<Story name="ugitech.png" inline={true}>
{{
data: () => ({ src: ugitechLogo }),
template: `<img :src="src" width="100">`
}}
</Story>
</Preview>
## ugitech+byline.svg
```js
import ugitechByline from '@ugitech/web-template/src/assets/ugitech+byline.svg'
```
<Preview>
<Story name="ugitech+byline.svg" inline={true}>
{{
data: () => ({ src: ugitechByline }),
template: `<img :src="src" width="100">`
}}
</Story>
</Preview>
## ugitech-original.svg
```js
import ugitechOriginal from '@ugitech/web-template/src/assets/ugitech-original.svg'
```
<Preview>
<Story name="ugitech-original.svg" inline={true}>
{{
data: () => ({ src: ugitechOriginal }),
template: `<img :src="src" width="100">`
}}
</Story>
</Preview>
## ugitech-variation.svg
```js
import ugitechVariation from '@ugitech/web-template/src/assets/ugitech-variation.svg'
```
<Preview>
<Story name="ugitech-variation.svg" inline={true}>
{{
data: () => ({ src: ugitechVariation }),
template: `<img :src="src" width="100">`
}}
</Story>
</Preview>
<file_sep>const path = require('path')
module.exports = {
stories: [
'../stories/doc/**/*.stories.(ts|mdx)',
'../stories/components/**/*.stories.(ts|mdx)',
'../stories/demo/**/*.stories.(ts|mdx)'
],
addons: [
'@storybook/addon-actions',
'@storybook/addon-links/register',
'@storybook/addon-viewport/register',
'@storybook/addon-docs',
{
name: '@storybook/preset-typescript',
}
],
};
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { action } from "@storybook/addon-actions";
import { VApp, VBtn, VIcon } from "vuetify/lib";
import { UtNavigationDrawer } from "@/components/UtNavigationDrawer";
import vuetify from "@/plugins/vuetify";
<Meta
title="Design System/Composants/Layout/UtNavigationDrawer"
component={UtNavigationDrawer}
parameters={{ custom: { wrapWithVuetifyApp: false, fullHeight: true } }}
/>
# Panneau Latéral
- Ce composant s'appuie sur:
- le composant [v-navigation-drawer](https://vuetifyjs.com/en/components/navigation-drawers/#navigation-drawers)
- il utilise [v-dialog](https://vuetifyjs.com/en/components/dialogs/#dialogs) pour les petits écrans
### API
#### Props
| Nom | Commentaires | Default |
|---|---|---|
| titre | Titre du panneau | required |
| toggle-options | Configuration du bouton | `{icon: undefined, color: '#f0f0f0', dark: false}` |
#### Slots
| Nom | Commentaires |
| --- | --- |
| default | |
#### Events
| Nom | Commentaires |
| --- | --- |
| input | voir [v-model](https://fr.vuejs.org/v2/guide/components.html#Utiliser-v-model-sur-les-composants) |
<Preview>
<Story name="Basique">
{{
vuetify,
components: {
VApp,
UtNavigationDrawer
},
template: `
<v-app>
<ut-navigation-drawer
v-model="drawer"
title="Titre"
:toggle-options="{ icon: 'mdi-filter-variant' }"
@input="toggleDrawerAction"
>
<div class="text-center pa-5">contenu</div>
</ut-navigation-drawer>
<v-content>
<v-container
class="fill-height"
fluid
>
<div class="px-10">contenu principal</div>
<v-btn
fab
v-if="$vuetify.breakpoint.mdAndDown"
@click="drawer = !drawer"
class="ut-navigation-drawer__float-button"
>
<v-icon>mdi-filter-variant</v-icon>
</v-btn>
</v-container>
</v-content>
</v-app>
`,
methods: {
toggleDrawerAction: action("toggleDrawer")
},
data: () => ({
drawer: false
})
}}
</Story>
</Preview>
<Preview>
<Story name="Contrôle externe">
{{
vuetify,
components: {
VApp,
VBtn,
UtNavigationDrawer
},
template: `
<v-app>
<ut-navigation-drawer v-model="drawer" title="Titre" :app-bar="false">
<div class="text-center pa-5">contenu</div>
</ut-navigation-drawer>
<v-content>
<v-container
class="fill-height"
fluid
>
<div class="px-10">
<v-btn @click="toggleDrawer">{{drawer ? 'fermer' : 'ouvrir'}}</v-btn>
</div>
</v-container>
</v-content>
</v-app>
`,
methods: {
toggleDrawer() {
this.drawer = !this.drawer;
}
},
data: () => ({
drawer: false
})
}}
</Story>
</Preview>
<Preview>
<Story name="Modifier le bouton">
{{
vuetify,
components: {
VApp,
VBtn,
UtNavigationDrawer,
VIcon
},
template: `
<v-app>
<ut-navigation-drawer
title="Titre"
v-model="drawer"
:toggle-options="toggleOptions"
>
<div class="text-center pa-5">contenu</div>
</ut-navigation-drawer>
<v-content>
<v-container
class="fill-height"
fluid
>
<v-row class="px-10">
<v-col
v-for="(value, key) in options"
>
<v-btn
:dark="value.dark"
:color="value.color"
@click="changeOptions(key)">
<v-icon>{{value.icon}}</v-icon>options {{key+1}}
</v-btn>
</v-col>
</v-row>
<v-btn
fab
:dark="toggleOptions.dark"
:color="toggleOptions.color"
v-if="$vuetify.breakpoint.mdAndDown"
@click="drawer = !drawer"
class="ut-navigation-drawer__float-button"
>
<v-icon>{{toggleOptions.icon}}</v-icon>
</v-btn>
</v-container>
</v-content>
</v-app>
`,
methods: {
changeOptions(index) {
this.toggleOptions = this.options[index];
},
},
data: () => ({
drawer: false,
options: [
{
icon: 'mdi-baguette',
color: 'primary',
dark: true
},
{
icon: 'mdi-account-search-outline',
},
{
icon: 'mdi-beach',
color: 'success',
dark: true
},
{
icon: 'mdi-filter-variant',
color: 'red',
dark: true
},
],
toggleOptions: {
icon: 'mdi-filter-variant',
color: 'red',
dark: true
}
})
}}
</Story>
</Preview>
<file_sep>import { Vue } from 'vue-property-decorator';
import moment from 'moment';
import './UtDatetimePicker.scss';
export default class UtDatetimePicker extends Vue {
value: Date;
get momentObj(): moment.Moment;
get date(): string;
get time(): string;
onTimeChange(newValue: string): void;
onDateChange(newValue: string): void;
}
<file_sep>import UtConnectionLayout from './UtConnectionLayout';
export { UtConnectionLayout, };
export default UtConnectionLayout;
<file_sep>import {
Component, Vue, Prop,
} from 'vue-property-decorator';
import {
VRow,
VCol,
VBtn,
VIcon,
VSpacer,
} from 'vuetify/lib';
import './UtNavigationBar.scss';
export interface UtNavigationBarButton {
show: boolean;
}
export interface UtNavigationBarOptions {
actions: {
home: UtNavigationBarButton;
refresh: UtNavigationBarButton;
next: UtNavigationBarButton;
back: UtNavigationBarButton;
close: UtNavigationBarButton;
}
}
@Component({
name: 'ut-navigation-bar',
components: {
VRow,
VCol,
VBtn,
VIcon,
VSpacer,
},
template: `
<v-row
no-gutters
class="ut-navigation-bar align-center"
>
<div class="d-flex justify-start">
<v-btn
text
v-if="options.buttons.back.show"
@click="back"
>
<v-icon>mdi-chevron-left</v-icon>
</v-btn>
<v-btn
text
v-if="options.buttons.next.show"
@click="next"
>
<v-icon>mdi-chevron-right</v-icon>
</v-btn>
<v-btn
text
v-if="options.buttons.home.show"
@click="home"
>
<v-icon>mdi-home</v-icon>
</v-btn>
<v-btn
text
v-if="options.buttons.refresh.show"
@click="refresh"
>
<v-icon>mdi-refresh</v-icon>
</v-btn>
<v-btn
text
v-if="$vuetify.breakpoint.xsOnly && options.buttons.close.show"
@click="close()"
class="ut-navigation-bar__close-btn--xs-only"
>
<v-icon>mdi-close</v-icon>
</v-btn>
</div>
<v-spacer />
<div v-if="$vuetify.breakpoint.smAndUp" class="d-flex justify-end">
<v-btn
text
v-if="options.buttons.close.show"
@click="close()"
>
<v-icon>mdi-close</v-icon>
<span v-if="$vuetify.breakpoint.mdAndUp">Fermer</span>
</v-btn>
</div>
</v-row>
`,
})
export default class UtNavigationBar extends Vue {
@Prop({
type: Object,
required: false,
default: () => ({
buttons: {
home: { show: true },
refresh: { show: true },
back: { show: true },
next: { show: true },
close: { show: true },
},
}),
}) options!: UtNavigationBarOptions;
public back() {
this.$emit('back');
}
public next() {
this.$emit('next');
}
public home() {
this.$emit('home');
}
public refresh() {
this.$emit('refresh');
}
public close() {
this.$emit('close');
}
}
<file_sep>import { Vue } from 'vue-property-decorator';
import './UtAppBarTitle.scss';
export default class UtAppBarTitle extends Vue {
}
<file_sep>import UtConnectionLayout from './UtConnectionLayout';
export {
UtConnectionLayout,
};
export default UtConnectionLayout;
<file_sep>/**
* rm -rf scss
* mkdir scss
* cp -r src/styles/* scss
* sed -i 's/~@\//~@ugitech\/web-template\/src\//g' scss/ugitech.scss
*/
const shell = require('shelljs');
shell.rm('-rf', './scss');
shell.mkdir('./scss');
shell.cp('-r', './src/styles/*', 'scss');
shell.sed('-i', /~@\//g, '~@ugitech/web-template/src/', './scss/ugitech.scss');
<file_sep>import { UtTimePicker } from '@/components/UtTimePicker';
import { action } from '@storybook/addon-actions';
export default {
title: 'Design System/Composants/UtTimePicker',
component: UtTimePicker,
};
export const basique = () => ({
components: { UtTimePicker },
template: '<ut-time-picker v-model="time" @input="change"/>',
data: () => ({ time: '12:30:45' }),
methods: {
change: action('change'),
},
});
<file_sep>declare module '@ugitech/web-template/lib/util/colors' {
export const primary: string;
export const secondary: string;
export const accent: string;
export const error: string;
export const warning: string;
export const success: string;
export const info: string;
interface ITheme {
primary?: string;
secondary?: string;
accent?: string;
error?: string;
warning?: string;
info?: string;
success?: string;
}
const theme: {
themes: {
light?: ITheme,
dark?: ITheme
}
}
export default theme;
}
<file_sep>import { Meta, Preview, Story } from "@storybook/addon-docs/blocks";
import LinkTo from "@storybook/addon-links/react";
import connexionComponent from './connexion-component'
import dataComponent from './data-component'
<Meta title="Design System/Demo"/>
# Utiliser la structure de base
Pour créer une application avec une structure de base, vous disposez des composants:
- <LinkTo kind="design-system-composants-layout-utnavigationbar">
ut-navigation-bar
</LinkTo> (pour l'affichage en mode "kiosque")
- <LinkTo kind="design-system-composants-layout-utappbar">ut-app-bar</LinkTo>
- <LinkTo kind="design-system-composants-layout-utnavigationdrawer">ut-navigation-drawer</LinkTo>
- <LinkTo kind="design-system-composants-layout-utconnectionlayout">ut-connection-layout</LinkTo>
Ici on utilise `v-if` pour l'affichage conditionnel de la page de connexion.
Pour naviguer entre les pages dans une application plus lourde, il est conseillé d'utiliser une solution plus robuste comme [vue-router](https://router.vuejs.org/)
Dans l'exemple suivant:
- Depuis la page de connexion, cliquez sur *Connexion*
- Depuis la page de contenu, cliquez sur le bouton de déconnexion (à côté du nom de l'utilisateur)
<Preview>
<Story
name="Utiliser la structure de base"
inline={true}
parameters={{ custom: { wrapWithVuetifyApp: false, fullHeight: true } }}
>
{() => connexionComponent}
</Story>
</Preview>
# Afficher des données
<Preview>
<Story
name="Afficher des données"
inline={true}
parameters={{ custom: { wrapWithVuetifyApp: false, fullHeight: true } }}
>
{() => dataComponent}
</Story>
</Preview>
<file_sep>import './UtAppMenuAppItem.scss';
declare const _default: {
name: string;
components: {
VIcon: import("vue").Component<import("vue/types/options").DefaultData<never>, import("vue/types/options").DefaultMethods<never>, import("vue/types/options").DefaultComputed, Record<string, any>>;
};
props: {
item: {
type: ObjectConstructor;
required: boolean;
};
};
template: string;
};
export default _default;
<file_sep>FROM node:12.16.1-alpine as base
WORKDIR /app
COPY package*.json /app/
ADD ./build /app/build
RUN npm install
RUN npm i --no-save vue@2.6.11 vuetify@2.2.18
COPY ./ /app/
FROM base as builder
RUN npm run build:storybook
FROM nginx:1.15.8-alpine as prod
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/storybook-static/ /usr/share/nginx/html<file_sep># @ugitech/web-template
Ce projet a pour but de servir de base à toute nouvelle application s'appuyant sur `Vue` et `Vuetify`.
Il permet d'appliquer par défaut le style graphique d'Ugitech et met à disposition quelques
composants prêts à l'emploi pour accélerer le développement de vos applications.
Ce projet permet:
- de déployer un package `npm` nommé `@ugitech/web-template`
- de déployer un [storybook](https://storybook.js.org/) servant de documentation et donnant des exemples d'utilisation du package
## Usage du package dans vos applications
`npm i @ugitech/web-template`
## Docker
Ce projet met à disposition:
- 1 `Dockerfile` pour construire l'image du [Storybook](https://storybook.js.org/)
- 1 fichier `docker-compose.yml` qui s'appuie sur le `Dockerfile` pour construire une image et lancer un container contenant le storybook
### Usage
#### docker-compose
```sh
# lance le container, accessible à l'adresse localhost:8080
docker-compose up
```
#### Construire l'image
```sh
docker build . -t ugitech-storybook:1.0
```
#### Lancer un container à partir de l'image
```sh
docker run --name storybook -d -p 8080:80 ugitech-storybook:1.0
```
## Développement
Grossièrement, le flux de travail pour publier une nouvelle version du package ressemble à ceci:
- Installation des dépendances pour le développement `npm i`
- Installation des [peerDependencies](https://npm.github.io/using-pkgs-docs/package-json/types/peerdependencies.html): `npm i --no-save vue vuetify`
- développement de nouvelles fonctionnalités / nouveaux composants
- déclaration des types pour Typescript: `npm run build:types`
- construction de la librairie: `npm run build:lib`
- MaJ de la version du package: manuellement dans le `package.json` ou avec [`npm version`](https://docs.npmjs.com/cli/version)
- publication: `npm publish` (**\/!\\** vous devez configurer npm pour cibler votre [registy](https://docs.npmjs.com/using-npm/registry.html) privé)
### Composants
**Attention**: si vos composants Vue utilise des composants Vuetify (`v-row` ou `v-tooltip` par exemple), vous devez impérativement les déclarer dans l'objet `components` du composant Vue.
```js
// components/MyCustomComponent/MyCustomComponent.ts
import { VRow } from 'vuetify/lib';
export default Vue.extend({
components: {
VRow
},
template: `
<v-row></v-row>
`
})
```
### Installation des **peerDependencies**
`npm i --no-save vue vuetify`
**\/!\\** A chaque fois qu'on lance `npm i`, les peerDependencies sont retirées du dossier `node_modules`
### Build du storybook
/!\ les **peerDependencies** sont requises
`npm run build:storybook`
### Build de la librairie
/!\ les **peerDependencies** sont requises
`npm run build:lib`
### Déclarations des types Typescript
/!\ les **peerDependencies** sont requises
`npm run build:types`
### Problèmes connus
#### fichiers `.mdx` du storybook
- les lignes vides dans le template font échouer la compilation.
#### support de IE11
Le composant `v-menu` s'affiche mal sur Internet Explorer 11 (au 25/03/2020).
**!! Ne pas utiliser [la destructuration](https://exploringjs.com/es6/ch_destructuring.html) dans vos templates de composants**
**Ne pas écrire**
```html
<template v-slot:activator="{ on }">
<div v-on="on"></div>
</template>
```
**Ecrire plutôt**
```html
<template v-slot:activator="obj">
<div v-on="obj.on"></div>
</template>
```
### Support des navigateurs
Voir:
- https://cli.vuejs.org/guide/browser-compatibility.html#browserslist
- https://vuetifyjs.com/en/getting-started/browser-support/
- https://github.com/vuetifyjs/vuetify/issues?q=IE11
Il peut être utile de mettre à jour Vuetify pour bénéficier des dernières corrections, notamment
concernant Internet Explorer 11.
<file_sep>import { UtTimePicker } from '@/components/UtTimePicker';
import { getMountedComponent } from '../../test-utils';
describe('UtTimePicker', () => {
it('decompose time from value', () => {
const cmp: any = getMountedComponent(UtTimePicker, {
value: '19:30:15',
});
expect(cmp.vm.value).toEqual('19:30:15');
expect(cmp.vm.decomposedTime).toEqual({
hours: '19',
minutes: '30',
seconds: '15',
});
});
});
<file_sep>import '@mdi/font/css/materialdesignicons.css';
import Vuetify from 'vuetify/lib';
import theme from '@/util/colors';
export default new Vuetify({
light: true,
theme,
});
<file_sep>import { UtNavigationBar } from './components/UtNavigationBar';
import { UtTimePicker } from './components/UtTimePicker';
import { UtAppMenu } from './components/UtAppMenu';
import { UtDatetimePicker } from './components/UtDatetimePicker';
import { UtAppBar } from './components/UtAppBar';
import { UtNavigationDrawer } from './components/UtNavigationDrawer';
import { UtConnectionLayout } from './components/UtConnectionLayout';
import '@mdi/font/css/materialdesignicons.css';
const install = (Vue: any) => {
Vue.component('ut-app-bar', UtAppBar);
Vue.component('ut-app-menu', UtAppMenu);
Vue.component('ut-datetime-picker', UtDatetimePicker);
Vue.component('ut-time-picker', UtTimePicker);
Vue.component('ut-navigation-bar', UtNavigationBar);
Vue.component('ut-navigation-drawer', UtNavigationDrawer);
Vue.component('ut-connection-layout', UtConnectionLayout);
};
export {
UtAppBar,
UtAppMenu,
UtDatetimePicker,
UtTimePicker,
UtNavigationBar,
UtNavigationDrawer,
UtConnectionLayout,
};
export default install;
<file_sep>import { Meta } from "@storybook/addon-docs/blocks";
import LinkTo from "@storybook/addon-links/react";
<Meta title="Design System/Introduction"/>
# Introduction
## Principales dépendances du projet
- node 12.16.1
- vue 2.6.11
- vuetify 2.2.18
- @vue/cli 4.2.2
- [Material Design Icons](https://materialdesignicons.com/) via le package [@mdi/font](@mdi/font)
## Prérequis
Les composants présentés sur ce site s'appuient très fortement sur [Vuetify](https://vuetifyjs.com/en/introduction/guide/).
Il est donc indispensable de comprendre le framework et de se référer à sa documentation.
La documentation de ce site se concentre exclusivement sur ce qui est spécifique à Ugitech.
## Utilisation
### Initialiser un projet avec vue-cli
```sh
vue create my-app
cd my-app
vue add vuetify
```
Dans le fichier `public/index.html`, retirer ces 2 lignes:
```html
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@latest/css/materialdesignicons.min.css">
```
### installation du package
Avant d'installer le package, vous devez [configurer npm pour cibler votre registry privé](https://docs.microsoft.com/en-us/azure/devops/artifacts/get-started-npm?view=azure-devops&tabs=windows#set-up-your-npmrc-files)
```sh
npm i @ugitech/web-template
```
### Surcharge des [variables SASS](https://vuetifyjs.com/en/customization/sass-variables/) de Vuetify
```js
// src/styles/variables.scss
@import '~@ugitech/web-template/scss/variables'
```
### Import des classes spécifiques "ut-*" et de la police Arial
```js
// src/App.vue
<style lang="scss">
@import '~@ugitech/web-template/scss/ugitech'
</style>
```
### Définition du [thème](https://vuetifyjs.com/en/customization/theme/) Ugitech pour Vuetify
```js
// src/plugins/vuetify.js
import Vue from "vue";
import Vuetify from "vuetify/lib";
import theme from "@ugitech/web-template/lib/util/colors";
import { ThemeOptions } from 'vuetify/types/services/theme';
Vue.use(Vuetify);
export default new Vuetify({
theme: theme as ThemeOptions
});
```
Si vous voulez personnaliser les thèmes vuetify vous pouvez aussi faire:
```js
// src/plugins/vuetify.js
import Vue from "vue";
import Vuetify from "vuetify/lib";
import { primary, error } from "@ugitech/web-template/lib/util/colors";
Vue.use(Vuetify);
export default new Vuetify({
theme: {
themes: {
light: {
primary,
error,
success: '#4CAF50',
},
},
}
});
```
### Installation des composants Vue
Placez ces lignes quelque part avant l'instanciation de Vue (dans le fichier `main.js` par exemple):
```js
import WebTemplate from '@ugitech/web-template';
Vue.use(WebTemplate);
```
### Utilisation du [runtime compiler](https://cli.vuejs.org/config/#runtimecompiler)
Certains composants Vue utilisant l'option `template`, on doit paramétrer Vue comme suit:
```js
// vue.config.(js|json)
{
...,
"runtimeCompiler": true
}
```
### Typescript (optionnel)
- exécuter ```vue add typescript```
- modifier `./tsconfig.json`: ajouter `"vuetify"` au tableau `"types"`
- ajouter le fichier `src/shims-png.d.ts`:
```ts
declare module "*.png" {
const value: any;
export default value;
}
```
### Utiliser le layout de base
Voir <LinkTo kind="design-system-demo--utiliser-la-structure-de-base">layout de base</LinkTo>
<file_sep>import { VTextField } from 'vuetify/lib';
import { UtDatetimePicker } from '@/components/UtDatetimePicker';
import moment from 'moment';
import { action } from '@storybook/addon-actions';
export default {
title: 'Design System/Composants/Formulaire/DateTime',
component: UtDatetimePicker,
decorators: [() => ({
template: `
<v-row class="pa-5">
<v-col cols="4">
<story/>
</v-col>
</v-row>
`,
})],
};
export const menu = () => ({
components: { UtDatetimePicker, VTextField },
template: `
<v-menu
ref="menu"
v-model="menu2"
:close-on-content-click="false"
transition="scale-transition"
offset-y
max-width="290px"
height="290px"
>
<template v-slot:activator="obj">
<v-text-field
v-model="formatedDateTime"
label="Choix de date"
append-icon="mdi-calendar"
readonly
filled
v-on="obj.on"
></v-text-field>
</template>
<div
v-if="menu2"
full-width
class="d-flex justify-center"
>
<ut-datetime-picker v-model="datetime" @input="change">
<v-spacer></v-spacer>
<div class="d-flex justify-end pa-2">
<v-btn text color="primary" @click="menu2 = false">Fermer</v-btn>
</div>
</ut-datetime-picker>
</div>
</v-menu>
`,
data: () => ({
datetime: new Date(),
menu2: false,
}),
computed: {
formatedDateTime() {
return moment(this.datetime).format('YYYY-MM-DD à HH:mm:ss');
},
},
methods: {
change: action('change'),
},
});
export const modal = () => ({
components: { UtDatetimePicker, VTextField },
template: `
<v-dialog
ref="dialog"
v-model="modal2"
:return-value.sync="datetime"
persistent
width="290px"
>
<template v-slot:activator="obj">
<v-text-field
v-model="formatedDateTime"
label="Choix de date"
append-icon="mdi-calendar"
readonly
filled
v-on="obj.on"
></v-text-field>
</template>
<div
v-if="modal2"
full-width
class="d-flex justify-center"
>
<ut-datetime-picker v-model="datetime" @input="change">
<v-spacer></v-spacer>
<div class="d-flex justify-end pa-2">
<v-btn text color="primary" @click="modal2 = false">Annuler</v-btn>
<v-btn text color="primary" @click="$refs.dialog.save(datetime)">OK</v-btn>
</div>
</ut-datetime-picker>
</div>
</v-dialog>
`,
data: () => ({
datetime: new Date(),
modal2: false,
}),
computed: {
formatedDateTime() {
return moment(this.datetime).format('YYYY-MM-DD à HH:mm:ss');
},
},
methods: {
change: action('change'),
},
});
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VSlider } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
<Meta title="Design System/Composants/Sliders" component={VSlider} />
# Sliders
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/sliders/#sliders) complète de Vuetify
<Preview>
<Story name="Basique" inline={true} height="50px">
{{
components: { VSlider },
template: `
<v-row justify="space-around">
<v-col cols="12">
<v-slider
v-model="min"
min="-100"
max="100"
label="Min"
></v-slider>
</v-col>
</v-row>
`,
data: () => ({ min: 0 })
}}
</Story>
</Preview>
<file_sep>import { Vue } from 'vue-property-decorator';
import './UtNavigationBar.scss';
export interface UtNavigationBarButton {
show: boolean;
}
export interface UtNavigationBarOptions {
actions: {
home: UtNavigationBarButton;
refresh: UtNavigationBarButton;
next: UtNavigationBarButton;
back: UtNavigationBarButton;
close: UtNavigationBarButton;
};
}
export default class UtNavigationBar extends Vue {
options: UtNavigationBarOptions;
back(): void;
next(): void;
home(): void;
refresh(): void;
close(): void;
}
<file_sep>import UtDatetimePicker from './UtDatetimePicker';
export { UtDatetimePicker, };
export default UtDatetimePicker;
<file_sep>import { UtAppBarTitle } from '@/components/UtAppBar';
import { getMountedComponent } from '../test-utils';
const $vuetifyMock = { breakpoint: { smAndUp: true } };
describe('UtAppBarTitle', () => {
it('affiche le nom de la page', () => {
expect(
getMountedComponent(UtAppBarTitle, {
page: 'page',
website: 'website',
}, $vuetifyMock).find('.ut-app-bar-title__page').text(),
).toBe('page');
});
it('affiche le nom du site', () => {
expect(
getMountedComponent(UtAppBarTitle, {
page: 'page',
website: 'website',
}, $vuetifyMock).find('.ut-app-bar-title__website').text(),
).toBe('website');
});
});
<file_sep>import { Vue } from 'vue-property-decorator';
import './UtNavigationDrawer.scss';
export interface NavigationDrawerToggleOptions {
icon?: string;
color?: string;
dark?: boolean;
}
export default class UtNavigationDrawer extends Vue {
toggleOptions: NavigationDrawerToggleOptions;
value: boolean;
title: string;
onDrawerInput(value: boolean): void;
toggleDrawer(): void;
closeDialog(): void;
}
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VSelect } from "vuetify/lib";
<Meta
title="Design System/Composants/Formulaire/Select"
component={VSelect}
decorators={[() => ({
template: '<div class="pa-2" style="height: 500px"><story/></div>'
})]}
/>
# Select
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/selects/#selects) complète de Vuetify
## Style
Pour l'apparence, on utilise les propriétés suivantes:
- `filled`
<Preview>
<Story name="Basique">
{{
components: { VSelect },
template: `
<v-select
v-model="role"
:items="items"
filled
label="Label"
></v-select>
`,
data: () => ({
role: [],
items: ['Administrateur', 'Invité', 'Technicien']
})
}}
</Story>
</Preview>
## Sélection multiple
<Preview>
<Story name="Sélection multiple">
{{
components: { VSelect },
template: `
<v-select
v-model="role"
:items="items"
filled
multiple
label="Label"
hint="Choisissez 1 ou plusieurs rôles"
persistent-hint
></v-select>
`,
data: () => ({
role: [],
items: ['Administrateur', 'Invité', 'Technicien']
})
}}
</Story>
</Preview>
<file_sep>import { UtTimePickerCounter } from '@/components/UtTimePicker';
import { getMountedComponent } from '../../test-utils';
describe('UtTimePickerCounter', () => {
it('add method emits "add" event', () => {
const cmp: any = getMountedComponent(UtTimePickerCounter, { value: '1' });
cmp.vm.$emit = jest.fn();
cmp.vm.add();
expect(cmp.vm.$emit).toHaveBeenCalledTimes(1);
expect(cmp.vm.$emit).toHaveBeenCalledWith('add');
});
it('subtract method emits "subtract" event', () => {
const cmp: any = getMountedComponent(UtTimePickerCounter, { value: '1' });
cmp.vm.$emit = jest.fn();
cmp.vm.subtract();
expect(cmp.vm.$emit).toHaveBeenCalledTimes(1);
expect(cmp.vm.$emit).toHaveBeenCalledWith('subtract');
});
it('format value to be 2 characters long', (done) => {
const cmp: any = getMountedComponent(UtTimePickerCounter, { value: '1' });
expect(cmp.vm.inputValue).toEqual('01');
cmp.setProps({ value: '60' });
cmp.vm.$nextTick(() => {
expect(cmp.vm.inputValue).toEqual('60');
done();
});
});
});
<file_sep>import { addons } from '@storybook/addons';
import { create } from '@storybook/theming/create';
addons.setConfig({
theme: create({
brandTitle: 'Ugitech',
brandUrl: 'https://www.ugitech.com/home/',
brandImage: './ugitech-logo.png'
}),
});
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import {
VDataTable,
VSimpleTable,
VSelect,
VTooltip,
VIcon,
VToolbar,
VToolbarTitle,
VSwitch,
VSpacer,
VTextField
} from "vuetify/lib";
import { action } from "@storybook/addon-actions";
import moment from 'moment';
import random from 'lodash/random';
import sample from 'lodash/sample';
<Meta title="Design System/Composants/Tableau" component={VDataTable} />
# Tableau
Le composant `v-data-table` de Vuetify est très versatile.
Veuillez consulter la [documentation officielle](https://vuetifyjs.com/en/components/data-tables/#data-tables) pour adapter les tableaux de données aux besoins de vos applications.
## Style
Notez:
- utilisation des classes `ut-table` et `ut-table--stripped` sur l'élément `v-data-table`
- utilisation de la classe `ut-table__select` sur l'élément `v-select`
## Tableau de données complexes
<Preview>
<Story name="Tableau de données complexes" inline={true}>
{{
components: {
VDataTable,
VSelect,
VTooltip,
VIcon,
VToolbar,
VToolbarTitle,
VSpacer,
VTextField
},
template: `
<v-data-table
v-model="selected"
@item-selected="onItemSelected"
@input="onInput"
:headers="headers"
:items="items"
:search="search"
item-key="id"
show-select
class="ut-table ut-table--stripped"
>
<template v-slot:top>
<v-toolbar flat>
<v-toolbar-title>Logs</v-toolbar-title>
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Recherche"
single-line
hide-details
></v-text-field>
</v-toolbar>
</template>
<template v-slot:item.date="{ item }">
{{ item.date | date('DD/MM/YYYY HH:mm:ss') }}
</template>
<template v-slot:item.type="{ item }">
<v-icon :class="item.type | iconClass">{{ item.type | icon }}</v-icon>
<span>{{ item.type | capitalize }}</span>
</template>
<template v-slot:item.fonction="{ item }">
<v-select hide-details class="ut-table__select" :items="fonctions" :value="item.fonction"></v-select>
</template>
<template v-slot:item.clé="{ item }">
<a v-if="item.clé.url" :href="item.clé.url" target="_blank">{{ item.clé.value | capitalize }}</a>
<span v-if="!item.clé.url">{{ item.clé.value | capitalize }}</span>
</template>
<template v-slot:item.infos="{ item }">
<v-tooltip bottom>
<template v-slot:activator="obj">
<div style="max-width: 800px;" class="ut-table-cell__nowrap d-none d-lg-block" v-on="obj.on">
<span v-if="item.infos instanceof Object" class="custom__separator" v-for="(val, key) in item.infos">
{{key | capitalize}}: {{val | capitalize}}
</span>
<span v-if="!(item.infos instanceof Object)">{{item.infos}}</span>
</div>
<v-icon v-on="obj.on" class="d-lg-none ut-pointer">mdi-information</v-icon>
</template>
<div>
<span v-if="item.infos instanceof Object" class="custom__separator" v-for="(val, key) in item.infos">
{{key | capitalize}}: {{val | capitalize}}
</span>
<span v-if="!(item.infos instanceof Object)">{{item.infos}}</span>
</div>
</v-tooltip>
</template>
</v-data-table>
`,
filters: {
capitalize(value) {
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
},
date(value, format) {
return moment(value).format(format);
},
icon(value) {
if (value == 'alert') {
return 'mdi-alert-circle';
}
if (value == 'info') {
return 'mdi-information';
}
if (value == 'check') {
return 'mdi-check-circle';
}
return '';
},
iconClass(value) {
if (value == 'alert') {
return 'ut-error';
}
if (value == 'info') {
return 'ut-info';
}
if (value == 'check') {
return 'ut-success';
}
return '';
}
},
data: () => ({
search: '',
fonctions: [{
text:'Connexion Web',
value:'Connexion Web',
},{
text:'Terminer Camion',
value:'Terminer Camion'
}],
selected: [],
headers: [
{
text: 'Date',
align: 'start',
sortable: true,
value: 'date',
},
{ text: 'Type', value: 'type', sortable: true, },
{ text: 'Fonction', value: 'fonction', sortable: false, },
{ text: 'Clé', value: 'clé', sortable: false, },
{ text: 'Infos', value: 'infos', sortable: false, },
],
items: [
{
id: 1,
date: new Date('03/03/2020 13:19:50'),
type: 'info',
fonction: 'Connexion Web',
clé: { value: 'administrateur', url: 'http://www.ugitech.com', },
infos: {
utilisateur: 'administrateur',
poste: 'matin',
role: 'administrateur',
emplacement: 'tous',
utilisateur2: 'administrateur',
poste2: 'matin',
role2: 'administrateur',
emplacement2: 'tous'
}
},
{
id: 2,
date: new Date('03/03/2020 13:17:20'),
type: 'check',
fonction: 'Terminer Camion',
clé: { value: '458878' },
infos: "L'étape PWT du BT 458878 a été terminée",
},
{
id: 3,
date: new Date('03/03/2020 13:45:55'),
type: 'alert',
fonction: 'Terminer Camion',
clé: { value: '458878', url: 'http://www.ugitech.com', },
infos: "L'étape PWT du BT 458878 a été terminée",
},
{
id: 4,
date: new Date('12/27/2019 13:19:50'),
type: 'info',
fonction: 'Connexion Web',
clé: { value: 'administrateur', url: 'http://www.ugitech.com', },
infos: {
utilisateur: 'administrateur',
poste: 'matin',
role: 'administrateur',
emplacement: 'tous',
utilisateur2: 'administrateur',
poste2: 'matin',
role2: 'administrateur',
emplacement2: 'tous'
}
},
{
id: 5,
date: new Date('07/03/2020 13:19:50'),
type: 'info',
fonction: 'Connexion Web',
clé: { value: 'administrateur' },
infos: {
utilisateur: 'administrateur',
poste: 'matin',
role: 'administrateur',
emplacement: 'tous',
utilisateur2: 'administrateur',
poste2: 'matin',
role2: 'administrateur',
emplacement2: 'tous'
}
},
{
id: 6,
date: new Date('07/04/2020 19:02:01'),
type: 'alert',
fonction: 'Connexion Web',
clé: { value: 'administrateur'},
infos: {
utilisateur: 'administrateur',
poste: 'matin',
role: 'administrateur',
emplacement: 'tous',
}
},
]
}),
methods: {
onItemSelected: action('selectItem'),
onInput: action('selectedItems'),
}
}}
</Story>
</Preview>
## Lignes extensibles
<Preview>
<Story name="Lignes extensibles" inline={true}>
{{
components: {
VDataTable,
VToolbar,
VSwitch,
VSpacer,
},
template: `
<v-data-table
@item-expanded="onItemExpanded"
:headers="headers"
:items="desserts"
:single-expand="singleExpand"
:expanded.sync="expanded"
item-key="name"
show-expand
class="ut-table ut-table--stripped"
>
<template v-slot:top>
<v-toolbar flat>
<v-toolbar-title>Lignes extensibles</v-toolbar-title>
<v-spacer></v-spacer>
<v-switch v-model="singleExpand" label="Extension simple" class="mt-2"></v-switch>
</v-toolbar>
</template>
<template v-slot:expanded-item="{ headers, item }">
<td :colspan="headers.length">Plus d'infos sur {{ item.name }}</td>
</template>
</v-data-table>
`,
methods: {
onItemExpanded: action('itemExpanded')
},
data () {
return {
expanded: [],
singleExpand: false,
headers: [
{
text: 'Dessert (100g serving)',
align: 'start',
sortable: false,
value: 'name',
},
{ text: 'Calories', value: 'calories' },
{ text: 'Fat (g)', value: 'fat' },
{ text: 'Carbs (g)', value: 'carbs' },
{ text: 'Protein (g)', value: 'protein' },
{ text: 'Iron (%)', value: 'iron' },
{ text: '', value: 'data-table-expand' },
],
desserts: [
{
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
iron: '1%',
},
{
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
iron: '1%',
},
{
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 23,
protein: 6.0,
iron: '7%',
},
{
name: 'Cupcake',
calories: 305,
fat: 3.7,
carbs: 67,
protein: 4.3,
iron: '8%',
},
],
}
},
}}
</Story>
</Preview>
## Pagination
<Preview>
<Story name="Pagination" inline={true}>
{{
components: {
VDataTable,
},
template: `
<v-data-table
light
:headers="headers"
:items="items"
item-key="name"
:options="{itemsPerPage: 5}"
class="ut-table ut-table--stripped"
@pagination="onPaginationEvent"
>
<template v-slot:top>
<v-toolbar flat>
<v-toolbar-title>Pagination</v-toolbar-title>
</v-toolbar>
</template>
<template v-slot:item.date="{ item }">
{{ item.date | date('DD/MM/YYYY') }}
</template>
<template v-slot:item.type="{ item }">
<v-icon :class="item.type | iconClass">{{ item.type | icon }}</v-icon>
<span>{{ item.type | capitalize }}</span>
</template>
</v-data-table>
`,
methods: {
onPaginationEvent: action('pagination')
},
filters: {
capitalize(value) {
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
},
date(value, format) {
return moment(value).format(format);
},
icon(value) {
if (value == 'alert') {
return 'mdi-alert-circle';
}
if (value == 'info') {
return 'mdi-information';
}
if (value == 'check') {
return 'mdi-check-circle';
}
return '';
},
iconClass(value) {
if (value == 'alert') {
return 'ut-error';
}
if (value == 'info') {
return 'ut-info';
}
if (value == 'check') {
return 'ut-success';
}
return '';
}
},
data () {
return {
headers: [
{
text: 'Date',
value: 'date',
align: 'start'
},
{ text: 'Type', value: 'type' },
],
items: new Array(40).fill(0).map(() => ({
date: new Date(`${random(1,12)}/${random(1,28)}/20${random(10,20)}`),
type: sample(['info', 'check', 'alert'])
}))
}
},
}}
</Story>
</Preview>
<file_sep>import { action } from '@storybook/addon-actions';
import {
VApp,
VSelect,
VDataTable,
VTooltip,
VTextField,
} from 'vuetify/lib';
import moment from 'moment';
import vuetifyConfig from '@/plugins/vuetify';
import { UtNavigationBar } from '@/components/UtNavigationBar';
import { UtAppBar } from '@/components/UtAppBar';
import { UtNavigationDrawer } from '@/components/UtNavigationDrawer';
import appImg from '@/assets/LogoA2iUgitech_FullRes.png';
const component = {
vuetify: vuetifyConfig,
components: {
UtAppBar,
UtNavigationBar,
UtNavigationDrawer,
VApp,
VSelect,
VDataTable,
VTooltip,
VTextField,
},
template: `
<v-app :class="{ 'ut-app--navigation-bar': navigationBar }">
<ut-navigation-bar
v-if="navigationBar"
@close="close"
@back="back"
@next="next"
@refresh="refresh"
@home="home"
@logout="logout"
/>
<ut-app-bar
dark
:items="menuItems"
website="Nom du site"
page="Titre de page 3"
username="<NAME>"
>
<template v-slot:menuImg>
<img :src="appImg" width="40"/>
</template>
</ut-app-bar>
<ut-navigation-drawer
v-model="drawer"
title="Filtres"
:toggle-options="{ icon: 'mdi-filter-variant' }"
>
<div class="pa-4">
<v-select
class="mt-5"
:items="['Tous']"
filled
hide-details
label="Types"
/>
<v-select
class="mt-5"
:items="['Toutes', 'Connexion Web', 'Terminer Camion']"
filled
hide-details
label="Fonctions"
/>
<v-select
class="mt-5"
:items="['Toutes', 'Connexion Web', 'Terminer Camion']"
filled
hide-details
multiple
label="Clés"
/>
<v-btn
class="mt-5"
:ripple="false"
color="primary"
>
Appliquer
</v-btn>
</div>
</ut-navigation-drawer>
<v-content>
<v-container
class="fill-height"
fluid
>
<v-btn
fab
v-if="$vuetify.breakpoint.mdAndDown"
@click="drawer = !drawer"
class="ut-navigation-drawer__float-button"
>
<v-icon>mdi-filter-variant</v-icon>
</v-btn>
<v-row
class="fill-height"
no-gutters
>
<v-col
cols="12"
class="px-10 py-2"
>
<v-row class="mb-6 mt-3" align="center">
<div class="display-1">
Logs
</div>
<v-spacer />
<div>
<v-text-field
v-model="search"
filled
label="Rechercher"
append-icon="mdi-magnify"
hide-details
dense
/>
</div>
</v-row>
<v-row class="mb-3">
<v-btn outlined color="primary" class="ut-btn ut-btn--outlined">
<v-icon>mdi-download</v-icon>
Export Tableur
</v-btn>
</v-row>
<v-row align="start">
<v-data-table
v-model="selected"
:search="search"
style="width: 100%"
:headers="headers"
:items="items"
:single-select="singleSelect"
item-key="id"
show-select
class="ut-table ut-table--stripped"
>
<template v-slot:item.date="{ item }">
{{ item.date | date('DD/MM/YYYY HH:mm:ss') }}
</template>
<template v-slot:item.type="{ item }">
<div class="d-flex align-center">
<v-icon
:class="item.type | iconClass"
class="mr-2"
>
{{ item.type | icon }}
</v-icon>
<span>{{ item.type | capitalize }}</span>
</div>
</template>
<template v-slot:item.fonction="{ item }">
<v-select
hide-details
class="ut-table__select"
:items="fonctions"
:value="item.fonction"
/>
</template>
<template v-slot:item.clé="{ item }">
<a
v-if="item.clé.url"
:href="item.clé.url"
target="_blank"
>{{ item.clé.value | capitalize }}</a>
<span v-if="!item.clé.url">{{ item.clé.value | capitalize }}</span>
</template>
<template v-slot:item.infos="{ item }">
<v-tooltip bottom>
<template v-slot:activator="obj">
<div
class="d-none d-lg-block"
v-on="obj.on"
>
<div
v-if="item.infos instanceof Object"
class="ut-table-cell__nowrap"
style="max-width: 500px;"
>
<span
v-for="(val, key) in item.infos"
:key="key"
class="custom__separator"
>
{{ key | capitalize }}: {{ val | capitalize }}
</span>
</div>
<span v-else>{{ item.infos }}</span>
</div>
<v-icon
class="d-lg-none ut-pointer"
v-on="obj.on"
>
mdi-information
</v-icon>
</template>
<div>
<div v-if="item.infos instanceof Object">
<span
v-for="(val, key) in item.infos"
:key="key"
class="custom__separator"
>
{{ key | capitalize }}: {{ val | capitalize }}
</span>
</div>
<span v-else>{{ item.infos }}</span>
</div>
</v-tooltip>
</template>
</v-data-table>
</v-row>
</v-col>
</v-row>
</v-container>
</v-content>
</v-app>
`,
methods: {
close: action('close'),
back: action('back'),
next: action('next'),
refresh: action('refresh'),
home: action('home'),
logout: action('logout'),
},
filters: {
capitalize(value: string) {
if (!value) return '';
return value.toString().charAt(0).toUpperCase() + value.slice(1);
},
date(value: any, format: any) {
return moment(value).format(format);
},
icon(value: string) {
if (value === 'alert') {
return 'mdi-alert-circle';
}
if (value === 'info') {
return 'mdi-information';
}
if (value === 'check') {
return 'mdi-check-circle';
}
return '';
},
iconClass(value: string) {
if (value === 'alert') {
return 'ut-error';
}
if (value === 'info') {
return 'ut-info';
}
if (value === 'check') {
return 'ut-success';
}
return '';
},
},
data: () => ({
// eslint-disable-next-line global-require
...require('./data'),
appImg,
}),
};
export default component;
<file_sep>import UtDatetimePicker from './UtDatetimePicker';
export {
UtDatetimePicker,
};
export default UtDatetimePicker;
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VSwitch } from "vuetify/lib";
<Meta
title="Design System/Composants/Formulaire/Toggle"
component={VSwitch}
decorators={[() => ({
template: '<div class="pa-2"><story/></div>'
})]}
/>
# Toggle / Switch
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/selection-controls/) complète de Vuetify
## Style
On utilise la classe `ut-input` pour appliquer le style *Ugitech*
<Preview>
<Story name="Basique" inline={true} height="200px">
{{
components: { VSwitch },
template: `
<v-switch inset v-model="mandatory" class="mx-2 ut-input" label="Mandatory"></v-switch>
`,
data: () => ({ mandatory: false })
}}
</Story>
</Preview>
<file_sep>import UtAppBar from './UtAppBar';
import UtAppBarTitle from './UtAppBarTitle';
export {
UtAppBar,
UtAppBarTitle,
};
export default UtAppBar;
<file_sep>const path = require('path');
module.exports = async ({ config }) => {
const { rules } = config.module;
rules.push({
test: /\.(ts|tsx)$/,
use: [
{
loader: require.resolve('ts-loader'),
options: {
appendTsSuffixTo: [/\.vue$/],
transpileOnly: true
},
},
],
});
rules.push({
test: /\.sass$/,
use: [
'vue-style-loader',
'css-loader',
'resolve-url-loader',
{
loader: 'sass-loader',
// Requires sass-loader@^8.0.0
options: {
sassOptions: {
fiber: require('fibers'),
indentedSyntax: true
},
prependData: "@import '@/styles/variables.scss'"
},
},
],
});
rules.push({
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'resolve-url-loader',
{
loader: 'sass-loader',
// Requires sass-loader@^8.0.0
options: {
sassOptions: {
fiber: require('fibers'),
indentedSyntax: false
},
},
},
],
});
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname, '../src')
}
return config;
};
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VBtn, VBtnToggle, VIcon } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
<Meta
title="Design System/Composants/Boutons"
component={VBtn}
decorators={[() => ({
template: '<div class="pa-2 d-flex justify-center"><story/></div>'
})]}
/>
# Boutons
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/buttons/) complète de Vuetify
## Style
### Principal
On applique la propriété `color="primary"`
### Secondaire
On utilise:
- la propriété `color="primary"`
- la propriété `outlined`
- les classes `ut-btn ut-btn--outlined`
### Tertiaire
On utilise:
- la propriété `color="primary"`
- la propriété `text`
<Preview>
<Story name="Basique" inline={true} height="50px">
{{
components: { VBtn, VIcon },
template: `
<div>
<v-btn :ripple="false" color="primary" @click="action"><v-icon left>mdi-pencil</v-icon>Principal</v-btn>
<v-btn outlined :ripple="false" color="primary" class="ut-btn ut-btn--outlined" @click="action"><v-icon left>mdi-pencil</v-icon>Secondaire</v-btn>
<v-btn text :ripple="false" color="primary" @click="action"><v-icon left>mdi-pencil</v-icon>Tertiaire</v-btn>
</div>
`,
methods: { action: action("clicked") }
}}
</Story>
</Preview>
## Toggle
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/button-groups/) complète de Vuetify
<Preview>
<Story name="Toggle" inline={true} height="50px">
{{
components: { VBtnToggle, VIcon },
template: `
<div>
<v-btn-toggle v-model="toggle_exclusive">
<v-btn>
<v-icon>mdi-brightness-1</v-icon>
</v-btn>
<v-btn>
<v-icon>mdi-brightness-2</v-icon>
</v-btn>
<v-btn>
<v-icon>mdi-brightness-3</v-icon>
</v-btn>
</v-btn-toggle>
</div>
`,
data: () => ({
toggle_exclusive: 2
})
}}
</Story>
</Preview>
<file_sep>import { UtNavigationBar } from '@/components/UtNavigationBar';
describe('UtNavigationBar', () => {
it('close method emits "close" event', () => {
const UtNavigationBarComponent: any = new UtNavigationBar();
UtNavigationBarComponent.$emit = jest.fn();
UtNavigationBarComponent.close();
expect(UtNavigationBarComponent.$emit).toHaveBeenCalledTimes(1);
expect(UtNavigationBarComponent.$emit).toHaveBeenCalledWith('close');
});
});
<file_sep>import UtTimePicker from './UtTimePicker';
import UtTimePickerCounter from './UtTimePickerCounter';
import UtTimePickerHeader from './UtTimePickerHeader';
export { UtTimePicker, UtTimePickerCounter, UtTimePickerHeader, };
export default UtTimePicker;
<file_sep>import UtTimePicker from './UtTimePicker';
import UtTimePickerCounter from './UtTimePickerCounter';
import UtTimePickerHeader from './UtTimePickerHeader';
export {
UtTimePicker,
UtTimePickerCounter,
UtTimePickerHeader,
};
export default UtTimePicker;
<file_sep>import moment from 'moment';
export type TimeComponent = 'hours' | 'seconds' | 'minutes';
export interface Time {
hours: string;
minutes: string;
seconds: string;
}
export const timeRegex = /^(\d?\d):(\d?\d):(\d?\d)$/;
export const isValidTime = (value: any) => timeRegex.test(value);
export const decomposeTime = (time: string): Time => {
const match: any = (time).match(timeRegex);
return {
hours: match ? match[1] : undefined,
minutes: match ? match[2] : undefined,
seconds: match ? match[3] : undefined,
};
};
export const dateToTimeString = (date: Date | string | number): string => {
const momentObj = moment(date);
return `${momentObj.hours()}:${momentObj.minutes()}:${momentObj.seconds()}`;
};
const ranges: { [x: string]: {max: number, min: number} } = {
hours: { min: 0, max: 23 },
minutes: { min: 0, max: 59 },
seconds: { min: 0, max: 59 },
};
const clamp = (timeComponent: TimeComponent, value: number) => {
if (value < ranges[timeComponent].min) {
return ranges[timeComponent].max;
}
if (value > ranges[timeComponent].max) {
return ranges[timeComponent].min;
}
return value;
};
export const timeToString = (time: Time): string => (
`${clamp('hours', +time.hours)}:${clamp('minutes', +time.minutes)}:${clamp('seconds', +time.seconds)}`
);
export const formatNumber = (value: string) => (value.length === 1 ? `0${value}` : `${value}`);
<file_sep>/**
* @see https://vuetifyjs.com/en/customization/theme/
*/
export const primary = '#00528D';
export const secondary = '#00809B';
export const accent = '#00809B';
export const error = '#b00020';
export const warning = '#db5933';
export const success = '#0C8346';
export const info = '#00528D';
const theme = {
themes: {
light: {
primary,
secondary,
accent,
error,
warning,
info,
success,
},
},
};
export default theme;
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VExpansionPanels, VExpansionPanel, VExpansionPanelHeader, VExpansionPanelContent } from "vuetify/lib";
<Meta
title="Design System/Composants/Accordéon"
component={VExpansionPanels}
decorators={[() => ({
template: '<div class="pa-2 d-flex justify-center"><story/></div>'
})]}
/>
# Accordéon
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/expansion-panels/) complète de Vuetify
<Preview>
<Story name="Basique" inline={true}>
{{
components: {
VExpansionPanels,
VExpansionPanel,
VExpansionPanelHeader,
VExpansionPanelContent
},
template: `
<v-expansion-panels>
<v-expansion-panel
v-for="(item,i) in 5"
:key="i"
>
<v-expansion-panel-header>Item</v-expansion-panel-header>
<v-expansion-panel-content>
Lorem ipsum dolor sit amet, consectetur adipiscing 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.
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
`,
}}
</Story>
</Preview>
<file_sep>import { Vue } from 'vue-property-decorator';
import { MenuItem } from '../UtAppMenu';
import './UtAppBar.scss';
export default class UtAppBar extends Vue {
logo: string;
username: string;
items: MenuItem[];
dark: boolean;
website: string;
page: string;
logout(): void;
navigate(item: MenuItem): void;
showMenu: boolean;
maxLength: number;
}
<file_sep>import { UtNavigationBar } from '@/components/UtNavigationBar';
import { action } from '@storybook/addon-actions';
import vuetifyConfig from '@/plugins/vuetify';
import { VBtn, VSwitch } from 'vuetify/lib';
export default {
title: 'Design System/Composants/Layout/UtNavigationBar',
component: UtNavigationBar,
};
export const basique = () => ({
vuetify: vuetifyConfig,
components: { UtNavigationBar, VBtn },
template: `
<div>
<ut-navigation-bar
v-if="showNavigationBar"
@close="close"
@back="back"
@next="next"
@refresh="refresh"
@home="home"
/>
<div class="text-center pa-10 mt-10">
<v-btn v-if="!showNavigationBar" @click="open">Ouvrir</v-btn>
<v-btn v-else @click="close">Fermer</v-btn>
</div>
</div>
`,
methods: {
open() {
this.openAction();
this.showNavigationBar = true;
},
close() {
this.closeAction();
this.showNavigationBar = false;
},
closeAction: action('close'),
openAction: action('open'),
back: action('back'),
next: action('next'),
refresh: action('refresh'),
home: action('home'),
},
data: () => ({
showNavigationBar: true,
}),
});
export const personnalisé = () => ({
vuetify: vuetifyConfig,
components: { UtNavigationBar, VSwitch },
template: `
<div>
<ut-navigation-bar :options="options"/>
<div class="text-center pa-10 mt-10">
<v-switch
v-for="(value, key) in options.buttons"
:key="key"
v-model="value.show"
class="mr-5"
:label="key"
>
</v-switch>
</div>
</div>
`,
data: () => ({
options: {
buttons: {
home: { show: true },
refresh: { show: true },
back: { show: false },
next: { show: false },
close: { show: true },
},
},
}),
});
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VAlert, VBtn } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
<Meta title="Design System/Composants/Alertes" component={VAlert} />
# Alertes
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/alerts/) complète
## Style
Notez:
- utilisation de la classe `ut-alert` sur un composant `v-alert` pour appliquer le style *Ugitech*
<Preview>
<Story name="Basique" inline={true}>
{{
components: { VAlert },
template: `
<v-alert
border="left"
class="text-left ut-alert"
icon="mdi-information"
>
<div class="title">Information</div>
<div>Je suis un message d'information basique</div>
</v-alert>
`,
}}
</Story>
</Preview>
<Preview>
<Story name="Dismissible" inline={true}>
{{
components: { VAlert, VBtn },
template: `
<div>
<v-alert
v-model="alert"
dismissible
border="left"
class="text-left ut-alert"
icon="mdi-information"
>
<div class="title">Information</div>
<div>Je transmets des informations qui ne sont pas capitales</div>
</v-alert>
<div class="text-center">
<v-btn
v-if="!alert"
color="accent-4"
dark
@click="alert = true"
>
Reset
</v-btn>
</div>
</div>
`,
data: () => ({
alert: true
})
}}
</Story>
</Preview>
Les classes ci-dessous permettent d'appliquer un style adapté au type d'information:
- `ut-alert--error`
- `ut-alert--warn`
- `ut-alert--info`
<Preview>
<Story name="Erreur" inline={true}>
{{
components: { VAlert },
template: `
<v-alert
border="left"
class="text-left ut-alert ut-alert--error"
icon="mdi-alert-circle"
>
<div class="title">Erreur</div>
<div>Je suis un message qui informe d'une erreur</div>
</v-alert>
`,
}}
</Story>
</Preview>
<Preview>
<Story name="Warning" inline={true}>
{{
components: { VAlert },
template: `
<v-alert
border="left"
class="text-left ut-alert ut-alert--warn"
icon="mdi-alert"
>
<div class="title">Attention</div>
<div>Je vous informe d'un message à prendre connaissance</div>
</v-alert>
`,
}}
</Story>
</Preview>
<Preview>
<Story name="Information" inline={true}>
{{
components: { VAlert },
template: `
<v-alert
border="left"
class="text-left ut-alert ut-alert--info"
icon="mdi-information"
>
<div class="title">Information</div>
<div>Je transmets des informations qui ne sont pas capitales</div>
</v-alert>
`,
}}
</Story>
</Preview>
<file_sep>import UtNavigationDrawer from './UtNavigationDrawer';
export { UtNavigationDrawer, };
export default UtNavigationDrawer;
<file_sep>import { shallowMount } from '@vue/test-utils';
export function getMountedComponent(Component: any, propsData: any, $vuetify: any = undefined) {
return shallowMount(Component, {
propsData,
mocks: {
$vuetify,
},
});
}
<file_sep>import { Component, Vue } from 'vue-property-decorator';
import {
VCol,
VRow,
} from 'vuetify/lib';
import ugitechLogo from '../../assets/ugitech+byline.svg';
import './UtConnectionLayout.scss';
@Component({
name: 'ut-connection-layout',
components: {
VCol,
VRow,
},
template: `
<v-row class="fill-height ut-connection-page">
<v-col class="ut-connection-page__fill d-none d-sm-none d-md-flex" md="3">
</v-col>
<v-col class="text-center" cols="12" md="9">
<div class="ut-connection-page__logo">
<img :src="src"/>
</div>
<v-row align="center" justify="center" class="ut-connection-page__form">
<slot></slot>
</v-row>
</v-col>
</v-row>
`,
})
export default class UtConnectionLayout extends Vue {
src: string = ugitechLogo
}
<file_sep>import Vue from 'vue';
import {
VListItem,
VListItemAction,
VListItemTitle,
VListItemContent,
VListGroup,
VIcon,
} from 'vuetify/lib';
// eslint-disable-next-line no-unused-vars
import { MenuNavItem } from './MenuItem';
import './UtAppMenuNavItem.scss';
export default Vue.extend({
name: 'ut-app-menu-nav-item',
components: {
VListItem,
VListItemAction,
VListItemTitle,
VListItemContent,
VListGroup,
VIcon,
},
props: {
item: {
type: Object,
required: true,
},
},
methods: {
click(item: MenuNavItem) {
this.$emit('click', item);
},
},
template: `
<v-list-item
v-if="!item.items"
:input-value="item.selected"
:disabled="item.disabled"
class="ut-app-menu__list-item"
:class="item.selected ? 'ut-app-menu__list-item--selected' : ''"
@click="click(item)"
>
<v-list-item-title>{{ item.title }}</v-list-item-title>
<v-list-item-action>
<v-icon :disabled="item.disabled">mdi-chevron-right</v-icon>
</v-list-item-action>
</v-list-item>
<v-list-group
v-else
dark
no-action
class="ut-app-menu__list-group"
style="color: #fff !important"
>
<template v-slot:activator>
<v-list-item-content class="ut-app-menu__list-group__header">
<v-list-item-title>{{ item.title }}</v-list-item-title>
</v-list-item-content>
</template>
<ut-app-menu-nav-item
v-for="(subItem, j) in item.items"
:key="j"
:item="subItem"
@click="click"
/>
</v-list-group>
`,
});
<file_sep>import UtAppMenu from './UtAppMenu';
import { MenuItem, MenuAppItem, MenuNavItem } from './MenuItem';
export {
UtAppMenu,
MenuItem,
MenuAppItem,
MenuNavItem,
};
export default UtAppMenu;
<file_sep>import { Component, Prop, Vue } from 'vue-property-decorator';
import {
VBtn,
VIcon,
VNavigationDrawer,
VDialog,
VCol,
VRow,
} from 'vuetify/lib';
import './UtNavigationDrawer.scss';
export interface NavigationDrawerToggleOptions {
icon?: string;
color?: string;
dark?: boolean;
}
@Component({
name: 'ut-navigation-drawer',
components: {
VBtn,
VIcon,
VNavigationDrawer,
VDialog,
VCol,
VRow,
},
computed: {
drawer: {
get() {
if (this.$vuetify.breakpoint.mdOnly) {
return (this as UtNavigationDrawer).value;
}
return true;
},
set(value) {
this.$emit('input', value);
},
},
},
template: `
<v-navigation-drawer
v-if="!$vuetify.breakpoint.smAndDown"
class="ut-navigation-drawer"
app
clipped
left
v-model="drawer"
:mini-variant="!value && $vuetify.breakpoint.lgAndUp"
mini-variant-width="30"
>
<div class="d-flex ut-navigation-drawer__header pa-5 align-center mt-5">
<span :style="{visibility: value ? 'visible' : 'hidden'}">{{title}}</span>
<v-btn
v-if="toggleOptions.icon"
class="ut-navigation-drawer__toggle"
:color="toggleOptions.color"
:dark="toggleOptions.dark"
fab
small
elevation="0"
:ripple="false"
@click.stop="toggleDrawer"
>
<v-icon>{{toggleOptions.icon}}</v-icon>
</v-btn>
</div>
<div
class="ut-navigation-drawer__content"
:style="{visibility: value ? 'visible' : 'hidden'}"
>
<slot />
</div>
</v-navigation-drawer>
<v-dialog
v-model="value"
v-else
fullscreen
hide-overlay
transition="scroll-x-transition"
>
<div class="pa-5 ut-navigation-drawer--dialog__content">
<v-row class="ut-navigation-drawer--dialog__header align-center" no-gutters>
<v-col cols="4"></v-col>
<v-col cols="4" class="text-center">{{ title }}</v-col>
<v-col cols="4" class="text-right">
<v-btn icon @click="closeDialog">
<v-icon>mdi-close</v-icon>
</v-btn>
</v-col>
</v-row>
<slot />
</div>
</v-dialog>
`,
})
export default class UtNavigationDrawer extends Vue {
@Prop({
type: Object,
required: false,
default: () => ({
icon: undefined,
color: '#f0f0f0',
dark: false,
}),
}) toggleOptions!: NavigationDrawerToggleOptions;
@Prop({
type: Boolean,
required: false,
default: false,
}) value!: boolean;
// @Prop({
// type: Boolean,
// required: false,
// default: false,
// }) navigationBar!: boolean;
// @Prop({
// type: Boolean,
// required: false,
// default: true,
// }) appBar!: boolean;
@Prop({
type: String,
required: true,
}) title!: string;
onDrawerInput(value: boolean) {
this.$emit('input', value);
}
toggleDrawer() {
this.$emit('input', !this.value);
}
closeDialog() {
this.$emit('input', false);
}
}
<file_sep>import { VRow, VCol } from 'vuetify/lib';
import './UtTimePickerHeader.scss';
export default {
name: 'ut-time-picker-header',
components: {
VRow,
VCol,
},
template: `
<v-row
class="ut-time-picker__header"
no-gutters
>
<v-col
cols="4"
class="text-center pb-0"
>
<span>H</span>
</v-col>
<v-col
cols="4"
class="text-center pb-0"
>
<span>Min</span>
</v-col>
<v-col
cols="4"
class="text-center pb-0"
>
<span>Sec</span>
</v-col>
</v-row>
`,
};
<file_sep>import {
Component, Vue, Prop,
} from 'vue-property-decorator';
import {
VRow,
VCol,
VBtn,
} from 'vuetify/lib';
import UtTimePickerHeader from './UtTimePickerHeader';
import UtTimePickerCounter from './UtTimePickerCounter';
import {
// eslint-disable-next-line no-unused-vars
TimeComponent, timeRegex, dateToTimeString, timeToString, decomposeTime,
} from './utils';
import './UtTimePicker.scss';
@Component({
name: 'ut-time-picker',
components: {
UtTimePickerCounter,
UtTimePickerHeader,
VRow,
VCol,
VBtn,
},
template: `
<div class="ut-time-picker pb-4">
<v-row
class="px-7 pt-4"
no-gutters
>
<v-col>
<ut-time-picker-header />
<v-row no-gutters>
<ut-time-picker-counter
class="ut-time-input__separator"
:value="decomposedTime.hours"
@add="add('hours')"
@subtract="subtract('hours')"
@change="change('hours', $event)"
/>
<ut-time-picker-counter
:value="decomposedTime.minutes"
class="ut-time-input__separator"
@add="add('minutes')"
@subtract="subtract('minutes')"
@change="change('minutes', $event)"
/>
<ut-time-picker-counter
:value="decomposedTime.seconds"
@add="add('seconds')"
@subtract="subtract('seconds')"
@change="change('seconds', $event)"
/>
</v-row>
<v-row justify="center">
<v-btn
outlined
color="primary"
class="mt-3 ut-btn ut-btn--outlined"
@click="now"
>
Maintenant
</v-btn>
</v-row>
</v-col>
</v-row>
<v-row class="mt-7">
<slot />
</v-row>
</div>
`,
})
export default class UtTimePicker extends Vue {
@Prop({
type: String,
required: true,
validator(value: string) {
return timeRegex.test(value);
},
}) value!: string;
get decomposedTime() {
return decomposeTime(this.value as string);
}
now() {
this.$emit('input', dateToTimeString(Date.now()));
}
add(timeComponent: TimeComponent) {
const { decomposedTime } = this;
this.$emit('input', timeToString({
...decomposedTime,
[timeComponent]: parseInt(decomposedTime[timeComponent], 10) + 1,
}));
}
subtract(timeComponent: TimeComponent) {
const { decomposedTime } = this;
this.$emit('input', timeToString({
...decomposedTime,
[timeComponent]: parseInt(decomposedTime[timeComponent], 10) - 1,
}));
}
change(timeComponent: TimeComponent, value: number) {
const { decomposedTime } = this;
this.$emit('input', timeToString({
...decomposedTime,
[timeComponent]: value,
}));
}
}
<file_sep>export declare type TimeComponent = 'hours' | 'seconds' | 'minutes';
export interface Time {
hours: string;
minutes: string;
seconds: string;
}
export declare const timeRegex: RegExp;
export declare const isValidTime: (value: any) => boolean;
export declare const decomposeTime: (time: string) => Time;
export declare const dateToTimeString: (date: string | number | Date) => string;
export declare const timeToString: (time: Time) => string;
export declare const formatNumber: (value: string) => string;
<file_sep>import UtNavigationDrawer from './UtNavigationDrawer';
export {
UtNavigationDrawer,
};
export default UtNavigationDrawer;
<file_sep>import './colors';
import { UtNavigationBar } from './components/UtNavigationBar';
import { UtTimePicker } from './components/UtTimePicker';
import { UtAppMenu } from './components/UtAppMenu';
import { UtDatetimePicker } from './components/UtDatetimePicker';
import { UtAppBar } from './components/UtAppBar';
import { UtNavigationDrawer } from './components/UtNavigationDrawer';
import { UtConnectionLayout } from './components/UtConnectionLayout';
import '@mdi/font/css/materialdesignicons.css';
declare const install: (Vue: any) => void;
export { UtAppBar, UtAppMenu, UtDatetimePicker, UtTimePicker, UtNavigationBar, UtNavigationDrawer, UtConnectionLayout, };
export default install;
<file_sep>/* eslint-disable semi */
export interface MenuItem {
title: string;
type?: 'app';
[x: string]: any;
}
export interface MenuNavItem extends MenuItem {
items?: MenuNavItem[];
selected?: boolean;
disabled?: boolean;
type: undefined;
}
export interface MenuAppItem extends MenuItem {
type: 'app';
color: string;
icon: string;
}
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VDatePicker, VMenu, VTextField, VSpacer, VBtn } from "vuetify/lib";
import { action } from '@storybook/addon-actions'
<Meta
title="Design System/Composants/Formulaire/Date"
component={VDatePicker}
decorators={[() => ({
template: '<div class="pa-2"><story/></div>'
})]}
/>
<Preview>
<Story name="Basique">
{{
components: { VDatePicker, VMenu, VTextField, VSpacer, VBtn },
template: `
<v-menu
ref="menu"
v-model="menu"
:close-on-content-click="false"
:return-value.sync="date"
transition="scale-transition"
offset-y
min-width="290px"
>
<template v-slot:activator="obj">
<v-text-field
filled
v-model="date"
label="Choix de date"
append-icon="mdi-calendar"
readonly
v-on="obj.on"
></v-text-field>
</template>
<v-date-picker v-model="date" no-title scrollable show-current="false" @input="change">
<v-spacer></v-spacer>
<v-btn text color="primary" @click="menu = false">Cancel</v-btn>
<v-btn text color="primary" @click="$refs.menu.save(date)">OK</v-btn>
</v-date-picker>
</v-menu>
`,
data: () => ({
date: new Date().toISOString().substr(0, 10),
menu: false
}),
methods: {
change: action('change'),
},
}}
</Story>
</Preview>
<file_sep>import { Vue } from 'vue-property-decorator';
import { TimeComponent } from './utils';
import './UtTimePicker.scss';
export default class UtTimePicker extends Vue {
value: string;
get decomposedTime(): import("./utils").Time;
now(): void;
add(timeComponent: TimeComponent): void;
subtract(timeComponent: TimeComponent): void;
change(timeComponent: TimeComponent, value: number): void;
}
<file_sep>import { Vue } from 'vue-property-decorator';
import './UtConnectionLayout.scss';
export default class UtConnectionLayout extends Vue {
src: string;
}
<file_sep>import Vue from 'vue';
import './UtTimePickerCounter.scss';
declare const _default: import("vue/types/vue").ExtendedVue<Vue, {
inputValue: string;
}, {
add(): void;
subtract(): void;
change({ target }: any): void;
}, unknown, {
value: string;
}>;
export default _default;
<file_sep>import { action } from '@storybook/addon-actions';
import { UtDatetimePicker } from '@/components/UtDatetimePicker';
export default {
title: 'Design System/Composants/UtDatetimePicker',
component: UtDatetimePicker,
};
export const basique = () => ({
components: { UtDatetimePicker },
template: '<ut-datetime-picker v-model="datetime" @input="change" />',
data: () => ({ datetime: new Date('03/20/2013 12:30:45') }),
methods: {
change: action('change'),
},
});
<file_sep>import { Component, Vue } from 'vue-property-decorator';
import { VToolbarTitle } from 'vuetify/lib';
import './UtAppBarTitle.scss';
@Component({
name: 'ut-app-bar-title',
components: {
VToolbarTitle,
},
template: `
<div class="ut-app-bar-title">
<v-toolbar-title>
<span class="ut-app-bar-title__page">{{ page }}</span>
<span
v-if="$vuetify.breakpoint.smAndUp"
class="ut-app-bar-title__website">
{{ website }}
</span>
</v-toolbar-title>
</div>
`,
props: {
website: {
type: String,
required: true,
},
page: {
type: String,
required: true,
},
},
})
export default class UtAppBarTitle extends Vue {
}
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VCard, VCardActions, VIcon, VListItem, VListItemAvatar, VBtn, VListItemTitle, VImg } from "vuetify/lib";
import { action } from "@storybook/addon-actions";
import smallCardImg from '@/assets/stories/picture1.png';
import mediumCardImg from '@/assets/stories/picture2.png';
import largeCardImg from '@/assets/stories/picture2.png';
<Meta title="Design System/Composants/Card" component={VCard} />
# Card
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/cards/#cards) complète
## Style
Notez:
- utilisation de la classe `ut-card` pour appliquer le style *Ugitech*
- utilisation de la classe `ut-card__favorite-icon`
<Preview>
<Story name="Petite" inline={true}>
{{
components: { VCard, VIcon, VListItem, VListItemAvatar, VBtn, VListItemTitle, VImg },
template: `
<v-card width="308" height="77" outlined class="mx-auto ut-card">
<v-list-item class="px-2">
<v-list-item-avatar
tile
size="60"
>
<v-img :src="smallCardImg"></v-img>
</v-list-item-avatar>
<v-list-item-title class="font-weight-bold">Nom de l'application</v-list-item-title>
<v-btn icon class="ut-card__favorite-icon" @click="isFavorite = !isFavorite">
<v-icon v-if="!isFavorite">mdi-star-outline</v-icon>
<v-icon v-if="isFavorite">mdi-star</v-icon>
</v-btn>
</v-list-item>
</v-card>
`,
data: ()=> ({
smallCardImg,
isFavorite: false
})
}}
</Story>
</Preview>
<Preview>
<Story name="Moyenne" inline={true}>
{{
components: { VCard, VCardActions, VBtn, VIcon, VImg },
template: `
<v-card width="309" height="167" outlined class="mx-auto pa-2 ut-card">
<v-img
:src="mediumCardImg"
height="70"
>
<v-btn icon class="white--text ut-card__favorite-icon" @click="isFavorite = !isFavorite">
<v-icon v-if="!isFavorite">mdi-star-outline</v-icon>
<v-icon v-if="isFavorite">mdi-star</v-icon>
</v-btn>
</v-img>
<div class="mt-2">
<div class="font-weight-bold">Nom de l'application</div>
</div>
<v-card-actions class="justify-end">
<v-btn color="primary" text>Ouvrir</v-btn>
</v-card-actions>
</v-card>
`,
data: ()=> ({
mediumCardImg,
isFavorite: false
})
}}
</Story>
</Preview>
<Preview>
<Story name="Grande" inline={true}>
{{
components: { VCard, VCardActions, VBtn, VIcon, VImg },
template: `
<v-card width="421" height="228" outlined class="mx-auto pa-2 ut-card">
<v-img
:src="largeCardImg"
height="135"
>
<v-btn icon class="white--text ut-card__favorite-icon" @click="isFavorite = !isFavorite">
<v-icon v-if="!isFavorite">mdi-star-outline</v-icon>
<v-icon v-if="isFavorite">mdi-star</v-icon>
</v-btn>
</v-img>
<div class="mt-2">
<div class="font-weight-bold">Nom de l'application</div>
</div>
<v-card-actions class="justify-end">
<v-btn color="primary" text>Ouvrir</v-btn>
</v-card-actions>
</v-card>
`,
data: ()=> ({
largeCardImg,
isFavorite: false
})
}}
</Story>
</Preview>
<file_sep>import { action } from '@storybook/addon-actions';
import {
VApp,
VTextField,
VBtn,
} from 'vuetify/lib';
import { UtConnectionLayout } from '@/components/UtConnectionLayout';
import vuetifyConfig from '@/plugins/vuetify';
export default {
title: 'Design System/Composants/Layout/UtConnectionLayout',
parameters: {
custom: {
wrapWithVuetifyApp: false,
fullHeight: true,
},
},
component: UtConnectionLayout,
};
export const basique = () => ({
vuetify: vuetifyConfig,
components: {
VTextField,
VBtn,
VApp,
UtConnectionLayout,
},
template: `
<v-app>
<v-content>
<ut-connection-layout>
<form class="px-10 col-12 col-md-6">
<div class="text-left title mb-4">
<span class="text-no-wrap">Bienvenue sur</span>
<span class="text-no-wrap">Nom du site</span>
</div>
<div class="display-2 text-left mb-6">Connexion</div>
<div class="mt-5">
<v-text-field
v-model="email"
label="Email"
filled
type="email"
name="email"
/>
<v-text-field
v-model="password"
label="<PASSWORD>"
name="password"
hide-details
filled
@click:append="togglePassword"
:type="showPassword ? 'text' : 'password'"
:append-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'" />
<div class="text-left mt-1">
<a @click="forgottenPassword" href="#" class="caption">Mot de passe oublié ?</a>
</div>
</div>
<div class="text-right mt-5">
<v-btn
:ripple="false"
color="primary"
@click="submit"
>Connexion</v-btn>
</div>
</form>
</ut-connection-layout>
</v-content>
</v-app>
`,
data: () => ({
showPassword: false,
password: '',
email: '',
}),
methods: {
togglePassword() {
this.showPassword = !this.showPassword;
},
forgottenPassword: action('forgottenPassword'),
submit() {
this.submitAction({
password: <PASSWORD>,
email: this.email,
});
},
submitAction: action('submit'),
},
});
<file_sep>export interface MenuItem {
title: string;
type?: 'app';
[x: string]: any;
}
export interface MenuNavItem extends MenuItem {
items?: MenuNavItem[];
selected?: boolean;
disabled?: boolean;
type: undefined;
}
export interface MenuAppItem extends MenuItem {
type: 'app';
color: string;
icon: string;
}
<file_sep>import { Prop, Component, Vue } from 'vue-property-decorator';
import {
VCard,
VToolbar,
VSpacer,
VBtn,
VToolbarTitle,
VIcon,
VList,
VDivider,
VSubheader,
VRow,
VCol,
} from 'vuetify/lib';
import UtAppMenuAppItem from './UtAppMenuAppItem';
import UtAppMenuNavItem from './UtAppMenuNavItem';
import './UtAppMenu.scss';
import { MenuItem } from './MenuItem';
@Component({
name: 'ut-app-menu',
components: {
UtAppMenuAppItem,
UtAppMenuNavItem,
VCard,
VToolbar,
VSpacer,
VBtn,
VToolbarTitle,
VIcon,
VList,
VDivider,
VSubheader,
VRow,
VCol,
},
template: `
<v-card class="ut-app-menu">
<v-toolbar
dark
flat
>
<slot name="img"/>
<v-spacer />
<v-toolbar-title>
<span class="ut-app-menu__title">{{ title }}</span>
</v-toolbar-title>
<v-spacer />
<v-btn
icon
@click="hide()"
>
<v-icon>mdi-close</v-icon>
</v-btn>
</v-toolbar>
<div
v-if="username && $vuetify.breakpoint.smAndDown"
class="d-flex align-center ut-app-menu__user text-no-wrap"
>
<div class="ut-app-menu__user__username">{{ username }}</div>
<v-spacer></v-spacer>
<v-btn @click="logout" icon><v-icon>mdi-power</v-icon></v-btn>
</div>
<v-divider />
<v-list v-if="hasPages">
<template v-for="(item, i) in pages">
<ut-app-menu-nav-item
:key="i"
:item="item"
@click="click"
/>
</template>
</v-list>
<v-divider />
<v-list
v-if="hasApps"
class="ut-app-menu__app-list"
subheader
>
<v-subheader>Autres sites</v-subheader>
<v-row
dark
class="px-4"
no-gutters
>
<v-col
v-for="(app, i) in apps"
:key="i"
cols="4"
class="d-flex justify-start mb-3"
>
<ut-app-menu-app-item
:item="app"
@click="click"
/>
</v-col>
</v-row>
</v-list>
</v-card>
`,
})
export default class UtAppMenu extends Vue {
@Prop({
type: Array,
required: true,
})
items!: MenuItem[];
@Prop({
type: String,
required: true,
})
title!: string;
@Prop({
type: String,
required: false,
})
username!: string;
get pages() {
return this.items.filter((i) => i.type !== 'app');
}
get apps() {
return this.items.filter((i) => i.type === 'app');
}
get hasApps() {
const { apps } = this;
return apps && apps.length > 0;
}
get hasPages() {
const { pages } = this;
return pages && pages.length > 0;
}
hide() {
this.$emit('hide');
}
click(item: MenuItem) {
this.$emit('click', item);
}
logout() {
this.$emit('logout');
}
}
<file_sep>import UtNavigationBar from './UtNavigationBar';
export { UtNavigationBar, };
export default UtNavigationBar;
<file_sep>import './UtAppMenuAppItem.scss';
import { VIcon } from 'vuetify/lib';
export default {
name: 'ut-app-menu-app-item',
components: {
VIcon,
},
props: {
item: {
type: Object,
required: true,
},
},
template: `
<div
class="ut-app-menu__site pa-3 d-flex flex-column justify-center align-center"
:style="{'background-color': item.color}"
@click="$emit('click', item)"
>
<v-icon color="white" class="ut-app-menu__site__icon">
{{ item.icon }}
</v-icon>
<div class="text-no-wrap white--text ut-app-menu__site__title">
{{ item.title }}
</div>
</div>
`,
};
<file_sep>/**
* rm ./storybook-static/*react-syntax-highlighter*
*/
const shell = require('shelljs');
shell.rm('./storybook-static/*react-syntax-highlighter*');
<file_sep>import Vue from 'vue';
import { MenuNavItem } from './MenuItem';
import './UtAppMenuNavItem.scss';
declare const _default: import("vue/types/vue").ExtendedVue<Vue, unknown, {
click(item: MenuNavItem): void;
}, unknown, {
item: any;
}>;
export default _default;
<file_sep>import { Vue } from 'vue-property-decorator';
import './UtAppMenu.scss';
import { MenuItem } from './MenuItem';
export default class UtAppMenu extends Vue {
items: MenuItem[];
title: string;
username: string;
get pages(): MenuItem[];
get apps(): MenuItem[];
get hasApps(): boolean;
get hasPages(): boolean;
hide(): void;
click(item: MenuItem): void;
logout(): void;
}
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VProgressCircular, VOverlay } from "vuetify/lib";
<Meta
title="Design System/Composants/Chargement"
component={VProgressCircular}
decorators={[() => ({
template: '<div class="pa-2 d-flex justify-center"><story/></div>'
})]}
/>
# Indicateur de chargement
Veuillez vous référer à la documentation complète de Vuetify:
- [progress circular](https://vuetifyjs.com/en/components/progress-circular/)
- [progress linear](https://vuetifyjs.com/en/components/progress-linear/)
- [overlays](https://vuetifyjs.com/en/components/overlays/)
<Preview>
<Story name="Basique" inline={true}>
{{
components: {
VProgressCircular,
VOverlay
},
template: `
<div class="text-center">
<v-btn
color="warning"
@click="chargement"
>
Chargement
</v-btn>
<v-overlay :value="overlay">
<v-progress-circular size="70" width="7" indeterminate color="primary"/>
</v-overlay>
</div>
`,
data: () => ({
overlay: false
}),
methods: {
chargement() {
this.overlay = true;
setTimeout(() => this.overlay = false, 2000)
}
}
}}
</Story>
</Preview>
<file_sep>import UtAppMenu from './UtAppMenu';
import { MenuItem, MenuAppItem, MenuNavItem } from './MenuItem';
export { UtAppMenu, MenuItem, MenuAppItem, MenuNavItem, };
export default UtAppMenu;
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { VCheckbox } from "vuetify/lib";
<Meta
title="Design System/Composants/Formulaire/Checkbox"
component={VCheckbox}
decorators={[() => ({
template: '<div class="pa-2"><story/></div>'
})]}
/>
# Checkbox
Veuillez vous référer à la [documentation](https://vuetifyjs.com/en/components/selection-controls/) complète de Vuetify
## Style
On utilise la classe `ut-input` pour appliquer le style *Ugitech*
<Preview>
<Story name="Basique" inline={true} height="200px">
{{
components: { VCheckbox },
template: `
<v-checkbox v-model="mandatory" class="mx-2 ut-input" label="Mandatory"></v-checkbox>
`,
data: () => ({ mandatory: false })
}}
</Story>
</Preview>
<file_sep>import { Meta, Story, Preview } from "@storybook/addon-docs/blocks";
import { action } from "@storybook/addon-actions";
import {
VNavigationDrawer,
VAppBar,
VSpacer,
VDialog
} from 'vuetify/lib';
import { UtAppMenu } from '@/components/UtAppMenu';
import appImg from '@/assets/LogoA2iUgitech_FullRes.png';
<Meta
title="Design System/Composants/UtAppMenu"
component={UtAppMenu}
/>
# UtAppMenu
## API
#### Props
| Nom | Commentaires | Required |
|---|---|---|
| items | MenuItem[] | oui |
| title | titre du menu | oui |
| username | nom de l'utilisateur connecté (apparait sur les petits écrans) | non |
#### Slots
| Nom | Commentaires |
|---|---|
| img | image apparaissant à côté du titre |
#### Events
| Nom | Commentaires |
|---|---|
| click | clique sur un item du menu, l'event handler récupère le NavItem en entrée |
| logout | clique sur le bouton de déconnection (il apparait sur les petits écrans) |
| hide | clique sur la croix de fermeture |
#### MenuItem
```ts
export interface MenuItem {
title: string;
type?: 'app';
}
export interface MenuNavItem extends MenuItem {
items?: MenuNavItem[];
selected?: boolean;
disabled?: boolean;
type: undefined;
}
export interface MenuAppItem {
type: 'app';
color: string;
icon: string;
}
```
## Complet
<Preview>
<Story name="Complet">
{{
components: {
UtAppMenu,
},
template: `
<v-menu
absolute
nav
:close-on-click="false"
:close-on-content-click="false"
dark
v-model="showMenu"
>
<template v-slot:activator="obj">
<v-btn dark icon v-on="obj.on" color="black">
<v-icon>mdi-menu</v-icon>
</v-btn>
</template>
<ut-app-menu
:items="menuItems"
username="<NAME>"
title="Menu"
@hide="hide"
@click="click">
<template v-slot:img>
<img :src="appImg" width="40"/>
</template>
</ut-app-menu>
</v-menu>
`,
data: () => ({
appImg,
menuItems: [
{ title: 'Titre de page 1' },
{ title: 'Titre de page 2' },
{
title: 'Ensemble de pages 1',
items: [
{ title: 'Titre de page 3' },
{ title: 'Titre de page 4' },
],
},
{ title: 'Titre de page 5' },
{
title: 'Applications',
color: '#99CD50',
icon: 'mdi-wrench',
type: 'app',
},
{
title: 'Ged-archive',
color: '#6A969C',
icon: 'mdi-package-down',
type: 'app',
},
{
title: 'Ged',
color: '#0280CA',
icon: 'mdi-cards',
type: 'app',
},
{
title: 'Projects',
color: '#F25B06',
icon: 'mdi-account-multiple',
type: 'app',
},
{
title: 'Teams',
color: '#537998',
icon: 'mdi-comment',
type: 'app',
},
{
title: 'Wikis',
color: '#9B5E62',
icon: 'mdi-book-open',
type: 'app',
},
],
showMenu: true,
}),
methods: {
click: action('click'),
hide($event) {
this.hideAction($event);
this.showMenu = false;
},
hideAction: action('hide'),
},
}}
</Story>
</Preview>
## Responsive
- Ecran large: on encapsule `ut-app-menu` dans un `v-menu` de vuetify
- Ecran petit: on encapsule `ut-app-menu` dans un `v-dialog` de Vuetify (avec l'option `fullscreen`)
<Preview>
<Story name="Responsive">
{{
components: {
UtAppMenu,
},
template: `
<v-dialog
v-if="$vuetify.breakpoint.xsOnly"
v-model="showMenu"
dark
transition="slide-x-reverse-transition"
fullscreen >
<template v-slot:activator="obj">
<v-app-bar-nav-icon v-on="obj.on" />
</template>
<ut-app-menu
:items="menuItems"
title="Menu"
@hide="showMenu = false"
>
<template v-slot:img>
<img :src="appImg" width="40"/>
</template>
</ut-app-menu>
</v-dialog>
<v-menu
v-else
absolute
nav
:close-on-click="false"
:close-on-content-click="false"
dark
v-model="showMenu"
>
<template v-slot:activator="obj">
<v-btn dark icon v-on="obj.on" color="black">
<v-icon>mdi-menu</v-icon>
</v-btn>
</template>
<ut-app-menu
:items="menuItems"
title="Menu"
@hide="hide"
@click="click">
<template v-slot:img>
<img :src="appImg" width="40"/>
</template>
</ut-app-menu>
</v-menu>
`,
data: () => ({
appImg,
menuItems: [
{ title: 'Titre de page 1' },
{ title: 'Titre de page 2' },
{
title: 'Ensemble de pages 1',
items: [
{ title: 'Titre de page 3' },
{ title: 'Titre de page 4' },
],
},
{ title: 'Titre de page 5' },
{
title: 'Applications',
color: '#99CD50',
icon: 'mdi-wrench',
type: 'app',
},
{
title: 'Ged-archive',
color: '#6A969C',
icon: 'mdi-package-down',
type: 'app',
},
{
title: 'Ged',
color: '#0280CA',
icon: 'mdi-cards',
type: 'app',
},
{
title: 'Projects',
color: '#F25B06',
icon: 'mdi-account-multiple',
type: 'app',
},
{
title: 'Teams',
color: '#537998',
icon: 'mdi-comment',
type: 'app',
},
{
title: 'Wikis',
color: '#9B5E62',
icon: 'mdi-book-open',
type: 'app',
},
],
showMenu: true,
}),
methods: {
click: action('click'),
hide($event) {
this.hideAction($event);
this.showMenu = false;
},
hideAction: action('hide'),
},
}}
</Story>
</Preview>
## Navigation Drawer
- Dans IE11, l'élément `v-menu` de Vuetify ne s'affiche pas correctement
- Si vous voulez supporter IE11, il est préférable d'utiliser un `v-navigation-drawer` pour afficher le menu
<Preview>
<Story name="Navigation Drawer">
{{
components: {
UtAppMenu,
VNavigationDrawer,
VAppBar,
VSpacer
},
template: `
<div>
<v-app-bar dark>
<v-spacer/>
<v-btn dark icon @click="showMenu = !showMenu">
<v-icon>mdi-menu</v-icon>
</v-btn>
</v-app-bar>
<v-navigation-drawer
v-model="showMenu"
dark
app
right
width="300"
>
<ut-app-menu
:items="menuItems"
username="<NAME>"
title="Menu"
@hide="hide"
@click="click">
<template v-slot:img>
<img :src="appImg" width="40"/>
</template>
</ut-app-menu>
</v-navigation-drawer>
</div>
`,
data: () => ({
appImg,
menuItems: [
{ title: 'Titre de page 1' },
{ title: 'Titre de page 2' },
{
title: 'Ensemble de pages 1',
items: [
{ title: 'Titre de page 3' },
{ title: 'Titre de page 4' },
],
},
{ title: 'Titre de page 5' },
{
title: 'Applications',
color: '#99CD50',
icon: 'mdi-wrench',
type: 'app',
},
{
title: 'Ged-archive',
color: '#6A969C',
icon: 'mdi-package-down',
type: 'app',
},
{
title: 'Ged',
color: '#0280CA',
icon: 'mdi-cards',
type: 'app',
},
{
title: 'Projects',
color: '#F25B06',
icon: 'mdi-account-multiple',
type: 'app',
},
{
title: 'Teams',
color: '#537998',
icon: 'mdi-comment',
type: 'app',
},
{
title: 'Wikis',
color: '#9B5E62',
icon: 'mdi-book-open',
type: 'app',
},
],
showMenu: true,
}),
methods: {
click: action('click'),
hide($event) {
this.hideAction($event);
this.showMenu = false;
},
hideAction: action('hide'),
},
}}
</Story>
</Preview>
## Liens d'applications (MenuAppItem)
<Preview>
<Story name="Liens d\'applications">
{{
components: {
UtAppMenu,
},
template: `
<v-menu
absolute
nav
:close-on-click="false"
:close-on-content-click="false"
dark
v-model="showMenu"
>
<template v-slot:activator="obj">
<v-btn dark icon v-on="obj.on" color="black">
<v-icon>mdi-menu</v-icon>
</v-btn>
</template>
<ut-app-menu v-bind:items="menuItems" title="Menu" @hide="hide" @click="click"/>
</v-menu>
`,
data: () => ({
menuItems: [
{
title: 'Applications',
color: '#99CD50',
icon: 'mdi-wrench',
type: 'app',
},
{
title: 'Ged-archive',
color: '#6A969C',
icon: 'mdi-package-down',
type: 'app',
},
{
title: 'Ged',
color: '#0280CA',
icon: 'mdi-cards',
type: 'app',
},
{
title: 'Projects',
color: '#F25B06',
icon: 'mdi-account-multiple',
type: 'app',
},
{
title: 'Teams',
color: '#537998',
icon: 'mdi-comment',
type: 'app',
},
{
title: 'Wikis',
color: '#9B5E62',
icon: 'mdi-book-open',
type: 'app',
},
],
showMenu: true,
}),
methods: {
click: action('click'),
hide($event) {
this.hideAction($event);
this.showMenu = false;
},
hideAction: action('hide'),
},
}}
</Story>
</Preview>
## Liens de navigation (MenuNavItem)
Un `NavItem` a une propriété `selected` et `disabled`.
Vous avez ici un exemple de code qui gère la sélection et la désactivation de certain liens.
<Preview>
<Story name="Liens de navigation">
{{
components: {
UtAppMenu,
},
template: `
<v-menu
absolute
nav
:close-on-click="false"
:close-on-content-click="false"
dark
v-model="showMenu"
>
<template v-slot:activator="obj">
<v-btn dark icon v-on="obj.on" color="black">
<v-icon>mdi-menu</v-icon>
</v-btn>
</template>
<ut-app-menu v-bind:items="menuItems" title="Menu" @hide="hide" @click="click"/>
</v-menu>
`,
data: () => ({
menuItems: [
{ title: 'Titre de page 1', selected: false },
{ title: 'Titre de page 2', disabled: true },
{
title: 'Ensemble de pages 1',
items: [
{ title: 'Titre de page 3', disabled: true },
{ title: 'Titre de page 4', selected: false },
],
},
{ title: 'Titre de page 5', selected: true },
{ title: 'Titre de page 6', selected: false },
],
showMenu: true,
}),
methods: {
deselect() {
const deselect = (it) => {
// eslint-disable-next-line no-param-reassign
it.selected = false;
if (it.items) {
it.items.forEach(deselect);
}
};
this.menuItems.forEach(deselect);
},
selectItem(itemToSelect) {
let found = false;
const select = (it) => {
if (it.title === itemToSelect.title) {
found = true;
// eslint-disable-next-line no-param-reassign
it.selected = true;
}
if (it.items && !found) {
it.items.forEach(select);
}
};
this.menuItems.forEach(select);
},
click(item) {
this.clickAction(item);
this.deselect();
this.selectItem(item);
},
hide($event) {
this.hideAction($event);
this.showMenu = false;
},
clickAction: action('click'),
hideAction: action('hide'),
},
}}
</Story>
</Preview>
<file_sep>import { UtAppBarTitle } from '@/components/UtAppBar';
export default {
title: 'Design System/Composants/UtAppBarTitle',
component: UtAppBarTitle,
};
export const basique = () => ({
components: { UtAppBarTitle },
template: '<ut-app-bar-title website="Nom du site" page="Titre de page 3"/>',
});
<file_sep>/* eslint-disable no-useless-escape */
import { VIcon, VCol, VBtn } from 'vuetify/lib';
import Vue from 'vue';
import { formatNumber } from './utils';
import './UtTimePickerCounter.scss';
export default Vue.extend({
name: 'ut-time-picker-counter',
components: {
VCol,
VBtn,
VIcon,
},
props: {
value: {
type: String,
required: true,
},
},
data: () => ({
inputValue: '',
}),
watch: {
value(newVal) {
this.inputValue = formatNumber(newVal);
},
},
created() {
this.inputValue = formatNumber(this.value);
},
methods: {
add() {
this.$emit('add');
},
subtract() {
this.$emit('subtract');
},
change({ target }: any) {
if (/\d?\d/.test(target.value)) {
this.$emit('change', parseInt(target.value, 10));
} else {
this.inputValue = formatNumber(this.value);
}
},
},
template: `
<v-col
cols="4"
class="ut-time-picker__counter"
>
<div class="d-flex justify-center">
<v-btn
tabindex="-1"
icon
@click="add"
>
<v-icon>mdi-chevron-up</v-icon>
</v-btn>
</div>
<div class="d-flex justify-center">
<input
v-model="inputValue"
size="2"
maxlength="2"
type="text"
pattern="[0-9]?[0-9]"
@change="change"
>
</div>
<div class="d-flex justify-center">
<v-btn
tabindex="-1"
icon
@click="subtract"
>
<v-icon>mdi-chevron-down</v-icon>
</v-btn>
</div>
</v-col>
`,
});
<file_sep>import { VTextField } from 'vuetify/lib';
import { UtTimePicker } from '@/components/UtTimePicker';
import moment from 'moment';
import { action } from '@storybook/addon-actions';
export default {
title: 'Design System/Composants/Formulaire/Time',
component: UtTimePicker,
decorators: [() => ({
template: `
<v-row class="pa-5">
<v-col cols="4">
<story/>
</v-col>
</v-row>
`,
})],
};
export const menu = () => ({
components: { UtTimePicker, VTextField },
template: `
<v-menu
ref="menu"
v-model="menu2"
:close-on-content-click="false"
transition="scale-transition"
offset-y
max-width="250px"
height="253px"
>
<template v-slot:activator="obj">
<v-text-field
v-model="time"
label="Choix d'heure"
append-icon="mdi-clock-outline"
readonly
filled
v-on="obj.on"
></v-text-field>
</template>
<div
v-if="menu2"
full-width
class="d-flex justify-center"
>
<ut-time-picker v-model="time" @input="change">
<v-spacer></v-spacer>
<v-btn text color="primary" @click="menu2 = false">Fermer</v-btn>
</ut-time-picker>
</div>
</v-menu>
`,
data: () => ({
time: moment(Date.now()).format('HH:mm:ss'),
menu2: false,
}),
methods: {
change: action('change'),
},
});
export const modal = () => ({
components: { UtTimePicker, VTextField },
template: `
<v-dialog
ref="dialog"
v-model="modal2"
:return-value.sync="time"
persistent
width="250px"
>
<template v-slot:activator="obj">
<v-text-field
v-model="time"
label="Choix d'heure"
append-icon="mdi-clock-outline"
readonly
filled
v-on="obj.on"
></v-text-field>
</template>
<div
v-if="modal2"
full-width
class="d-flex justify-center"
style="background-color: white"
>
<ut-time-picker v-model="time" @input="change">
<v-spacer></v-spacer>
<v-btn text color="primary" @click="modal2 = false">Annuler</v-btn>
<v-btn text color="primary" @click="$refs.dialog.save(time)">OK</v-btn>
</ut-time-picker>
</div>
</v-dialog>
`,
data: () => ({
time: moment(Date.now()).format('HH:mm:ss'),
modal2: false,
}),
methods: {
change: action('change'),
},
});
<file_sep>import UtAppBar from './UtAppBar';
import UtAppBarTitle from './UtAppBarTitle';
export { UtAppBar, UtAppBarTitle, };
export default UtAppBar;
| 0f10ae7c9f28ebd0310ddb4c5809bebf1af3fcfe | [
"Markdown",
"TypeScript",
"JavaScript",
"Dockerfile"
] | 91 | TypeScript | HeleneDalBoSerial/ut-web-template | 023ac27ebce03be9f7a347ed08fa0bfb6fd95e6f | 410d646a18cf38974c231f2dc024117f66c92821 |
refs/heads/main | <file_sep>import React from 'react';
import Checkbox from 'rc-checkbox';
import './index.less';
const DexDesktopCheckbox = ({ label, checked, onChange }) => {
return (
<div className="dex-desktop-checkbox-container">
<label className="desktop-checkbox-label" htmlFor="">{label}</label>
<Checkbox checked={checked} onChange={onChange} />
</div>
);
};
export default DexDesktopCheckbox;
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as CommonActions from '_src/redux/actions/CommonAction';
import PageURL from '_src/constants/PageURL';
import DexTab from '_component/DexTab';
import WalletAddress from '_component/WalletAddress';
import AssetsAccounts from './AssetsAccounts';
import AssetsTransactions from './AssetsTransactions';
import assetsUtil from './assetsUtil';
import './Assets.less';
function mapStateToProps() {
return {};
}
function mapDispatchToProps(dispatch) {
return {
commonActions: bindActionCreators(CommonActions, dispatch),
};
}
/* eslint-disable react/sort-comp, no-nested-ternary */
@connect(mapStateToProps, mapDispatchToProps)
class Assets extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
copySuccess: false,
};
this.isAssets = this.props.location.pathname === PageURL.walletAssets;
if (!window.OM_GLOBAL.senderAddr) {
this.props.history.replace(PageURL.walletImport);
}
}
componentDidMount() {}
onChangeTab = (current) => {
return () => {
if (this.state.loading) return;
this.props.history.replace(current === 1 ? PageURL.walletAssets : PageURL.walletTransactions);
if ((current === 1 && this.isAssets) || (current === 2 && !this.isAssets)) {
this.setState({ loading: true });
setTimeout(() => {
this.setState({ loading: false });
}, 100);
}
};
};
onCopy = () => {
if (this.state.copySuccess) return;
this.setState({ copySuccess: true });
clearTimeout(this.copyTimer);
this.copyTimer = setTimeout(() => {
this.setState({ copySuccess: false });
}, 1000);
};
render() {
const { loading } = this.state;
return (
<div className="wallet-main">
<WalletAddress />
<DexTab tabs={assetsUtil.tabs} current={this.isAssets ? 1 : 2} onChangeTab={this.onChangeTab} />
{
loading ? null : (this.isAssets ? <AssetsAccounts /> : <AssetsTransactions />)
}
</div>
);
}
}
export default Assets;
<file_sep>import React from 'react';
import moment from 'moment';
import { toLocale } from '_src/locale/react-locale';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { crypto } from '@omexchain/javascript-sdk';
import { Dialog } from '_component/Dialog';
import Menu from '_src/component/Menu';
import util from '_src/utils/util';
import Icon from '_src/component/IconLite';
import { withRouter, NavLink } from 'react-router-dom';
import PageURL from '_constants/PageURL';
import Config from '_constants/Config';
import PassWordDialog from '_component/PasswordDialog';
import * as CommonAction from '../../redux/actions/CommonAction';
import WalletMenuTool from './WalletMenuTool';
// import LinesEllipsis from 'react-lines-ellipsis';
import './index.less';
const SubMenu = Menu.SubMenu;
const IconFountUnfold = () => { return <Icon className="icon-Unfold" style={{ fontSize: '14px', marginLeft: '6px' }} />; };
function mapStateToProps(state) { // 绑定redux中相关state
const { privateKey } = state.Common;
return {
privateKey
};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class DexLoggedMenu extends React.Component {
state = {
isShowPassword: false,
passwordError: '',
};
// 下载keyStore 显示输入密码窗口
handleDownKeyStore = () => {
this.setState({
isShowPassword: true, passwordError: ''
});
};
// Dailog Down KeyStore Core function
downKeyStoreCore = (passValue) => {
// 2019-08-13 增加用户清空全部缓存的判断
if (!util.isLogined()) {
window.location.reload();
}
const keyStoreName = `keystore_${moment().format('YYYY-MM-DD HH:mm:ss')}`;
const User = window.localStorage.getItem('dex_user');
if (User) {
try {
const UserObj = JSON.parse(User);
const { info: keyStore } = UserObj;
const privateKey = crypto.getPrivateKeyFromKeyStore(keyStore, passValue);
if (privateKey) {
util.downloadObjectAsJson(keyStore || '', keyStoreName);
this.setState({ isShowPassword: false, passwordError: '' });
}
} catch (e) {
this.setState({ isShowPassword: true, passwordError: toLocale('pwd_error') });
}
}
};
// 下载KeyStore时,取消输入密码
handleClosePassWordDialog = () => {
this.setState({
isShowPassword: false
});
};
// 退出登录
handleLogOut = () => {
const dialog = Dialog.confirm({
title: toLocale('header_menu_logout1'),
confirmText: toLocale('ensure'),
cancelText: toLocale('cancel'),
theme: 'dark',
dialogId: 'omdex-logout',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
util.doLogout();
dialog.destroy();
window.location.reload();
},
});
};
render() {
const { isShowPassword, passwordError } = this.state;
let addr = '';
try {
const user = JSON.parse(window.localStorage.getItem('dex_user'));
addr = user ? user.addr : '';
} catch (e) {
console.warn(e);
}
return (
<React.Fragment>
<PassWordDialog
isShow={isShowPassword}
onEnter={this.downKeyStoreCore}
warning={passwordError}
updateWarning={(err) => { this.setState({ passwordError: err }); }}
onClose={this.handleClosePassWordDialog}
/>
<Menu
mode="horizontal"
selectable={false}
className="omdex-menu"
>
{/*
<Menu.Item key="trade" >
<NavLink to={PageURL.spotFullPage} activeClassName="active-menu-item" >{toLocale('header_menu_trade')}</NavLink>
</Menu.Item>
*/}
<SubMenu
key="wallet"
title={
<React.Fragment>{toLocale('header_menu_wallet')}<IconFountUnfold /></React.Fragment>
}
>
<Menu.Item key="wallet-1" style={{ height: 'auto', cursor: 'default' }}>
<WalletMenuTool address={addr} />
</Menu.Item>
<Menu.Item key="wallet-2">
<NavLink to={PageURL.walletAssets} activeClassName="active-menu-item" >{toLocale('header_menu_assets')}</NavLink>
</Menu.Item>
<Menu.Item key="wallet-3" onClick={this.handleDownKeyStore}>
{toLocale('header_menu_down_keystore')}
</Menu.Item>
<Menu.Item key="wallet-4" onClick={this.handleLogOut} >{toLocale('header_menu_logout')}</Menu.Item>
</SubMenu>
<SubMenu
key="order"
title={
<React.Fragment>{toLocale('header_menu_order')}<IconFountUnfold /></React.Fragment>
}
>
<Menu.Item key="order-1">
<NavLink to={PageURL.spotOpenPage} activeClassName="active-menu-item" >{toLocale('header_menu_current_entrust')}</NavLink>
</Menu.Item>
<Menu.Item key="order-2">
<NavLink to={PageURL.spotHistoryPage} activeClassName="active-menu-item" >{toLocale('header_menu_history_entrust')}</NavLink>
</Menu.Item>
<Menu.Item key="order-3">
<NavLink to={PageURL.spotDealsPage} activeClassName="active-menu-item" >{toLocale('header_menu_deal_entrust')}</NavLink>
</Menu.Item>
</SubMenu>
{/*
<Menu.Item key="omChain" >
<a target="_blank" rel="noopener noreferrer" href={Config.omchain.browserUrl}>{toLocale('header_menu_explorer_omchain')}</a>
</Menu.Item>
*/}
</Menu>
</React.Fragment>
);
}
}
export default DexLoggedMenu;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { storage } from '_component/omit';
import Cookies from 'js-cookie';
import { wsV3, channelsV3 } from '../utils/websocket';
// import RouterCredential from '../RouterCredential';
import * as CommonActions from '../redux/actions/CommonAction';
import * as SpotTradeActions from '../redux/actions/SpotTradeAction';
import * as SpotActions from '../redux/actions/SpotAction';
import * as OrderActions from '../redux/actions/OrderAction';
import * as FormAction from '../redux/actions/FormAction';
import Enum from '../utils/Enum';
import util from '../utils/util';
function mapStateToProps(state) {
const {
product, productList, productObj
} = state.SpotTrade;
const { wsIsOnlineV3, wsErrCounterV3, wsIsDelayLogin } = state.Spot;
return {
wsIsOnlineV3,
wsErrCounterV3,
wsIsDelayLogin,
product,
productList,
productObj
};
}
function mapDispatchToProps(dispatch) {
return {
commonActions: bindActionCreators(CommonActions, dispatch),
spotActions: bindActionCreators(SpotActions, dispatch),
spotTradeActions: bindActionCreators(SpotTradeActions, dispatch),
orderActions: bindActionCreators(OrderActions, dispatch),
formAction: bindActionCreators(FormAction, dispatch),
};
}
// 全屏交易/简约交易调用
const SpotTradeWrapper = (Component) => {
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class SpotTrade extends React.Component {
constructor(props) {
super(props);
util.isLogined(); // 为确保正确
const { tradeType } = window.OM_GLOBAL;
this.isFullTrade = tradeType === Enum.tradeType.fullTrade;
}
componentDidMount() {
const {
spotActions, commonActions, wsIsOnlineV3, product, productObj, productList
} = this.props;
if (product) { // 从其他页面(账单等)切回来,开始redux中就有product
this.getInitData(product); // 获取初始全量数据(api方式)
// 订阅ws
if (wsIsOnlineV3) {
this.startWs(product);
}
} else {
// 初始化product
spotActions.initProduct(productObj, productList, () => {
// 订阅ws
if (wsIsOnlineV3) {
const product1 = storage.get('product');
this.startWs(product1);
}
});
}
// 全屏交易隐藏我的客服
if (this.isFullTrade) {
const eles = document.querySelector('.entrance');
if (eles) {
eles.style.display = 'none';
}
}
// 初始化 主题
const theme = localStorage.getItem('theme');
if (theme === null) {
localStorage.setItem('theme', 'theme-1');
// document.body.setAttribute('class', 'theme-1');
document.body.classList.add('theme-1');
} else {
document.body.setAttribute('class', theme);
}
document.body.classList.remove('full-body');
// 初始化omchain客户端 TODO已经加载过了还要加载???
// commonActions.initOMChainClient();
}
componentWillReceiveProps(nextProps) {
const {
spotTradeActions, orderActions
} = this.props;
/* product变化相关 */
const oldProduct = this.props.product;
const newProduct = nextProps.product;
if (newProduct !== oldProduct) {
if (oldProduct === '') { // 首次获取product
this.getInitData(newProduct);
} else if (newProduct !== '') { // product发生改变,比如左侧菜单切换
this.changeProduct(oldProduct, newProduct);
}
}
/* ws状态变化相关 */
const newWsIsOnline = nextProps.wsIsOnlineV3;
const oldWsIsOnline = this.props.wsIsOnlineV3;
// 检测延迟变化
if (newWsIsOnline && nextProps.wsIsDelayLogin) { // && (this.props.wsIsDelayLogin !== nextProps.wsIsDelayLogin)
this.delaySubWs(nextProps.product);
}
// ws首次连接或者重连成功
if (!oldWsIsOnline && newWsIsOnline && newProduct !== '') {
// 【断网补偿】获取我的资产和订单
util.isLogined() && spotTradeActions.fetchAccountAssets();
orderActions.getNoDealList({ page: 1 });
// 连接推送
this.startWs(newProduct);
}
// ws断线,执行轮询
const oldWsErrCounter = this.props.wsErrCounterV3;
const newWsErrCounter = nextProps.wsErrCounterV3;
// ws断线,执行轮询
if (newWsErrCounter > oldWsErrCounter) {
// 获取所有币对行情的逻辑在 ProductListMenu 组件中
// 获取资产
if (util.isLogined()) {
spotTradeActions.fetchAccountAssets();
// orderActions.getNoDealList({ page: 1 });
}
// 更新深度
spotTradeActions.fetchDepth(newProduct);
}
}
componentWillUnmount() {
const { wsIsOnlineV3, spotActions } = this.props;
if (wsIsOnlineV3) {
this.stopWs();
}
spotActions.updateProduct('');
}
// 获取初始全量数据(api方式)
getInitData = (product) => {
const { spotTradeActions, wsIsOnlineV3 } = this.props;
// 1,资产
if (util.isLogined()) { // const { isLogin } = window.OM_GLOBAL;
spotTradeActions.fetchAccountAssets();
}
// 2,深度
// ws断线时,使用ajax数据;若ws链接,则使用ws数据
if (!wsIsOnlineV3) {
spotTradeActions.fetchDepth(product);
}
};
delaySubWs = (product) => {
const unsubChannels = [];
const subChannels = [];
// 更新币币资产
if (util.isLogined()) {
unsubChannels.push(channelsV3.getBaseBalance(product)); // 订阅base资产
unsubChannels.push(channelsV3.getQuoteBalance(product)); // 订阅quote资产
unsubChannels.push(channelsV3.getOpenOrder()); // 订阅quote资产
subChannels.push(channelsV3.getBaseBalance(product)); // 订阅base资产
subChannels.push(channelsV3.getQuoteBalance(product)); // 订阅quote资产
subChannels.push(channelsV3.getOpenOrder()); // 订阅quote资产
}
// 统一取消老订阅、发布新订阅
wsV3.stop(unsubChannels);
wsV3.send(subChannels);
};
// 开启ws订阅
startWs = (product) => {
const { spotTradeActions } = this.props;
const v3ChannelArr = [];
// if (util.isWsLogin()) {
// v3ChannelArr.push(channelsV3.getBaseBalance(product)); // 订阅base资产
// v3ChannelArr.push(channelsV3.getQuoteBalance(product)); // 订阅quote资产
// v3ChannelArr.push(channelsV3.getOpenOrder()); // 订阅全部未成交订单
// }
// 订阅当前币对ticker
v3ChannelArr.push(channelsV3.getTicker(product));
// 订阅全部币对all_tickers_3s getAllMarketTickers 在 FullTradeProduct.js中
// 清空深度缓存数据
spotTradeActions.clearSortPushDepthData();
// 订阅深度
v3ChannelArr.push(channelsV3.getDepth(product));
wsV3.send(v3ChannelArr);
};
// 停止ws订阅
stopWs = () => {
const { product } = this.props;
if (!product) {
return;
}
const v3ChannelArr = [];
if (util.isLogined()) {
// 停止订阅全部币对资产
v3ChannelArr.push(channelsV3.getBaseBalance(product));
v3ChannelArr.push(channelsV3.getQuoteBalance(product));
v3ChannelArr.push(channelsV3.getOpenOrder());
}
// 停止订阅当前币对ticker
v3ChannelArr.push(channelsV3.getTicker(product));
// 停止订阅深度
v3ChannelArr.push(channelsV3.getDepth(product));
wsV3.stop(v3ChannelArr);
};
// 切币
changeProduct = (oldProduct, newProduct) => {
const {
wsIsOnlineV3, spotTradeActions
} = this.props;
if (wsIsOnlineV3) {
const unsubChannels = [];
const subChannels = [];
// 更新币币资产
if (util.isLogined()) {
spotTradeActions.refreshAsset();
unsubChannels.push(channelsV3.getBaseBalance(oldProduct)); // 订阅base资产
unsubChannels.push(channelsV3.getQuoteBalance(oldProduct)); // 订阅quote资产
subChannels.push(channelsV3.getBaseBalance(newProduct)); // 订阅base资产
subChannels.push(channelsV3.getQuoteBalance(newProduct)); // 订阅quote资产
}
// 当前币对ticker
unsubChannels.push(channelsV3.getTicker(oldProduct));
subChannels.push(channelsV3.getTicker(newProduct));
// 深度
unsubChannels.push(channelsV3.getDepth(oldProduct));
spotTradeActions.clearSortPushDepthData(); // 清空深度缓存
subChannels.push(channelsV3.getDepth(newProduct));
// 统一取消老订阅、发布新订阅
wsV3.stop(unsubChannels);
wsV3.send(subChannels);
} else { // ws未连接,则通过ajax方式保证数据正确显示
// tickers的数据刷新逻辑在 productListMenu 组件中
// 更新深度
spotTradeActions.fetchDepth(newProduct);
}
};
render() {
const { product } = this.props;
const currProduct = window.OM_GLOBAL.productConfig;
if (!product || !currProduct) {
return null;
}
return (<Component />);
}
}
return SpotTrade;
};
export default SpotTradeWrapper;
<file_sep>import React from 'react';
import SpotOrderHeaderSecondWrapper from '../../wrapper/SpotOrderHeaderSecondWrapper';
import Enum from '../../utils/Enum';
const OrderHeaderSecond = ({
periodIntervalType, dataSource, onTabChange, extraOperations
}) => {
return (
<div className="full-trade-order-sec-head">
<div>
{extraOperations}
</div>
<div className="period-interval">
{
dataSource.map(({ type: headerType, name }, index) => {
return (
<div
key={index}
className={periodIntervalType === headerType ? 'active' : ''}
onClick={onTabChange(headerType)}
>
{name}
</div>
);
})
}
</div>
</div>
);
};
export default SpotOrderHeaderSecondWrapper(OrderHeaderSecond);
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as SpotTradeActions from '../redux/actions/SpotTradeAction';
function mapStateToProps(state) { // 绑定redux中相关state
const {
product
} = state.SpotTrade;
return {
product
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(SpotTradeActions, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class DialogSet extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
// transOpen: false
};
}
render() {
return (
<div className="dialog-set">
{/* */}
</div>
);
}
}
export default DialogSet;
<file_sep>/* eslint-disable no-else-return */
import React from 'react';
import Tooltip from 'rc-tooltip';
import { Link } from 'react-router-dom';
import Icon from '_src/component/IconLite';
import { toLocale } from '_src/locale/react-locale';
import FormatNum from '_src/utils/FormatNum';
import { calc } from '_component/omit';
import util from '../../utils/util';
import { OrderStatus } from '../../constants/OrderStatus';
import PageURL from '../../constants/PageURL';
import Enum from '../../utils/Enum';
import Config from '../../constants/Config';
const commonUtil = {
// 公共列
getCommonColumns: (onClickProduct) => {
return [
{ // 哈希值
title: toLocale('spot.myOrder.hash'),
key: 'txhash',
render: (text) => {
const str = FormatNum.hashShort(text); // `${text.substr(0, 9)}...${text.substring(text.length - 3)}`;
const href = `${Config.omchain.browserUrl}/tx/${text}`; // trade-info/
return (
<a
title={text}
className="can-click"
href={href}
target="_blank"
rel="noopener noreferrer"
>
{str}
</a>
);
}
}, { // 时间
title: toLocale('spot.myOrder.date'),
key: 'timestamp',
render: (text) => {
const d = text.split(' ')[0];
const t = text.split(' ')[1];
return (
<span>{d}<br />{t}</span>
);
}
}, { // 交易对
title: toLocale('spot.myOrder.product'),
key: 'product',
render: (text, data) => {
// 相同币对不可点
const isSame = (data.activeProduct && data.orginalProduct.toUpperCase() === data.activeProduct.toUpperCase());
return (
<span
onClick={() => {
onClickProduct && onClickProduct(data.orginalProduct);
}}
className={(isSame || !onClickProduct) ? '' : 'can-click'}
>
{text}
</span>
);
}
}, { // 方向
title: toLocale('spot.myOrder.direction'),
key: 'side',
render: (text, data) => {
return <div className={data.sideClass}>{text}</div>;
}
}, { // 成交比例
title: toLocale('spot.myOrder.filledPercentage'),
key: 'filledPercentage',
render: (text) => {
return (
<span>{text}</span>
);
}
}, { // 已成交量 | 委托总量
title: (
<span>
{toLocale('spot.myOrder.filledAmount')} | {toLocale('spot.myOrder.amount')}
</span>
),
key: 'quantity',
render: (text, data) => {
const baseSymbolShort = data.product.split('/')[0];
return (<div>{data.filledQuantity} | {text} {baseSymbolShort}</div>);
}
}, { // 成交均价 | 委托价
title: (
<span>
{toLocale('spot.myOrder.filledPrice')} | {toLocale('spot.myOrder.price')}
</span>
),
key: 'price',
render: (text, data) => {
const quoteSymbol = data.product.split('/')[1];
return (<div>{data.filled_avg_price} | {text} {quoteSymbol}</div>);
}
}, { // 状态
title: toLocale('spot.orders.status'),
key: 'status',
render: (text) => {
return (
<span>{text}</span>
);
}
}
];
},
// 公共列
getColumns: (onClickSymbol) => {
return [
{ // 委托时间
title: toLocale('spot.orders.date'),
key: 'createTime',
render: (text) => {
const dateTime = util.timeStampToTime(parseInt(text, 10), 'yyyy-MM-dd hh:mm:ss');
const date = dateTime.split(' ')[0];
const time = dateTime.split(' ')[1];
return (
<div className="flex-row">
<div>
<span style={{ display: 'inline-block' }}>{date}</span><br />
<span style={{ display: 'inline-block' }}>{time}</span>
</div>
</div>
);
}
}, { // 币对
title: toLocale('spot.orders.symbol'),
key: 'symbol',
render: (text) => {
return (
<span
onClick={() => {
onClickSymbol(text);
}}
className="can-click"
>
{text.replace('_', '/')
.toUpperCase()}
</span>
);
}
}, { // 类型
title: toLocale('spot.orders.type'),
key: 'systemType',
render: (text) => {
const intlId = text === 1 ? 'spot.orders.side.spot' : 'spot.orders.side.margin';
return toLocale(intlId);
}
}, { // 方向
title: toLocale('spot.orders.direction'),
key: 'side',
render: (text) => {
const side = text === 1 ? 'spot.orders.actionBuy' : 'spot.orders.actionSell';
const classType = text === 1 ? 'buy' : 'sell';
return <div className={classType}>{toLocale(side)}</div>;
}
}
];
},
// 策略委托"状态"列
getStatusColumns: (data) => {
let explanation = null;
const { removeType, status } = data;
switch (Number(removeType)) {
case 0: // 委托超时撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation0')}
</div>
);
break;
case 1: // 用户手动撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation1')}
</div>
);
break;
case 2: // 余额不足撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation3')}
</div>
);
break;
default:
break;
}
switch (status) {
case 1: // 待生效
return (
<div>
{toLocale('spot.orders.status1')}
</div>
);
case 2: // 已生效
return (
<div>
{toLocale('spot.orders.status2')}
</div>
);
case 3: // 已撤销-有解释浮层以说明
return (
<Tooltip placement="top" overlay={explanation}>
<div>
{toLocale('spot.orders.status3')}
</div>
</Tooltip>
);
default:
break;
}
return false;
},
// 策略委托"状态"列(冰山和时间规划)
getStatusColumnsIceAndTime: (data) => {
let explanation = null;
const { removeType, status } = data;
switch (removeType) {
case 0: // 委托超时撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation0')}
</div>
);
break;
case 1: // 用户手动撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation1')}
</div>
);
break;
case 2: // 余额不足撤单
explanation = (
<div className="tooltip-content">
{toLocale('spot.orders.cancelExplanation3')}
</div>
);
break;
default:
break;
}
switch (status) {
case 1: // 待生效
return (
<div>
{toLocale('spot.orders.status1')}
</div>
);
case 2: // 已生效
return (
<div>
{toLocale('spot.orders.status2')}
</div>
);
case 3: // 已撤销
return (
<Tooltip placement="top" overlay={explanation}>
<div>
{toLocale('spot.orders.status3')}
</div>
</Tooltip>
);
case 4: // 部分生效
return (
<div>
{toLocale('spot.orders.partialStatus')}
</div>
);
case 5: // 暂停生效
return (
<div>
{toLocale('spot.orders.pausedStatus')}
</div>
);
default:
break;
}
return false;
},
// 获取table空数据时的样式
getEmpty: () => {
const isLogin = util.isLogined();
const { tradeType } = window.OM_GLOBAL;
const NoData = (
<div className="flex-column" style={{ alignItems: 'center' }}>
<Icon
className="icon-Nodeallist"
isColor
style={{
width: '48px',
height: '48px',
opacity: tradeType === Enum.tradeType.fullTrade ? 0.65 : 1
}}
/>
<div className="mar-top10">
{toLocale('spot.orders.noData')}
</div>
</div>
);
const NotLogin = (
<div className="order-list-not-login">
<p className="c-title">
<br />
<Link to={`${PageURL.homePage}/wallet/create`}>
{toLocale('wallet_create_step1')}
</Link>
<a> / </a>
<Link to={`${PageURL.homePage}/wallet/import`}>
{toLocale('wallet_import')}
</Link>
</p>
</div>
);
return (
isLogin ? NoData : NotLogin
);
},
// 渲染页码
renderPagination: (pagination, type, onPageChange, theme) => {
const { page, per_page, total } = pagination;
const tblContainer = document.querySelector('.om-table-container');
const totalPage = Math.ceil((total || 0) / per_page);
let path = 'open';
if (type === Enum.order.type.history) {
path = 'history';
} else if (type === Enum.order.type.detail) {
path = 'deals';
}
if (totalPage < 2) { // 1页以内的不显示分页控件
tblContainer && (tblContainer.style.height = '155px');
return false;
}
tblContainer && (tblContainer.style.height = '125px');
if (type === Enum.order.type.noDeal) {
return null;
}
return (
<div style={{ textAlign: 'center' }}>
<Link to={path}>
{toLocale('link_to_all')}
</Link>
</div>
);
},
formatDataCommon: (order, config) => {
const priceTruncate = 'max_price_digit' in config ? config.max_price_digit : 4; // 价格精度
const sizeTruncate = 'max_size_digit' in config ? config.max_size_digit : 4; // 数量精度
const newOrder = { ...order }; // 避免修改原始对象
newOrder.timestamp = util.timeStampToTime(parseInt(newOrder.timestamp, 10), 'yyyy-MM-dd hh:mm:ss'); // .substring(5);
newOrder.orginalProduct = newOrder.product;
newOrder.product = util.getShortName(newOrder.product); // newOrder.product.replace('_', '/').toUpperCase();
newOrder.sideClass = newOrder.side === 'BUY' ? 'buy' : 'sell';
newOrder.side = toLocale(newOrder.side === 'BUY' ? 'spot.buy' : 'spot.sell');
newOrder.money = calc.showFloorTruncation(calc.mul(newOrder.price, newOrder.quantity), priceTruncate);
newOrder.filledPercentage = '';
if (Number(calc.sub(newOrder.quantity, newOrder.remain_quantity)) === 0) { // 未成交
newOrder.filledPercentage = '0.00%';
} else if (calc.sub(newOrder.quantity, newOrder.remain_quantity) < newOrder.quantity) { // 部分成交
newOrder.filledPercentage = `${calc.floorDiv(calc.sub(newOrder.quantity, newOrder.remain_quantity) * 100, newOrder.quantity, 2)}%`;
// TODO 后端接口实现后去掉改行 部分成交
if (![4, 5].includes(Number(newOrder.status))) {
newOrder.status = 6;
}
} else { // 完全成交
newOrder.filledPercentage = '100%';
}
newOrder.status = toLocale(`spot.myOrder.${OrderStatus[newOrder.status]}`);
newOrder.price = calc.showFloorTruncation(newOrder.price, priceTruncate);
newOrder.filled_avg_price = calc.showFloorTruncation(newOrder.filled_avg_price, priceTruncate);
newOrder.filledQuantity = calc.showFloorTruncation(calc.sub(newOrder.quantity, newOrder.remain_quantity), sizeTruncate);
newOrder.quantity = calc.showFloorTruncation(newOrder.quantity, sizeTruncate);
// 配置写进对象
newOrder.priceTruncate = priceTruncate;
newOrder.sizeTruncate = sizeTruncate;
return newOrder;
},
formatOpenData: (orderList, productObj, activeProduct) => {
return orderList.map((order) => {
const config = productObj[order.product] || {};
return commonUtil.formatDataCommon({ ...order, activeProduct }, config);
});
},
formatClosedData: (orderList, productObj) => {
return orderList.map((order) => {
const config = productObj[order.product] || {};
const o = commonUtil.formatDataCommon(order, config);
// o.filled_avg_price = (o.filled_avg_price > 0) ? calc.showFloorTruncation(o.filled_avg_price, o.priceTruncate) : '--';
return o;
});
},
formatDealsData: (orderList, productObj) => {
return orderList.map((order) => {
const config = productObj[order.product] || {};
const priceTruncate = 'max_price_digit' in config ? config.max_price_digit : 4; // 价格精度
const sizeTruncate = 'max_size_digit' in config ? config.max_size_digit : 4; // 数量精度
const newOrder = { ...order }; // 避免修改原始对象
newOrder.timestamp = util.timeStampToTime(parseInt(newOrder.timestamp, 10), 'yyyy-MM-dd hh:mm:ss'); // .substring(5);
newOrder.orginalProduct = newOrder.product;
newOrder.product = util.getShortName(newOrder.product); // newOrder.product.replace('_', '/').toUpperCase();
newOrder.sideClass = newOrder.side === 'BUY' ? 'buy' : 'sell';
newOrder.side = toLocale(newOrder.side === 'BUY' ? 'spot.buy' : 'spot.sell');
newOrder.money = calc.showFloorTruncation(newOrder.price * newOrder.volume, priceTruncate);
newOrder.price = calc.showFloorTruncation(newOrder.price, priceTruncate);
newOrder.volume = calc.showFloorTruncation(newOrder.volume, sizeTruncate);
return newOrder;
});
}
};
export default commonUtil;
<file_sep>import zhCN from '../locale/zh';
import enUS from '../locale/en';
import zhHK from '../locale/hk';
import koKR from '../locale/ko';
export default (language) => {
let messages = null;
if (language === 'zh_CN') { // 简体中文
messages = zhCN;
} else if (language === 'en_US') { // 英文
messages = enUS;
} else if (language === 'zh_HK') { // 繁体中文
messages = zhHK;
} else if (language === 'ko_KR') { // 韩文
messages = koKR;
}
return messages;
};
<file_sep>const prefix = 'om_';
const DEFAULT = 'default';
const GLOBAL = 'global';
let storageProjectKey = prefix + DEFAULT;
const storageGlobalKey = prefix + GLOBAL;
const localStorageKey = 'localStorage';
const sessionStorageKey = 'sessionStorage';
const expireKey = '_expire';
/**
* 是正确的有效期时间戳
* @param expire
* @returns {boolean}
*/
function isCorrectExpire(expire) {
return (Number.isInteger(Number(expire)) && Number.isSafeInteger(expire) && expire > new Date().getTime());
}
/**
* 是正确的有效期秒数
* @param expireSeconds
* @returns {boolean}
*/
function isCorrectExpireSeconds(expireSeconds) {
return (Number.isInteger(expireSeconds) && Number.isSafeInteger(expireSeconds) && expireSeconds > 0);
}
/**
* 获取有效期时间戳
* @param expireSeconds
* @returns {boolean}
*/
function getExpire(expireSeconds) {
return new Date().getTime() + (expireSeconds * 1000);
}
/**
* 获取对应storage下、对应模块的数据对象 只返回有效的
* @param storageKey
* @param projectKey
* @param notContainExpire 返回的参数不包含有效期
*/
function getProjectData(storageKey, projectKey, notContainExpire) {
// 获取存储的所有的值
const dataStr = window[storageKey].getItem(projectKey);
let data = {};
try {
data = JSON.parse(dataStr || {});
} catch (e) {
data = {};
}
// 过滤出有效的返回
const newData = { [expireKey]: {} };
const expireMap = data[expireKey] || {};
Object.keys(data).forEach((key) => {
// _expire 作为保留字段 不处理
if (key === expireKey) {
return;
}
// 如果不处理上边这步,走到_expire字段,会把里边的原始值全部覆盖到newData上,newData的_expire会出现个_expire
if (expireMap[key] === undefined || isCorrectExpire(expireMap[key])) {
newData[key] = data[key];
newData[expireKey][key] = expireMap[key];
}
});
// 不返回时效对象
if (notContainExpire) {
delete newData[expireKey];
}
return newData;
}
// 清除无效的数据 init 的时候触发
function cleanInvalidData(storageKey, projectKey) {
window[storageKey].setItem(projectKey, JSON.stringify(getProjectData(storageKey, projectKey)));
}
// 公用方法
const api = {
/**
* 获取对应模块下的参数
*/
get(storageKey, projectKey, key) {
if (key === null || key === undefined || key instanceof Function
|| key instanceof Array || key instanceof Object) {
return undefined;
}
const projectStorage = getProjectData(storageKey, projectKey);
return projectStorage[key];
},
/**
* 设置对应模块下的参数
* @param storageKey
* @param projectKey
* @param key 键
* @param value 值
* @param expireSeconds 有效期 秒数
*/
set(storageKey, projectKey, key, value, expireSeconds) {
if (key === null || key === undefined || key instanceof Function || key instanceof Array) {
return false;
}
// key 不允许等于 _expire 该字段留作有效期使用
if (key === expireKey) {
return false;
}
const projectStorage = getProjectData(storageKey, projectKey);
// 单独的一个key
if (!(key instanceof Object)) {
projectStorage[key] = value;
// 是正常的数值且大于当前时间,则存一个有效期时间
// 否则删除有效期,一直有效
if (isCorrectExpireSeconds(expireSeconds)) {
projectStorage[expireKey][key] = getExpire(expireSeconds);
} else {
delete projectStorage[expireKey][key];
}
window[storageKey].setItem(projectKey, JSON.stringify(projectStorage));
return true;
}
// 对象
return api.setAll(storageKey, projectKey, key, value);
},
/**
* 设置对应模块下的参数
* @param storageKey
* @param projectKey
* @param paramsMap 参数对象
* @param expireMap 有效期对象
*/
setAll(storageKey, projectKey, paramsMap = {}, expireMap = {}) {
const projectStorage = getProjectData(storageKey, projectKey);
Object.entries(paramsMap).forEach((item) => {
const key = item[0];
// key 不允许等于 _expire 该字段留作有效期使用
if (key === expireKey) {
return;
}
const expireSeconds = expireMap[key];
projectStorage[key] = item[1];
// 有效期秒数正确 则存入有效期,否则永久存储
if (isCorrectExpireSeconds(expireSeconds)) {
projectStorage[expireKey][key] = getExpire(expireSeconds);
} else {
delete projectStorage[expireKey][key];
}
});
window[storageKey].setItem(projectKey, JSON.stringify(projectStorage));
return true;
},
/**
* 移除对应模块下的参数
*/
remove(storageKey, projectKey, key) {
if (key === null || key === undefined || key instanceof Function) {
return false;
}
// 判断是对象
if (key.constructor && key.constructor === Object) {
return false;
}
let keyArray = [];
if (!(key instanceof Array)) {
keyArray.push(key);
} else {
keyArray = key;
}
const projectStorage = getProjectData(storageKey, projectKey);
keyArray.forEach((k) => {
delete projectStorage[k];
delete projectStorage[expireKey][k];
});
window[storageKey].setItem(projectKey, JSON.stringify(projectStorage));
return true;
},
/**
* 获取对应模块下所有参数
*/
getAll(storageKey, projectKey) {
return getProjectData(storageKey, projectKey, true);
},
/**
* 清空
*/
cleanAll(storageKey, projectKey) {
window[storageKey].setItem(projectKey, JSON.stringify({}));
}
};
/**
* 生成api
* @param isLocal 是否localStorage
* @param isGlobal 是否是获取全局命名空间
*/
function apiFactory({ isLocal, isGlobal }) {
function getStorageKey() {
return isLocal ? localStorageKey : sessionStorageKey;
}
function getProjectKey() {
return isGlobal ? storageGlobalKey : storageProjectKey;
}
return {
set(key, value, expire) {
return api.set(getStorageKey(), getProjectKey(), key, value, expire);
},
get(key) {
return api.get(getStorageKey(), getProjectKey(), key);
},
remove(key) {
return api.remove(getStorageKey(), getProjectKey(), key);
},
getAll() {
return api.getAll(getStorageKey(), getProjectKey());
},
cleanAll() {
return api.cleanAll(getStorageKey(), getProjectKey());
}
};
}
/**
* 初始化方法,全局设置模块
*/
function init({ project }) {
// 不允许用'global'作为模块名
const key = project === GLOBAL ? DEFAULT : project;
storageProjectKey = prefix + key;
// 清除无效数据,节省空间
cleanInvalidData(localStorageKey, storageProjectKey);
cleanInvalidData(localStorageKey, storageGlobalKey);
// 如果设置了命名空间,那就再单独清个key
key !== DEFAULT && cleanInvalidData(localStorageKey, prefix + DEFAULT);
}
// localStorage 操作对象
const local = {
...apiFactory({
isLocal: true,
isGlobal: false
}),
getProjectStorage(name) {
return getProjectData(localStorageKey, prefix + name, true);
},
g: {
...apiFactory({
isLocal: true,
isGlobal: true
}),
}
};
local.global = local.g;
// sessionStorage 操作对象
const session = {
...apiFactory({
isLocal: false,
isGlobal: false
}),
getProjectStorage(name) {
return getProjectData(sessionStorageKey, prefix + name, true);
},
g: {
...apiFactory({
isLocal: false,
isGlobal: true
}),
}
};
session.global = session.g;
const storage = {
init,
...local,
local,
session
};
export default storage;
<file_sep>## Development environment
### Release method description
Reason: due to the special dex project,there are some problems with the use of front-end release system to build, so the use of local build.Publishing uses a front-end publishing system.
Premise:each version iteration pulls the latest development branch based on the master branch,i.e. ' daily / X.y.z '(for example 'daily / 0.1.0'), submit the build results to gitlab after the local build.
Build & release:
1. Everyday
In the daily branch, build and commit the code
```
$ npm run daily
```
2. Pre-issue
In the prepub branch, build and commit the code
```
$ npm run prepub
```
3. Online
To be perfect
```
$ npm run publish
```
### Step 1: Configure WebStorm
Setting up the React syntax environment
Preferences > Languages & Frameworks > JavaScript > [select React JSX]
Configuring eslint rules and plug-ins
Link:http://gitlab.omcoin-inc.com/omfe/eslint
### Step 2: run the app
Switch npm warehouse address to company private warehouse (nrm tool is recommended)
```shell
sudo npm i nrm -g
nrm add omex http://192.168.80.41:4873
nrm use omex
```
Installing dependent libraries:
```shell
npm install
```
Then run the application:
```shell
npm run omex
```
According to webpack / dev.common.the proxy path configured in js gets the token to ensure that the request can get the data correctly
Take online data(const mockUrl = 'https://omexcomweb.bafang.com') as an example:
1. Visit https://omexcomweb.bafang.com/index, login(registration);
2. copy the token from Local Storage to local Local Storage;
3. Visit http://localhost:3000/spot/trade;
### npm script command description
1. mock-start the mock data service locally (currently does not ensure that the mock data is 100% correct, in most cases the request is forwarded to the development / test environment);
2. dev-omex,dev-omcoin,dev-omkr are used for three different site developers to start local services;
3. build and testbuild related commands for on-line build and test environment build;
### File naming
You must use hump style naming when creating JS and style files:
```
home
Home.js
Home.scss
HomeConversion.js
HomeConversion.scss
```
When creating a new internationalized Text Property,`key`is used uniformly.Connection:
```js
const messages = {
'spot.asset.freeze':'freeze',
'spot.asset.risk': 'risk rate',
'spot.asset.forceClose':'burst price',
'spot.asset.interest':'interest',
};
```
CSS class names must be named in hyphen style
Testing
Private key:<KEY>
Password: <PASSWORD><file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { toLocale } from '_src/locale/react-locale';
import { Button } from '_component/Button';
import { crypto } from '@omexchain/javascript-sdk';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as commonActions from '_src/redux/actions/CommonAction';
import PageURL from '_constants/PageURL';
import WalletPassword from '_component/WalletPassword';
import ValidateCheckbox from '_component/ValidateCheckbox';
import walletUtil from './walletUtil';
import './ImportByMnemonic.less';
function mapStateToProps() {
return {};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(commonActions, dispatch),
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class ImportByMnemonic extends Component {
constructor(props) {
super(props);
this.state = {
mnemonic: '',
password: '',
isValidatedMnemonic: true,
buttonLoading: false,
// updateLengthCheck: 'none',
// updateChartCheck: 'none',
isNone: false,
};
this.isValidatedPassword = false;
}
changeMnemonic = (e) => {
const mnemonic = e.target.value;
this.setState({
mnemonic,
isValidatedMnemonic: true,
isNone: false,
});
};
changePassword = ({ value, lengthCheck, chartCheck }) => {
this.isValidatedPassword = lengthCheck === 'right' && chartCheck === 'right';
this.setState({
password: value,
});
}
handleEnsure = () => {
if (this.state.mnemonic.length === 0) {
this.setState({
isNone: true
});
return;
}
// 密码校验失败 或者 助记词校验失败
if (!this.isValidatedPassword || !this.state.isValidatedMnemonic) {
this.setState({
updateLengthCheck: 'wrong',
updateChartCheck: 'wrong'
});
return;
}
this.setState({
buttonLoading: true,
}, () => {
setTimeout(this.validateMnemonic, 10);
});
};
// 校验助记词
validateMnemonic = () => {
try {
const { password } = this.state;
const mnemonic = this.state.mnemonic.trim();
// 在getPrivateKeyFromMnemonic的时候,会自动校验助记词格式
// if (crypto.validateMnemonic(mnemonic)) {
// this.setState({
// isValidatedMnemonic: false
// });
// return;
// }
const privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic);
const keyStore = crypto.generateKeyStore(privateKey, password);
walletUtil.setUserInSessionStroage(privateKey, keyStore);
this.setState({
isValidatedMnemonic: true,
buttonLoading: false,
isNone: false
});
this.props.commonAction.setPrivateKey(privateKey);
this.props.history.push(PageURL.spotFullPage);
} catch (e) {
this.setState({
isValidatedMnemonic: false,
buttonLoading: false,
isNone: false
});
}
}
render() {
const {
mnemonic, isValidatedMnemonic, buttonLoading, isNone
} = this.state;
let p;
let className = '';
if (isNone) {
p = 'wallet_import_mnemonic_none';
className = 'prompt-container';
} else if (isValidatedMnemonic) {
p = 'wallet_import_mnemonic_splitTip';
} else {
className = 'prompt-container';
p = 'wallet_import_mnemonic_error';
}
return (
<div className="import-by-mnemonic-container">
<div className="mnemonic-container">
<div>{toLocale('wallet_import_mnemonic_enter')}</div>
<textarea value={mnemonic} onChange={this.changeMnemonic} />
<div className={className} style={{ fontSize: '12px' }}>{toLocale(p)}</div>
</div>
<div className="password-container">
<WalletPassword
placeholder={toLocale('wallet_import_mnemonic_sessionPassword')}
onChange={this.changePassword}
updateLengthCheck={this.state.updateLengthCheck}
updateChartCheck={this.state.updateChartCheck}
/>
<ValidateCheckbox type="warning" className="mar-top8">
{toLocale('wallet_import_sessionPasswordTip')}
</ValidateCheckbox>
</div>
<Button
type="primary"
loading={buttonLoading}
onClick={this.handleEnsure}
>
{toLocale('wallet_ensure')}
</Button>
</div>
);
}
}
export default ImportByMnemonic;
<file_sep>export default {
blue: '#3075EE',
red: '#EE6560',
green: '#4DB872',
info: '#FFBF00',
blueRGB: (alpha = 1) => {
return `rgba(87, 149, 241, ${alpha})`;
},
redRGB: (alpha = 1) => {
return `rgba(238, 101, 96, ${alpha})`;
},
greenRGB: (alpha = 1) => {
return `rgba(77, 184, 114, ${alpha})`;
},
whiteRGB: (alpha = 1) => {
return `rgba(255, 255, 255, ${alpha})`;
},
blackRGB: (alpha = 1) => {
return `rgba(0, 0, 0, ${alpha})`;
},
};
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Menu from '_src/component/Menu';
import { withRouter, Link } from 'react-router-dom';
import { toLocale } from '_src/locale/react-locale';
import Icon from '_src/component/IconLite';
import { getLangURL } from '_src/utils/navigation';
import PageURL from '_constants/PageURL';
import Config from '_constants/Config';
import * as walletActions from '_src/redux/actions/WalletAction';
import './index.less';
const SubMenu = Menu.SubMenu;
// 菜单
const IconFountUnfold = () => { return <Icon className="icon-Unfold" style={{ fontSize: '14px', marginLeft: '6px' }} />; };
function mapStateToProps(state) { // 绑定redux中相关state
const { WalletStore } = state;
// step 创建钱包状态
return {
WalletStore
};
}
function mapDispatchToProps(dispatch) {
return {
walletAction: bindActionCreators(walletActions, dispatch),
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class DexLoginMenu extends React.Component {
handleCreateWallet=() => {
const { walletAction } = this.props;
walletAction.updateCreateStep(1);
// 重新走流程,需要出现安全提示
walletAction.updateIsShowSafeTip(true);
};
render() {
return (
<Menu
mode="horizontal"
className="omdex-menu"
>
{/*
<Menu.Item key="trade" >
<NavLink exact to={PageURL.spotFullPage} activeClassName="active-menu-item" >
{toLocale('header_menu_trade')}
</NavLink>
</Menu.Item>
*/}
<Menu.Item key="createWallet">
<Link to={getLangURL(`${PageURL.homePage}/wallet/create`)} >{toLocale('header_menu_create_wallet')}</Link>
{/*
<NavLink exact to="javascript:void(0);" onClick={this.RedirectToCreate} activeClassName="active-menu-item" >
{toLocale('header_menu_create_wallet')}
</NavLink> */}
</Menu.Item>
<Menu.Item key="importWallet" >
<Link to={getLangURL(`${PageURL.homePage}/wallet/import`)} >{toLocale('header_menu_import_wallet')}</Link>
{/*
<NavLink exact to={PageURL.walletImport} onClick={this.RedirectToImport} activeClassName="active-menu-item" >
{toLocale('header_menu_import_wallet')}
</NavLink> */}
</Menu.Item>
{/*
<Menu.Item key="omChain" >
<a target="_blank" rel="noopener noreferrer" href={Config.omchain.browserUrl}>{toLocale('header_menu_explorer_omchain')}</a>
</Menu.Item>
*/}
</Menu>
);
}
}
export default DexLoginMenu;
<file_sep>// 全屏交易数据加载组件
import React from 'react';
import DialogSet from '../../pages/DialogSet';
import SpotTradeWrapper from '../../wrapper/SpotTradeWrapper';
import InitWrapper from '../../wrapper/InitWrapper';
import './FullTrade.less';
@InitWrapper
@SpotTradeWrapper
class FullTradeData extends React.Component {
render() {
return <DialogSet />;
}
}
export default FullTradeData;
<file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import DexHelp from '_component/DexHelp';
import WalletAddress from '_component/WalletAddress';
import PageURL from '_constants/PageURL';
import Loading from '_component/Loading';
import './index.less';
@withRouter
class DexDesktopContainer extends Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
const { needLogin } = this.props;
const { senderAddr } = window.OM_GLOBAL || {};
if (needLogin && !senderAddr) {
this.props.history.replace(PageURL.walletImport);
}
}
render() {
const { isShowHelp, isShowAddress, loading = false } = this.props;
const { senderAddr } = window.OM_GLOBAL || {};
return (
<div className="dex-desktop-container">
<Loading when={loading} />
{
(isShowAddress && senderAddr) && (
<div className="dex-chain-address">
<div className="address-main">
<WalletAddress />
</div>
</div>
)
}
<div className="dex-desktop-main">
{
isShowHelp && <DexHelp />
}
{ this.props.children }
</div>
</div>
);
}
}
export default DexDesktopContainer;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './BaseButton.less';
import { TYPE, THEME } from './constants';
export default class BaseButton extends React.PureComponent {
static propTypes = {
/** 按钮使能 */
disabled: PropTypes.bool,
/** 按钮类型 可选值为 primary success info warning error default。根据UI规范 目前只需要用到 primary/default,请从Button.TYPE的常量中选择 */
type: PropTypes.oneOf([TYPE.default, TYPE.primary, TYPE.info, TYPE.success, TYPE.warn, TYPE.error]),
/** button 原生的 type 值 */
htmlType: PropTypes.string,
/** click 事件的 handler */
onClick: PropTypes.func,
/** 点击跳转的地址,指定此属性 button 的行为和 a 链接一致。 有该属性最终会被渲染为a标签。但同时带有disabled属性会渲染为button标签 */
href: PropTypes.string,
/** 相当于 a 链接的 target 属性,href 存在时生效。 */
target: PropTypes.string,
/** 将按钮宽度调整为其父宽度的选项 */
block: PropTypes.bool,
/** 主题或模式 支持 dark 即夜间模式 请从Button.THEME中选择 */
theme: PropTypes.oneOf([THEME.default, THEME.dark]),
};
static defaultProps = {
disabled: false,
type: TYPE.default,
htmlType: 'button',
onClick: null,
href: '',
target: '',
block: false,
theme: THEME.default
};
render() {
const {
children, type, className, htmlType, onClick, disabled, block, href, target, theme, loading, ...attr
} = this.props;
const Type = (btnType) => {
return type.indexOf(btnType) !== -1;
};
const button = (
<button
disabled={disabled || loading}
{...attr}
type={htmlType}
onClick={onClick}
className={
classNames(
'btn',
{ block },
{ [theme]: theme },
{ 'btn-primary': Type(TYPE.primary) },
{ 'btn-warning': Type(TYPE.warn) },
{ 'btn-success': Type(TYPE.success) },
{ 'btn-error': Type(TYPE.error) },
{ 'btn-default': Type(TYPE.default) },
{ 'btn-info': Type(TYPE.info) },
{ 'btn-disabled': disabled && !loading },
className
)
}
>
{children}
</button>
);
const hrefButton = (
<a
href={href}
target={target}
{...attr}
onClick={onClick}
className={
classNames(
'btn',
'btn-link',
{ block },
{ 'btn-primary': Type(TYPE.primary) },
{ 'btn-warning': Type(TYPE.warn) },
{ 'btn-success': Type(TYPE.success) },
{ 'btn-error': Type(TYPE.error) },
{ 'btn-default': Type(TYPE.default) },
{ 'btn-info': Type(TYPE.info) },
{ 'btn-disabled': disabled },
className
)
}
>
{children}
</a>
);
const content = href && !disabled ? hrefButton : button;
return (content);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './Deals.less';
export default class Deals extends React.Component {
// constructor(props, context) {
// super(props, context);
// }
renderBody = () => {
const { columns, dataSource } = this.props;
return (
<ul className="deals-list">
{dataSource.map((data, index) => {
return (
<li key={index}>
{columns.map((column) => {
if (column.render && typeof column.render === 'function') {
return (
<span key={column.key}>
{column.render(data[column.key], data, index)}
</span>
);
}
return (
<span key={column.key}>
{data[column.key]}
</span>
);
})}
</li>
);
})
}
</ul>
);
};
renderEmpty = () => {
const { empty } = this.props;
return (
<div style={{
display: 'flex', justifyContent: 'center', padding: '10px', color: 'rgba(255,255,255, 0.45)'
}}
>
{empty}
</div>
);
};
render() {
const { columns, dataSource, style } = this.props;
const haveData = dataSource && dataSource.length > 0;
return (
<div className="deals-rec" style={{ position: 'relative', ...style }}>
<ul className="deals-header">
{
columns.map((column) => {
const { key, title } = column;
return <li key={key}>{title}</li>;
})
}
</ul>
{
haveData ? this.renderBody() : this.renderEmpty()
}
</div>
);
}
}
Deals.defaultProps = {
dataSource: [],
columns: [],
empty: {},
style: {},
// loading: false
};
Deals.propTypes = {
dataSource: PropTypes.array,
columns: PropTypes.array,
empty: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
style: PropTypes.object,
// loading: PropTypes.bool
};
<file_sep>import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import DexDesktopContainer from '_component/DexDesktopContainer';
import { toLocale } from '_src/locale/react-locale';
import ClientWrapper from '_src/wrapper/ClientWrapper';
import PasswordDialog from '_component/PasswordDialog';
import { Dialog } from '_component/Dialog';
import Message from '_src/component/Message';
import DexDesktopInput from '_component/DexDesktopInput';
import PageURL from '_constants/PageURL';
import util from '_src/utils/util';
import Config from '_constants/Config';
import './index.less';
const showError = () => {
Message.error({
content: '服务端异常,请稍后重试'
});
};
@ClientWrapper
@withRouter
class ListTokenpair extends Component {
constructor() {
super();
this.state = {
baseAsset: '',
quoteAsset: '',
initPrice: '',
isActionLoading: false,
};
}
onBaseAssetChange = (e) => {
this.setState({ baseAsset: e.target.value });
}
onQuoteAssetChange = (e) => {
this.setState({ quoteAsset: e.target.value });
}
onInitPriceChange = (e) => {
this.setState({ initPrice: e.target.value });
}
onList = () => {
this.setState({ isActionLoading: true });
const { baseAsset, quoteAsset, initPrice } = this.state;
const { omchainClient } = this.props;
const fBase = baseAsset.toLowerCase();
const fQuote = quoteAsset.toLowerCase();
const fInitPrice = util.precisionInput(initPrice);
omchainClient.sendListTokenPairTransaction(fBase, fQuote, fInitPrice).then((res) => {
this.setState({ isActionLoading: false });
const { result, status } = res;
const { txhash } = result;
const log = JSON.parse(result.raw_log);
if (status !== 200 || (log && !log[0].success)) {
showError();
} else {
const dialog = Dialog.success({
className: 'desktop-success-dialog',
confirmText: 'Get detail',
theme: 'dark',
title: 'List tokenpair success!',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
window.open(`${Config.omchain.browserUrl}/tx/${txhash}`);
dialog.destroy();
},
});
}
}).catch((err) => {
console.log(err);
this.setState({ isActionLoading: false });
showError();
});
}
onPwdEnter = (password) => {
this.props.onPwdEnter(password, this.onList);
}
handleList = () => {
this.props.checkPK(this.onList);
}
toRegister = () => {
this.props.history.push(PageURL.registerPage);
}
render() {
const {
baseAsset, quoteAsset, initPrice, isActionLoading
} = this.state;
const { isShowPwdDialog, isLoading, warning } = this.props;
return (
<DexDesktopContainer
isShowHelp
isShowAddress
needLogin
loading={isActionLoading}
>
<div className="list-tokenpair-container">
<label className="tokenpair-label" htmlFor="">{toLocale('listToken.label')}</label>
<div className="tokenpair-input-container">
<input
type="text"
className="tokenpair-input"
value={baseAsset}
onChange={this.onBaseAssetChange}
/>
<div className="tokenpair-input-separator">/</div>
<input
type="text"
className="tokenpair-input"
value={quoteAsset}
onChange={this.onQuoteAssetChange}
/>
</div>
<DexDesktopInput
label={toLocale('listToken.initPrice.label')}
value={initPrice}
onChange={this.onInitPriceChange}
/>
<button className="dex-desktop-btn tokenpair-btn" onClick={this.handleList}>
{toLocale('listToken.list.btn')}
</button>
<div className="tokenpair-register-hint">
{toLocale('listToken.hint')}
<span onClick={this.toRegister}>{toLocale('listToken.hint.register')}</span>
</div>
</div>
<PasswordDialog
btnLoading={isLoading}
warning={warning}
isShow={isShowPwdDialog}
updateWarning={this.props.updateWarning}
onEnter={this.onPwdEnter}
onClose={this.props.onPwdClose}
/>
</DexDesktopContainer>
);
}
}
export default ListTokenpair;
<file_sep>import React from 'react';
import Icon from '_src/component/IconLite';
// import { toLocale } from '_src/locale/react-locale';
import './index.less';
const DexFooter = () => {
return (
<footer className="omdex-footer">
<div className="row-center">
©2014-2019 OMEX.app. All Rights Reserved
</div>
<div className="row-right">
<div className="omex-footer-links">
<a href=""><Icon className="icon-twitter" /></a>
<div className="line-divider" />
<a href=""><Icon className="icon-Telegram" /></a>
<div className="line-divider" />
<a href="">Q&A</a>
{/* <div className="line-divider" /> */}
{/* <a href="">{toLocale('footer_standard_rates')}</a> */}
</div>
</div>
</footer>
);
};
export default DexFooter;
<file_sep>import Depth from './Depth.js'; // eslint-disable-line
const depth = new Depth();
export {
// 类,对应多实例场景
Depth,
// 实例,对应多处共享状态场景
depth
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './index.less';
const WalletLeft = (props) => {
const { stepNo, stepName, imgUrl } = props;
return (
<div className="wallet-left">
<div className="title">
<div className="step-no">
<span className="current">
{stepNo}
</span>
<span className="total">
/3
</span>
</div>
<div className="step-name">
{stepName}
</div>
</div>
<div className="img">
<img src={imgUrl} />
</div>
</div>
);
};
WalletLeft.propTypes = {
stepNo: PropTypes.number,
stepName: PropTypes.string,
imgUrl: PropTypes.string
};
WalletLeft.defaultProps = {
stepNo: 1,
stepName: '',
imgUrl: ''
};
export default WalletLeft;
<file_sep>## Development environment
### Step 1: Configure WebStorm
Setting up the React syntax environment
Preferences > Languages & Frameworks > JavaScript > [select React JSX]
Configuring eslint rules and plug-ins
Link:http://gitlab.omcoin-inc.com/omfe/eslint
### Step 2: run the app
Switch npm warehouse address to company private warehouse (nrm tool is recommended)
```shell
sudo npm i nrm -g
nrm add omex http://npm.omcoin-inc.com:7001
nrm use omex
```
Installing dependent libraries:
```shell
npm install
```
Then run the application:
```shell
npm run dev
```
Access the app:
http://127.0.0.1:5200/dex-test
### nginx.conf configuration
Involving cross-domain, need to be resolved through Nginx proxy.
`vi /usr/local/etc/nginx/servers/omchain.conf`
```shell
upstream getsvr {
server 192.168.13.125:20159; # backend node IP
}
server {
listen 7777;
location / {
# Need to set the address of the front-end deployment
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'POST, GET, OPTIONS';
add_header Access-Control-Allow-Headers 'X-Requested-With,Content-Type,origin, content-type, accept, authorization,Action, Module, access-control-allow-origin,app-type,timeout,devid';
add_header Access-Control-Allow-Credentials true;
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://getsvr;
}
}
```
### Back-end data access instructions
In src/constants / config.configure api address in js
```shell
omchain: {
browserUrl: '${omchainExplorerBaseUrl} / explorer / omchain'` / / browser address
searchrUrL: '${omchainExplorerBaseUrl} / explorer / omchain` search', / / Search address
clientUrl: 'http://127.0.0.1:7777', / / nginx address
},
```
Among them,
omchainExplorerBaseUrl is the browser address.Since the project is not open source, block browser is not available for the time being.
clientUrl is the back-end interface address<file_sep>import { calc } from '_component/omit';
import { storage } from '_component/omit';
import Cookies from 'js-cookie';
import Enum from '../../utils/Enum';
import ont from '../../utils/dataProxy';
import SpotActionType from '../actionTypes/SpotActionType';
import util from '../../utils/util';
import URL from '../../constants/URL';
import SpotTradeActionType from '../actionTypes/SpotTradeActionType';
/*
* 重置当前币对配置信息
* */
function resetProductConfig(product, productList) {
if (!product) return;
const currProduct = productList.filter((item) => { return item.product === product; })[0];
if (currProduct) {
let defaultMerge = Enum.defaultMergeType;
if (currProduct.mergeTypes && currProduct.mergeTypes.split) {
defaultMerge = currProduct.mergeTypes.split(',')[0] || Enum.defaultMergeType;
}
currProduct.mergeType = Cookies.get(`${product}_depth_merge_stock`) || defaultMerge; // 深度合并系数
window.OM_GLOBAL.productConfig = currProduct;
}
}
/**
* 更新ws登录为延迟
*/
export function updateWsIsDelay(status) {
return (dispatch) => {
dispatch({
type: SpotActionType.UPDATE_WS_IS_DELAY,
data: status
});
};
}
/**
* 更新ws连接状态-已连接
*/
export function updateWsStatus(status) {
return (dispatch) => {
dispatch({
type: SpotActionType.UPDATE_WS_STATUS_V3,
data: status
});
};
}
/**
* 更新ws连接状态-断线
*/
export function addWsErrCounter() {
return (dispatch, getState) => {
const { wsErrCounterV3 } = getState().Spot;
dispatch({
type: SpotActionType.UPDATE_WS_ERR_COUNTER_V3,
data: wsErrCounterV3 + 1
});
};
}
/**
* 获取所有在线币对
*/
export function fetchProducts() {
return (dispatch, getState) => {
ont.get(URL.GET_PRODUCTS).then((res) => {
const { productList, productObj } = getState().SpotTrade;
// if (deleteFirst) {
// productList.forEach((item) => {
// const { groupIds } = item;
// const groupIndex = groupIds.indexOf(groupId);
// if (groupIndex > -1) {
// groupIds.splice(groupIndex, 1);
// }
// });
// }
if (res.data) {
res.data.forEach((item, index) => {
// TODO
// if (item.quote_asset_symbol === 'tomt') {
// item.quote_asset_symbol = 'tusdk';
// }
const product = `${item.base_asset_symbol}_${item.quote_asset_symbol}`;
let newItem = productObj[product];
if (newItem) {
// if (!newItem.groupIds.includes(groupId)) {
// newItem.groupIds.push(groupId);
// }
} else {
newItem = {
...item,
product,
// groupIds: [groupId]
};
newItem.max_price_digit = Number(newItem.max_price_digit);
newItem.max_size_digit = Number(newItem.max_size_digit);
newItem.min_trade_size = Number(newItem.min_trade_size);
newItem.price = calc.floorTruncate(newItem.price, newItem.max_price_digit);
productObj[product] = newItem;
productList.push(newItem);
}
// newItem[`productSort${groupId}`] = index;
});
// 设置配置信息在 initProduct 方法中
// window.OM_GLOBAL.productConfig = productObj[product];
dispatch({
type: SpotTradeActionType.FETCH_SUCCESS_PRODUCT_LIST,
data: { productList, productObj }
});
}
});
};
}
/**
* 获取所有收藏币对,然后获取币对
*/
export function fetchCollectAndProducts() {
return () => {
this.fetchProducts();
};
}
/**
* 获取所有币种
*/
export function fetchCurrency() {
return (dispatch) => {
ont.get(URL.GET_TOKENS).then((res) => {
const currencyList = res.data;
const currencyObjByName = {};
if (currencyList.length) {
currencyList.forEach((item) => {
currencyObjByName[item.symbol] = item;
});
}
dispatch({
type: SpotActionType.FETCH_SUCCESS_CURRENCY_LIST,
data: { currencyList, currencyObjByName }
});
}).catch((res) => {
dispatch({
type: SpotActionType.FETCH_ERROR_CURRENCY_LIST,
data: res
});
});
};
}
/**
* 更新交易区
*/
export function updateActiveMarket(market) {
return (dispatch) => {
storage.set('activeMarket', JSON.stringify(market || {}));
dispatch({
type: SpotActionType.UPDATE_ACTIVE_MARKET,
data: market
});
};
}
/**
* 更新本地收藏列表
* @param {Array} list
*/
export function updateFavoriteList(list) {
return (dispatch) => {
storage.set('favorites', list || []);
dispatch({
type: SpotTradeActionType.UPDATE_FAVORITES,
data: list,
});
};
}
/*
* 初始化更新设置当前币对
* */
export function initProduct(productObj, productList, callback) {
let product = '';
const symbolInHash = util.getQueryHashString('product');
if (symbolInHash) {
// 1、尝试从url的hash中取当前币对
if (productObj[symbolInHash.toLowerCase()]) {
product = symbolInHash.toLowerCase();
} else {
// 去掉hash
window.history.replaceState(null, null, ' ');
}
}
if (!product) {
const favorites = storage.get('favorites');
if (favorites) {
product = favorites[0] || '';
} else {
product = 'tbtc_tusdk';
}
}
// 重置当前币对配置信息
resetProductConfig(product, productList);
// 更新cookie
if (!storage.get('product') || storage.get('product') !== product) {
storage.set('product', product);
}
return (dispatch, getState) => {
// dispatch({
// type: SpotActionType.UPDATE_ACTIVE_MARKET,
// data: activeMarket
// });
const { tickers } = getState().Spot;
if (product) {
dispatch({
type: SpotActionType.UPDATE_SYMBOL,
data: { product }
});
if (tickers && tickers[product]) {
dispatch({
type: SpotTradeActionType.UPDATE_TICKER,
data: tickers[product]
});
}
}
callback && callback();
};
}
/**
* 更新查询条件
*/
export function updateSearch(text) {
return (dispatch) => {
dispatch({
type: SpotActionType.UPDATE_SEARCH,
data: text
});
};
}
/**
* 获取所有币对行情
*/
export function fetchTickers() {
return (dispatch, getState) => {
const product = getState().SpotTrade.product;
ont.get(URL.GET_PRODUCT_TICKERS).then((res) => {
const tickers = {};
const arr = res.data;
if (arr.length) {
arr.forEach((item) => {
const newO = { ...item };
newO.change = (Number(newO.price) === -1) ? 0 : (newO.price - newO.open);
newO.changePercentage = util.getChangePercentage(newO);
tickers[item.product] = newO;
});
}
dispatch({
type: SpotActionType.FETCH_SUCCESS_TICKERS,
data: tickers
});
if (product && tickers[product]) {
// ws推送连接不上,需用通过这里轮询更新currencyTicker
dispatch({
type: SpotTradeActionType.UPDATE_TICKER,
data: tickers[product]
});
}
});
};
}
/**
* 批量更新tickers
*/
export function wsUpdateTickers(data) {
return (dispatch, getState) => {
const { tickers } = getState().Spot;
const newTickers = tickers ? util.cloneDeep(tickers) : {};
data.forEach((item) => {
const product = item.product;
if (product) {
newTickers[product] = item;
}
});
dispatch({
type: SpotActionType.UPDATE_TICKERS,
data: newTickers
});
};
}
/*
* 更新当前币对
* */
export function updateProduct(product) {
return (dispatch, getState) => {
const spotTradeStore = getState().SpotTrade;
const oldProduct = spotTradeStore.product;
if (product === oldProduct) {
return false;
}
if (product) { // 去"账单"等页面时,会清空symbol
if (oldProduct) { // 没有symbol认为是从账单页面跳转过来的,统计由RouterCredential负责
// 页面统计
// util.logRecord();
}
}
// 重置当前币对配置信息
resetProductConfig(product, spotTradeStore.productList);
dispatch({
type: SpotActionType.UPDATE_SYMBOL,
data: {
product
}
});
dispatch({
type: SpotTradeActionType.UPDATE_TICKER,
data: getState().Spot.tickers[product]
});
storage.set('product', product);
return true;
};
}
/*
* 币对收藏
* */
export function collectProduct(product) {
return (dispatch, getState) => {
const state = { ...getState().SpotTrade };
const { productList, productObj } = state;
const collect = product.collect ? 1 : 0;
const newList = productList.map((item) => {
const newItem = item;
if (item.product === product.product) {
newItem.collect = collect;
}
return newItem;
});
// todo 修改了原始的state,最好Immutable
productObj[product.product].collect = collect;
dispatch({
type: SpotActionType.COLLECT_PRODUCT,
data: { productList: newList, productObj }
});
};
}
/*
* 获取人民币汇率
* */
export function fetchCnyRate() {
return (dispatch) => {
const fetchParam = {
headers: {
Authorization: localStorage.getItem('dex_token') || '',
Accept: 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
method: 'GET'
};
fetch(URL.GET_CNY_RATE, fetchParam)
.then((response) => { return response.json(); })
.then((response) => {
const cnyRate = response.usd_cny_rate;
dispatch({
type: SpotActionType.UPDATE_CNY_RATE,
data: cnyRate
});
});
};
}
/*
* 更改当前主题
* */
export function updateTheme(theme) {
return (dispatch) => {
dispatch({
type: SpotActionType.UPDATE_THEME,
data: theme
});
};
}
<file_sep>import React from 'react';
import { withRouter } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import DatePicker from '_component/ReactDatepicker';
import Select from '_component/ReactSelect';
import 'react-datepicker/dist/react-datepicker.css';
import { toLocale } from '_src/locale/react-locale';
import Message from '_src/component/Message';
import Checkbox from 'rc-checkbox';
import moment from 'moment';
import Cookies from 'js-cookie';
import RouterCredential from '../../RouterCredential';
import ont from '../../utils/dataProxy';
import DexTable from '../../component/DexTable';
import URL from '../../constants/URL';
import * as SpotActions from '../../redux/actions/SpotAction';
import * as OrderActions from '../../redux/actions/OrderAction';
import Enum from '../../utils/Enum';
import orderUtil from './orderUtil';
import './OrderList.less';
import { Button } from '_component/Button';
import normalColumns from '../spotOrders/normalColumns';
import commonUtil from '../spotOrders/commonUtil';
import util from '../../utils/util';
function mapStateToProps(state) { // 绑定redux中相关state'
const { product, productList, productObj } = state.SpotTrade;
const { data } = state.OrderStore;
const { theme } = state.Spot;
return {
product, productList, productObj, data, theme
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch),
orderActions: bindActionCreators(OrderActions, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class DealsList extends RouterCredential {
constructor(props, context) {
super(props, context);
this.threeDaysAgo = moment().subtract(3, 'days').endOf('day');
this.todayAgo = moment().subtract(0, 'days').endOf('day');
this.minDate = moment().subtract(3, 'month');
this.maxDate = moment();
this.state = {
product: 'all',
side: 'all',
start: this.threeDaysAgo,
end: this.todayAgo
};
}
componentWillMount() {
const { orderActions } = this.props;
orderActions.resetData();
if (this.props.location.state && this.props.location.state.product) {
this.setState({
product: this.props.location.state.product
});
}
if (this.props.location.state && this.props.location.state.period) {
let interval = 1;
const period = this.props.location.state.period;
if (period === 'oneWeek') {
interval = 7;
} else if (period === 'oneMonth') {
interval = 30;
} else if (period === 'threeMonth') {
interval = 90;
}
const start = moment().subtract(interval, 'days').endOf('day');
const end = moment().subtract(0, 'days').endOf('day');
this.setState({
start,
end
});
}
}
componentDidMount() {
const { spotActions } = this.props;
spotActions.fetchProducts();
const { webType } = window.OM_GLOBAL;
document.title = toLocale('spot.myOrder.detail') + toLocale('spot.page.title');
this.onSearch();
}
componentWillReceiveProps(nextProps) {
}
componentWillUnmount() {
const { orderActions } = this.props;
orderActions.resetData();
}
// 查询
onBtnSearch = () => {
this.onSearch({ page: 1 });
};
onSearch = (param) => {
const { orderActions } = this.props;
const { start, end } = this.state;
const params = {
...this.state,
...param
};
params.start = Math.floor(start.valueOf() / 1000) - 86400;
params.end = Math.floor(end.valueOf() / 1000);
if (params.start >= params.end) {
Message.warn({ content: toLocale('spot.orders.tips.dateRange') });
return false;
}
params.from = 'IndependentPage';
orderActions.getDetailList(params);
};
// 币对改变
onProductsChange = (obj) => {
const value = obj.value;
if (value.length > 0) {
this.setState({
product: value
}, () => {
this.onSearch({ page: 1 });
});
}
};
// 买卖筛选的改版
onSideChange = (obj) => {
const value = obj.value;
let side = 'all';
if (+value === 1) {
side = 'BUY';
} else if (+value === 2) {
side = 'SELL';
}
this.setState({
side
}, () => {
this.onSearch({ page: 1 });
});
};
// 设置日期
onDatePickerChange(key) {
return (date) => {
this.setState({
[key]: date
}, () => {
this.onSearch({ page: 1 });
});
};
}
// 页码变化
onPageChange = (page) => {
this.onSearch({ page });
};
handleDateChangeRaw = (e) => {
e.preventDefault();
};
// 渲染查询条件行
renderQuery = () => {
const { productList } = this.props;
const sortProductList = productList.sort((a, b) => { return (a.base_asset_symbol).localeCompare(b.base_asset_symbol); });
const newProductList = sortProductList.map((obj) => {
return {
value: obj.product,
label: obj.product.replace('_', '/').toUpperCase()
};
});
const {
product, side, start, end
} = this.state;
newProductList.unshift({ value: 'all', label: toLocale('spot.orders.allProduct') });
return (
<div className="query-container">
<div className="sub-query">
<span>{toLocale('spot.orders.symbol')}</span>
<Select
clearable={false}
searchable={false}
small
theme="dark"
name="form-field-name"
value={product}
onChange={this.onProductsChange}
options={newProductList}
style={{ width: 160 }}
/>
<span>{toLocale('spot.myOrder.direction')}</span>
<Select
clearable={false}
searchable={false}
small
theme="dark"
name="form-field-name"
value={side === 'all' ? 0 : (side === 'BUY' ? 1 : 2)}
onChange={this.onSideChange}
options={orderUtil.sideList()}
className="select-theme-controls mar-rig16 select-container"
style={{ width: 160 }}
/>
<span />
<DatePicker
small
selectsStart
theme="dark"
placeholderText="起始时间"
selected={start || null}
startDate={start || null}
endDate={end || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={this.minDate}
maxDate={end || this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('start')}
/>
<div className="dash" />
<DatePicker
small
selectsEnd
theme="dark"
placeholderText="截止时间"
selected={end || null}
startDate={start || null}
endDate={end || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={start || this.minDate}
maxDate={this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('end')}
/>
<Button size={Button.size.small} type={Button.btnType.primary} onClick={this.onBtnSearch}>{toLocale('spot.search')}</Button>
</div>
</div>
);
};
render() {
const { theme, productObj, data } = this.props;
const { orderList, isLoading, page } = data;
const themeColor = (theme === Enum.themes.theme2) ? 'dark' : '';
return (
<div className="spot-orders flex10">
<div className="title">{toLocale('spot.myOrder.detail')}</div>
{this.renderQuery()}
<DexTable
columns={normalColumns.detailColumns()}
dataSource={commonUtil.formatDealsData(orderList, productObj)}
empty={orderUtil.getEmptyContent()}
rowKey="uniqueKey"
style={{ clear: 'both', zIndex: 0 }}
isLoading={isLoading}
theme={themeColor}
pagination={page}
onPageChange={this.onPageChange}
/>
<p className="spot-orders-utips c-disabled" style={{ display: 'none' }}>
{toLocale('spot.bills.clearTips')}
</p>
</div>
);
}
}
export default DealsList;
<file_sep>import React, { Component } from 'react';
import Select from '_component/ReactSelect';
import './TabLocal.less';
const defaultOptions = [
{ value: 0, label: '币币' },
{ value: 1, label: '杠杆' },
{ value: 2, label: '其他' },
];
class TabLocal extends Component {
constructor() {
super();
this.state = {
options: defaultOptions,
selected: defaultOptions[0],
};
}
onChange = () => {
return (option) => {
this.setState({ selected: option });
};
}
render() {
const { options, selected } = this.state;
return (
<div className="node-local-container">
<div className="local-set-container">
<div className="local-set-cell">
<label htmlFor="" className="local-set-label">Network</label>
<Select
className="network-select"
clearable={false}
searchable={false}
theme="dark"
name="form-field-name"
value={selected}
onChange={this.onChange()}
options={options}
/>
</div>
<div className="local-set-cell">
<label htmlFor="" className="local-set-label">Network</label>
<Select
className="network-select"
clearable={false}
searchable={false}
theme="dark"
name="form-field-name"
value={selected}
onChange={this.onChange()}
options={options}
/>
</div>
<div className="local-set-cell">
<label htmlFor="" className="local-set-label">Network</label>
<Select
className="network-select"
clearable={false}
searchable={false}
theme="dark"
name="form-field-name"
value={selected}
onChange={this.onChange()}
options={options}
/>
</div>
<div className="local-set-cell">
<label htmlFor="" className="local-set-label">Network</label>
<Select
className="network-select"
clearable={false}
searchable={false}
theme="dark"
name="form-field-name"
value={selected}
onChange={this.onChange()}
options={options}
/>
</div>
<div className="local-set-cell">
<label htmlFor="" className="local-set-label">Network</label>
<Select
className="network-select"
clearable={false}
searchable={false}
theme="dark"
name="form-field-name"
value={selected}
onChange={this.onChange()}
options={options}
/>
</div>
</div>
<div className="local-set-terminal">
<h4 className="local-terminal-title">Terminal</h4>
<div className="local-terminal-content" />
</div>
</div>
);
}
}
export default TabLocal;
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { toLocale } from '_src/locale/react-locale';
import PageURL from '_src/constants/PageURL';
import IconLite from '_src/component/IconLite';
import Config from '_src/constants/Config';
import { getLangURL } from '_src/utils/navigation';
import Image from '../image';
import './index.less';
import './index-md.less';
import './index-lg.less';
import './index-xl.less';
const StepItem = (props) => {
const {
imgNum, index, icon, title, content, buttonTxt, buttonUrl, isLink
} = props.data;
return (
<section className="step-item">
<div className={imgNum !== index ? 'top' : 'top top-select'}>
<IconLite className={`step-icon ${icon}`} />
<h3 className="step-title">{toLocale(title)}</h3>
</div>
<div className="bottom">
<p className="step-content">{toLocale(content)}</p>
{
isLink ? (
<Link
className="step-button"
to={getLangURL(buttonUrl)}
rel="noopener noreferrer"
title={toLocale(buttonTxt)}
/>
) : (
<a
className="step-button"
href={getLangURL(buttonUrl)}
rel="noopener noreferrer"
title={toLocale(buttonTxt)}
>
{toLocale(buttonTxt)}
<IconLite className="icon-go" />
</a>
)
}
</div>
</section>
);
};
const getIcon = (imgNum, index, circleTime) => {
// const icon = { 4: 'icon-icon_one', 3: 'icon-icon_two', 2: 'icon-icon_three', 1: 'icon-icon_four' };
const iconSelect = {
4000: 'icon-icon_one_', 3000: 'icon-icon_two_', 2000: 'icon-icon_three_', 1000: 'icon-icon_four_'
};
if (imgNum === index) {
return iconSelect[circleTime];
}
// const val = imgNum > index ? index + 1 : index;
return 'icon-icon_four';
};
const stepsImgList = [
'home_steps_item0_img',
'home_steps_item1_img',
'home_steps_item2_img',
'home_steps_item3_img',
];
const StepList = (props) => {
const { imgNum, circleTime } = props.data;
const list = [
{
imgNum,
index: 0,
icon: getIcon(imgNum, 0, circleTime),
title: 'home_steps_item0_title',
content: 'home_steps_item0_content',
buttonTxt: 'home_steps_item0_button',
buttonUrl: PageURL.walletCreate,
isLink: true
},
{
imgNum,
index: 1,
icon: getIcon(imgNum, 1, circleTime),
title: 'home_steps_item1_title',
content: 'home_steps_item1_content',
buttonTxt: 'home_steps_item1_button',
buttonUrl: Config.omchain.receiveCoinUrl,
isLink: false
},
{
imgNum,
index: 2,
icon: getIcon(imgNum, 2, circleTime),
title: 'home_steps_item2_title',
content: 'home_steps_item2_content',
buttonTxt: 'home_steps_item2_button',
buttonUrl: PageURL.spotFullPage,
isLink: true
},
{
imgNum,
index: 3,
icon: getIcon(imgNum, 3, circleTime),
title: 'home_steps_item3_title',
content: 'home_steps_item3_content',
buttonTxt: 'home_steps_item3_button',
buttonUrl: Config.omchain.browserUrl,
isLink: false
}
];
return (
<div className="step-list-container">
{
list.map((item, index) => {
return (<StepItem key={index} data={item} />);
})
}
</div>
);
};
class Steps extends Component {
constructor(props) {
super(props);
this.state = {
imgNum: 0, // 轮播图片的顺序
circleTime: 4000, // 轮播图片0的切换时间ms
};
}
componentDidMount() {
this.countDown();
}
countDown() {
setInterval(() => {
const { circleTime, imgNum } = this.state;
if (circleTime > 1000) {
const newTime = circleTime - 1000;
this.setState({
circleTime: newTime
});
} else {
const newImgNum = imgNum < 3 ? imgNum + 1 : 0;
this.setState({
imgNum: newImgNum,
circleTime: 4000
});
}
}, 1000);
}
componentWillUnmount() {
clearInterval(this.countDown);
}
render() {
const { imgNum, circleTime } = this.state;
return (
<article className="steps-grid">
<h2 className="steps-title">{toLocale('home_steps_title')}</h2>
<div className="steps-content">
{
stepsImgList.map((img, index) => {
return (
<img
key={index}
className={index === imgNum ? `step-img${imgNum}` : 'non-dis'}
src={toLocale(img) || Image[`step${imgNum}`]}
alt={toLocale('home_steps_title')}
/>
);
})
}
<StepList data={{ imgNum, circleTime }} />
</div>
</article>
);
}
}
export default Steps;
<file_sep>import React from 'react';
import OrderSecHeaderWrapper from '../../wrapper/SpotOrderSecHeaderWrapper';
import Enum from '../../utils/Enum';
const SecHeader = ({ entrustType, dataSource, onEntrustTypeChange }) => {
const {
tradeType, webType, webTypes
} = window.OM_GLOBAL;
const isKr = webType === webTypes.OMKr;
if (isKr || tradeType === Enum.tradeType.fullTrade) {
return <div />;
}
return (
<div className="types-line">
<ul>
{
dataSource.map(({ type, name }) => {
return (
<li
className={`type-btn ${entrustType === type ? 'current' : ''}`}
onClick={onEntrustTypeChange(type)}
key={type}
>
{name}
</li>
);
})
}
</ul>
</div>
);
};
export default OrderSecHeaderWrapper(SecHeader);
<file_sep>import React from 'react';
import './index.less';
const WalletRight = (props) => {
return (
<div className="wallet-right">
{props.children}
</div>
);
};
export default WalletRight;
<file_sep>/**
* 弹框-基础层
* Created by yuxin.zhang on 2018/9/1.
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Loading from '../Loading';
import './Dialog.less';
/**
* 拖拽
* @param currentDialogId 可以拖拽的元素的id
*/
function dragFunc(currentDialogId) {
const titleDiv = document.getElementById(currentDialogId);
if (!titleDiv) {
return false;
}
const dialog = titleDiv.parentNode;
titleDiv.onmousedown = (ev) => {
const oEvent = ev || window.event;
const distanceX = oEvent.clientX - dialog.offsetLeft;
const distanceY = oEvent.clientY - dialog.offsetTop;
document.onmousemove = (ev1) => {
const oEvent1 = ev1 || window.event;
dialog.style.left = `${oEvent1.clientX - distanceX}px`;
dialog.style.top = `${oEvent1.clientY - distanceY}px`;
};
document.onmouseup = () => {
document.onmousemove = null;
document.onmouseup = null;
};
oEvent.cancelBubble = true;
oEvent.stopPropagation();
};
return true;
}
export default class BaseDialog extends React.PureComponent {
static propTypes = {
/** 弹框是否可见 */
visible: PropTypes.bool,
/** 是否展示加载状态 */
showLoading: PropTypes.bool,
/** 隐藏关闭按钮 */
hideCloseBtn: PropTypes.bool,
/** 自定义关闭按钮 */
closeBtn: PropTypes.any,
/** 标题 */
title: PropTypes.string,
/** 关闭回调 */
onClose: PropTypes.func,
/** 主题 目前只支持dark 用于夜间模式 */
theme: PropTypes.string,
/** 是否可拖拽 */
canDrag: PropTypes.bool,
/** 弹框Id 可拖拽必传 */
dialogId: PropTypes.string,
/** 设置 Dialog 的 z-index */
zIndex: PropTypes.number,
/** 指定宽度 默认无 一般情况应该根据内容撑宽 而不是指定宽度 */
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** 里层window样式 即弹框体 */
windowStyle: PropTypes.object,
/** 是否显示蒙层 */
mask: PropTypes.bool,
/** 点击蒙层是否允许关闭 */
maskClosable: PropTypes.bool,
/** 遮罩蒙层样式 */
maskStyle: PropTypes.object,
};
static defaultProps = {
visible: false,
showLoading: false,
hideCloseBtn: false,
closeBtn: null,
canDrag: false,
title: '',
theme: '',
dialogId: '',
onClose: null,
zIndex: undefined,
width: null,
windowStyle: {},
mask: true,
maskClosable: false,
maskStyle: {},
};
state = {
dragInitialized: false
};
componentDidMount() {
const { visible, canDrag, dialogId } = this.props;
if (visible && canDrag) {
this.state.dragInitialized = dragFunc(dialogId);
}
}
componentDidUpdate() {
const { visible, canDrag, dialogId } = this.props;
if (visible && canDrag) {
this.state.dragInitialized = dragFunc(dialogId);
}
}
onClose = () => {
const { onClose } = this.props;
onClose && onClose();
};
render() {
const {
visible, showLoading, hideCloseBtn, canDrag, children,
title, dialogId, theme, zIndex, width, closeBtn,
mask, maskClosable, maskStyle, className
} = this.props;
const dialogStyle = zIndex ? { zIndex } : {};
const windowStyle = { ...(width ? { width } : {}), ...this.props.windowStyle };
return (
visible &&
<div
className={
classNames(
'om-dialog',
{ [theme]: theme },
{ 'dialog-show': visible },
{ 'dialog-hide': !visible },
className
)
}
style={dialogStyle}
>
{/* 蒙层 */}
<div
className={
classNames(
'om-dialog-mask',
{ 'mask-hide': !mask },
)
}
onClick={maskClosable ? this.onClose : null}
style={maskStyle || {}}
/>
{/* 弹框体 */}
<div className="dialog-window" style={windowStyle}>
<div className={`dialog-top ${title.length === 0 ? 'no-title-bottom-line' : ''} ${canDrag ? 'drag' : ''}`} id={dialogId}>
<span className="dialog-title">{title}</span>
{
!hideCloseBtn && (closeBtn === null ? <span className="close-btn" onClick={this.onClose}>×</span> : <span onClick={this.onClose}>{closeBtn}</span>)
}
</div>
<div className={`dialog-box ${(!title || title.length === 0) ? 'no-title' : ''}`}>
{children}
<Loading when={showLoading} theme={theme} />
</div>
</div>
</div>
);
}
}
<file_sep>import moment from 'moment';
import { calc, depth } from '_component/omit';
import ont from '../../utils/dataProxy';
import util from '../../utils/util';
import URL from '../../constants/URL';
import SpotTradeActionType from '../actionTypes/SpotTradeActionType';
import Enum from '../../utils/Enum';
import SpotActionType from '../actionTypes/SpotActionType';
import FormatAsset from '../../utils/FormatAsset';
/**
* 获取所有币种资产或者某一个
* 新增获取币币交易资产数据格式化 wanghongguang 2018-05-23
*/
export function fetchAccountAssets(callback) {
return (dispatch, getState) => {
const senderAddr = util.getMyAddr();
if (!senderAddr) return;
ont.get(`${URL.GET_ACCOUNTS}/${senderAddr}`).then((res) => {
const { currencies } = res.data;
const account = {};
currencies.forEach((item) => {
// 将数据的key变换成currency货币,记录到redux里
account[item.symbol.toLowerCase()] = item;
});
const { product } = getState().SpotTrade;
const { productConfig } = window.OM_GLOBAL;
const spotAsset = FormatAsset.getSpotData(product, account, productConfig);
dispatch({
type: SpotTradeActionType.FETCH_UPDATE_ASSETS,
data: { account, spotAsset }
});
return callback && callback();
}).catch((res) => {
return dispatch({
type: SpotTradeActionType.FETCH_ERROR_ASSETS,
data: res.msg
});
});
};
}
// 将接口返回的数据转为DepthMerge工具类希望的二维数组格式
const transferDepth = (data) => {
const result = {
bids: [],
asks: []
};
if (data.bids) {
result.bids = data.bids.map((item) => {
return [+item.price, +item.quantity, calc.mul(+item.price, +item.quantity)];
});
}
if (data.asks) {
result.asks = data.asks.map((item) => {
return [+item.price, +item.quantity, calc.mul(+item.price, +item.quantity)];
});
}
return result;
};
/*
* ws清空深度 - 数组
* */
export function clearSortPushDepthData() {
return (dispatch) => {
depth.clear();
dispatch({
type: SpotTradeActionType.FETCH_CLEAR_UPDATE_DEPTH
});
};
}
/**
* 获取深度(非集合竞价)
*/
export function fetchDepth(product) {
return (dispatch, getState) => {
ont.get(URL.GET_DEPTH_BOOK, { params: { product } }).then((res) => {
// 如果websocket已经链接 则不将ajax数据设置到store
if (window.OM_GLOBAL.ws_v3.isConnected()) {
console.log('trace,websocket,error,ajax回调发生在websocket推送之后');
return;
}
// 格式化数据
const formattedData = transferDepth(res.data); // 将asks和bids分别转为二维数组
const { productConfig, tradeType } = window.OM_GLOBAL;
dispatch(clearSortPushDepthData()); // depth.clear();
const depth200 = depth.addData(formattedData);
const depthSize = tradeType === Enum.tradeType.normalTrade ? 20 : 30;
const defaultMergeType = util.generateMergeType(Number(productConfig.max_price_digit));
const depthData = depth.getDepth(defaultMergeType, depthSize); // productConfig.mergeType
dispatch({
type: SpotTradeActionType.UPDATE_DEPTH,
data: {
depth: depthData,
depth200
}
});
});
};
}
/*
* ws更新深度
* */
export function wsUpdateDepth(data) {
return (dispatch, getState) => {
const tradeState = getState().SpotTrade;
// yao ws初次订阅会返回全量 清空一下store里的数据
if (data.action === 'partial') {
// yao 监听一下ajax回调发生在原本清空逻辑之后的情况
const traceDepth = tradeState.depth || { asks: [] };
if (traceDepth.asks.length) {
console.log('trace,websocket,error,ajax回调发生在websocket原清空逻辑之后');
}
dispatch(clearSortPushDepthData());
}
const { product } = tradeState;
if (product === '') { // 有可能组件卸载了,但是上一个推送过来了
return false;
}
if ((`${data.base}_${data.quote}`) !== product) { // 只接受当前币对的推送数据,重要!
return false;
}
// 格式化数据
const formattedData = transferDepth(data.data); // 将asks和bids分别转为二维数组
const { productConfig, tradeType } = window.OM_GLOBAL;
const depth200 = depth.addData(formattedData);
const depthSize = tradeType === Enum.tradeType.fullTrade ? 30 : 20;
const defaultMergeType = util.generateMergeType(Number(productConfig.max_price_digit)); // productConfig.mergeType
const depthData = depth.getDepth(defaultMergeType, depthSize);
return dispatch({
type: SpotTradeActionType.UPDATE_DEPTH,
data: {
depth: depthData,
depth200
}
});
};
}
/**
* 刷新资产
*/
export function refreshAsset() {
return (dispatch, getState) => {
const { product, account } = getState().SpotTrade;
const { productConfig } = window.OM_GLOBAL;
const spotAsset = FormatAsset.getSpotData(product, account, productConfig);
return dispatch({
type: SpotTradeActionType.REFRESH_ASSETS,
data: { spotAsset }
});
};
}
/**
* 更新资产
* 新增获取币币交易资产数据格式化 wanghongguang 2018-05-23
*/
export function wsUpdateAsset(data) {
return (dispatch, getState) => {
const { product, currencyObjByName } = getState().SpotTrade;
const state = getState().SpotTrade;
const account = { ...state.account };
if (data instanceof Array && data.length) {
for (let i = 0; i < data.length; i++) {
const symbol = data[i].symbol;
if (currencyObjByName[symbol]) {
account[currencyObjByName[symbol].symbol.toLowerCase()] = data[i];
}
}
} else if (Object.prototype.toString.call(data) === '[object Object]' &&
Object.keys(data).length > 0) {
account[currencyObjByName[data.symbol].symbol.toLowerCase()] = data;
}
const { productConfig } = window.OM_GLOBAL;
const spotAsset = FormatAsset.getSpotData(product, account, productConfig);
dispatch({
type: SpotTradeActionType.FETCH_UPDATE_ASSETS,
data: { account, spotAsset }
});
};
}
/**
* 更新ticker
*/
export function wsUpdateTicker(data) {
return (dispatch, getState) => {
const { currencyTicker, product } = getState().SpotTrade;
if (product.toLowerCase() !== data.product.toLowerCase()) {
return false;
}
let newCurrencyTicker = currencyTicker ? util.cloneDeep(currencyTicker) : {};
if (data instanceof Array) {
newCurrencyTicker = { ...newCurrencyTicker, ...data[0] };
} else {
newCurrencyTicker = { ...newCurrencyTicker, ...data };
}
const { tickers } = getState().Spot;
const newTickers = tickers ? util.cloneDeep(tickers) : {};
newTickers[product] = newCurrencyTicker;
dispatch({
type: SpotTradeActionType.UPDATE_TICKER,
data: newCurrencyTicker
});
// 更新所有币对行情,确保左侧菜单实时刷新
dispatch({
type: SpotActionType.UPDATE_TICKERS,
data: newTickers
});
return false;
};
}
/*
* 清空分时K线数据
* */
export function clearKlineData() {
return (dispatch) => {
dispatch({
type: SpotTradeActionType.FETCH_SUCCESS_KLINE_DATA,
data: []
});
};
}
/*
* 获取分时K线数据
* */
export function getKlineDataByAjax(product, callback) {
return (dispatch, getState) => {
// 不清空数据,防止ws断线后,K线总闪
// dispatch({
// type: SpotTradeActionType.FETCH_SUCCESS_KLINE_DATA,
// data: []
// });
ont.get(URL.GET_KLINE_DATA, {
params: {
product,
type: '1min'
}
}).then((res) => {
if (getState().SpotTrade.product.toLowerCase() !== product) {
return false;
}
let klineData = res.data;
if (klineData.length > 300) {
klineData = klineData.slice(klineData.length - 300);
}
dispatch({
type: SpotTradeActionType.FETCH_SUCCESS_KLINE_DATA,
data: klineData
});
return callback && callback();
});
};
}
/*
* ws更新K线数据
* */
export function wsUpdateKlineData(klinedata) {
// 先ajax全量,然后合成ws增量数据
return (dispatch, getState) => {
const state = getState().SpotTrade;
const { product } = state;
if (product === '') { // 有可能组件卸载了,但是上一个推送过来了
return false;
}
if (product.toLowerCase() !== (`${klinedata.base}_${klinedata.quote}`).toLowerCase()) {
return false;
}
const data = klinedata.data;
let klineData = [...state.klineData];
if (klineData.length) {
const lastItem = klineData[klineData.length - 1];
// 需要追加的数组
const appendData = [];
for (let i = 0; i < data.length; i++) {
const e = data[i];
if (Number(e.createdDate) === Number(lastItem.createdDate)) {
const isEqual = Number(lastItem.close) === Number(e.close);
// 收盘价不等时 需要更新
if (!isEqual) {
klineData[klineData.length - 1] = e;
}
} else if (Number(e.createdDate) > Number(lastItem.createdDate)) {
appendData.push(e);
}
}
if (appendData.length) {
let newData = klineData.concat(appendData);
if (newData.length > 300) {
newData = newData.slice(newData.length - 300);
}
klineData = newData;
}
} else {
// klineData = data;
return false;
}
return dispatch({
type: SpotTradeActionType.FETCH_SUCCESS_KLINE_DATA,
data: klineData
});
};
}
/*
* 币币-修改资金划转对话框
* */
export function updateTransfer(value) {
return (dispatch) => {
dispatch({
type: SpotTradeActionType.UPDATE_TRANSFER,
data: value
});
};
}
export function addColorToDeals(arr) {
const data = [...arr];
const l = data.length;
if (!data[l - 1].color) {
data[l - 1].color = 'deals-green';
}
if (data.length === 1) {
return data;
}
for (let i = l - 1; i > 0; i--) {
if (data[i - 1].price > data[i].price) {
data[i - 1].color = 'deals-green';
} else if (data[i - 1].price < data[i].price) {
data[i - 1].color = 'deals-red';
} else if (data[i].color === 'deals-green') {
data[i - 1].color = 'deals-green';
} else {
data[i - 1].color = 'deals-red';
}
}
return data;
}
/*
* 全屏交易-获取所有成交
* */
export function getDeals(product, callback) {
return (dispatch) => {
ont.get(URL.GET_LATEST_MATCHES, { params: { product, page: 0, per_page: 60 } }).then((res) => {
const data = res.data.data || [];
data.sort((d1, d2) => {
return d2.timestamp - d1.timestamp;
});
// 增加方向
const Finalist = data.length > 0 ? addColorToDeals(data) : [];
dispatch({
type: SpotTradeActionType.FETCH_SUCCESS_DEALS,
data: Finalist
});
callback && callback();
});
};
}
export function clearDeals() {
return (dispatch) => {
dispatch({
type: SpotTradeActionType.CLEAR_DEALS,
data: []
});
};
}
/*
* 全屏交易-已成交
* */
export function wsUpdateDeals(data = []) {
return (dispatch, getState) => {
const state = getState().SpotTrade;
const { product } = state;
if (product === '') {
return false;
}
const dataFilted = data.filter((item) => {
const itemProduct = item.product;
if (itemProduct) {
return itemProduct.toLowerCase() === product;
}
return false;
});
// 推送不包含全量推送,所以直接合并去重
if (dataFilted.length > 0) {
// 后面不修改deals
let deals = [...state.deals];
// 合并
deals = dataFilted.concat(deals);
let newArr = [];
const newObj = {};
// 去重
for (let i = 0, len = deals.length; i < len; i++) {
deals[i].id = deals[i].product + deals[i].timestamp + deals[i].block_height + deals[i].price + deals[i].volume;
if (deals[i].id && !newObj[deals[i].id]) {
newObj[deals[i].id] = true;
newArr.push(deals[i]);
}
}
// 切割
if (newArr.length > 60) {
newArr = newArr.slice(0, 60);
}
// 排序
newArr.sort((d1, d2) => {
return d2.timestamp - d1.timestamp;
});
// 增加方向
const Finalist = data.length > 0 ? addColorToDeals(newArr) : [];
dispatch({
type: SpotTradeActionType.WS_UPDATE_DEALS,
data: Finalist
});
}
return true;
};
}
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import Deals from '../../component/deals/Deals';
import LastestDealWrapper from '../../wrapper/LastestDealWrapper';
import './FullTradeDeals.less';
const FullTradeDeals = (props) => {
const { dataSource, empty, columns } = props;
return (
<div className="full-deals">
<div className="full-deals-title">{toLocale('spot.deals.title')}</div>
<Deals
dataSource={dataSource}
columns={columns}
empty={empty}
/>
</div>
);
};
export default LastestDealWrapper(FullTradeDeals);
<file_sep>import React, { Component } from 'react';
import { Button } from '_component/Button';
import URL from '_src/constants/URL';
import { toLocale } from '_src/locale/react-locale';
import Config from '_constants/Config';
import DatePicker from '_component/ReactDatepicker';
import Select from '_component/ReactSelect';
import DexTable from '_component/DexTable';
import moment from 'moment';
import { calc } from '_component/omit';
import Cookies from 'js-cookie';
import assetsUtil from './assetsUtil';
import './Assets.less';
import ont from '../../utils/dataProxy';
import util from '../../utils/util';
/* eslint-disable react/sort-comp */
class AssetsTransactions extends Component {
constructor(props) {
super(props);
this.minDate = moment().subtract(1, 'years');
this.maxDate = moment();
this.defaultPage = {
page: 1, per_page: 20, total: 0
};
this.state = {
transactions: [],
startDate: 0,
endDate: 0,
type: 0,
loading: false,
param_page: this.defaultPage
};
this.typeOptions = [{ value: 0, label: toLocale('all') }].concat(assetsUtil.transactionsTypes);
this.addr = window.OM_GLOBAL.senderAddr;
}
componentDidMount() {
document.title = toLocale('assets_tab_transactions') + toLocale('spot.page.title');
if (this.addr) {
this.fetchTransactions();
}
}
onDatePickerChange = (type) => {
return (date) => {
this.setState({ [type]: date });
};
};
onTypeChange = ({ value: type }) => {
this.setState({ type });
};
fetchTransactions = (page = 1) => {
const { startDate, endDate, type } = this.state;
const params = {
address: this.addr,
page,
per_page: 20,
type: type || undefined,
start: startDate ? calc.div(moment(startDate).startOf('day').valueOf(), 1000) : undefined,
end: endDate ? calc.div(moment(endDate).endOf('day').valueOf() - 999, 1000) : undefined,
};
this.setState({ loading: true });
ont.get(URL.GET_TRANSACTIONS, { params }).then(({ data }) => {
const list = data.data.map((item) => {
const newItem = { ...item };
newItem.uniqueKey = newItem.txhash + newItem.type + newItem.side + newItem.symbol + newItem.timestamp;
return newItem;
});
this.setState({
transactions: list || [],
param_page: data.param_page || this.defaultPage
});
}).catch().then(() => {
this.setState({ loading: false });
});
};
handleDateChangeRaw = (e) => {
e.preventDefault();
};
render() {
const {
transactions, startDate, endDate, type, loading, param_page
} = this.state;
return (
<div>
<div className="query-container">
<div className="sub-query">
<DatePicker
small
selectsStart
theme="dark"
placeholderText={toLocale('trade_query_begin')}
selected={startDate || null}
startDate={startDate || null}
endDate={endDate || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={this.minDate}
maxDate={endDate || this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('startDate')}
/>
<div className="dash" />
<DatePicker
small
selectsEnd
theme="dark"
placeholderText={toLocale('trade_query_end')}
selected={endDate || null}
startDate={startDate || null}
endDate={endDate || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={startDate || this.minDate}
maxDate={this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('endDate')}
/>
<span>{toLocale('trade_query_order_type')}</span>
<Select
clearable={false}
searchable={false}
small
theme="dark"
options={this.typeOptions}
value={type}
onChange={this.onTypeChange}
style={{ width: 180 }}
/>
<Button size={Button.size.small} type={Button.btnType.primary} onClick={() => { this.fetchTransactions(); }}>{toLocale('trade_query_search')}</Button>
</div>
<a
href={Config.omchain.browserUrl}
target="_blank"
rel="noopener noreferrer"
>{toLocale('trade_query_more')} >>
</a>
</div>
<DexTable
columns={assetsUtil.transactionsCols}
dataSource={transactions}
rowKey="uniqueKey"
pagination={param_page}
onPageChange={this.fetchTransactions}
isLoading={loading}
empty={<div>{toLocale('trade_emtpy')}</div>}
/>
</div>
);
}
}
export default AssetsTransactions;
<file_sep>import Message from '_src/component/Message';
import ont from '../../utils/dataProxy';
import OrderActionType from '../actionTypes/OrderActionType';
import URL from '../../constants/URL';
import Enum from '../../utils/Enum';
import util from '../../utils/util';
import { OrderStatus } from '../../constants/OrderStatus';
const defaultPage = {
page: 1,
per_page: 20
};
const defaultRespPage = {
page: 1, // 当前页码
per_page: 20,
totalSize: 0
};
export function handleCommonParam(periodInterval) {
let start = new Date();
const end = Math.floor(new Date().getTime() / 1000);
if (periodInterval === Enum.order.periodInterval.oneDay) {
start = start.setDate(start.getDate() - 1);
} else if (periodInterval === Enum.order.periodInterval.oneWeek) {
start = start.setDate(start.getDate() - 7);
} else if (periodInterval === Enum.order.periodInterval.oneMonth) {
start = start.setDate(start.getDate() - 30);
} else if (periodInterval === Enum.order.periodInterval.threeMonth) {
start = start.setDate(start.getDate() - 90);
}
start = Math.floor(new Date(start).getTime() / 1000);
return {
start,
end
};
}
// 处理未成交订单、已完成订单和成交明细三个接口的请求
export function handleRequestCommon(params, url) {
return (dispatch, getState) => {
const store = getState();
const { product } = store.SpotTrade;
const { isHideOthers, periodIntervalType } = store.OrderStore;
const { senderAddr } = window.OM_GLOBAL;
// const startEnd = handleCommonParam(periodIntervalType);
const newParams = {
...defaultPage,
// ...startEnd,
product,
...params
};
if (newParams.from === 'IndependentPage') {
if (newParams.product === 'all') {
delete newParams.product;
}
delete newParams.from;
} else if (!isHideOthers) {
delete newParams.product;
}
if (newParams.side === 'all') {
delete newParams.side;
}
if (senderAddr) {
newParams.address = senderAddr;
} else {
return;
}
const ajaxUrl = url;
const listKey = 'data'; // response中存放数据信息字段名
const pageKey = 'param_page'; // response中存放分页信息字段名
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: true,
orderList: []
}
});
ont.get(ajaxUrl, { params: newParams }).then((res) => {
const resData = res.data;
let list = resData[listKey] ? resData[listKey] : [];
if (ajaxUrl.indexOf('deals') > -1) {
let newItem = {};
list = list.map((item) => {
newItem = { ...item };
newItem.uniqueKey = newItem.order_id + newItem.block_height;
return newItem;
});
}
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: false,
orderList: list,
page: resData[pageKey]
}
});
}).catch(() => {
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: false,
orderList: [],
page: defaultRespPage
}
});
});
};
}
/**
* 重置数据
*/
export function resetData() {
return (dispatch) => {
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: false,
orderList: [],
page: defaultRespPage
}
});
};
}
/**
* 获取未成交订单
*/
export function getNoDealList(params = {}) {
return (dispatch, getState) => {
const store = getState();
const { product } = store.SpotTrade;
const { isHideOthers, periodIntervalType } = store.OrderStore;
const { senderAddr } = window.OM_GLOBAL;
// const startEnd = handleCommonParam(periodIntervalType);
const newParams = {
...defaultPage,
// ...startEnd,
product,
...params
};
if (newParams.from === 'IndependentPage') {
if (newParams.product === 'all') {
delete newParams.product;
}
delete newParams.from;
} else if (!isHideOthers) {
delete newParams.product;
}
if (newParams.side === 'all') {
delete newParams.side;
}
if (senderAddr) {
newParams.address = senderAddr;
} else {
return;
}
const ajaxUrl = URL.GET_ORDER_OPEN;
const listKey = 'data'; // response中存放数据信息字段名
const pageKey = 'param_page'; // response中存放分页信息字段名
ont.get(ajaxUrl, { params: newParams }).then((res) => {
const resData = res.data;
const list = resData[listKey] ? resData[listKey] : [];
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: false,
orderList: list,
page: resData[pageKey]
}
});
}).catch(() => {
dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
isLoading: false,
orderList: [],
page: defaultRespPage
}
});
});
};
}
/**
* 获取历史订单
*/
export function getHistoryList(params = {}) {
return (dispatch, getState) => {
handleRequestCommon(params, URL.GET_ORDER_CLOSED)(dispatch, getState);
};
}
/**
* 获取成交明细
*/
export function getDetailList(params = {}) {
return (dispatch, getState) => {
handleRequestCommon(params, URL.GET_PRODUCT_DEALS)(dispatch, getState);
};
}
/**
* 获取订单,本action内部自动判断获取"未成交"还是"历史"
*/
export function getOrderList(params) {
return (dispatch, getState) => {
const { type } = getState().OrderStore;
// const { isLogin } = window.OM_GLOBAL;
if (util.isLogined()) {
if (type === Enum.order.type.noDeal) {
getNoDealList(params)(dispatch, getState);
} else if (type === Enum.order.type.history) {
getHistoryList(params)(dispatch, getState);
} else if (type === Enum.order.type.detail) {
getDetailList(params)(dispatch, getState);
}
}
};
}
/**
* 更新一级tab类型
*/
export function updateType(type) {
return (dispatch, getState) => {
dispatch({
type: OrderActionType.UPDATE_ORDER_TYPE,
data: type
});
getOrderList({ page: 1 })(dispatch, getState);
};
}
/**
* 更新二级 周期间隔
*/
export function updatePeriodInterval(type) {
return (dispatch, getState) => {
dispatch({
type: OrderActionType.UPDATE_ORDER_PERIOD_INTERVAL,
data: type
});
getOrderList({ page: 1 })(dispatch, getState);
};
}
/**
* 隐藏其他币对
*/
export function updateHideOthers(isHide) {
return (dispatch, getState) => {
dispatch({
type: OrderActionType.UPDATE_HIDE_OTHERS,
data: isHide
});
getOrderList({ page: 1 })(dispatch, getState);
};
}
/**
* 隐藏已撤销
*/
export function updateHideOrders(isHide) {
return (dispatch, getState) => {
dispatch({
type: OrderActionType.UPDATE_HIDE_ORDERS,
data: isHide
});
// const symbol = isHide ? getState().SpotTrade.symbol : 'all';
getHistoryList()(dispatch, getState);
};
}
/**
* 更新二级委托类型
*/
export function updateEntrustType(entrustType) {
return (dispatch, getState) => {
dispatch({
type: OrderActionType.UPDATE_ENTRUST_TYPE,
data: entrustType
});
getOrderList({ page: 1 })(dispatch, getState);
};
}
/**
* 撤销订单
*/
export function cancelOrder(params, successCallback, errCallback) {
return (dispatch, getState) => {
const { omchainClient } = getState().Common;
// const { senderAddr } = window.OM_GLOBAL; // senderAddr,
omchainClient.setAccountInfo(params.pk).then(() => {
omchainClient.sendCancelOrderTransaction(params.order_id).then((r) => {
if (r.result.code) {
errCallback && errCallback({ msg: r.result.error });
} else {
successCallback && successCallback(r.result);
const searchConditions = {
// start: params.start,
// end: params.end,
product: params.product,
side: params.side
};
getNoDealList(searchConditions)(dispatch, getState);
}
}, (e) => {
errCallback && errCallback(e);
});
}).catch((err) => {
Message.error({ content: err.message, duration: 3 });
errCallback && errCallback();
});
};
}
/**
* 当前币对全撤
*/
export function cancelAll() {
return (dispatch, getState) => {
const store = getState();
const { wsIsOnline } = store.Spot;
const { symbol, isMarginOpen, spotOrMargin } = store.SpotTrade;
const systemType = isMarginOpen ? spotOrMargin : Enum.spotOrMargin.spot;
const cancelAllUrl = URL.POST_CANCELALL_ORDER.replace('{0}', symbol).replace('{1}', systemType);
ont.delete(cancelAllUrl).then(() => {
// 只能发生在未成交普通委托情况下,会有推送
if (!wsIsOnline) {
getNoDealList()(dispatch, getState);
}
});
};
}
/**
* 推送数据更新普通未成交订单
*/
export function wsUpdateList(noDealObj) {
return (dispatch, getState) => {
const wsData = noDealObj;
const store = getState();
const {
type, entrustType, data, isHideOthers
} = store.OrderStore;// 隐藏其他币对
if (type !== Enum.order.type.noDeal || entrustType !== Enum.order.entrustType.normal) {
// 只在普通委托未成交下处理推送数据
return false;
}
if (typeof wsData === 'string') {
return false;
}
// noDealObj是后端返回的数组
// if (Object.prototype.toString.call(noDealObj) === '[object Object]' &&
// Object.keys(noDealObj).length > 0) {
// // 转换之后的数据如果是对象,则转换成数组
// wsData = [noDealObj];
// } else {
// return false;
// }
const { Open } = OrderStatus;
let currentData = [...data.orderList];
// 未成交列表中有数据
if (currentData && currentData.length) {
wsData.forEach((wsItem) => {
let idIsExist = false;
currentData.some((currentItem, currentIndex) => {
if (wsItem.order_id === currentItem.order_id) {
idIsExist = true;
// 部分成交、撤单中等其他状态,则直接数据覆盖更新状态
if ([Open].includes(wsItem.status.toString())) {
currentData[currentIndex] = wsItem;
} else { // 在未成交列表中,状态发生变化,变为"已撤销"或者"完全成交",则删除该条数据
currentData.splice(currentIndex, 1);
}
return true;
}
return false;
});
// 不在未成交列表中,且状态不是"已撤销"或者"完全成交",则插入该条数据
if (!idIsExist && [Open].includes(wsItem.status.toString())) {
currentData.unshift(wsItem);
}
});
} else {
// 未成交列表中没有数据
currentData = wsData.filter((wsItem) => {
return [Open].includes(wsItem.status.toString());
});
}
// 当隐藏其他币对勾选时,筛除其他币对
if (isHideOthers) {
const { product } = store.SpotTrade;
currentData = currentData.filter((item) => {
return item.product === product;
});
}
return dispatch({
type: OrderActionType.UPDATE_DATA,
data: {
orderList: currentData.splice(0, 20)
}
});
};
}
<file_sep>import React from 'react';
import moment from 'moment';
import { calc } from '_component/omit';
import Icon from '_src/component/IconLite';
import { toLocale } from '_src/locale/react-locale';
import { OrderStatus, OrderType } from '../../constants/OrderStatus';
const orderUtil = {
// 买卖方向类型
sideType: () => {
return {
1: toLocale('spot.buy'),
2: toLocale('spot.sell')
};
},
// 交易方向列表
sideList: () => {
return [{
value: 0,
label: toLocale('spot.buyAndSell')
}, {
value: 1,
label: toLocale('spot.buy')
}, {
value: 2,
label: toLocale('spot.sell')
}];
},
// 获取table空数据时的样式
getEmptyContent: () => {
return (
<div className="flex-column" style={{ alignItems: 'center', color: 'rgba(255, 255, 255, 0.45)' }}>
<Icon
className="icon-Nodeallist"
isColor
style={{ width: '48px', height: '48px' }}
/>
<div className="mar-top10">
{toLocale('spot.orders.noData')}
</div>
</div>
);
},
// 获取列配置
getColumns: (productObj, cancelHandler) => {
return [{
title: toLocale('spot.orders.date'),
key: 'createTime',
render: (text) => {
return (
<div className="date-str">
{moment(text).format('YYYY-MM-DD HH:mm:ss')}
</div>
);
}
}, {
title: toLocale('spot.orders.symbol'),
key: 'symbol',
render: (text) => { return text.toString().replace('_', '/').toUpperCase(); }
}, {
title: toLocale('spot.orders.type'),
key: 'systemType',
render: (text) => {
const intlId = Number(text) === 1 ? 'spot.orders.side.spot' : 'spot.orders.side.margin';
return (
<div style={{ minWidth: '45px' }}>
{ toLocale(intlId) }
</div>
);
}
}, {
title: <div style={{ minWidth: '30px' }}>{ toLocale('spot.orders.side2') }</div>,
key: 'side',
render: (text) => {
const colorClass = Number(text) === 1 ? 'primary-green' : 'primary-red';
return (
<label className={colorClass}>
{orderUtil.sideType()[text]}
</label>
);
}
}, {
title: toLocale('spot.orders.entrustMount'),
key: 'size',
render: (text) => {
return (
<div className="digits-str">
{text}
</div>
);
}
}, {
title: toLocale('spot.orders.orderType'),
key: 'orderType',
render: (text) => {
return <div className="order-option-str one-line">{toLocale(OrderType[text] || '')}</div>;
}
},
{
title: toLocale('spot.orders.entrustPrice'),
key: 'price',
render: (text, record) => {
if (Number(record.orderType) === 1) { // 市价
return toLocale('spot.market');
}
return (
<div className="digits-str">
{text}
</div>
);
}
}, {
title: toLocale('spot.orders.entrustMoney'),
key: 'total',
render: (text) => {
return (
<div className="digits-str">
{text}
</div>
);
}
}, {// 已成交
title: toLocale('spot.orders.dealt'),
key: 'filledSize',
render: (text) => {
return (
<div className="digits-str">
{text}
</div>
);
}
}, {
title: toLocale('spot.orders.dealAveragePrice'),
key: 'avgPrice',
render: (text) => {
return (
<div className="digits-str">
{text}
</div>
);
}
}, {
title: toLocale('spot.orders.status'),
key: 'status',
render: (text, record) => {
const { CANCELING, CANCELLED, COMPLETE_FILLED } = OrderStatus;
const { FAK, FOK } = OrderType;
return (
<div style={{ minWidth: '90px' }}>
{ toLocale(`spot.orders.${OrderStatus[text]}`) }
{
[CANCELING, CANCELLED, COMPLETE_FILLED].indexOf(record.status.toString()) > -1 ||
(productObj[record.symbol] && Number(productObj[record.symbol].tradingMode) === 2) ||
[FAK, FOK].includes(record.orderType.toString()) ? null :
<a
className="order-cancel"
onClick={cancelHandler(record.id, record.symbol)}
>
{ toLocale('spot.orders.cancel') }
</a>
}
</div>
);
}
}];
},
// 数据格式化
formatOrders: (orders, productList) => {
return orders.map((oriOrder) => {
const order = { ...oriOrder }; // 避免修改原始对象
const { orderType, side, symbol } = order;
// 获取当前币对配置
const currProduct = productList.filter((product) => { return product.symbol === symbol; })[0] || {};
const priceTruncate = currProduct.max_price_digit ? currProduct.max_price_digit : 2;
const sizeTruncate = 'max_size_digit' in currProduct ? currProduct.max_size_digit : 2;
// 价格、数量、金额、未成交
let price = '';
let size = '';
let total = '';
let notNealSize = 0;
if (Number(orderType) === 1) { // 市价
if (Number(side) === 1) { // 市价买入
size = '--';
total = calc.showFloorTruncation(order.quoteSize, priceTruncate);
} else { // 市价卖出
size = calc.showFloorTruncation(order.size, sizeTruncate);
total = '--';
}
notNealSize = 0;
} else { // 限价
price = order.price.replace(/,/g, '');
price = calc.showFloorTruncation(price, priceTruncate);
size = calc.showFloorTruncation(order.size, sizeTruncate);
total = calc.showFloorTruncation(calc.mul(order.size, order.price), priceTruncate);
notNealSize = order.size - order.filledSize;
}
notNealSize = calc.showFloorTruncation(notNealSize, sizeTruncate);
const baseCurr = order.symbol.split('_')[1].toUpperCase();
const tradeCurr = order.symbol.split('_')[0].toUpperCase();
order.size = size === '--' ? size : `${size} ${tradeCurr}`;
order.price = `${price} ${baseCurr}`;
order.total = total === '--' ? total : `${total} ${baseCurr}`;
order.notNealSize = notNealSize;
// 均价
let avgPrice = 0;
if (+order.filledSize !== 0) {
avgPrice = calc.div(order.executedValue, order.filledSize);
}
if (Number(side) === 1) {
order.avgPrice = `${calc.showFloorTruncation(avgPrice, priceTruncate)} ${baseCurr}`;
} else {
order.avgPrice = `${calc.showCeilTruncation(avgPrice, priceTruncate)} ${baseCurr}`;
}
// 成交数量
order.filledSize = `${calc.showFloorTruncation(order.filledSize, sizeTruncate)} ${tradeCurr}`;
return order;
});
}
};
export default orderUtil;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import InputNum from '_component/InputNum';
import Tooltip from 'rc-tooltip';
import { toLocale } from '_src/locale/react-locale';
import { calc } from '_component/omit';
import config from '_src/constants/Config';
import navigation from '../../utils/navigation';
import * as FormActions from '../../redux/actions/FormAction';
import StrategyTypeSelect from '../placeOrders/StrategyTypeSelect';
import FormatNum from '../../utils/FormatNum';
import Available from '../../component/placeOrder/Available';
import LegalPrice from '../../component/placeOrder/LegalPrice';
import QuoteIncrement from '../../component/placeOrder/QuoteIncrement';
import SubmitButton from '../../component/placeOrder/SubmitButton';
import TradeSliderBar from '../../component/TradeSliderBar';
import Enum from '../../utils/Enum';
import util from '../../utils/util';
function mapStateToProps(state) { // 绑定redux中相关state
const { SpotTrade, FormStore } = state;
const { product, currencyTicker, productObj } = SpotTrade;
const { inputObjFromDepth, inputObj } = FormStore;
return {
product,
inputObj,
currencyTicker,
inputObjFromDepth,
productObj
};
}
function mapDispatchToProps(dispatch) {
return {
formActions: bindActionCreators(FormActions, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class LimitForm extends React.Component {
static propTypes = {
asset: PropTypes.object
};
static defaultProps = {
asset: {}
};
constructor(props) {
super(props);
this.state = {
inputObj: { // 下单的input值(由原来的reducer移动到这里)
price: '',
amount: '',
total: ''
},
isLoading: false, // 下单按钮loading状态
warning: '', // 错误信息
};
this.formParam = {}; // 表单参数
}
componentDidMount() {
const {
currencyTicker, product, productObj, inputObjFromDepth
} = this.props;
const {
price, amount, total,
} = inputObjFromDepth;
const initPrice = (productObj && productObj[product]) ? productObj[product].price : 0;
let tickerPrice = 0;
if (currencyTicker) {
if (+currencyTicker.price === -1) {
tickerPrice = initPrice;
} else {
tickerPrice = currencyTicker.price;
}
}
this.updateInput({
price: tickerPrice
});
if (price || amount || total) {
this.updateInput({
price, amount, total
});
}
}
componentWillReceiveProps(nextProps) {
const {
product, productObj, currencyTicker, type, inputObjFromDepth
} = nextProps;
if (this.props.product !== product) { // 切换币对
this.clearForm();
this.updateWarning();
const initPrice = (productObj && productObj[product]) ? productObj[product].price : 0;
let tickerPrice = 0;
if (currencyTicker) {
if (+currencyTicker.price === -1) {
tickerPrice = initPrice;
} else {
tickerPrice = currencyTicker.price;
}
}
this.updateInput({
price: tickerPrice
});
}
if (this.props.type !== type) {
this.clearForm();
}
const {
price, amount, total,
} = inputObjFromDepth;
const { price: oldPrice, amount: oldAmount, total: oldTotal } = this.props.inputObjFromDepth;
if (price !== oldPrice || amount !== oldAmount || total !== oldTotal) {
const input = { ...inputObjFromDepth };
delete input.type;
this.clearForm();
this.updateWarning();
this.updateInput(inputObjFromDepth);
}
}
componentWillUnmount() {
this.props.formActions.updateDepthInput({
type: Enum.placeOrder.type.buy,
price: '',
amount: '',
total: '',
couponId: ''
});
}
// 价格Input失去焦点
onBlurPrice = () => {
const { productConfig } = window.OM_GLOBAL;
const priceTruncate = productConfig.max_price_digit;
const sizeTruncate = productConfig.max_size_digit;
const { inputObj } = this.state;
const input = { ...inputObj };
if (input.amount.trim().length > 0 && input.price.trim().length > 0) {
// 数量有值,重新计算总额
input.total = calc.ceilMul(input.amount, input.price, priceTruncate);
} else if (input.total.trim().length > 0 && input.price.trim().length > 0) {
// 总额有值,重新计算数量
input.amount = calc.floorDiv(input.total, input.price, sizeTruncate);
}
return this.updateInput(input);
};
// 输入改变
onInputChange = (key) => {
return (inputValue) => {
const { inputObj } = this.state;
const { productConfig } = window.OM_GLOBAL;
const input = { ...inputObj };
const priceTruncate = productConfig.max_price_digit || 4;
const sizeTruncate = productConfig.max_size_digit || 4;
// 当输入只有.的时候,切换为空
const value = inputValue === '.' ? '' : inputValue;
if (key === 'price') {
// 输入价格
input[key] = FormatNum.CheckInputNumber(value, priceTruncate);
if (String(input.amount).trim() !== '') {
// 存在数量,则计算总价
const total = calc.ceilMul(input.amount, input.price, priceTruncate);
if (total > 0) {
input.total = total;
} else {
input.total = '';
}
} else if (String(input.total).trim() !== '') {
// 存在总价,则计算数量
if (Number(input.price) > 0) {
const amount = calc.floorDiv(input.total, input.price, priceTruncate);
if (amount > 0) {
input.amount = amount;
} else {
input.amount = '';
}
}
}
} else if (key === 'amount') {
// 输入数量
input[key] = FormatNum.CheckInputNumber(value, sizeTruncate);
if (String(input.price).trim() !== '' && Number(input.price) !== 0) {
// 存在价格,则计算总价
const total = calc.ceilMul(input.amount, input.price, priceTruncate);
if (total > 0) {
input.total = total;
} else {
input.total = '';
}
}
} else if (key === 'total') {
// 输入总金额
input[key] = FormatNum.CheckInputNumber(value, sizeTruncate);
if (String(input.price).trim() !== '' && Number(input.price) !== 0) {
// 存在价格,则计算数量
const amount = calc.floorDiv(input.total, input.price, sizeTruncate);
if (amount > 0) {
input.amount = amount;
} else {
input.amount = '';
}
}
}
this.updateWarning(''); // 清空错误提示
this.updateInput(input); // 更新input值
};
};
// 拖动百分比sliderBar
onTradeSliderBarChange = (value) => {
const { productConfig } = window.OM_GLOBAL;
const { asset, type } = this.props;
const { baseAvailable, tradeAvailable } = asset;
const { inputObj } = this.state;
const newInputObj = { ...inputObj };
const barValue = calc.mul(value, 0.01);
// 精度有可能是0
const priceTruncate = 'max_price_digit' in productConfig ? productConfig.max_price_digit : 8;
const sizeTruncate = 'max_size_digit' in productConfig ? productConfig.max_size_digit : 8;
// 价格有值
if (newInputObj.price > 0) {
if (type === Enum.placeOrder.type.buy) { // 买单
if (baseAvailable === 0) {
return false;
}
// BTC数量 = USDT可用*百分比/价格
const currValue = calc.mul(baseAvailable, barValue);
newInputObj.amount = calc.floorDiv(currValue, newInputObj.price, sizeTruncate);
// USDT金额 = 价格 * 数量
newInputObj.total = calc.floorTruncate(currValue, priceTruncate);
} else { // 卖单
if (tradeAvailable === 0) {
return false;
}
// BTC数量 = BTC可用*百分比
const currValue = calc.mul(tradeAvailable, barValue);
newInputObj.amount = calc.floorTruncate(currValue, sizeTruncate);
// USDT金额 = 价格 * 数量
newInputObj.total = calc.floorMul(newInputObj.price, newInputObj.amount, priceTruncate);
}
} else {
return false;
}
newInputObj.total = newInputObj.total > 0 ? newInputObj.total : '';
newInputObj.amount = newInputObj.amount > 0 ? newInputObj.amount : '';
return this.updateInput(newInputObj);
};
// 提交表单
onOrderSubmit = () => {
const isLogin = util.isLogined();
if (!isLogin) {
navigation.import();
return false;
}
const { asset, type } = this.props;
const { updateWarning } = this;
const { inputObj, isLoading } = this.state;
if (isLoading) return false;
const {
baseCurr, baseAvailable,
tradeCurr, tradeAvailable,
} = asset;
const { productConfig } = window.OM_GLOBAL;
const { min_trade_size, max_price_digit } = productConfig;
const tradePrice = Number(inputObj.price);
const tradeAmount = Number(inputObj.amount);
const totalMoney = Number(inputObj.total);
let userBalance = 0;
if (type === Enum.placeOrder.type.buy) {
userBalance = baseAvailable;
}
if (type === Enum.placeOrder.type.sell) {
userBalance = tradeAvailable;
}
if (String(tradePrice).trim() === '' || tradePrice === 0) {
// 请输入交易价格
this.focus('price');
return updateWarning(toLocale('spot.place.tips.price'));
}
if (String(tradeAmount).trim() === '' || tradeAmount === 0) {
// 请输入交易数量
this.focus('amount');
return updateWarning(toLocale('spot.place.tips.amount'));
}
if (String(totalMoney).trim() === '' || totalMoney === 0) {
// 请输入交易总金额
this.focus('total');
return updateWarning(toLocale('spot.place.tips.total'));
}
if (type === Enum.placeOrder.type.buy) { // 买
// 资产 < 数量*价格
if (Number(userBalance) < calc.floorMul(tradePrice, tradeAmount, max_price_digit)) {
// 提示余额不足
return updateWarning(toLocale('spot.place.tips.money2'));
}
} else if (type === Enum.placeOrder.type.sell) { // 卖
if (Number(userBalance) < tradeAmount) {
// 提示交易货币余额不足
return updateWarning(toLocale('spot.place.tips.money2'));
}
}
// 最小交易数量
if (tradeAmount < Number(min_trade_size)) {
return updateWarning(`${toLocale('spot.place.tips.minsize') + min_trade_size} ${util.getSymbolShortName(tradeCurr)}`);
}
// 总交易金额(价格*数量)<=0 不能下单
if (totalMoney <= 0) {
return updateWarning(toLocale('spot.place.tips.greaterthan0'));
}
this.formParam = {
product: `${tradeCurr}_${baseCurr}`,
side: type,
price: tradePrice,
size: tradeAmount,
quoteSize: totalMoney,
orderType: 0 // 0表示限价单
};
updateWarning('');
this.setLoading(true);
return this.props.onSubmit(this.formParam, () => {
this.clearForm();
this.setLoading(false);
}, (res) => {
if (res && res.msg) {
this.updateWarning(res.msg);
}
this.setLoading(false);
});
};
// 获取sliderBar当前percent
getPercent = (baseAvailable, tradeAvailable) => {
let percent = 0;
const { productConfig } = window.OM_GLOBAL;
const { type } = this.props;
const { inputObj } = this.state;
const { total, amount } = inputObj;
const priceTruncate = 'max_price_digit' in productConfig ? productConfig.max_price_digit : 2;
const sizeTruncate = 'max_size_digit' in productConfig ? productConfig.max_size_digit : 2;
const truncatedBase = Number(calc.floorTruncate(baseAvailable, priceTruncate));
const truncatedTrade = Number(calc.floorTruncate(tradeAvailable, sizeTruncate));
if (type === Enum.placeOrder.type.buy) { // 买单,根据总金额计算百分比
percent = truncatedBase === 0 ? 0 : calc.div(Number(total), truncatedBase);
} else { // 卖单,根据数量计算百分比
percent = truncatedTrade === 0 ? 0 : calc.div(Number(amount), truncatedTrade);
}
percent = percent > 1 ? 1 : percent;
return Number((percent * 100).toFixed(2));
};
setLoading = (isLoading = false) => {
this.setState({ isLoading });
};
focus = (id = '') => {
const ele = document.querySelector(`input.limit-${id}`);
ele && ele.focus();
};
updateInput = (inputObj) => {
this.setState(Object.assign(this.state.inputObj, inputObj));
};
updateWarning = (warning = '') => {
this.setState({ warning });
};
clearForm = () => {
this.setState(Object.assign(this.state.inputObj, {
amount: '',
total: '',
couponID: ''
}));
};
// 渲染价格
renderPrice = () => {
const { tradeType } = window.OM_GLOBAL;
const { asset } = this.props;
const { inputObj } = this.state;
const price = inputObj.price === '--' ? '0' : inputObj.price;
const { baseCurr, tradeCurr } = asset;
let priceTitle = `${toLocale('spot.placeorder.pleaseEnter')
+ toLocale('spot.price')} (${baseCurr})`;
const isFullTrade = tradeType === Enum.tradeType.fullTrade;
if (!isFullTrade) {
priceTitle = (
<span className="input-title">
<Tooltip
placement="bottom"
overlay={<QuoteIncrement />}
>
<label className="detail">
{toLocale('spot.price')}
</label>
</Tooltip>
({baseCurr})
</span>
);
}
return (
<div className="spot-price input-container">
{isFullTrade ? null : priceTitle}
<InputNum
type="text"
onChange={this.onInputChange('price')}
onBlur={this.onBlurPrice}
value={price}
className="input-theme-controls limit-price"
placeholder={isFullTrade ? priceTitle : null}
/>
{config.needLegalPrice && <LegalPrice currency={tradeCurr} value={price} />}
</div>
);
};
// 渲染数量
renderAmount = () => {
const { tradeType, productConfig } = window.OM_GLOBAL;
const { asset } = this.props;
const { inputObj } = this.state;
const { tradeCurr } = asset;
const tradeSymbol = util.getSymbolShortName(tradeCurr);
let placeholder = `${toLocale('spot.placeorder.pleaseEnter')
+ toLocale('spot.amount')} (${tradeSymbol})`;
if (tradeType === Enum.tradeType.normalTrade) {
// 非全屏模式
placeholder = `${toLocale('spot.place.tips.minsize')}${productConfig.min_trade_size}${tradeSymbol}`;
}
return (
<div className="input-container">
{
tradeType === Enum.tradeType.normalTrade ?
<span className="input-title">{toLocale('spot.amount')} ({tradeSymbol})</span> : null
}
<InputNum
type="text"
onChange={this.onInputChange('amount')}
value={inputObj.amount}
className="input-theme-controls limit-amount"
placeholder={placeholder}
/>
</div>
);
};
// 渲染滑动条
renderSliderBar = () => {
const { asset, type } = this.props;
const { baseAvailable, tradeAvailable } = asset;
const isFullTrade = window.OM_GLOBAL.tradeType === Enum.tradeType.fullTrade;
const sliderColor = type === Enum.placeOrder.type.buy ? 'green' : 'red';
const percent = this.getPercent(baseAvailable, tradeAvailable);
return (
<TradeSliderBar
value={percent}
onChange={this.onTradeSliderBarChange}
theme={isFullTrade ? 'dark' : 'light'}
color={sliderColor}
/>
);
};
// 渲染总金额
renderTotal = () => {
const { tradeType } = window.OM_GLOBAL;
const { asset } = this.props;
const { inputObj } = this.state;
const { baseCurr } = asset;
return (
<div className="input-container">
{
tradeType === Enum.tradeType.normalTrade ?
<span className="input-title">
{toLocale('spot.total')} ({baseCurr})
</span> : null
}
<InputNum
type="text"
onChange={this.onInputChange('total')}
autoComplete="off"
value={inputObj.total}
className="input-theme-controls limit-total"
placeholder={
tradeType === Enum.tradeType.normalTrade ?
null : `${toLocale('spot.placeorder.pleaseEnter')
+ toLocale('spot.total')} (${baseCurr})`
}
/>
</div>
);
};
render() {
const { tradeType } = window.OM_GLOBAL;
const { needWarning, asset, type } = this.props;
const { isLoading, warning } = this.state;
const isFullTrade = tradeType === Enum.tradeType.fullTrade;
return (
<div className="spot-trade-limit">
<div className={isFullTrade ? '' : ''}>
<StrategyTypeSelect strategyType={Enum.placeOrder.strategyType.limit} />
{this.renderPrice()}
</div>
{this.renderAmount()}
{this.renderSliderBar()}
{this.renderTotal()}
<Available asset={asset} type={type} />
<SubmitButton
type={type}
unit={util.getSymbolShortName(asset.tradeCurr)}
isMargin={asset.isMargin}
isLoading={isLoading}
onClick={this.onOrderSubmit}
warning={needWarning ? warning : ''}
/>
</div>
);
}
}
export default LimitForm;
<file_sep>/**
* Created by zhaiyibo on 2018/1/15.
*/
import React from 'react';
import PropTypes from 'prop-types';
import Icon from '_src/component/IconLite';
import util from '_src/utils/util';
import './index.less';
const SortTypes = {
noSort: 'noSort',
asc: 'asc',
des: 'des'
};
export default class LeftMenu extends React.Component {
static propTypes = {
menuList: PropTypes.array,
listHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
listEmpty: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
searchPlaceholder: PropTypes.string,
searchBar: PropTypes.bool,
searchText: PropTypes.string,
subTitle: PropTypes.array,
activeId: PropTypes.string,
theme: PropTypes.string,
canStar: PropTypes.bool,
onSearch: PropTypes.func,
onSelect: PropTypes.func,
onClickStar: PropTypes.func
};
static defaultProps = {
menuList: [],
listHeight: 'auto',
listEmpty: '',
searchBar: false,
searchPlaceholder: 'search',
searchText: '',
subTitle: undefined,
activeId: '',
theme: '',
canStar: false,
onSearch: null,
onSelect: null,
onClickStar: null
};
constructor(props) {
super(props);
this.state = {
menuList: props.menuList,
sortType: SortTypes.noSort,
activeId: props.activeId
};
}
componentWillReceiveProps(nextProps) {
// const { sortType } = this.state;
const { menuList, activeId } = nextProps;
// const newList = [...menuList];
// if (sortType === SortTypes.noSort) {
// newList.sort((a, b) => { return (a.text).localeCompare(b.text); });
// } else if (sortType === SortTypes.asc) {
// newList.sort((a, b) => { return parseFloat(a.changePercentage) - parseFloat(b.changePercentage); });
// } else if (sortType === SortTypes.des) {
// newList.sort((a, b) => { return parseFloat(b.changePercentage) - parseFloat(a.changePercentage); });
// }
this.setState({
menuList,
activeId
});
}
// 模糊搜索
handleSearchChange = (e) => {
const args = e.target.value;
if (this.props.onSearch) {
this.props.onSearch(args);
return false;
}
const allList = this.props.menuList;
const filterList = allList.filter((item) => {
return [args.toLowerCase(), args.toUpperCase()].includes(item.text);
});
this.setState({
menuList: filterList
});
return false;
};
// 排序
handleSort = () => {
const { sortType, menuList } = this.state;
const newList = [...menuList];
let newSortType = SortTypes.noSort;
if (sortType === SortTypes.asc) { // 升序切换为降序
newList.sort((a, b) => { return parseFloat(b.changePercentage) - parseFloat(a.changePercentage); });
newSortType = SortTypes.des;
} else if (sortType === SortTypes.des) { // 降序切换为默认
newList.sort((a, b) => { return (a.text).localeCompare(b.text); });
newSortType = SortTypes.noSort;
} else { // 默认切换为升序
newList.sort((a, b) => { return parseFloat(a.changePercentage) - parseFloat(b.changePercentage); });
newSortType = SortTypes.asc;
}
this.setState({
sortType: newSortType,
menuList: newList
});
};
// 收藏/取消收藏
handleStar = (item) => {
return (e) => {
e.preventDefault();
e.stopPropagation();
const { onClickStar } = this.props;
if (onClickStar) {
onClickStar(!item.stared, item);
}
};
};
// 选中菜单项
handleSelect = (item) => {
return () => {
const { onSelect } = this.props;
if (onSelect) {
onSelect(item);
}
};
};
// 渲染list
renderList = (menuList) => {
const { canStar } = this.props;
const { activeId } = this.state;
return (
<div>
{
menuList.map((item, index) => {
const {
id, stared, text, change, changePercentage, lever
} = item;
const color = change.toString().indexOf('-') > -1 ? 'red' : 'green';
return (
<li
key={index}
className={id === activeId ? 'active' : ''}
onClick={this.handleSelect(item)}
>
<span
style={{ display: canStar ? 'block' : 'none' }}
onClick={this.handleStar(item)}
>
<Icon className={stared ? 'icon-Star' : 'icon-Star-o'} />
</span>
<label className="pair">{util.getShortName(text)}</label>
{lever ? <span className="lever"><span>{lever}X</span></span> : null}
<label className={`change change-${color}`}>{changePercentage}</label>
</li>
);
})
}
</div>
);
};
renderEmpty = () => {
const { listEmpty } = this.props;
return (
<div className="empty-container">
{listEmpty}
</div>
);
};
render() {
const {
searchPlaceholder, searchBar, subTitle, title, style,
searchText, listHeight, theme
} = this.props;
let pair = '';
let change = '';
if (subTitle && subTitle.length) {
pair = subTitle[0];
change = subTitle[1];
}
const { menuList, sortType } = this.state;
const ascSort = sortType === SortTypes.asc;
const desSort = sortType === SortTypes.des;
const haveData = menuList && menuList.length > 0;
const hasScroll = menuList && menuList.length > 9;
const themeClass = theme || '';
return (
<div className={`om-left-menu ${themeClass} ${hasScroll ? 'has-scroll' : ''}`} style={style}>
{searchBar ?
<div className="list-search">
<div className="search-wrap">
{/* debug-chrome自动记住用户名 */}
<input type="text" style={{ display: 'none' }} />
<input
type="text"
autoComplete="off"
value={searchText}
placeholder={searchPlaceholder}
onChange={this.handleSearchChange}
className="input-theme-controls"
/>
<Icon className="icon-search" />
</div>
</div> : null}
<div className={`${searchBar ? '' : 'top-border'} list-container`}>
{title}
{subTitle ?
<div className="list-head">
<div className="head-left">{pair}</div>
<div className="head-right" onClick={this.handleSort}>
<span>{change}</span>
<span className="change-icons">
<Icon className={`${ascSort ? 'active' : ''} icon-retract`} />
<Icon className={`${desSort ? 'active' : ''} icon-spread`} />
</span>
</div>
</div> : null}
<ul className="list-main" style={{ height: listHeight }}>
{haveData ? this.renderList(menuList) : this.renderEmpty()}
</ul>
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import { calc } from '_component/omit';
import ont from '../utils/dataProxy';
import URL from '../constants/URL';
import Enum from '../utils/Enum';
const util = {
getSupportLocale(lang) {
if (lang.toLowerCase().indexOf('cn') === -1) {
return 'en_US';
}
return 'zh_CN';
},
getChangePercentage(ticker) {
if (!ticker) {
return '+0.00%';
}
if (!ticker.open) {
return '+0.00%';
}
if (+ticker.price === -1) {
return '+0.00%';
}
const changePercent = calc.floorDiv(calc.sub(ticker.price, ticker.open) * 100, ticker.open, 2);
const changeSignStr = changePercent >= 0 ? '+' : '';
return `${changeSignStr}${changePercent}%`;
},
getShortName(paramProduct) {
let product = paramProduct;
if (!product) {
return '';
}
if (product.split('_').length === 2) {
product = product.toUpperCase().replace('_', '/');
}
if (product.split('/').length === 2) {
const [baseSymbol, quoteSymbol] = product.split('/');
return `${baseSymbol.split('-')[0]}/${quoteSymbol.split('-')[0]}`;
}
return product;
},
getSymbolShortName(symbol) {
if (!symbol) {
return '';
}
if (symbol.split('-').length > 1) {
return symbol.split('-')[0];
}
return symbol;
},
getMyToken() {
const tok = window.localStorage.getItem('dex_token');
if (tok) {
return tok;
}
return '';
},
generateMergeType(num) {
let s = '0.';
if (num > 0) {
for (let i = 0; i < num - 1; i++) {
s += '0';
}
s += '1';
} else {
s = '0.0001';
}
return s;
},
getMyAddr() {
let addr = '';
try {
const user = JSON.parse(window.localStorage.getItem('dex_user') || '{}');
addr = (user && user.addr) ? user.addr : '';
} catch (e) {
console.warn(e.message);
// throw e;
}
return addr;
},
doLogout() {
window.localStorage.removeItem('dex_user');
window.localStorage.removeItem('dex_token');
window.localStorage.removeItem('dex_legalCurrencyId');
},
isWsLogin() {
const tok = window.localStorage.getItem('dex_token');
if (tok && util.isLogined()) {
return true;
}
return false;
},
isLogined() {
const user = window.localStorage.getItem('dex_user');
if (user) {
try {
const userObj = JSON.parse(user) || {};
if (userObj.addr || userObj.address) {
window.OM_GLOBAL.isLogin = true;
}
} catch (e) {
window.OM_GLOBAL.isLogin = false;
}
} else {
window.OM_GLOBAL.isLogin = false;
}
return window.OM_GLOBAL.isLogin;
},
// js生成文件,下载
downloadObjectAsJson(exportObj, exportName) {
const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(exportObj))}`;
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute('href', dataStr);
downloadAnchorNode.setAttribute('download', `${exportName}.txt`);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
},
// IE11判断
lessThanIE11() {
const UA = navigator.userAgent;
const isIE = UA.indexOf('MSIE') > -1;
const v = isIE ? /\d+/.exec(UA.split(';')[1]) : 11;
return v < 11;
},
objToQueryString(obj) {
if (!obj) {
return '';
}
const str = [];
Object.keys(obj).forEach((key) => {
str.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
});
return str.join('&');
},
getQueryHashString(name) {
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
const r = window.location.hash.substr(1).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
}
return '';
},
timeStampToTime(timestamp) {
const date = timestamp.toString().length === 10 ? new Date(timestamp * 1000) : new Date(timestamp);
const Y = `${date.getFullYear()}-`;
const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}-`;
const D = `${date.getDate() < 10 ? (`0${date.getDate()}`) : date.getDate()} `;
const h = `${date.getHours() < 10 ? (`0${date.getHours()}`) : date.getHours()}:`;
const m = `${date.getMinutes() < 10 ? (`0${date.getMinutes()}`) : date.getMinutes()}:`;
const s = (date.getSeconds() < 10 ? (`0${date.getSeconds()}`) : date.getSeconds());
return Y + M + D + h + m + s;
},
// 数组转对象
arrayToObj(arr, keyName) {
const result = {};
arr.forEach((item) => {
result[item[keyName]] = item;
});
return result;
},
getCountByTime(timestamp) {
let sec = timestamp / 1000;
if (sec >= 3600) {
const hours = Math.floor(sec / 3600);
if (sec % 3600 === 0) {
return `${hours > 10 ? hours : `0${hours}`}:00:00`;
}
sec %= 3600;
if (sec >= 60) {
const min = Math.floor(sec / 60);
if (sec % 60 === 0) {
return `${hours > 10 ? hours : `0${hours}`}:${min > 10 ? min : `0${min}`}:00`;
}
sec = (timestamp / 1000) - (hours * 3600) - (min * 60);
return `${hours > 10 ? hours : `0${hours}`}:${min > 10 ? min : `0${min}`}:${sec >= 10 ? sec : `0${sec}`}`;
}
return `${hours > 10 ? hours : `0${hours}`}:00:${sec >= 10 ? sec : `0${sec}`}`;
} else if (sec >= 60) {
if (sec % 60 === 0) {
const min = Math.floor(sec / 60);
return `${min > 10 ? min : `0${min}`}:00`;
}
const i = Math.floor(sec / 60);
const j = sec % 60;
return `${i >= 10 ? i : `0${i}`}:${j >= 10 ? j : `0${j}`}`;
}
return `00:${sec >= 10 ? sec : `0${sec}`}`;
},
// ctrl or tab
ctrlAorTab(e) {
// control-17;tab-9;
if (e != null && (e.keyCode === 17 || e.keyCode === 9)) {
return true;
}
// ctrl + A A-65
return (e != null && e.ctrlKey && e.keyCode === 65);
},
cloneDeep(obj) {
return JSON.parse(JSON.stringify(obj));
},
isEmpty(obj) {
return Object.keys(obj).length === 0;
},
// 函数防抖
debounce(fn, delay = 200) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
};
},
// 函数节流
throttle(fn, delay = 200) {
let timer = null;
return (...args) => {
if (!timer) {
timer = setTimeout(() => {
fn(...args);
clearTimeout(timer);
}, delay);
}
};
},
addColor(text) {
let colorClass = '';
let textShown = text;
const num = Number(text);
// text为0则不添加颜色
if (num > 0) {
colorClass = 'primary-green';
textShown = `+${calc.thousandFormat(text)}`;
}
if (num < 0) {
colorClass = 'primary-red';
textShown = calc.thousandFormat(text);
}
return <label className={colorClass}>{textShown}</label>;
},
logRecord() { // 当前页面打log
if (window.location.hostname.indexOf('local') === -1) { // 本地就不发log了
ont.post(URL.LOG_RECORD, { c_url: window.location.href }).catch(() => {});
}
},
getTheme() {
return localStorage.getItem('theme') === Enum.themes.theme2 ? 'dark' : '';
},
precisionInput(num) {
return Number(num).toFixed(8);
}
};
export default util;
<file_sep>import { storage } from '_component/omit';
import NodeActionType from '../actionTypes/NodeActionType';
/* eslint-disable */
/**
* 更新当前节点
*/
export function updateCurrenntNode(node) {
return (dispatch) => {
storage.set('currentNode', node);
dispatch({
type: NodeActionType.UPDATE_CURRENT_NODE,
data: node,
});
};
}
export function updateRemoteList(list) {
return (dispatch) => {
dispatch({
type: NodeActionType.UPDATE_REMOTE_LIST,
data: list,
})
}
}
<file_sep>import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import Reducer from '../reducers';
export default function configureStore() {
let store = null;
// 生产环境下不需要调试
if (process.env.NODE_ENV === 'production') {
store = createStore(Reducer, compose(applyMiddleware(thunk)));
} else {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
store = createStore(Reducer, composeEnhancers(applyMiddleware(thunk)));
}
return store;
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../IconLite';
import './Button.less';
import BaseButton from './BaseButton';
import { SIZE, TYPE } from './constants';
export default class Button extends React.PureComponent {
static propTypes = {
/** 设置按钮载入状态。引用该组件的工程中需要有 icon-Loading 图标 */
loading: PropTypes.bool,
/** 设置按钮为圆形 */
circle: PropTypes.bool,
/** 设置按钮的图标 图标需在引用该组件的工程中含有 */
icon: PropTypes.string,
/** 外部传入类,用于覆写样式 */
className: PropTypes.string,
/** 设置按钮大小,可选值为 mini small large default 请从Button.SIZE中选择 */
size: PropTypes.oneOf([SIZE.default, SIZE.mini, SIZE.small, SIZE.large]),
};
static defaultProps = {
loading: false,
circle: false,
icon: '',
className: '',
size: SIZE.default,
};
render() {
const {
loading, circle, icon, className, size, children, ...attr
} = this.props;
const loadingIcon = loading ? <Icon className="icon-Loading loading-icon btn-icon" /> : null;
const customerIcon = icon && icon.length !== 0 && !loading ? <Icon className={`btn-icon ${icon}`} /> : null;
return (
<BaseButton
{...attr}
loading={loading}
className={
classNames(
`size-${size}`,
{ circle },
{ [`circle-${size}`]: circle },
{ 'circle-icon': circle && !children },
className
)
}
>
{loadingIcon}
{customerIcon}
{
(loadingIcon || customerIcon) && children ? <span className="btn-content">{children}</span> : children
}
</BaseButton>
);
}
}
Button.btnType = TYPE;
Button.size = SIZE;
Button.TYPE = TYPE;
Button.SIZE = SIZE;
<file_sep>/*
* 相关数据格式化
*/
export default class FormatNum {
/*
* 添加千分位,支持负数
*/
static NumAddDot(n) {
let newN = n.toString();
let lessThan0 = false;
if (newN.indexOf('-') === 0) {
lessThan0 = true;
newN = newN.substring(1);
}
const re = /\d{1,3}(?=(\d{3})+$)/g;
const n1 = newN.replace(/^(\d+)((\.\d+)?)$/, (s, s1, s2) => { return s1.replace(re, '$&,') + s2; });
return lessThan0 ? `-${n1}` : n1;
}
/*
* 保留小数多少位
*/
static CheckInputNumber = (inputValue, precision) => {
const valueArray = inputValue.toString().replace(/\s+/g, '').split('.');
if (valueArray.length > 1) {
return `${valueArray[0].replace(/\D/g, '')}.${valueArray[1].replace(/\D/g, '').slice(0, precision)}`;
}
return valueArray[0].replace(/\D/g, '');
};
/*
* 数字转字符串
*/
static formatNumber2String = (num) => {
const str = String(num);
let retStr = '';
if (str.indexOf('.') >= 0) {
let appendix = '';
const len = 8 - str.split('.')[1].length;
for (let i = 0; i < len; i++) {
appendix += '0';
}
retStr = str + appendix;
} else {
retStr += `${str}.00000000`;
}
return retStr;
};
/**
* 哈希值简写,前10位,后6位
* @param hash
*/
static hashShort = (hash = '') => {
return hash.replace(/^(.{10}).*(.{6})$/, '$1...$2');
};
/**
* 手续费加空格
* @param hash
*/
static formatFeeStr = (feeStr = '') => {
if (!feeStr) {
return '';
}
const arr = /(\d*\.*\d*)\s*(\w*)/.exec(feeStr);
return `${arr[1]} ${arr[2]}`;
};
}
<file_sep># TradeSliderBar组件
### 用法
```sh
import TradeSliderBar from '../../components/tradeSliderBar/TradeSliderBar';
<TradeSliderBar
value={10.12}
color={'green'}
theme={'dark'}
onChange={foo}
/>
```
### Notice
Prop|Explain|默认值
-|-|-
value | 当前值 | 0
color | 颜色(大部分情况用于区分买/卖) 'green' or 'red' | green
theme | 主题 'light' or 'dark' | light
onChange | 回调参数为百分值,不含'%', 即0~100 | 无
<file_sep>import WalletActionType from '../actionTypes/WalletActionType';
const initialState = {
isShowSafeTip: true, // 在Step2加载时,是否自动出现下载Keystore的安全提示
isPass: true, // 助记词校验状态
step: 1, // 创建钱包-当前步骤
mnemonic: '', // 助记词
privateKey: '', // 私钥
keyStore: '', // keyStore
};
export default function reducer(state = initialState, action) {
switch (action.type) {
// 更新创建钱包-当前步骤
case WalletActionType.UPDATE_CREATE_STEP:
return {
...state,
step: action.data
};
// 更新助记词校验状态
case WalletActionType.UPDATE_IS_PASS:
return {
...state,
isPass: action.data
};
// 更新是否显示安全提示
case WalletActionType.UPDATE_IS_SHOW_SAFE_TIP:
return {
...state,
isShowSafeTip: action.data
};
// 更新助记词
case WalletActionType.UPDATE_MNEMONIC:
return {
...state,
mnemonic: action.data
};
// 更新私钥
case WalletActionType.UPDATE_PRIVATE:
return {
...state,
privateKey: action.data
};
// 更新keystore
case WalletActionType.UPDATE_KEYSTORE:
return {
...state,
keyStore: action.data
};
default:
return state;
}
}
<file_sep>import hirestime from 'hirestime';
import { storage } from '_src/component/omit';
import { MAX_LATENCY, NODE_TYPE } from '_constants/Node';
const TIMEOUT = 2000;
export const getDelayType = (delayTime) => {
let delayType;
if (delayTime === MAX_LATENCY) {
delayType = NODE_TYPE.UNREACHABLE;
} else if (delayTime > 150) {
delayType = NODE_TYPE.HIGH;
} else {
delayType = NODE_TYPE.LOW;
}
return delayType;
};
export const setcurrentNode = (node) => {
storage.set('currentNode', node);
window.location.reload();
};
export const getNodeLatency = (node) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(MAX_LATENCY);
}, TIMEOUT);
const { wsUrl } = node;
const connection = new window.WebSocketCore({ connectUrl: wsUrl });
let getElapsed;
connection.onSocketError(() => {
resolve(MAX_LATENCY);
});
connection.onSocketConnected(() => {
connection.sendChannel('ping');
getElapsed = hirestime();
});
connection.setPushDataResolver(() => {
const pingTime = getElapsed && getElapsed();
connection.disconnect();
resolve(pingTime);
});
connection.connect();
});
};
<file_sep>import OrderActionTypes from '../actionTypes/OrderActionType';
import Enum from '../../utils/Enum';
const initialState = {
type: Enum.order.type.noDeal, // 一级tab类型 未成交 or 历史委托
periodIntervalType: Enum.order.periodInterval.oneDay,
isHideOthers: true, // 是否勾选"隐藏其他币对",
isHideOrders: false, // 是否勾选"隐藏已撤销",
entrustType: Enum.order.entrustType.normal, // 二级委托类型 普通、计划、跟踪。。。
data: { // table数据展示
isLoading: false,
orderList: [],
page: {
page: 1, // 当前页码
per_page: 20,
total: 0
}
}
};
export default function reducer(state = initialState, action) {
switch (action.type) {
// 更新一级tab类型
case OrderActionTypes.UPDATE_ORDER_TYPE:
return {
...state,
type: action.data
};
// 更新二级 周期间隔
case OrderActionTypes.UPDATE_ORDER_PERIOD_INTERVAL:
return {
...state,
periodIntervalType: action.data
};
// 更新是否勾选"隐藏其他币对"
case OrderActionTypes.UPDATE_HIDE_OTHERS:
return {
...state,
isHideOthers: action.data
};
// 更新是否勾选"隐藏已撤单"
case OrderActionTypes.UPDATE_HIDE_ORDERS:
return {
...state,
isHideOrders: action.data
};
// 更新二级委托类型
case OrderActionTypes.UPDATE_ENTRUST_TYPE:
return {
...state,
entrustType: action.data
};
// 更新table数据
case OrderActionTypes.UPDATE_DATA:
return {
...state,
data: {
...state.data,
...action.data
}
};
default:
return state;
}
}
<file_sep>/**
* 状态弹框
* Created by yuxin.zhang on 2018/9/1.
*/
import React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import Icon from '../IconLite';
import Dialog from './Dialog';
import './PromptDialog.less';
const typeIcon = {
error: 'icon-close',
warn: 'icon-exclamation',
prompt: 'icon-remind',
info: 'icon-info',
success: 'icon-check'
};
const PromptDialogType = {
confirm: 'confirm',
prompt: 'prompt'
};
const PromptInfoType = {
error: 'error',
warn: 'warn',
prompt: 'prompt',
info: 'info',
success: 'success'
};
export default class PromptDialog extends React.PureComponent {
static propTypes = {
/** 提示弹框的类型 可从 PromptDialog.dialogType枚举中选择:confirm:双按钮 prompt:单按钮 */
dialogType: PropTypes.string,
/** 提示弹信息的类型 PromptDialog.infoType枚举中选择: error:错误/失败 warn:警告 prompt:提示 info:说明 success:成功 */
infoType: PropTypes.string,
/** 标题 */
title: PropTypes.string,
/** 标题列表 适用于多行标题的情况 */
titleList: PropTypes.array,
/** 文案:标题下方解释说明性文字 */
text: PropTypes.string,
/** 文本列表 适用于多行文本的情况 */
textList: PropTypes.array,
/** 确认按钮文案 */
confirmText: PropTypes.string,
/** 确认按钮回调 */
onConfirm: PropTypes.func,
/** 取消按钮文案 dialogType=confirm 使用 */
cancelText: PropTypes.string,
/** 取消按钮回调 dialogType=confirm 使用 */
onCancel: PropTypes.func,
};
static defaultProps = {
dialogType: PromptDialogType.prompt,
infoType: PromptInfoType.prompt,
title: '',
titleList: [],
text: '',
textList: [],
confirmText: '',
cancelText: '',
onConfirm: null,
onCancel: null
};
onConfirm = () => {
const { onConfirm } = this.props;
return onConfirm && onConfirm();
};
onCancel = () => {
const { onCancel, onClose } = this.props;
if (onCancel) {
return onCancel();
}
onClose && onClose();
return null;
};
render() {
const {
dialogType, infoType, title, titleList, text, textList,
cancelText,
...attr
} = this.props;
const newTitleList = title && title.length !== 0 ? [title] : titleList || [];
const newTextList = text && text.length !== 0 ? [text] : textList || [];
return (
<Dialog
{...attr}
cancelText={dialogType === PromptDialog.dialogType.confirm ? cancelText : null}
onConfirm={this.onConfirm}
onCancel={this.onCancel}
>
<div className="prompt-dialog-content">
<div className={`icon-bg ${infoType}-bg`}>
<Icon className={`prompt-icon ${typeIcon[infoType]}`} />
</div>
{
newTitleList.map((item, index) => {
return <div className="prompt-title" key={`tip_title${index}`}>{item}</div>;
})
}
{
newTextList.map((item, index) => {
return <div className="prompt-text" key={`tip_text${index}`}>{item}</div>;
})
}
</div>
</Dialog>
);
}
}
function create(config) {
const div = document.createElement('div');
document.body.appendChild(div);
function destroy() {
const unmountResult = ReactDOM.unmountComponentAtNode(div);
if (unmountResult && div.parentNode) {
div.parentNode.removeChild(div);
}
}
function close() {
destroy();
if (config.onClose) {
config.onClose();
}
}
function cancel() {
destroy();
if (config.onCancel) {
config.onCancel();
}
}
let currentConfig = {
...config, visible: true, onCancel: cancel, onClose: close
};
function render(props) {
ReactDOM.render(<PromptDialog {...props} />, div);
}
function update(newConfig) {
currentConfig = {
...currentConfig,
...newConfig,
};
render(currentConfig);
}
render(currentConfig);
return {
destroy,
update
};
}
PromptDialog.create = create;
PromptDialog.infoType = PromptInfoType;
PromptDialog.dialogType = PromptDialogType;
<file_sep>/*
* @Descripttion: 获取当前设备类型
* @LastEditors: 翟懿博
*/
import mediaSet from '../mediaSet';
const getMedia = () => {
let result = mediaSet._sm;
const orderList = ['xl', 'lg', 'md', 'sm'];
orderList.some((mediaType) => {
const currentMedia = mediaSet[`_${mediaType}`];
if (window.matchMedia(currentMedia.query).matches) {
result = currentMedia;
return true;
}
return false;
});
return result;
};
export default getMedia;
<file_sep>import React from 'react';
import OrderHeaderWrapper from '../../wrapper/SpotOrderHeaderWrapper';
import Enum from '../../utils/Enum';
const OrderHeader = (props) => {
const { type, dataSource, onTabChange } = props;
const { tradeType } = window.OM_GLOBAL;
let headerContainerCls = '';
if (tradeType === Enum.tradeType.normalTrade) {
headerContainerCls = 'tab-heads';
} else if (tradeType === Enum.tradeType.fullTrade) {
headerContainerCls = 'full-trade-order-head';
}
return (
<div className={`clear-fix ${headerContainerCls}`}>
<ul className="tabs clear-fix">
{/* 币币页面去掉,全屏页面保留 from PM张博 */}
{/* {tradeType === Enum.tradeType.fullTrade ? `(${noDeal.length > 20 ? 20 : noDeal.length})` : null} */}
{
dataSource.map(({ type: headerType, name }) => {
return (
<li
key={headerType}
className={type === headerType ? 'active' : ''}
onClick={onTabChange(headerType)}
>
{name}
</li>
);
})
}
</ul>
{props.children}
{/* orderPageLink */}
</div>
);
};
export default OrderHeaderWrapper(OrderHeader);
<file_sep>import React from 'react';
import Tabs, { TabPane } from 'rc-tabs';
import { toLocale } from '_src/locale/react-locale';
import Icon from '_src/component/IconLite';
import Message from '_src/component/Message';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import { calc } from '_component/omit';
import { wsV3, channelsV3 } from '../../utils/websocket';
import Enum from '../../utils/Enum';
import util from '../../utils/util';
import './FullTradeProductList.less';
import LeftMenu from '../../component/leftMenu';
import Introduce from '../../component/kline/Introduce';
import FullTradeProductListTab from './FullTradeProductListTab';
import * as SpotActions from '../../redux/actions/SpotAction';
import PageURL from '../../constants/PageURL';
function mapStateToProps(state) { // 绑定redux中相关state
const {
wsIsOnlineV3, wsErrCounterV3, tickers, activeMarket // , searchText
} = state.Spot;
const {
groupList, productList, product, productObj, isMarginOpen, spotOrMargin, favorites
} = state.SpotTrade;
// let myProductList = productList;
// yao 未登录时使用本地数据
// if (!window.OM_GLOBAL.isLogin) {
// myProductList = productList.map((item) => {
// const isLocalCollect = localCollects.includes(item.productId);
// return {
// ...item,
// collect: isLocalCollect ? 1 : item.collect,
// };
// });
// }
return {
wsIsOnlineV3,
wsErrCounterV3,
groupList,
productList,
tickers,
activeMarket,
// searchText,
product,
productObj,
isMarginOpen,
spotOrMargin,
favorites,
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class FullTradeProductList extends React.Component {
constructor(props) {
super(props);
this.state = {
activeMarket: props.activeMarket,
// searchText: '',
isShowList: false, // false,
isShowProduction: false
};
this.canStar = true; // 收藏可用标志
}
componentDidMount() {
const { wsIsOnlineV3 } = this.props;
if (wsIsOnlineV3) {
this.startWs();
}
}
componentWillReceiveProps(nextProps) {
const { spotActions } = this.props;
/* ws状态变化相关 */
const newWsIsOnline = nextProps.wsIsOnlineV3;
const oldWsIsOnline = this.props.wsIsOnlineV3;
// ws首次连接或者重连成功
if (!oldWsIsOnline && newWsIsOnline) {
this.startWs();
}
const oldWsErrCounter = this.props.wsErrCounterV3;
const newWsErrCounter = nextProps.wsErrCounterV3;
// ws断线
if (newWsErrCounter > oldWsErrCounter) {
// 获取所有币对行情
spotActions.fetchTickers();
}
/* 自身显隐 */
if (this.state.isShowList) {
return false;
}
return false;
}
componentWillUnmount() {
const { wsIsOnlineV3 } = this.props;
if (wsIsOnlineV3) {
this.stopWs();
}
}
// 获取当前交易区币对列表
getCurrListByArea = (productList, activeMarket) => {
const { groupId } = activeMarket;
return productList.filter((item) => {
return item.groupIds.includes(groupId);
});
};
// 显示菜单
showList = () => {
this.setState({
isShowList: true // false
});
};
// 隐藏菜单
hideList = () => {
this.setState({
isShowList: false // false
});
};
// 显示币种介绍
showProduction = () => {
this.setState({
isShowProduction: true
});
};
// 隐藏币种介绍
hideProduction = () => {
this.setState({
isShowProduction: false
});
};
// 改变交易区
// handleMarketChange = (market) => {
// return () => {
// this.setState({
// searchText: '',
// activeMarket: market
// });
// };
// };
// 模糊搜索
// handleSearch = (e) => {
// this.setState({
// searchText: e.target.value
// });
// };
// 切换币对
handleSelectMenu = (item) => {
// const newSymbol = item.text.replace('/', '_').toLowerCase();
const { spotActions } = this.props;
const product = item.product;
let urlLink = `${PageURL.spotFullPage}#product=${product.toLowerCase()}`;
if (window.OM_GLOBAL.isMarginType) {
urlLink = `${PageURL.spotFullMarginPage}#product=${product.toLowerCase()}`;
}
if (this.state.activeMarket.groupId === -1) {
this.props.history.replace(`${urlLink}&favorites=1`);
} else {
this.props.history.replace(urlLink);
}
spotActions.updateActiveMarket(this.state.activeMarket);
spotActions.updateProduct(product);
this.hideList();
};
// 收藏
handleClickStar = (isStared, item) => {
const { spotActions } = this.props;
if (this.canStar) {
this.canStar = false;
const product = {
productId: item.productId,
collect: isStared ? 1 : 0,
symbol: item.symbol
};
spotActions.collectProduct(product)
.catch((res) => {
if (res && res.msg) {
Message.error({ content: res.msg });
}
})
.then(() => {
this.canStar = true;
});
}
};
// 本地收藏
handleClickFavorite = (item) => {
const { isFavorite, product } = item;
const { spotActions, favorites } = this.props;
if (!isFavorite) {
spotActions.updateFavoriteList([...favorites, product]);
} else {
const dList = util.cloneDeep(favorites);
const list = dList.filter((l) => {
return l !== product;
});
spotActions.updateFavoriteList(list);
}
}
// 开启ws订阅
startWs = () => {
wsV3.send(channelsV3.getAllMarketTickers());
};
// 停止ws订阅
stopWs = () => {
// 停止订阅所有币行情,即ticker
wsV3.stop(channelsV3.getAllMarketTickers());
};
filterGroupList = () => {
const { groupList, spotOrMargin } = this.props;
const { webTypes, webType } = window.OM_GLOBAL;
if (webType !== webTypes.OMCoin || spotOrMargin === Enum.spotOrMargin.spot) {
return groupList;
}
return groupList.filter((g) => {
return g.marginCount > 0;
});
};
// 杠杆标识
renderMarginTip = () => {
const { productConfig } = window.OM_GLOBAL;
const { isMarginOpen } = this.props;
if (isMarginOpen) {
return <span className="margin-x">{productConfig.maxMarginLeverage}X</span>;
}
return null;
};
render() {
const {
tickers, productList, product, favorites, // productObj,
} = this.props;
const {
isShowList, isShowProduction, // searchText, activeMarket
} = this.state;
// const currList = this.getCurrListByArea(productList, activeMarket);
let activeId = product ? product.toUpperCase().replace('_', '/') : '';
// const menuList = currList.map((item) => {
// const productIterative = item.product; // item.symbol;
// const pair = productIterative.toUpperCase().replace('_', '/');
// if (!activeId) {
// activeId = pair;
// }
// let change = 0;
// let changePercentage = '--';
// let volume = '--';
// const currTicker = tickers[productIterative];
// const initPrice = (productObj && productObj[productIterative]) ? productObj[productIterative].price : 0;
// let price = '--';
// if (currTicker) {
// if (+currTicker.price === -1) { // -1表示从未成交
// price = initPrice;
// } else {
// price = currTicker.price;
// }
// change = currTicker.change;
// changePercentage = currTicker.changePercentage;
// volume = currTicker.volume;
// }
// const {
// productId, collect, isMarginOpen, maxMarginLeverage
// } = item;
// const max_price_digit = item.max_price_digit || 4;
// const [symbol] = productIterative.split('_');
// const [shortToken] = symbol.split('-');
// return {
// ...item,
// id: productIterative.toUpperCase().replace('_', '/'),
// price: (price !== '--') ? calc.showFloorTruncation(price, max_price_digit) : '--',
// volume: (volume !== '--') ? calc.showFloorTruncation(volume, 0) : '--',
// productId,
// product: item.product,
// text: pair,
// change,
// changePercentage,
// shortToken,
// stared: Number(collect) == 1,
// lever: isMarginOpen ? maxMarginLeverage : false,
// listDisplay: item.listDisplay // list_display存在且为1则隐藏
// };
// }).filter((item) => {
// let filterTag = true;
// // 搜索到了显示
// if (searchText.trim() !== '') {
// filterTag = item.shortToken.indexOf(searchText.trim().toLowerCase().toString()) > -1;
// }
// return filterTag;
// }).sort((itemA, itemB) => {
// const sortKey = `productSort${activeMarket.groupId}`;
// return itemA[sortKey] - itemB[sortKey];
// });
let favoriteList = [];
// const notFavoriteList = [];
const tabList = productList.map((item) => {
const productIterative = item.product; // item.symbol;
const pair = productIterative.toUpperCase().replace('_', '/');
const isFavorite = favorites.some((fav) => {
return fav === item.product;
});
if (!activeId) {
activeId = pair;
}
let change = 0;
let changePercentage = '--';
const currTicker = tickers[productIterative];
if (currTicker) {
change = currTicker.change;
changePercentage = currTicker.changePercentage;
}
const [symbol] = productIterative.split('_');
const [shortToken] = symbol.split('-');
const exItem = {
...item,
changePercentage,
text: pair,
change,
id: productIterative.toUpperCase().replace('_', '/'),
shortToken,
isFavorite,
};
if (isFavorite) {
favoriteList.push(exItem);
}
return exItem;
});
favoriteList = favorites.map((fav) => {
return favoriteList.find((item) => {
return fav === item.product;
});
}).filter((item) => {
return !!item;
});
const listEmpty = toLocale('spot.noData');
// langForRaw
return (
<div className="full-product-list">
<span
className="current-symbol"
onMouseEnter={this.showList}
onMouseLeave={this.hideList}
>
<em>{util.getShortName(product)}</em>
{this.renderMarginTip()}
<a className="down-arrow" />
<div className="product-list-container-new" style={{ display: isShowList ? 'block' : 'none' }}>
<Tabs defaultActiveKey="1" prefixCls="product-list-tab">
<TabPane tab={toLocale('productList.favorite')} key="1">
<FullTradeProductListTab
tabList={favoriteList}
type={FullTradeProductListTab.TYPE.FAVORITE}
searchType={FullTradeProductListTab.SEARCH_TYPE.TOKEN}
activeId={activeId}
onSelect={this.handleSelectMenu}
onFavorite={this.handleClickFavorite}
/>
</TabPane>
<TabPane tab={toLocale('productList.owner')} key="2">
<FullTradeProductListTab
tabList={tabList}
type={FullTradeProductListTab.TYPE.NORMAL}
searchType={FullTradeProductListTab.SEARCH_TYPE.OWNER}
activeId={activeId}
onSelect={this.handleSelectMenu}
onFavorite={this.handleClickFavorite}
/>
</TabPane>
<TabPane tab={toLocale('productList.token')} key="3">
<FullTradeProductListTab
tabList={tabList}
type={FullTradeProductListTab.TYPE.NORMAL}
searchType={FullTradeProductListTab.SEARCH_TYPE.TOKEN}
activeId={activeId}
onSelect={this.handleSelectMenu}
onFavorite={this.handleClickFavorite}
/>
</TabPane>
</Tabs>
</div>
{/* ZCHTODO:删掉原来的product-list-container */}
{/* style={{ display: isShowList ? 'block' : 'none' }} */}
{/* <div className="product-list-container" style={{ display: 'none' }}>
<div className="search-bar">
<input
placeholder={toLocale('search')}
onChange={this.handleSearch}
value={searchText}
/>
<Icon className="icon-search" />
</div>
<div className="product-list">
<div className="trad-area">
<ul className="spot-head-tab">
<li className="market-label" style={{ cursor: 'default', height: '26px', lineHeight: '26px' }}>
{ toLocale('spot.marketDict') }
</li>
{
this.filterGroupList().map((market) => {
const { groupId, groupName, groupKey } = market;
return (
<li
key={groupId}
className={groupId === activeMarket.groupId ? 'active' : ''}
onClick={this.handleMarketChange(market)}
>
{groupKey ? toLocale(groupKey) : groupName}
</li>
);
})
}
</ul>
</div>
<LeftMenu
subTitle={[toLocale('pair'), toLocale('change')]}
searchPlaceholder={toLocale('search')}
menuList={menuList}
listHeight={360}
listEmpty={listEmpty}
activeId={activeId}
canStar={false}
theme="dark"
onSelect={this.handleSelectMenu}
onClickStar={this.handleClickStar}
/>
</div>
</div> */}
</span>
<span
onMouseEnter={this.showProduction}
onMouseLeave={this.hideProduction}
style={{ position: 'relative' }}
>
<Icon
className="icon-annotation-night"
isColor
style={{ width: '16px', height: '16px', marginBottom: '-3px' }}
/>
<div style={{ display: isShowProduction ? 'block' : 'none' }} className="production-container-outer">
<div
className="production-container"
>
<Introduce />
</div>
</div>
</span>
</div>);
}
}
export default FullTradeProductList;
<file_sep>/*
* @Descripttion: 媒体设备配置,供JS使用
* @LastEditors: 翟懿博
*/
const mediaSet = {
_sm: {
media: 'sm',
query: '(max-width: 767px)',
gutter: 16,
colCount: 4,
bodyPadding: 8
},
_md: {
media: 'md',
preMedia: 'sm',
query: '(min-width: 768px)',
gutter: 24,
colCount: 12,
bodyPadding: 12
},
_lg: {
media: 'lg',
preMedia: 'md',
query: '(min-width: 1024px)',
gutter: 24,
colCount: 12,
bodyPadding: 12,
contentWidth: 960
},
_xl: {
media: 'xl',
preMedia: 'lg',
query: '(min-width: 1280px)',
gutter: 24,
colCount: 12,
bodyPadding: 12,
contentWidth: 1248
}
};
export default mediaSet;
<file_sep>import Icon from '_src/component/IconLite';
import { toLocale } from '_src/locale/react-locale';
import React from 'react';
import PropTypes from 'prop-types';
import Cookies from 'js-cookie';
// import { calc } from '_component/omit';
import DepthTooltip from './DepthTooltip';
import './DepthList.less';
import DepthBar from '../../utils/DepthBar';
import EnumUtil from '../../utils/Enum';
import util from '../../utils/util';
const Enum = {
dark: 'dark',
up: 'up',
down: 'down',
buy: EnumUtil.placeOrder.type.buy,
sell: EnumUtil.placeOrder.type.sell,
};
export default class DepthList extends React.Component {
constructor(props) {
super(props);
this.state = {
sellIndex: -1,
buyIndex: -1,
isShowMergeList: false
};
}
// 组件再次render后,深度数据已经渲染,此时再进行垂直居中计算
componentDidUpdate(prevProps) {
let needToCenter = false; // 是否需要居中
const prevData = prevProps.dataSource;
const nowData = this.props.dataSource;
try {
// 上一次dataSource为空,且本次有数据,则认为需要重新居中
if (!prevData.sellList.length && !prevData.buyList.length) {
if (nowData.sellList.length || nowData.buyList.length) {
needToCenter = true;
}
}
// 如果需要居中,则判断是否出现滚动条,若有滚动条,则进行滚动居中操作
if (needToCenter) {
this.tickerCloneDom.style.visibility = 'hidden';
// 出现滚动条的情况
if (this.scrollDom.scrollHeight > this.scrollDom.clientHeight) {
this.toCenter();
}
}
} catch (e) {
//
}
}
// 合并系数over
onMergeTypeOver = () => {
this.setState({
isShowMergeList: true
});
};
// 合并系数out
onMergeTypeOut = () => {
this.setState({
isShowMergeList: false
});
};
// 选择某个合并系数
setChooseMergeType = (key) => {
return () => {
this.setState({
isShowMergeList: false
});
const { onChooseMergeType } = this.props;
onChooseMergeType && onChooseMergeType(key);
};
};
// ticker居中
// toCenter = () => {
// const { centerBarDom, scrollDom } = this;
// scrollDom.scrollTop = centerBarDom.offsetTop
// - (scrollDom.clientHeight / 2)
// + (centerBarDom.clientHeight / 2);
// };
// 浮点转'X'位小数
floatToXDecimal = (originFloat) => {
const tempStr = originFloat.toString();
let intlId = 'spot.xDecimal';
let preStr = '';
switch (tempStr) {
case '0.1':
preStr = 1;
intlId = 'spot.singleDecimal';
break;
case '1':
preStr = '0';
break;
case '10':
intlId = 'spot.10Decimal';
break;
case '100':
intlId = 'spot.100Decimal';
break;
case '1000':
intlId = 'spot.1000Decimal';
break;
case '10000':
intlId = 'spot.10000Decimal';
break;
default:
preStr = tempStr.length - (tempStr.indexOf('.') + 1);
break;
}
const locale = util.getSupportLocale(Cookies.get('locale') || 'en_US');
if (locale && locale.indexOf('ko') > -1) { // 韩国站单独特殊处理
if (Number(tempStr) < 10) {
preStr = tempStr;
intlId = 'spot.xDecimal';
}
}
return (
<span className="spot-depth-desc">
{preStr}
{toLocale(intlId)}
</span>
);
};
// 手动设置事件
// 滚动事件,改变ticker clone状态
scrollToPosition = (position) => {
const { scrollDom, tickerDom, tickerCloneDom } = this;
const cloneStyle = tickerCloneDom.style;
const maxScrollPx = tickerDom.offsetTop;
const minScrollPx = tickerDom.offsetTop - scrollDom.clientHeight + tickerDom.clientHeight;
if (position === 'top') { // ticker clone置顶
scrollDom.scrollTop = maxScrollPx;
} else if (position === 'bottom') { // ticker clone置底
scrollDom.scrollTop = minScrollPx;
} else if (position === 'center') { // ticker 居中
this.toCenter();
} else {
cloneStyle.visibility = 'hidden';
}
};
/*
scrollToPosition = (position) => {
const { scrollDom, centerBarDom, tickerCloneDom } = this;
const cloneStyle = tickerCloneDom.style;
const maxScrollPx = centerBarDom.offsetTop;
const minScrollPx = centerBarDom.offsetTop - scrollDom.clientHeight + centerBarDom.clientHeight;
if (position === 'top') { // ticker clone置顶
scrollDom.scrollTop = maxScrollPx;
} else if (position === 'bottom') { // ticker clone置底
scrollDom.scrollTop = minScrollPx;
} else if (position === 'center') { // ticker 居中
this.toCenter();
// scrollDom.scrollTop = centerBarDom.offsetTop - (scrollDom.clientHeight / 2) + (centerBarDom.clientHeight / 2);
} else {
cloneStyle.visibility = 'hidden';
}
};
// 滚动事件,改变ticker clone状态
handleScrollForTickerClone = () => {
const { scrollDom, centerBarDom, tickerCloneDom } = this;
const cloneStyle = tickerCloneDom.style;
const maxScrollPx = centerBarDom.offsetTop - 28;
if (scrollDom.scrollTop > maxScrollPx) { // ticker clone置底
cloneStyle.bottom = 0;
cloneStyle.top = 'unset';
cloneStyle.visibility = 'visible';
} else if (scrollDom.scrollTop == 0) { // ticker clone置顶
cloneStyle.bottom = 'unset';
cloneStyle.top = 0;
cloneStyle.visibility = 'visible';
} else { // ticker clone隐藏
cloneStyle.visibility = 'hidden';
}
}; */
// 滚动事件,改变ticker clone状态
handleScroll = () => {
const { scrollDom, tickerDom, tickerCloneDom } = this;
const cloneStyle = tickerCloneDom.style;
const maxScrollPx = tickerDom.offsetTop;
const minScrollPx = tickerDom.offsetTop - scrollDom.clientHeight + tickerDom.clientHeight;
if (scrollDom.scrollTop > maxScrollPx) { // ticker clone置顶
cloneStyle.top = 0;
cloneStyle.bottom = 'unset';
cloneStyle.visibility = 'visible';
} else if (scrollDom.scrollTop < minScrollPx) { // ticker clone置底
cloneStyle.bottom = 0;
cloneStyle.top = 'unset';
cloneStyle.visibility = 'visible';
} else { // ticker clone隐藏
cloneStyle.visibility = 'hidden';
}
};
// ticker居中
toCenter = () => {
const { tickerDom, scrollDom } = this;
scrollDom.scrollTop = tickerDom.offsetTop
- (scrollDom.clientHeight / 2)
+ (tickerDom.clientHeight / 2);
};
// 点击某条数据
handleClickItem = (index, type) => {
return () => {
const { selectItem } = this.props;
selectItem && selectItem(index, type);
};
};
render() {
const { sellIndex, buyIndex } = this.state;
const {
needSum, needBgColor, dataSource, style, columnTitle, toCenterLabel, theme, product
} = this.props;
const { sellList, buyList, ticker } = dataSource;
const trendClass = ticker.trend === Enum.down ? 'down' : 'up';
const iconClass = `icon-${trendClass}`;
const isDark = theme === Enum.dark;
const containerClass = isDark ? 'om-depth-container-dark' : 'om-depth-container';
// 全屏交易需要widthBar
const median = needBgColor ? DepthBar.medianUnit(sellList, buyList) : 0; // 返回没有逗号,不需要再判断
// const config = window.OM_GLOBAL.productConfig;
// const { mergeType, mergeTypes } = config;
//
// const defaultMerge = (mergeTypes && mergeTypes.split) ? mergeTypes.split(',')[0] : EnumUtil.defaultMergeType;
// const { isShowMergeList } = this.state;
// const allMerge = (mergeTypes && mergeTypes.split) ? mergeTypes.split(',') : EnumUtil.defaultMergeTypes;
// const currMergeType = mergeType || defaultMerge;
return (
<div
className={containerClass}
style={style}
// ref={(dom) => {
// if (dom) {
// this.scrollDom = dom.parentElement.parentElement;
// this.scrollDom.onscroll = this.handleScrollForTickerClone;
// }
// }}
>
<div className="title">
{columnTitle.map((item, index) => {
return <span key={`om-depth-title${index}`}>{item}</span>;
})}
</div>
<div className="scroll-container">
<div
className="scroll-box"
ref={(dom) => {
this.scrollDom = dom;
}}
onScroll={this.handleScroll}
>
<ul className="sell-list">
{sellList.map((item, index) => {
const {
price, amount, amountValue, sum, tooltipSum, tooltipTotal, tooltipAvg
} = item;
let barWidth = 0;
if (needBgColor) {
barWidth = `${DepthBar.width(amount.replace(/,/, ''), median)}%`;
}
return (
<DepthTooltip
key={`om-depth-sell-tooltip-${index}`}
tooltipAvg={tooltipAvg}
tooltipTotal={tooltipTotal}
tooltipSum={tooltipSum}
placement={isDark ? 'right' : 'left'}
symbol={product}
align={{
offset: isDark ? [6, -10] : [-10, -10],
}}
>
<li
key={`om-depth-sell-${index}`}
className={`sell-item ${sellIndex > -1 && index >= sellIndex ? 'has-bg' : ''}`}
onClick={this.handleClickItem(index, Enum.sell)}
onMouseEnter={() => { this.setState({ sellIndex: index }); }}
onMouseLeave={() => { this.setState({ sellIndex: -1 }); }}
>
<span>{price}</span>
<span>{amountValue < 0.001 ? '0.001' : amount}</span>
{needSum && <span>{sum}</span>}
{needBgColor && <div className="process-bar" style={{ width: barWidth }} />}
</li>
</DepthTooltip>
);
})}
</ul>
{/* <div
className="center-bar"
ref={(dom) => {
this.centerBarDom = dom;
}}
> */}
{/* 行情 */}
<div
className={`${trendClass} ticker`}
ref={(dom) => {
this.tickerDom = dom;
}}
>
<span>{(ticker.price === undefined || ticker.price === 'NaN') ? '-- ' : ticker.price}</span>
<Icon className={iconClass} />
</div>
{/* 合并深度
<div
className="spot-depth-drop"
style={{ display: this.props.isShowMerge ? 'block' : 'none' }}
onMouseOver={this.onMergeTypeOver}
onMouseOut={this.onMergeTypeOut}
>
{this.floatToXDecimal(currMergeType)}
<Icon className="icon-spread" />
<div
className="spot-depth-drop-list"
style={{ display: isShowMergeList ? 'block' : 'none' }}
>
{
allMerge.map((x, index) => {
return (
<p
onClick={this.setChooseMergeType(x)}
key={index.toString() + x}
>
{this.floatToXDecimal(x)}
</p>
);
})
}
</div>
</div> */}
{/* </div> */}
<ul className="buy-list">
{buyList.map((item, index) => {
const {
price, amount, amountValue, sum, tooltipSum, tooltipTotal, tooltipAvg
} = item;
let barWidth = 0;
if (needBgColor) {
barWidth = `${DepthBar.width(amount.replace(/,/, ''), median)}%`;
}
return (
<DepthTooltip
key={`om-depth-buy-tooltip-${index}`}
tooltipAvg={tooltipAvg}
tooltipTotal={tooltipTotal}
tooltipSum={tooltipSum}
placement={isDark ? 'right' : 'left'}
symbol={product}
align={{
offset: isDark ? [6, 8] : [-10, 10],
}}
>
<li
key={`om-depth-buy-${index}`}
className={`buy-item ${buyIndex > -1 && index <= buyIndex ? 'has-bg' : ''}`}
onClick={this.handleClickItem(index, Enum.buy)}
onMouseEnter={() => { this.setState({ buyIndex: index }); }}
onMouseLeave={() => { this.setState({ buyIndex: -1 }); }}
>
<span>{price}</span>
<span>{amountValue < 0.001 ? '0.001' : amount}</span>
{needSum && <span>{sum}</span>}
{
needBgColor && <div className="process-bar" style={{ width: barWidth }} />
}
</li>
</DepthTooltip>
);
})}
</ul>
</div>
{/* 行情clone(动态浮动) */}
{/* (this.scrollDom && (this.scrollDom.scrollHeight > this.scrollDom.clientHeight)) */}
<div
className={`${trendClass} ticker-clone`}
ref={(dom) => {
this.tickerCloneDom = dom;
}}
>
<span>{ticker.price}</span>
<Icon className={iconClass} />
<div
className="return-center"
onClick={this.toCenter}
>
{toCenterLabel}
</div>
</div>
</div>
</div>
);
}
}
DepthList.defaultProps = {
isShowMerge: true,
onChooseMergeType: null,
dataSource: {
sellList: [],
buyList: [],
ticker: {
price: '--',
trend: Enum.up
}
},
style: {},
columnTitle: [],
selectItem: null,
toCenterLabel: '返回盘口',
theme: ''
};
DepthList.propTypes = {
isShowMerge: PropTypes.bool,
onChooseMergeType: PropTypes.func,
dataSource: PropTypes.object,
style: PropTypes.object,
columnTitle: PropTypes.array,
selectItem: PropTypes.func,
toCenterLabel: PropTypes.string,
theme: PropTypes.string
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import * as ReactDOM from 'react-dom';
import Icon from '../IconLite';
import './Message.less';
const prefixCls = 'om-ui-message';
// Message 类型
const MessageType = {
success: 'success',
info: 'info',
warn: 'warn',
error: 'error',
loading: 'loading',
};
// 类型对应图标
const typeIcon = {
error: 'icon-close-circle',
warn: 'icon-exclamation-circle',
info: 'icon-info-circle',
success: 'icon-check-circle',
loading: 'icon-Loading',
};
// 当前展示中的Message的列表
let messageList = [];
let messageCount = 0;
// 全局通用配置
let globalConfig = {
top: 16,
duration: 3,
maxCount: 10
};
// 从 messageList 移除对应的Message销毁方法和定时器ID
function removeMessageFromList(id) {
const newList = [];
let aimItem = null;
messageList.forEach((item) => {
if (item.messageId === id) {
aimItem = item;
} else {
newList.push(item);
}
});
// 停止定时器
aimItem && aimItem.destroyClockId && clearTimeout(aimItem.destroyClockId);
// 从列表移除
messageList = newList;
// 返回移除的项 可用于销毁
return aimItem;
}
export default class Message extends React.PureComponent {
static propTypes = {
/** 提示内容 */
content: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 是否显示辅助图标 */
showIcon: PropTypes.bool,
/** 提示的样式,有四种选择,存在Message.Type中的常量:success、info、warn、error、loading */
type: PropTypes.string,
/** 自动关闭的延时,单位秒。设为 0 时不自动关闭。 */
duration: PropTypes.number,
/** 关闭后触发的回调函数 */
onClose: PropTypes.func,
};
static defaultProps = {
content: '',
showIcon: true,
type: MessageType.info,
duration: 3,
onClose: null,
};
render() {
const { showIcon, content, type } = this.props;
return (
<div className={`${prefixCls}-box`}>
{
showIcon && <Icon className={`${prefixCls}-icon ${typeIcon[type]} ${type}`} />
}
{
content && <span className={`${prefixCls}-text`}>{content}</span>
}
</div>
);
}
}
function create(conf) {
// 当前message的唯一标志
const messageId = ++messageCount;
// 当前配置
let currentConfig = conf;
// 用于销毁的定时器的ID
let destroyClockId = null;
// 获取所有Message的父容器
let parentContainer = document.getElementsByClassName(prefixCls)[0];
// 没有 则创建所有Message的父容器
if (!parentContainer) {
parentContainer = document.createElement('div');
parentContainer.className = prefixCls;
// 设置据顶端的高度
parentContainer.style.top = globalConfig.top;
document.body.appendChild(parentContainer);
}
// 创建当前Message的用于挂载的容器 并挂载到父容器
const container = document.createElement('div');
container.className = `${prefixCls}-container`;
parentContainer.appendChild(container);
function destroy() {
// 已进入销毁流程 如果存在销毁定时 则清除定时器并从定时器列表中移除
removeMessageFromList(messageId);
// 添加移除动画
container.className += ' container-remove';
// 延时等动画完毕再移除
setTimeout(() => {
const unmountResult = ReactDOM.unmountComponentAtNode(container);
if (unmountResult && container.parentNode) {
container.parentNode.removeChild(container);
}
if (conf.onClose) {
conf.onClose();
}
}, 500);
}
function render(props) {
ReactDOM.render(<Message {...props} />, container);
}
function update(newConfig) {
currentConfig = {
...currentConfig,
...newConfig,
};
render(currentConfig);
}
render(currentConfig);
// 有延时 怎延时自动关闭
if (conf.duration !== 0) {
destroyClockId = setTimeout(() => {
destroy();
}, Number(conf.duration || globalConfig.duration) * 1000);
}
// 将新Message 存入列表
messageList.push({ messageId, destroyClockId, destroy });
// 如果数量多于10的时候 清除第一个
if (messageList.length >= globalConfig.maxCount) {
const message = removeMessageFromList(messageList[0].messageId);
message.destroy();
}
return {
destroy,
update
};
}
// 销毁所有显示的Message
function destroyAll() {
// 移除message的根父容器
const parentContainer = document.getElementsByClassName(prefixCls)[0];
parentContainer && parentContainer.parentNode.removeChild(parentContainer);
// 清除所有定时器
messageList.forEach((item) => {
clearTimeout(item.destroyClockId);
});
messageList = [];
}
// 全局配置
function config(conf) {
globalConfig = Object.assign(globalConfig, conf);
}
Message.config = config;
Message.create = create;
Message.destroyAll = destroyAll;
Message.TYPE = MessageType;
<file_sep>// const zh_CN = {
// borrow: '借',
// needBorrow: '需借 ',
// repay: '還',
// ensure: '確定',
// cancel: '取消',
// 'spot.noData': '暫無數據',
// search: '搜索',
// pair: '幣對',
// change: '漲幅',
// /* spot */
// 'spot.all': '全部',
// 'spot.asset': '資產',
// 'spot.asset.marginTrade': 'X杠桿交易',
// 'spot.asset.spotTrade': '幣幣交易',
// 'spot.asset.futureTrade': '合約交易',
// 'spot.asset.ava': '可用',
// 'spot.asset.borrow': '已借',
// 'spot.asset.freeze': '凍結',
// 'spot.asset.risk': '風險率',
// 'spot.asset.forceClose': '爆倉價',
// 'spot.asset.interest': '利息',
// 'spot.asset.deposit': '充{currency}',
// 'spot.asset.transfer': '轉入資產',
// 'spot.asset.transferSuccess': '劃入成功',
// 'spot.asset.borrowBill': '借幣',
// 'spot.asset.goBorrow': '去借幣',
// 'spot.asset.borrowBillSuccess': '借幣成功',
// 'spot.asset.repayBill': '還幣',
// 'spot.asset.repayBillSuccess': '還幣成功',
// /* spot.bills */
// 'spot.bills.coin': '幣種',
// 'spot.bills.tradeDate': '成交時間',
// 'spot.bills.tradeType': '類型',
// 'spot.bills.tradeAmount': '數量',
// 'spot.bills.balance': '余額',
// 'spot.bills.fee': '手續費',
// 'spot.bills.clearTips': '為了提升系統性能,我們會根據空間情況,定期清除部分用戶3個月前的歷史數據。',
// 'spot.coin': '幣種',
// 'spot.marketDict': '市場',
// 'spot.favorites': '自選',
// /* spot.margin */
// 'spot.margin.marginTips1': '杠桿交易使得投資者可以投資更大規模資產,預期收益和風險被同步放大,用戶存在爆倉並損失自有資產的風險。投資者應當正確認識此風險,謹慎投資,量力而行。',
// 'spot.margin.marginTips2': '我已閱讀並同意',
// 'spot.margin.marginTips2-2': '的',
// 'spot.margin.marginTips3': '《借幣業務用戶使用協議》',
// 'spot.margin.marginTips4': '並同意開通“幣幣杠桿交易”業務我已知曉此風險並確認開通。',
// 'spot.margin.activate': '開通杠桿協議',
// 'spot.margin.safe': '安全',
// 'spot.margin.risk': '風險',
// 'spot.margin.forceliq': '已爆倉',
// 'spot.margin.borrow': '借幣',
// 'spot.margin.repay': '還幣',
// 'spot.margin.long': '看漲',
// 'spot.margin.short': '看跌',
// 'spot.margin.marginBorrow': 'X杠桿可借',
// 'spot.margin.dailyRate': '日利率',
// 'spot.margin.borrowAmount': '借入數量',
// 'spot.margin.repayAmount': '應還數量',
// 'spot.margin.loanAmount': '借貸數量',
// 'spot.maring.interest': '利息',
// 'spot.margin.amountRepay': '還幣數量',
// 'spot.margin.avaRepay': '可還',
// 'spot.margin.repayAll': '全部還幣',
// 'spot.margin.noLoanTips': '借款数量不能大于您的可借数量',
// 'spot.margin.noBorrowAmountTips': '借幣數量不能為空',
// 'spot.margin.borrowLessThanTips': '借幣數量必須大於0',
// 'spot.margin.noRepayAmountTips': '還幣數量不能為空',
// 'spot.margin.repayLessThanTips': '還幣數量不能大於您的可還數量',
// 'spot.margin.transferBalanceTip': '您的{symbol}杠桿賬戶余額不足,需轉入資產方可進行杠桿交易',
// 'spot.margin.transferRiskTip': '您的{symbol}杠桿賬戶風險率過低,請轉入資產降低風險',
// 'spot.margin.needMore': '如需使用杠桿交易買賣更多幣,請完成借幣操作',
// 'spot.margin.borrowAction': '借入',
// 'spot.margin.borrowAvailable': '可借',
// 'spot.margin.borrowAll': '全部借入',
// /* spot.market */
// 'spot.market.more': '查看更多',
// 'spot.market.orders': '交易信息',
// 'spot.menu.market.orders': '幣幣委托',
// 'spot.menu.market.bills': '幣幣賬單',
// 'spot.menu.market.currencyIntro': '幣種介紹',
// 'spot.menu.market.marginIntro': '杠桿解釋說明',
// 'spot.menu.market.history': '借幣歷史記錄',
// 'spot.menu.market.strategy': '策略委托說明',
// /* spot.orders */
// 'spot.bills.spot': '幣幣賬單',
// 'spot.bills.margin': '幣幣杠桿賬單',
// 'spot.orders.currencies': '幣對',
// 'spot.orders.types': '過濾器',
// 'spot.orders.last2': '最近兩天',
// 'spot.orders.2daysago': '兩天以前',
// 'spot.search': '查詢',
// 'spot.orders.allOrders': '全部掛單',
// 'spot.orders.amount': '數量',
// 'spot.orders.averPrice': '平均成交價',
// 'spot.orders.cancel': '撤單',
// 'spot.orders.cancelled': '已撤銷',
// 'spot.orders.canceling': '撤單中',
// 'spot.orders.cancelAll': '全撤',
// 'spot.orders.date': '委托時間',
// 'spot.orders.filled': '成交數量',
// 'spot.orders.completeFilled': '完全成交',
// 'spot.orders.noorders': '您暫時沒有未完成訂單',
// 'spot.orders.noorders2day': '您最近兩天沒有已成交的歷史掛單',
// 'spot.orders.noorders2dayago': '您兩天以前沒有已成交的歷史掛單',
// 'spot.orders.more': '查看更多',
// 'spot.orders.open': '尚未成交',
// 'spot.orders.openOrders': '未成交委託',
// 'spot.orders.oneDay': '1天',
// 'spot.orders.oneWeek': '1周',
// 'spot.orders.oneMonth': '1月',
// 'spot.orders.threeMonth': '3月',
// 'spot.orders.unfinished': '未成交',
// 'spot.orders.orderHistory': '歷史委托',
// 'spot.orders.partialFilled': '部分成交',
// 'spot.orders.price': '價格',
// 'spot.orders.side': '類別',
// 'spot.orders.side.spot': '幣幣',
// 'spot.orders.side.margin': '杠桿',
// 'spot.orders.source': '訂單來源',
// 'spot.orders.status': '狀態',
// 'spot.orders.operation': '操作',
// 'spot.orders.tips.datepicker': '請選擇開始日期或結束日期',
// 'spot.orders.tips.dateRange': '結束日期必須晚於開始日期',
// 'spot.orders.title': '幣幣委托',
// 'spot.orders.total': '金額',
// 'spot.orders.type': '類型',
// 'spot.orders.symbol': '幣對',
// 'spot.orders.side2': '方向',
// 'spot.orders.toast.unhis': '歷史委托暫不支持全部查詢,請選擇幣對後進行查詢',
// 'spot.orders.historyRecord': '隱藏交易對',
// 'spot.orders.historyRescinded': '隱藏已撤銷',
// 'spot.orders.dealAveragePrice': '成交均價',
// 'spot.orders.dealt': '已成',
// 'spot.orders.entrustMoney': '委託金額',
// 'spot.orders.entrustPrice': '委託價',
// 'spot.orders.entrustMount': '委託總量',
// 'spot.orders.direction': '方向',
// 'spot.orders.myDealList': '我的掛單',
// 'spot.orders.normalSell': '普通委託',
// 'spot.orders.planSell': '計劃委託',
// 'spot.orders.triggerPop': '當市場最新成交價達到您設置的觸發價格時,系統將自動按您設置的委托價格和數量下達限價委托單。',
// 'spot.orders.triggerPopPlanOrder': '計劃委托是指用戶預先設置好委托單和委托單觸發價格,當市場的最新成交價達到設置的觸發價格時,系統即會將用戶事先設置的委托單送入市場的交易策略。',
// 'spot.orders.triggerPopDetail': '更多詳情',
// 'spot.orders.triggerPopLimitOrder': '限價單是指用戶設置委托數量以及可接受的最高買價或最低賣價,當市場價格符合用戶預期時,系統會以限價範圍內的最優價格進行成交。',
// 'spot.orders.triggerPopMarketOrder': '市價單是指用戶以當前市場最優價格立即執行買入或者賣出。',
// 'spot.orders.triggerPopTrackOrder': '跟蹤委托無數量限制,跟蹤委托被觸發時下達的',
// 'spot.orders.triggerPopTrackOrder2': '委托單數量以當時用戶可下達的最大數量與用戶跟蹤委托設置的委托數量,兩者中小者為準。',
// 'spot.orders.triggerPopIcebergOrder': '冰山委托無數量限制,當冰⼭委托在委托時的可下單數量為0時,則冰山委托將被撤銷。每個⽤戶最多可同時持有6筆冰山委托。',
// 'spot.orders.triggerPopTimeWeightOrder': '時間加權委托無數量限制,當時間加權委托在委托時的可下單數量為0時,則時間加權委托將被撤銷。每個用戶最多同時持有6筆時間加權委托。',
// 'spot.orders.range': '回調幅度',
// 'spot.orders.rangeExplain': '“回調幅度”是跟蹤委托觸發條件之壹,當最新成交價相比跟蹤委托下達後市場的最高/最低價的比例大於等於回調幅度時,視為該條件被滿足。',
// 'spot.orders.activatePriceExplain': '“激活價格”是跟蹤委托觸發條件之壹,當跟蹤委托下達後市場的最高/最低價達到或超過激活價格,視為該條件被滿足。',
// 'spot.orders.priceVariance': '委托深度',
// 'spot.orders.priceVarianceExplain': '買單時,系統將以下達限價單時的買壹價 * (1-委托深度)作為限價單的價格。賣單時,系統將以下達限價單時的賣壹價 * (1+委托深度)作為限價單的價格。',
// 'spot.orders.totalAmount': '委托總數',
// 'spot.orders.totalAmountExplain': '您希望買入或賣出的總數量。',
// 'spot.orders.avgAmount': '單筆均值',
// 'spot.orders.avgAmountExplain': '系統將在您設置的數量的範圍內,設定每次限價單的數量。',
// 'spot.orders.priceLimit': '價格限制',
// 'spot.orders.priceLimitExplain': '買單時,當最新成交價大於您設置的價格限制後,該冰山委托將暫停;賣單時,當最新成交價小於您設置的價格限制後,該冰山委托將暫停。',
// 'spot.orders.filledCount': '已成交量',
// 'spot.orders.partialStatus': '部分生效',
// 'spot.orders.pausedStatus': '暫停生效',
// 'spot.orders.timeWeight.priceVariance': '掃單範圍',
// 'spot.orders.timeWeight.priceVarianceExplain': '買單時,系統將以下達限價單時的買壹價*(1+掃單範圍)為價格下達限價委托單;賣單時,系統將以下達限價單時的賣壹價*(1-掃單範圍)為價格下達限價委托單。',
// 'spot.orders.timeWeight.sweepRatio': '掃單比例',
// 'spot.orders.timeWeight.sweepRatioExplain': '買單時,每次系統將以低於委托價格的賣單總數量*掃單比例為數量下達限價委托單。賣單時,每次系統將以高於委托價格的買單總數量*掃單比例為數量下達限價委托單。',
// 'spot.orders.timeWeight.totalAmount': '委托總數',
// 'spot.orders.timeWeight.totalAmountExplain': '您希望買入或賣出的總數量。',
// 'spot.orders.timeWeight.priceLimitTrade': '單筆上限',
// 'spot.orders.timeWeight.priceLimitTradeExplain': '當委托的數量大於單筆委托上限時,系統將會自動按照客戶設定的單筆委托上限進行委托。',
// 'spot.orders.timeWeight.priceLimitBase': '價格限制',
// 'spot.orders.timeWeight.priceLimitBaseExplain': '買單時,當最新成交價大於您設置的價格限制後,該時間加權委托將暫停;賣單時,當最新成交價小於您設置的價格限制後,該時間加權委托將暫停。',
// 'spot.orders.timeWeight.timeInterval': '委托間隔',
// 'spot.orders.timeWeight.timeIntervalExplain': '當距離最後壹次下達限價委托單的時間大於委托間隔後,系統將下達新的限價委托單。',
// 'spot.orders.kyc2.warning': '為了更好的保障您賬戶的資金安全,OMCoin從2018年6月7號起部分交易功能(充值、提現、充幣、交易),都需完成基本身份認證(相當於調整前的KYC Lv2)。',
// 'spot.orders.kyc2.details': '公告鏈接',
// 'spot.orders.kyc2.detailsText': 'OMCoin KYC相關調整',
// 'spot.orders.kyc2.verify': '去認證',
// 'spot.orders.download': '下載',
// 'spot.orders.borrowedId': '借幣單號',
// 'spot.orders.accountBorrowedToken': '借幣賬戶',
// 'spot.orders.borrowedPair': '借幣幣種',
// 'spot.orders.borrowedTime': '借幣時間',
// 'spot.orders.borrowedQuantity': '借幣數',
// 'spot.orders.dailyRate': '利率',
// 'spot.orders.timeUnit': '天',
// 'spot.orders.interestTime': '計息時間',
// 'spot.orders.totalInterest': '利息',
// 'spot.orders.outstandingLoans': '剩余應還',
// 'spot.orders.statusOnly': '狀態',
// 'spot.orders.operationOnly': '操作',
// 'spot.orders.loansRepay': '還幣',
// 'spot.orders.borrowing': '借款中',
// 'spot.orders.loansRepaid': '已還清',
// 'spot.orders.noOrders': '您暫時沒有未成交的掛單',
// 'spot.orders.noHistory': '您最近兩天沒有已成交的歷史掛單',
// 'spot.orders.noData': '您暫時沒有相關數據',
// 'spot.orders.triggerPrice': '觸發價格',
// 'spot.place.tips.range': '回調幅度不能為空',
// 'spot.place.tips.activatePrice': '激活價格不能為空',
// 'spot.orders.tradePrice': '委託價格',
// 'spot.orders.activatePrice': '激活價格',
// 'spot.order.noSpotBills': '您暫時沒有幣幣賬單信息',
// 'spot.order.noMarginBills': '您暫時沒有幣幣杠桿賬單信息',
// 'spot.order.noBorrowOrder': '您暫時沒有借款中的訂單',
// 'spot.order.noPayoffOrder': '您暫時沒有已還清的訂單',
// 'spot.orders.orderSuccess': '下單成功',
// 'spot.orders.orderError': '下单失败,请重试!',
// 'spot.orders.status1': '待生效',
// 'spot.orders.status2': '已生效',
// 'spot.orders.status3': '已撤銷',
// 'spot.orders.rise': '上漲',
// 'spot.orders.fall': '下跌',
// 'spot.orders.higher': '高於',
// 'spot.orders.lower': '低於',
// 'spot.orders.entrustWords': '当价格{direction}至或{compare}{triggerPrice}{baseCurr}时,则触发以{tradePrice}{baseCurr}的价格{action}{amount}{tradeCurr}',
// 'spot.orders.cancelExplanation0': '委託超時撤單',
// 'spot.orders.cancelExplanation1': '用戶手動撤單',
// 'spot.orders.cancelExplanation3': '餘額不足撤單',
// 'spot.orders.actionBuy': '買入',
// 'spot.orders.actionSell': '賣出',
// /* spot.trade */
// 'spot.trade': '交易',
// 'spot.trade.title': '幣幣交易',
// 'spot.menu.orders': '幣幣委托',
// 'spot.app': 'app',
// 'spot.ios': 'ios',
// 'spot.web': '網頁',
// 'spot.android': '安卓',
// 'spot.bid': '買',
// 'spot.ask': '賣',
// 'spot.amount': '數量',
// 'spot.group': '合並深度',
// 'spot.xDecimal': '位小數',
// 'spot.10Decimal': '十位整數',
// 'spot.100Decimal': '百位整數',
// 'spot.1000Decimal': '千位整數',
// 'spot.10000Decimal': '万位整數',
// 'spot.price': '價格',
// 'spot.total': '金額',
// 'spot.placeorder.pleaseEnter': '請輸入',
// 'spot.pwd': '<PASSWORD>',
// 'spot.orderType': '委托類型',
// 'spot.type': '類型',
// 'spot.depth.amount': '數量',
// 'spot.depth.backToCenter': '返回盤口',
// 'spot.limitOrder': '限價單',
// 'spot.shortLimitOrder': '限價',
// 'spot.shortMarketOrder': '市價',
// 'spot.marketOrder': '市價單',
// 'spot.planOrder': '計劃委託',
// 'spot.trackOrder': '跟蹤委托',
// 'spot.icebergOrder': '冰山委托',
// 'spot.timeWeightOrder': '時間加權委托',
// 'spot.market': '市價',
// 'spot.buy': '買',
// 'spot.sell': '賣',
// 'spot.buyin': '買入{currency}',
// 'spot.sellout': '賣出{currency}',
// 'spot.fee': '費率標準',
// 'spot.fee.broker': '當前手續費費率:',
// 'spot.submit.loading': '正在提交...',
// 'spot.ava.buy': '可買',
// 'spot.ava.sell': '可賣',
// 'spot.callmarket.title': '價格發現',
// 'spot.callmarket.title.all': '價格發現-第N階段',
// 'spot.callmarket.session': '第N階段',
// 'spot.callmarket.desc1': '只能下限價單,可以撤單',
// 'spot.callmarket.desc2': '只能下限價單,不可以撤單',
// 'spot.callmarket.ended': '已結束',
// 'spot.callmarket.endedin': '距結束',
// 'spot.callmarket.startedin': '距開始',
// 'spot.callmarket.open': '預計開盤價',
// 'spot.callmarket.matched': '申報匹配量',
// 'spot.callmarket.unmatched': '申報未匹配量',
// 'spot.callmarket.startingsoon': '暫未開始',
// 'spot.place.tips.price': '請輸入交易價格',
// 'spot.place.tips.amount': '請輸入交易數量',
// 'spot.place.tips.total': '請輸入交易總金額',
// 'spot.place.tips.money2': '您的余額不足,請先充值',
// 'spot.place.tips.triggerPrice': '觸發價格不能為空',
// 'spot.place.tips.orderPrice': '委託價格不能為空',
// 'spot.place.tips.minsize': '最小交易數量是',
// 'spot.place.tips.greaterthan0': '總金額必須大於0',
// 'spot.place.tips.minbuy': '最小買入',
// 'spot.place.tips.minsell': '最小賣出',
// 'spot.place.tips.pwd': '請輸入交易密碼',
// 'spot.place.tips.must': '必須',
// 'spot.place.tips.multiple': '的整數倍',
// 'spot.place.tips.margin': '杠桿交易存在爆倉風險,請註意理性投資',
// 'spot.place.tips.priceVariance': '委托深度不能為空',
// 'spot.place.tips.totalAmount': '委托總數不能為空',
// 'spot.place.tips.avgAmount': '單筆均值不能為空',
// 'spot.place.tips.avgAmountLessThanMin': '單筆均值不能低於委托總數的千分之⼀',
// 'spot.place.tips.avgAmountLargerThanMax': '單筆均值不能超過委托總數',
// 'spot.place.tips.priceLimit': '價格限制不能為空',
// 'spot.place.tips.priceVarianceNotGreaterThan': '委托深度不能大於{max}%',
// 'spot.place.tips.timeWeight.priceVariance': '掃單範圍不能為空',
// 'spot.place.tips.timeWeight.priceVarianceNotGreaterThan': '掃單範圍不能超過{max}%',
// 'spot.place.tips.timeWeight.sweepRatio': '掃單比例不能為空',
// 'spot.place.tips.timeWeight.sweepRatioNotGreaterThan': '掃單比例不能超過{max}%',
// 'spot.place.tips.timeWeight.totalAmount': '委托總數不能為空',
// 'spot.place.tips.timeWeight.priceLimitTrade': '單筆上限不能為空',
// 'spot.place.tips.timeWeight.priceLimitTradeLessThanMin': '單筆上限不能小於委托總數千分之一',
// 'spot.place.tips.timeWeight.priceLimitTradeLargerThanMax': '單筆上限不能大於委托總數',
// 'spot.place.tips.timeWeight.priceLimitBase': '價格限制不能為空',
// 'spot.place.tips.timeWeight.timeInterval': '委托間隔不能為空',
// 'spot.place.tips.timeWeight.timeIntervalRange': '委托間隔不能小於{min}秒大於{max}秒',
// 'spot.place.confirm.buy': '確認買入',
// 'spot.place.confirm.sell': '確認賣出',
// 'spot.place.confirm.normalTrade.buy': '輸入資金密碼',
// 'spot.place.marketPrice': '按市場最優價格成交',
// 'spot.place.forgetPwd': '忘記密碼',
// 'spot.place.nopwd': '免輸資金密碼',
// 'spot.place.autoBorrowWarn': '完成此次交易您需借幣',
// 'spot.place.forcePrice': '預估爆倉價格',
// 'spot.place.noWarn': '下次不再提醒',
// 'spot.place.kline': 'K線',
// 'spot.place.kline.title': '實時行情',
// 'spot.place.kline.more': '更多',
// 'spot.kline.noInfo': '暫無信息',
// 'spot.place.fullScreen': '全屏交易',
// 'spot.ticker.legal': '人民幣價格',
// 'spot.ticker.highest': '24h最高價',
// 'spot.ticker.lowest': '24h最低價',
// 'spot.ticker.volume': '24h成交量',
// 'spot.ticker.inflows': '24h資金流入',
// 'spot.ticker.outflows': '24h資金流出',
// 'spot.ticker.inflowTips': '過去24小時主動買入成交量',
// 'spot.ticker.outflowTips': '過去24小時主動賣出成交量',
// 'spot.ticker.introduce.releaseTime': '發行時間',
// 'spot.ticker.introduce.distributionAmount': '發行總量',
// 'spot.ticker.introduce.circulationAmount': '流通總量',
// 'spot.ticker.introduce.crowdfunding': '眾籌價格',
// 'spot.ticker.introduce.website': '官網',
// 'spot.ticker.introduce.whitePaper': '白皮書',
// 'spot.ticker.introduce.introduction': '介紹',
// 'spot.deals.title': '最新交易',
// 'spot.deals.price': '價格(-)',
// 'spot.deals.amount': '數量(-)',
// 'spot.deals.time': '時間',
// 'spot.deals.no': '暫時沒有最新成交',
// 'spot.kline.price': '成交價',
// 'spot.kline.tabs[0]': '行情',
// 'spot.kline.tabs[1]': '介紹',
// 'spot.page.title': '- 全球領先的比特幣/數字貨幣交易平臺 |',
// 'spot.page.title.tokens': '幣幣委托 ',
// 'spot.page.title.bills': '幣幣賬單 ',
// 'spot.page.title.marginHistory': '借幣歷史記錄 '
// };
// export default zh_CN;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toLocale } from '_src/locale/react-locale';
import util from '../../utils/util';
import Enum from '../../utils/Enum';
import './Introduce.less';
function mapStateToProps(state) {
return {
product: state.SpotTrade.product,
currencyObjByName: state.SpotTrade.currencyObjByName
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({}, dispatch);
}
@connect(mapStateToProps, mapDispatchToProps)
class Introduce extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
introduceObj: {} // 不用null,是防止后端正确返回的就是空对象
};
}
componentDidMount() {
if (this.props.product) {
this.getIntroduceBySymbol(this.props.product.split('_')[0]);
}
}
componentWillReceiveProps(nextProps) {
const product = nextProps.product;
if (product) {
this.getIntroduceBySymbol(product.split('_')[0]);
}
}
getIntroduceBySymbol = (currency) => {
if (window.OM_GLOBAL.tradeType === Enum.tradeType.fullTrade) {
// document.body.classList.add('full-body');
}
const currencyObj = this.props.currencyObjByName;
// const name = currencyObj[currency] ? currencyObj[currency].description : '';
const o = currencyObj[currency];
if (o) {
this.setState({
introduceObj: {
name: o.description ? o.description : '',
whole_name: o.whole_name ? o.whole_name : '',
original_symbol: o.original_symbol ? o.original_symbol : '',
total_supply: o.total_supply ? o.total_supply : '',
}
});
}
// ont.get(URL.GET_INTRODUCE, {
// params: {
// currency
// }
// }).then((res) => {
// const introduceObj = res.data;
// this.setState({
// introduceObj
// });
// }).catch(() => {
// this.setState({
// introduceObj: {}
// });
// });
/* this.setState({
introduceObj: {
"blockUrl": "www.bit.com",
"circulationAmount": "2000",
"connect": "www.bit.com",
"crowdfunding": "100",
"currencyId": 0,
"distributionAmount": "10000",
"exchangeRate": "200",
"icoBasecoinPrice": "100",
"introduction": "它诞生于2009年1月3日,它诞生于2009年1月3日,它诞生于2009年1月3日",
"name": "比特币",
"releaseTime": "2015-01-01",
"website": "https://bitcoin.org/en/",
"whitePaper": "www.bit.com"
}
}); */
};
render() {
const { product } = this.props;
const currency = product.split('_')[0].toUpperCase();
const { introduceObj } = this.state;
if (util.isEmpty(introduceObj)) {
return <div>{toLocale('spot.kline.noInfo')}</div>;
}
const moreLink = introduceObj.connect ? (
<a
href={introduceObj.connect}
style={{ marginLeft: '10px' }}
rel="noopener noreferrer"
target="_blank"
>
{toLocale('spot.place.kline.more')}
</a>
) : null;
return (
<div className="introduce-container">
<div className="introduce-pairTitle">
{toLocale('symbolWholeName')} {`${introduceObj.whole_name}`} <br /><br />
{toLocale('symbolId')} {`${currency}`} <br /><br />
{toLocale('symbolDesc')} {`${introduceObj.name}`}
</div>
{/*
<a
href={`/project/${projectId || ''}`}
className="project-detail-link"
rel="noopener noreferrer"
target="_blank"
>
{toLocale('spot.project.info')}
</a> */}
{/*
<div className="introduce-layer">
<div>
<span className="introduce-label">
{toLocale('spot.ticker.introduce.releaseTime')}
</span>
<span className="introduce-label-connent">{introduceObj.releaseTime || '--'}</span>
</div>
<div>
<span
className="introduce-label"
>{toLocale('spot.ticker.introduce.distributionAmount')}
</span>
<span className="introduce-label-connent">{introduceObj.distributionAmount || '--'}</span>
</div>
<div>
<span
className="introduce-label"
>{toLocale('spot.ticker.introduce.circulationAmount')}
</span>
<span className="introduce-label-connent">{introduceObj.circulationAmount || '--'}</span>
</div>
<div>
<span className="introduce-label">
{toLocale('spot.ticker.introduce.crowdfunding')}
</span>
<span className="introduce-label-connent">{introduceObj.crowdfunding || '--'}</span>
</div>
</div>
<div className="flex-row">
<span className="introduce-label">
{toLocale('spot.ticker.introduce.website')}
</span>
{
introduceObj.website ? (
<a
href={introduceObj.website}
rel="noopener noreferrer"
target="_blank"
>
{introduceObj.website}
</a>
) : <span className="introduce-label-connent">--</span>
}
</div>
<div className="flex-row">
<span className="introduce-label">
{toLocale('spot.ticker.introduce.whitePaper')}
</span>
{
introduceObj.whitePaper ? (
<a
href={introduceObj.whitePaper}
rel="noopener noreferrer"
target="_blank"
>
{introduceObj.whitePaper}
</a>
) : <span className="introduce-label-connent">--</span>
}
</div>
<div>
<span className="introduce-label">
{toLocale('spot.ticker.introduce.introduction')}
{moreLink}
</span>
<p className="introduce-label-connent">
{introduceObj.introduction || '--'}
</p>
</div>
*/}
</div>
);
}
}
export default Introduce;
<file_sep>var path = require('path');
module.exports = {
"parser": "babel-eslint",
"extends": "@ok/eslint-config-ok",
"rules": {
"class-methods-use-this": 0
},
"env": {
"browser": true
},
"settings": {
'import/resolver': {
alias: {
map: [
['_src', path.resolve(__dirname, './src/')],
['_component', path.resolve(__dirname, './src/component/')],
['_constants', path.resolve(__dirname, './src/constants/')]
],
extensions: ['.js', '.less', '.jsx']
}
}
}
}
<file_sep>const enUS = {
seoTitle: 'Decentralized trading platform DEX',
borrow: 'Borrow',
needBorrow: 'Borrow ',
repay: 'Repay',
sysError: 'System error, please try again later.',
operationSuccessful: 'Operation is successful.',
on: 'ON',
off: 'OFF',
cancel: 'Cancel',
'spot.noData': 'No Data',
search: 'search',
pair: 'Pair',
price: 'Price',
change: 'Change',
login: 'Login',
signUp: 'Sign Up',
settings: 'OMEX Notice',
phone: 'mobile',
email: 'email address',
symbolDesc: 'Symbol Desc:',
symbolWholeName: 'Symbol wholeName:',
symbolId: 'Symbol ID:',
/* spot */
'spot.coin': 'coin',
'spot.marketDict': 'Markets',
'spot.favorites': 'Favorites',
'spot.account.spot': 'Spot Account',
/* spot asset */
'spot.asset.newMarginTrade': 'Margin',
'spot.asset.futureswapTrade': 'Perpetual',
'spot.asset': 'Asset',
'spot.asset.ava': 'Avail',
'spot.asset.borrow': 'Borrowed',
'spot.asset.interest': 'Interest',
'spot.asset.risk': 'Risk Ratio',
'spot.asset.forceClose': 'Liquidation',
'spot.asset.freeze': 'On Hold',
'spot.asset.marginTrade': 'x Leverage',
'spot.asset.spotTrade': 'Spot',
'spot.asset.dexTest': 'DEX Trade',
'spot.asset.futureTrade': 'Futures',
'spot.asset.deposit': 'Deposit {currency}',
'spot.asset.transfer': 'Transfer',
'spot.asset.transferSuccess': 'Transfer Success',
'spot.asset.borrowBill': 'Borrow',
'spot.asset.goBorrow': 'Borrow',
'spot.asset.borrowBillSuccess': 'Borrow Success',
'spot.asset.repayBill': 'Repay',
'spot.asset.repayBillSuccess': 'Repay Success',
'spot.asset.repayBonus': 'Repay Bonus',
'spot.asset.repayBonus.tips-0': 'You are requested to repay the {bonus} bonus generated from your {currency} margin lending. Please reserve a sufficient amount of {bonus} in your spot account.',
'spot.asset.repayBonus.tips-1': '1. Your unpaid bonus will be counted as a liability when calculating your risk rate.',
'spot.asset.repayBonus.tips-2': '2. Your asset will not be allowed to transfer out before you repay the bonus.',
/* spot.market */
'spot.market.more': 'more',
'spot.market.orders': 'Details',
'spot.menu.market.orders': 'Orders',
'spot.menu.market.bills': 'Bills',
'spot.menu.market.currencyIntro': 'Token education',
'spot.menu.market.marginIntro': 'Margin Trading Glossary',
'spot.menu.market.marginGuide': 'Margin Trading Guide',
'spot.menu.market.history': 'Loan Records',
'spot.menu.market.strategy': 'Algo Orders',
/* spot.orders */
'spot.orders.currencies': 'Currency',
'spot.orders.types': 'Filter',
'spot.orders.last2': 'Last 2 Days',
'spot.orders.2daysago': '2+ Days',
'spot.search': 'Search',
// dex相关
'spot.myOrder.detail': 'Details',
'spot.myOrder.hash': 'TxHash',
'spot.myOrder.date': 'Date',
'spot.myOrder.product': 'Pair',
'spot.myOrder.direction': 'Side',
'spot.myOrder.filledPercentage': 'Filled Ratio',
'spot.myOrder.price': 'Order Price',
'spot.myOrder.amount': 'Order Amount',
'spot.myOrder.money': 'Money',
'spot.myOrder.status': 'Status',
'spot.myOrder.operate': 'Action',
'spot.myOrder.filledPrice': 'Avg. Filled Price',
'spot.myOrder.filledAmount': 'Filled',
'spot.myOrder.filledStatus': 'FilledStatus',
'spot.myOrder.filledMoney': 'FilledMoney',
'spot.myOrder.height': 'Height',
'spot.myOrder.id': 'OrderId',
'spot.myOrder.fee': 'Fee',
'spot.myOrder.Open': 'Open',
'spot.myOrder.Filled': 'Filled',
'spot.myOrder.Cancelled': 'Cancelled',
'spot.myOrder.Expired': 'Expired',
'spot.myOrder.PartialFilledCancelled': 'PartialFilledCancelled',
'spot.myOrder.PartialFilledExpired': 'PartialFilledExpired',
'spot.myOrder.PartialFilled': 'PartialFilled',
'spot.myOrder.cancelFailed': 'Cancel Failed',
'spot.myOrder.cancelSuccessed': 'Cancel Successed',
'spot.myOrder.cancelNoDealTip': 'Cancelling an unfulfilled order involves transaction fees. Are you sure you want to cancel?',
'spot.myOrder.cancelPartDealTip': 'Confirm to cancel order?',
'spot.orders.amount': 'Amount',
'spot.orders.averPrice': 'Average Price',
'spot.orders.cancel': 'Cancel',
'spot.orders.cancelled': 'Cancelled',
'spot.orders.canceling': 'Canceling',
'spot.orders.cancelAll': 'Cancel All (Pair)',
'spot.orders.date': 'Date',
'spot.orders.filled': 'Filled',
'spot.orders.completeFilled': 'Filled',
'spot.orders.noorders': 'You have no open orders.',
'spot.orders.noorders2day': 'You have no filled orders in the last two days.',
'spot.orders.noorders2dayago': 'You have no filled orders in the two days ago.',
'spot.orders.more': 'More',
'spot.orders.open': 'Open',
'spot.orders.openOrders': 'Open Orders',
'spot.orders.oneDay': 'OneDay',
'spot.orders.oneWeek': 'OneWeek',
'spot.orders.oneMonth': 'OneMonth',
'spot.orders.threeMonth': 'ThreeMonth',
'spot.orders.unfinished': 'Open',
'spot.orders.orderHistory': 'Order History',
'spot.orders.partialFilled': 'Partial Filled',
'spot.orders.partial': 'Partial',
'spot.orders.allProduct': 'All Token Pairs',
'spot.orders.price': 'Price',
'spot.orders.side': 'Side',
'spot.orders.side.spot': 'Spot',
'spot.orders.side.margin': 'Margin',
'spot.orders.side.spotAndMargin': 'Token & Margin',
'spot.orders.source': 'Details',
'spot.orders.status': 'Status',
'spot.orders.operation': 'Action',
'spot.orders.tips.datepicker': 'please select date',
'spot.orders.tips.dateRange': 'The end date must be later than the start date',
'spot.orders.title': 'spot orders',
'spot.orders.total': 'Total',
'spot.orders.type': 'Type',
'spot.orders.symbol': 'Pair',
'spot.orders.side2': 'Side',
'spot.orders.historyRecord': 'Hide other pairs',
'spot.orders.historyRescinded': 'Hiding undone',
'spot.orders.dealAveragePrice': 'Avg. Price',
'spot.orders.dealt': 'Filled',
'spot.orders.entrustMoney': 'Total',
'spot.orders.entrustPrice': 'Price',
'spot.orders.entrustMount': 'Volume',
'spot.orders.direction': 'side',
'spot.orders.myDealList': 'My orders',
'spot.orders.toast.unhis': 'Please select a trading pair to view order history',
'spot.orders.allOrders': 'All Orders',
'spot.orders.download': 'Download',
'spot.orders.borrowedId': 'ID',
'spot.orders.accountBorrowedToken': 'Account',
'spot.orders.borrowedPair': 'Pair',
'spot.orders.borrowedTime': 'Loan Time',
'spot.orders.borrowedQuantity': 'Amount',
'spot.orders.dailyRate': 'Daily Interest Rate"',
'spot.orders.timeUnit': 'day',
'spot.orders.timeUnitDay': 'Day',
'spot.orders.timeUnitHour': 'Hour',
'spot.orders.interestTime': 'Interest incurred time',
'spot.orders.totalInterest': 'Total interest',
'spot.orders.outstandingLoans': 'Outstanding Loans',
'spot.orders.statusOnly': 'Status',
'spot.orders.operationOnly': 'Action',
'spot.orders.loansRepay': 'Loans Repay',
'spot.orders.borrowing': 'Loan',
'spot.orders.loansRepaid': 'Repayment',
'spot.orders.notRepaidAmount': 'Unpaid principal',
'spot.orders.notRepaidInterest': 'Unpaid interest',
'spot.orders.allInterest': 'Accrued interest',
'spot.orders.noOrders': 'You have no open orders',
'spot.orders.noHistory': 'You have no filled orders in the last two days',
'spot.orders.noData': 'You have no relevant data for the time being',
'spot.order.noSpotBills': 'You have no spot trading bills',
'spot.order.noMarginBills': 'You have no leverage trading bills',
'spot.order.noBorrowOrder': 'You have no loan record',
'spot.order.noPayoffOrder': 'You have no repayment record',
'spot.orders.normalSell': 'Limit Order',
'spot.orders.status1': 'Pending',
'spot.orders.status2': 'Triggered',
'spot.orders.status3': 'Canceled',
'spot.orders.triggerPrice': 'Trigger Price',
'spot.orders.tradePrice': 'Order Price',
'spot.orders.activatePrice': 'Trigger Price',
'spot.orders.rise': ' rise ',
'spot.orders.fall': ' fall ',
'spot.orders.higher': ' higher than ',
'spot.orders.lower': ' lower than ',
'spot.orders.entrustWords': 'When the market price is {direction} to or {compare} {triggerPrice}{baseCurr},it will trigger the order of {action} {amount}{tradeCurr} at the price {tradePrice}{baseCurr}',
'spot.orders.cancelExplanation0': 'Cancelled due to timeout',
'spot.orders.cancelExplanation1': 'Cancelled manually by user',
'spot.orders.cancelExplanation3': 'Cancel failed order',
'spot.orders.actionBuy': 'Buy',
'spot.orders.actionSell': 'Sell',
'spot.orders.triggerPop': 'When the last traded price hits the stop price, system will execute the order you set to buy or sell at a specified price and volume. ',
'spot.orders.triggerPopPlanOrder': 'Trigger order is an instruction to submit a limit order at a specified price and volume when the user-specified stop trigger price is attained or penetrated.',
'spot.orders.triggerPopDetail': 'Detail',
'spot.orders.triggerPopLimitOrder': 'A limit order is an order to buy or sell an amount of digital asset at a specific price or better.',
'spot.orders.triggerPopMarketOrder': 'A market order is an order to buy or sell an amount of digital asset immediately at current market prices.',
'spot.orders.triggerPopTrackOrder': 'Trail Order Quantity: Of the maximum number of trail orders for any trigger price and the maximum number for currently held contracts, the smaller of the two will apply. Each user can hold up to 10 non-triggered trail orders at once.',
'spot.orders.triggerPopTrackOrder2': ' ',
'spot.orders.triggerPopIcebergOrder': 'No limit on the order amount. Each user can place up to 6 orders simultaneously.',
'spot.orders.triggerPopTimeWeightOrder': 'No limit on the order amount. Each user can place up to 6 orders simultaneously.',
'spot.orders.range': 'Callback Rate',
'spot.orders.rangeExplain': 'The callback rate is one condition for a trail order, satisfied when the last price compared with the maximum market price / minimum market price is greater than or equal to the user-defined callback rate.',
'spot.orders.activatePriceExplain': 'The trigger price is one condition for a trail order, satisfied when it is met or exceeded by the maximum or minimum market price.',
'spot.orders.priceVariance': 'Price variance',
'spot.orders.priceVarianceExplain': 'The buy order price will be the latest buy price* (1-price variance). The sell order price will be the latest buy price* (1-price variance).',
'spot.orders.totalAmount': 'Total amount',
'spot.orders.totalAmountExplain': 'The total amount you wish to buy or sell',
'spot.orders.avgAmount': 'Average amount',
'spot.orders.avgAmountExplain': 'The amount you wish to buy or sell in each order',
'spot.orders.priceLimit': 'Price limit',
'spot.orders.priceLimitExplain': 'When the last market price exceeds the price limit, the iceberg order would be temporarily halted.',
'spot.orders.filledCount': 'Filled',
'spot.orders.partialStatus': 'Partially effective',
'spot.orders.pausedStatus': 'Order terminated',
/* spot.trade */
'spot.trade': 'Trade',
'spot.menu.orders': 'Spot Orders',
'spot.orders.orderSuccess': 'Success',
'spot.orders.buySuccess': 'Buy Success',
'spot.orders.sellSuccess': 'Sell Success',
'spot.orders.buyFail': 'system error,retry please!',
'spot.orders.sellFail': 'system error,retry please!',
'spot.orders.orderError': 'system error,retry please!',
'spot.web': 'web',
'spot.android': 'android',
'spot.bid': 'Bid',
'spot.ask': 'Ask',
'spot.amount': 'Amount',
'spot.group': 'Aggregation',
'spot.xDecimal': ' decimals',
'spot.singleDecimal': 'decimal',
'spot.10Decimal': '10-bit integer',
'spot.100Decimal': '100-bit integer',
'spot.1000Decimal': '1000-bit integer',
'spot.10000Decimal': '10000-bit integer',
'spot.price': 'Price',
'spot.total': 'Total',
'spot.placeorder.pleaseEnter': 'Please enter ',
'spot.pwd': '<PASSWORD>',
'spot.depth.amount': 'Amout',
'spot.depth.backToCenter': 'BBO',
'spot.orderType': 'Order Type',
'spot.FullLimitOrder': 'Limit Order',
'spot.limitOrder': 'Limit Order',
'spot.marketOrder': 'Market Order',
'spot.planOrder': 'Trigger Order',
'spot.trackOrder': 'Trail Order',
'spot.icebergOrder': 'Iceberg order',
'spot.timeWeightOrder': 'TWAP',
'spot.market': 'Market price',
'spot.shortLimitOrder': 'Limit',
'spot.shortMarketOrder': 'Market',
'spot.type': 'Type',
'spot.buy': 'Buy',
'spot.sell': 'Sell',
'spot.buyAndSell': 'Buy & Sell',
'spot.buyin': 'Buy {currency}',
'spot.sellout': 'Sell {currency}',
'spot.callmarket.title': 'Call Auction',
'spot.callmarket.title.all': 'Call Auction-Session N',
'spot.callmarket.session': 'Session N',
'spot.callmarket.desc1': 'Limit order only (cancellable)',
'spot.callmarket.desc2': 'Limit order only (non-cancellable)',
'spot.callmarket.ended': 'Ended',
'spot.callmarket.endedin': 'Ending in',
'spot.callmarket.startedin': 'Starting in',
'spot.callmarket.open': 'Indicative opening price',
'spot.callmarket.matched': 'Orders matched',
'spot.callmarket.unmatched': 'Orders not yet matched',
'spot.callmarket.startingsoon': 'Starting soon',
'spot.fee': 'Fee',
'spot.fee.broker': 'Current fee rate:',
'spot.submit.loading': 'Loading...',
'spot.ava.buy': 'Max. buy ',
'spot.ava.sell': 'Available sell',
'spot.place.tips.price': 'Please enter the transaction price',
'spot.place.tips.amount': 'Please enter the amount',
'spot.place.tips.total': 'Please enter the total amount of transaction',
'spot.place.tips.money2': 'The balance is insufficient',
'spot.place.tips.triggerPrice': 'Trigger price Cannot be empty',
'spot.place.tips.range': 'Callback rate Cannot be empty',
'spot.place.tips.activatePrice': 'Price variance Cannot be empty',
'spot.place.tips.orderPrice': 'Order price Cannot be empty',
'spot.place.tips.minsize': 'Minimum amount is ',
'spot.place.tips.greaterthan0': 'The total amount must be more than 0',
'spot.place.tips.minbuy': 'Minimum buying',
'spot.place.tips.minsell': 'Minimum selling',
'spot.place.tips.pwd': '<PASSWORD>',
'spot.place.tips.margin': 'Margin trading involves significant risks which include forced liquidation of all the assets in your account. Please invest responsibly',
'spot.place.tips.priceVariance': 'Price variance Cannot be empty',
'spot.place.tips.totalAmount': 'Total amount Cannot be empty',
'spot.place.tips.avgAmount': 'Average amount Cannot be empty',
'spot.place.tips.avgAmountLessThanMin': 'Single order average amount cannot be lower than 0.1% of total order amount',
'spot.place.tips.avgAmountLargerThanMax': 'Single order average amount cannot exceed total order amount',
'spot.place.tips.priceLimit': 'Price limit Cannot be empty',
'spot.place.tips.priceVarianceNotGreaterThan': 'Order variance cannot exceed {max}%',
'spot.place.marketPrice': 'Execute at the best available price',
'spot.place.forgetPwd': '<PASSWORD>',
'spot.place.nopwd': 'Password settings',
'spot.place.autoBorrowWarn': ' Buy on margin to complete the trade',
'spot.place.forcePrice': 'Est. Liq. Price',
'spot.place.noWarn': 'Don\'t show this again',
'spot.place.kline': 'K Line',
'spot.place.kline.title': 'Real-Time Quotes',
'spot.place.kline.more': 'More',
'spot.kline.noInfo': 'No information',
'spot.place.fullScreen': 'Full screen',
'spot.place.tips.must': 'The quote must be a multiple of ',
'spot.place.tips.multiple': ' ',
'spot.place.confirm.buy': 'Confirm buying ',
'spot.place.confirm.sell': 'Confirm selling ',
'spot.place.confirm.normalTrade.buy': 'Enter fund password ',
'spot.ticker.legal': 'USD',
'spot.ticker.legal.new': '{currency}',
'spot.ticker.legal.unit': 'Currency',
'spot.ticker.highest': '24hr high',
'spot.ticker.lowest': '24hr low',
'spot.ticker.volume': 'Volume',
'spot.ticker.inflows': '24hr inFlows',
'spot.ticker.outflows': '24hr outFlows',
'spot.ticker.inflowTips': '24hr Taker Buying Volume',
'spot.ticker.outflowTips': '24hr Taker Selling Volume',
'spot.ticker.introduce.releaseTime': 'release time',
'spot.ticker.introduce.distributionAmount': 'distribution amount',
'spot.ticker.introduce.circulationAmount': 'circulation amount',
'spot.ticker.introduce.crowdfunding': 'crowdfunding',
'spot.ticker.introduce.website': 'website',
'spot.ticker.introduce.whitePaper': 'white paper',
'spot.ticker.introduce.introduction': 'introduction',
'spot.kline.price': 'Price',
'spot.kline.tabs[0]': 'Quotation',
'spot.kline.tabs[1]': ' Info',
'spot.kline.tabs[2]': 'Report',
'spot.kline.tabs[3]': 'Rating',
'spot.kline.tabs[2].more': 'More',
'spot.kline.tabs[3].more': 'More',
'spot.kline.tabs.news': 'News',
'spot.kline.tabs.news.more': 'More',
'spot.deals.title': 'Transactions',
'spot.deals.price': 'Price(-)',
'spot.deals.amount': 'Volume(-)',
'spot.deals.time': 'Time',
'spot.deals.no': 'There is no data.',
'spot.page.title': '- The Leading Global Bitcoin/Cryptocurrency Exchange |',
'spot.page.title.tokens': 'Token trading orders ',
/* not login */
'spot.notlogin.tradenow': 'Start trading now',
'spot.notlogin.preview': 'This is the preview of the {site} exchange All data is real-time',
'spot.notlogin.logintoview1': 'You must be ',
'spot.notlogin.logintoview2': 'logged in',
'spot.notlogin.logintoview3': ' to view this content.',
'notice.category.week': 'Weekly updates',
'notice.category.month': 'Monthly updates',
'notice.category.news': 'News',
'notice.category.act': 'Activities',
'notice.category.treasure': 'Financial report',
'notice.category.rate': 'Rating',
/* 项目披露 */
'spot.project.info': 'Project Info',
/* 高阶限价单 */
'spot.advancedLimitOrder': 'Advanced Limit Order',
'spot.orders.triggerPopAdvancedLimitOrder': 'Advanced Limit Order offers 3 additional order options, including "Post Only", "Fill or Kill", and "Immediate or Cancel". For normal Limit Order, the order option is always defaulted as "Good till Canceled". ',
'spot.orders.orderType': 'Order Types',
'spot.orders.orderType.postOnly': 'Post Only',
'spot.orders.orderType.FOK': 'Fill or Kill',
'spot.orders.orderType.FAK': 'Immediate or Cancel',
'spot.orders.orderTypeShort.always': 'Good Till Canceled',
'spot.orders.orderTypeShort.postOnly': 'Post only',
'spot.orders.orderTypeShort.FOK': 'FillorKill',
'spot.orders.orderTypeShort.FAK': 'ImmediateorCancel',
'spot.place.tips.orderType': 'How the order is executed. "Post Only" never takes liquidity and makes sure the trader will be a market maker. If your order would cause a match with a pre-existing order, your post-only limit order will be canceled. "Fill or Kill" makes sure the buy/sell order is executed or canceled entirely without partial fulfillments. "Immediate or Cancel" requires all or part of the order to be executed immediately, and any unfilled parts of the order are canceled.',
'spot.orders.actionBuyMargin': 'Buy (Long) ',
'spot.orders.actionSellMargin': 'Sell (Short) ',
/* 深度tooltip */
'spot.depth.tooltip.sumTrade': 'Total {trade}',
'spot.depth.tooltip.sumBase': 'Total {base}',
'spot.depth.tooltip.avgPrice': 'Average Price',
// 通用
all: 'All',
go_back: 'Back',
next_step: 'Next',
prev_step: 'Return',
ensure: 'Submit',
OK: 'OK',
please_select: 'Please Select',
please_input_pwd: '<PASSWORD>',
pwd_error: '<PASSWORD>',
valuation: ' Valuation',
link_to_all: 'Click to see all >>',
// 钱包
// 创建钱包
wallet_create_step1: 'Create Wallet',
wallet_setPassword: '<PASSWORD>',
wallet_password_placeholder: 'Please use 10 or more characters with a mix of letters and numbers for your password',
wallet_password_lengthValidate: 'At least 10 or more characters',
wallet_password_chartValidate: 'At least an upper-case letter, a lower-case letter and a number',
wallet_twicePassword: '<PASSWORD>',
wallet_passwordNotSame: 'Password<PASSWORD>',
wallet_unsaveTip: 'I confirm DEX will not save any of passwords/mnemonic phrases/keystores/private keys',
wallet_hadWallet: 'I already have a wallet',
wallet_importNow: 'Import Now >>',
wallet_nextStep: 'Next',
// safetip 安全提示
wallet_safeTip_title: 'Security Alert',
wallet_safeTip_beforeKeystore: 'Please download the file and record your mnemonic phrase ',
wallet_safeTip_afterKeystore: 'in a secure environment. Do not take photos or screen capture to avoid leak.',
wallet_known: 'I understand',
// step2 备份助记词
wallet_create_step2: 'Mnemonic Phrase Backup',
wallet_create_backupMnemonic: 'Please back up the below mnemonic phrases in sequence',
wallet_create_backupMnemonic_error: 'Not verified. Please back up again',
wallet_create_beginValidate: 'I have copied it. Verify now',
wallet_create_step3: 'Mnemonic Phrase Verification',
wallet_choiceMnemonicPre: 'Select the number',
wallet_choiceMnemonicSuf: 'mnemonic phrase',
wallet_ensure: 'Confirm',
wallet_confirm: 'Confirm',
wallet_create_step4: 'Verification Successful',
wallet_mnemonicSuccess: 'Congratulations! You have verified your mnemonic phrase. Please keep it safe.',
wallet_toTrade: 'Trade Now',
wallet_seePrivate: 'Check Private Key',
wallet_privateKey: 'Private Key',
// 导入钱包
wallet_import: 'Import Wallet',
wallet_import_mnemonic: 'Mnemonic Phrase',
// keystore导入
wallet_import_upload_todo: 'Drag here to upload keystore documents',
wallet_import_upload_doing: 'Uploading',
wallet_import_upload_retry: 'Re-Upload',
wallet_import_passwordTip: 'This password is generated from the keystore document setup. You can’t import your wallet without this password',
wallet_import_enterPassword: '<PASSWORD>',
wallet_import_fileError: 'Incorrect document format/illegal content',
wallet_import_noFile: 'Please upload keystore documents',
wallet_import_passwordError: '<PASSWORD>',
// 助记词导入
wallet_import_mnemonic_enter: 'Enter Mnemonic Phrase',
wallet_import_mnemonic_splitTip: 'Enter space between the mnemonic phrases',
wallet_import_mnemonic_error: 'Illegal mnemonic phrase',
wallet_import_mnemonic_sessionPassword: '<PASSWORD>',
wallet_import_mnemonic_sessionPasswordTip: 'This password is only valid for this login. It is not related to the password you set up when creating your wallet',
wallet_import_mnemonic_none: 'Mnemonic cannot be empty',
// 私钥导入
wallet_import_private_enter: 'Enter Wallet Private Key',
wallet_import_password_placeholder: '<PASSWORD>',
wallet_import_private_error: 'Illegal Private Key',
wallet_import_sessionPasswordTip: 'This password is valid only for this login',
wallet_import_private_none: 'The private key cannot be empty',
// Header
header_menu_trade: 'Trade',
header_menu_order: 'Order',
header_menu_create_wallet: 'Create Wallet',
header_menu_import_wallet: 'Import Wallet',
header_menu_current_entrust: 'Pending Orders',
header_menu_history_entrust: 'Past Orders',
header_menu_deal_entrust: 'Details',
header_menu_wallet: 'Wallet',
header_menu_assets: 'Asset Balance',
header_menu_down_keystore: 'Download Keystore Document',
header_menu_logout: 'Logout',
header_menu_logout1: 'Make sure to exit the current wallet?',
header_menu_help: 'Help',
header_menu_instructions: 'Documentation',
header_menu_draw_okdex: 'Claim Test Token',
header_menu_item_address: 'Address',
header_menu_explorer_okchain: 'Explorer',
footer_standard_rates: 'Transaction Fee Rates',
// 首页
home_banner_title: 'OMEx DEX',
home_banner_subtitle: 'Borderless decentralized trading platform',
home_banner_btn_trade: 'Start trading',
home_adv_title: 'Product advantages',
home_adv_item0_title: 'Secure and reliable',
home_adv_item0_content: 'Relying on the Secp256k1 elliptic curve algorithm, users\' digital assets are stored in their own wallets and can be traded without custody',
home_adv_item1_title: 'Fast and convenient',
home_adv_item1_content: 'OMEx DEX reviews the on-chain assets with a strict standard, sets stable digital assets as the pricing currency, and provides various trading options.',
home_adv_item2_title: 'Continuous iteration',
home_adv_item2_content: 'OMEx DEX will support the new functions of OMChain sooner to providing a better trading experience for users.',
home_exp_title: 'Experience simulated trading',
home_exp_content: 'OMEx users who have created OMChain wallets will be distributed with a certain amount of testing currencies. The amount is limited, first come first served.',
home_steps_title: 'Quick start',
home_steps_item0_title: '1.Create OMChain wallet',
home_steps_item0_content: 'DEX will not save any information of your wallet on the chain; mnemonic words and keystore files are the only proofs for your personal assets, please keep them properly. If mnemonic words and keystore files have been created, you can directly import them into the wallet.',
home_steps_item0_button: 'Create wallet',
home_steps_item1_title: '2.Wallet deposit',
home_steps_item1_content: 'Log in to the OMChain on-chain wallet, enter asset management, and obtain the OMChain on-chain address; DEX trading can be initiated on TestNet by getting the test currencies; the account record can be viewed in on-chain wallet- -asset record.',
home_steps_item1_button: 'Get testing currencies',
home_steps_item2_title: '3.Go trading',
home_steps_item2_content: 'Trade any trading pair with the testing currencies; Each time you place an order or cancel an order, a hash value is generated and broadcast to the blockchain network.',
home_steps_item2_button: 'Trade now',
home_steps_item3_title: '4.Check trading info',
home_steps_item3_content: 'For each transaction and transfer, you can query the corresponding information in the blockchain browser through the transaction hash value and address.',
home_steps_item3_button: 'Check block data',
home_steps_item0_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/7285906D63E20BD639AA7C8A3429755E.png',
home_steps_item1_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/9088F851DF59FD358F6EAA08BFDE08A4.png',
home_steps_item2_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/1CDBD8D16A98147F82E9E7703FE9DE61.png',
home_steps_item3_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/298BA40D0EF5D30907E47C018D8D1B7B.png',
home_exp_more: 'Learn more about "DEX, OMChain detailed design rules',
home_exp_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/A4C4128B4E548183A3D05A8463ED45F6.png',
home_subtitle: 'OMChain testnet is launched. Check your transaction history on-chain.',
home_receive_coin: 'Claim Test Token',
home_step5_title: 'Help',
// 资产余额
assets_tab_accounts: 'Asset Balance',
assets_tab_transactions: 'Transaction Record',
assets_address: 'Address:',
assets_product_search: 'Search Asset',
assets_hide_zero: 'Hiding 0 balance assets',
assets_empty: 'No Assets',
assets_column_assets: 'Assets',
assets_column_total: 'Total Amount',
assets_column_balance: 'Available',
assets_column_freeze: 'Fronzen',
assets_column_list: 'Place Order',
assets_trans_btn: 'Transfer',
assets_copy_success: 'Copied',
// 交易记录
trade_query_begin: 'Start Time',
trade_query_end: 'End Time',
trade_query_order_type: 'Order Type',
trade_query_more: 'For more transaction records, please search on the blockchain explorer',
trade_query_search: 'Search',
trade_emtpy: 'No Transaction Record',
trade_column_hash: 'Transaction Hash',
trade_column_time: 'Time',
trade_column_assets: 'Assets',
trade_column_type: 'Transaction Type',
trade_column_direction: 'Direction',
trade_column_amount: 'Amount',
trade_column_fee: 'Transaction Fee',
trade_type_order: 'Place Order',
trade_type_cancle: 'Cancel Order',
trade_type_trans: 'Transfer',
trade_type_receive: 'Receive',
trade_type_pay: 'Pay',
trade_type_buy: 'Buy',
trade_type_sell: 'Sell',
// 转账
trans_address: 'Transfer Address',
trans_step_1: 'Transfer',
trans_step_2: 'Please confirm the transaction details',
trans_choose_token: 'Select Asset',
trans_no_token_found: 'No Asset Found',
trans_err_addr_format: 'Invalid Address Format',
trans_err_addr_same: 'Please Don\'t Transfer to Yourself',
trans_amount: 'Transfer Amount',
trans_available: 'Available Transferrable Amount:',
trans_available_not_enough: 'Insufficient Balance',
trans_fee: 'Transaction Fee',
trans_fee_not_enough: 'Insufficient Fee',
trans_note: 'Remarks',
trans_middle_step_show_token: 'Select Asset',
trans_middle_step_show_sender: 'My Address',
trans_middle_step_show_taker: 'Receiving Address',
trans_middle_step_show_amount: 'Transfer Amount',
trans_middle_step_show_fee: 'Transaction Fee',
trans_middle_step_show_note: 'Remarks',
trans_err_pwd: '<PASSWORD>',
trans_success: 'Transfer Successful',
trans_fail: 'Transfer Failed',
group_hot: '24h Vol',
group_new: 'New Tokens',
// desktop新增
'node.main.title': 'Node settings',
'node.active.title': 'Active Node',
'node.delay.type.low': 'Low latency',
'node.delay.type.high': 'High latency',
'node.delay.type.unreachable': 'Unreachable',
'node.tab.wellenow': 'WELLENOW',
'node.tab.local': 'Local',
'node.tab.customerlize': 'CUSTOMERLIZE',
'dex.help.title': 'Is there a problem in DEX operator',
'dex.help.item1': '- DEX Operators Overview',
'dex.help.item2': '- DEX Operators Guide (CLI)',
'dex.help.item3': '- DEX Operators FAQ',
'register.website.label': 'Website',
'register.website.hint': 'Other partners in the ecosystem can get more information through websita. Such as logo, community contact information, etc.',
'register.feeAddress.label': 'HandlingFeeAddress',
'register.feeAddress.hint': 'For security reasons, you can designate another address to collect handling fees.',
'issueToken.symbol.label': 'Symbol',
'issueToken.symbol.hint': 'symbol is a non-case-sensitive token ticker limited to 6 alphanumeric characters, but the first character cannot be a number, eg. “bcoin” since the system will automatically add 3 random characters, such as “bcoin-gf6”',
'issueToken.wholename.label': 'Wholename',
'issueToken.totalSupply.label': 'TotalSupply',
'issueToken.desc.label': 'Desc',
'issueToken.mintable.label': 'Mintable',
'issueToken.issue.btn': 'Issue',
'listToken.label': 'BaseAsset/QuoteAsset',
'listToken.list.btn': 'List',
'listToken.hint': 'Not yet the DEX operation?',
'listToken.hint.register': 'Register',
'listToken.initPrice.label': 'Init-price',
'productList.favorite': 'Favorites',
'productList.owner': 'DEX operator',
'productList.token': 'Token pair',
'productList.noFavorite': 'No results found',
'productList.noResult': 'No Results Found',
'productList.item.pair': 'Token pair',
'productList.item.change': '24h Change',
'productList.item.owner': 'DEX operator',
'productList.item.deposit': 'Deposits',
'linkMenu.Dashboard': 'Dashboard',
'linkMenu.Token': 'Token',
'linkMenu.operator': 'DEX Operator',
'linkMenu.version': 'Version',
'linkMenu.register': 'Register',
'linkMenu.tokenPair': 'List TokenPair',
'linkMenu.deposits': 'Add Deposits',
'linkMenu.handlingFee': 'HandlingFee',
'linkMenu.issue': 'Issue',
'linkMenu.mintBurn': 'Mint&Burn',
'nodeMenu.remote': 'Remote Node',
'nodeMenu.block': 'Block',
'nodeMenu.latency': 'Latency',
'nodeMenu.local': 'Local Node',
'nodeMenu.more': 'more',
'node.stopped': 'Stopped',
tokenPair_emtpy: 'No TokenPair',
issue_empty: 'No Issue',
dashboard_more: 'More',
dashboard_asset_title: 'My Asset',
dashboard_tokenPair_title: 'My List TokenPair',
tokenPair_column_tokenPair: 'TokenPair',
tokenPair_column_birth: 'BirthDay',
tokenPair_column_deposit: 'Deposits',
tokenPair_column_rank: 'Rank',
tokenPair_cell_add: 'Add Deposits',
dashboard_issue_title: 'My Issue',
issue_cell_mint: 'Mint',
issue_cell_burn: 'Burn',
issue_column_token: 'Token',
issue_column_mintable: 'Mintable',
issue_column_original: 'Original totalsupply',
issue_column_total: 'Totalsupply',
dashboard_transaction_title: 'Transaction',
};
export default enUS;
<file_sep>/*
* @Descripttion: 监听设备类型
* @LastEditors: 翟懿博
*/
import mediaSet from '../mediaSet';
const {
_sm, _md, _lg, _xl
} = mediaSet;
const getResult = (media, mediaQueryEvent) => {
let result = mediaSet[media];
if (mediaQueryEvent && !mediaQueryEvent.matches) {
const { preMedia } = mediaSet[media];
result = mediaSet[`_${preMedia}`];
}
return result;
};
class WatchMedia {
constructor() {
this.fn = null;
this.mdWatcher = window.matchMedia(_md.query);
this.lgWatcher = window.matchMedia(_lg.query);
this.xlWatcher = window.matchMedia(_xl.query);
}
_mdListener = (mediaQueryEvent) => {
const result = getResult('_md', mediaQueryEvent);
this.fn(result);
};
_lgListener = (mediaQueryEvent) => {
const result = getResult('_lg', mediaQueryEvent);
this.fn(result);
};
_xlListener = (mediaQueryEvent) => {
const result = getResult('_xl', mediaQueryEvent);
this.fn(result);
};
// 监听设备
// boolean:runNow 是否立即执行回调,默认true
watch(fn, { runNow = true } = {}) {
this.fn = fn;
this.mdWatcher.addListener(this._mdListener);
this.lgWatcher.addListener(this._lgListener);
this.xlWatcher.addListener(this._xlListener);
if (runNow) {
let result = _sm;
if (this.xlWatcher.matches) {
result = _xl;
} else if (this.lgWatcher.matches) {
result = _lg;
} else if (this.mdWatcher.matches) {
result = _md;
}
fn(result);
}
}
destroy() {
this.mdWatcher.removeListener(this._mdListener);
this.lgWatcher.removeListener(this._lgListener);
this.xlWatcher.removeListener(this._xlListener);
}
}
export default WatchMedia;
<file_sep>const zhCN = {
seoTitle: '去中心化交易平台DEX',
borrow: '借',
needBorrow: '需借 ',
repay: '还',
sysError: '系统错误,请稍后再试。',
operationSuccessful: '操作成功',
on: '开',
off: '关',
cancel: '取消',
search: '搜索',
pair: '币对',
price: '最新价',
change: '涨幅',
volume: '成交量',
login: '登录',
signUp: '注册',
phone: '手机',
email: '邮箱',
settings: '更改设置',
symbolDesc: '描述:',
symbolWholeName: '全称:',
symbolId: '币种ID:',
/* spot */
'spot.noData': '暂无数据',
'spot.asset': '资产',
'spot.asset.marginTrade': '杠杆交易',
'spot.asset.newMarginTrade': '杠杆交易',
'spot.asset.spotTrade': '币币交易',
'spot.asset.dexTest': 'DEX交易',
'spot.account.spot': '币币账户',
'spot.asset.futureTrade': '交割合约交易',
'spot.asset.futureswapTrade': '永续合约交易',
'spot.asset.ava': '可用',
'spot.asset.borrow': '已借',
'spot.asset.freeze': '冻结',
'spot.asset.risk': '风险率',
'spot.asset.forceClose': '爆仓价',
'spot.asset.interest': '利息',
'spot.asset.deposit': '充{currency}',
'spot.asset.transfer': '转入资产',
'spot.asset.transferSuccess': '划入成功',
'spot.asset.borrowBill': '借币',
'spot.asset.goBorrow': '去借币',
'spot.asset.borrowBillSuccess': '借币成功',
'spot.asset.repayBill': '还币',
'spot.asset.repayBillSuccess': '还币成功',
'spot.asset.repayBonus': '还糖果',
'spot.asset.repayBonus.tips-0': '您的借币{currency}需要归还糖果{bonus},请在币币账户中留足{bonus}',
'spot.asset.repayBonus.tips-1': '1、未还糖果资产会计入负债计算风险率',
'spot.asset.repayBonus.tips-2': '2、未还清糖果,该币对杠杆账户资产不可转出',
/* spot.bills */
'spot.bills.allCurrency': '全部币种',
'spot.bills.allProduct': '全部币对',
'spot.bills.coin': '币种',
'spot.bills.tradeDate': '成交时间',
'spot.bills.tradeType': '类型',
'spot.bills.allTradeType': '全部类型',
'spot.bills.tradeAmount': '数量',
'spot.bills.balance': '余额',
'spot.bills.fee': '手续费',
'spot.bills.clearTips': '为了提升系统性能,我们会根据空间情况,定期清除部分用户3个月前的历史数据。',
'spot.bills.sentOngoing': '您所需的历史数据正在查询中,预计在10分钟内,下载链接将发送至您的{contactType}{contact}。如有其它问题,请联系在线客服。',
'spot.bills.sentConflict': '您当前仍有查询任务正在进行中,查询完成后,下载链接将发送至您的{contactType}{contact}。如有其它问题,请联系在线客服。',
'spot.bills.sentTooMany': '对不起,您所下载数据量太大,请分批下载(目前单次下载最多支持1000万条数据)。',
'spot.coin': '币种',
'spot.marketDict': '市场',
'spot.favorites': '自选',
/* spot.market */
'spot.market.more': '查看更多',
'spot.market.orders': '交易信息',
'spot.menu.market.orders': '币币委托',
'spot.menu.market.bills': '币币账单',
'spot.menu.market.currencyIntro': '币种介绍',
'spot.menu.market.marginIntro': '杠杆解释说明',
'spot.menu.market.marginGuide': '教你玩转杠杆',
'spot.menu.market.history': '借币历史记录',
'spot.menu.market.strategy': '策略委托说明',
'spot.menu.bills.force': '爆仓订单',
'spot.menu.ready.risk': '风险准备金',
/* spot.orders */
'spot.bills.spot': '币币账单',
'spot.bills.margin': '币币杠杆账单',
'spot.orders.currencies': '币对',
'spot.orders.types': '过滤器',
'spot.orders.last2': '最近两天',
'spot.orders.2daysago': '两天以前',
'spot.search': '查询',
// dex相关
'spot.myOrder.detail': '成交明细',
'spot.myOrder.hash': '哈希值',
'spot.myOrder.date': '委托时间',
'spot.myOrder.product': '币对',
'spot.myOrder.direction': '方向',
'spot.myOrder.filledPercentage': '成交比例',
'spot.myOrder.amount': '委托总量',
'spot.myOrder.price': '委托价',
'spot.myOrder.money': '委托金额',
'spot.myOrder.status': '状态',
'spot.myOrder.operate': '操作',
'spot.myOrder.filledPrice': '成交均价',
'spot.myOrder.filledAmount': '已成交量',
'spot.myOrder.filledStatus': '成交状态',
'spot.myOrder.filledMoney': '成交额',
'spot.myOrder.height': '区块高度',
'spot.myOrder.id': '订单号',
'spot.myOrder.fee': '手续费',
'spot.myOrder.Open': '未成交',
'spot.myOrder.Filled': '完全成交',
'spot.myOrder.Cancelled': '已取消',
'spot.myOrder.Expired': '已过期',
'spot.myOrder.PartialFilledCancelled': '部分成交撤消',
'spot.myOrder.PartialFilledExpired': '部分成交过期',
'spot.myOrder.PartialFilled': '部分成交',
'spot.myOrder.cancelFailed': '撤单失败',
'spot.myOrder.cancelSuccessed': '撤单成功',
'spot.myOrder.cancelNoDealTip': '未成交的订单撤销时将会收取手续费,是否确定撤单?',
'spot.myOrder.cancelPartDealTip': '是否确定撤单?',
'spot.orders.allOrders': '全部挂单',
'spot.orders.amount': '数量',
'spot.orders.averPrice': '平均成交价',
'spot.orders.cancel': '撤单',
'spot.orders.cancelled': '已撤销',
'spot.orders.canceling': '撤单中',
'spot.orders.cancelAll': '当前币对全撤',
'spot.orders.date': '委托时间',
'spot.orders.filled': '成交数量',
'spot.orders.completeFilled': '完全成交',
'spot.orders.noorders': '您暂时没有未完成订单',
'spot.orders.noorders2day': '您最近两天没有已成交的历史挂单',
'spot.orders.noorders2dayago': '您两天以前没有已成交的历史挂单',
'spot.orders.more': '查看更多',
'spot.orders.open': '尚未成交',
'spot.orders.openOrders': '当前委托',
'spot.orders.oneDay': '1天',
'spot.orders.oneWeek': '1周',
'spot.orders.oneMonth': '1月',
'spot.orders.threeMonth': '3月',
'spot.orders.unfinished': '未成交',
'spot.orders.orderHistory': '历史委托',
'spot.orders.partialFilled': '部分成交',
'spot.orders.partial': '部分',
'spot.orders.allProduct': '全部币对',
'spot.orders.price': '价格',
'spot.orders.side': '类别',
'spot.orders.side.spot': '币币',
'spot.orders.side.margin': '杠杆',
'spot.orders.side.spotAndMargin': '币币&杠杆',
'spot.orders.source': '订单来源',
'spot.orders.status': '状态',
'spot.orders.operation': '操作',
'spot.orders.tips.datepicker': '请选择开始日期与结束日期',
'spot.orders.tips.dateRange': '结束日期必须晚于开始日期',
'spot.orders.title': '币币委托',
'spot.orders.total': '金额',
'spot.orders.type': '类型',
'spot.orders.symbol': '币对',
'spot.orders.side2': '方向',
'spot.orders.toast.unhis': '历史委托暂不支持全部查询,请选择币对后进行查询',
'spot.orders.historyRecord': '仅展示当前币对',
'spot.orders.historyRescinded': '隐藏已撤销',
'spot.orders.dealAveragePrice': '成交均价',
'spot.orders.dealt': '已成',
'spot.orders.entrustMoney': '委托金额',
'spot.orders.entrustPrice': '委托价',
'spot.orders.entrustMount': '委托总量',
'spot.orders.direction': '方向',
'spot.orders.myDealList': '我的挂单',
'spot.orders.download': '下载',
'spot.orders.timeUnit': '天',
'spot.orders.timeUnitDay': '天',
'spot.orders.timeUnitHour': '小时',
'spot.orders.statusOnly': '状态',
'spot.orders.operationOnly': '操作',
'spot.orders.noOrders': '您暂时没有未成交的挂单',
'spot.orders.noHistory': '您最近两天没有已成交的历史挂单',
'spot.orders.noData': '您暂时还没有相关数据',
'spot.order.noSpotBills': '您暂时没有币币账单信息',
'spot.order.noMarginBills': '您暂时没有币币杠杆账单信息',
'spot.order.noBorrowOrder': '您暂时没有借款中的订单',
'spot.order.noPayoffOrder': '您暂时没有已还清的订单',
'spot.orders.normalSell': '普通委托',
'spot.orders.triggerPrice': '触发价格',
'spot.orders.tradePrice': '委托价格',
'spot.orders.activatePrice': '激活价格',
'spot.orders.orderSuccess': '委托成功',
'spot.orders.buySuccess': '买单委托成功',
'spot.orders.sellSuccess': '卖单委托成功',
'spot.orders.buyFail': '买单委托失败,请重试!',
'spot.orders.sellFail': '卖单委托失败,请重试!',
'spot.orders.status1': '待生效',
'spot.orders.status2': '已生效',
'spot.orders.status3': '已撤销',
'spot.orders.rise': '上涨',
'spot.orders.fall': '下跌',
'spot.orders.higher': '高于',
'spot.orders.lower': '低于',
'spot.orders.entrustWords': '当价格{direction}至或{compare}{triggerPrice}{baseCurr}时,则以{tradePrice}{baseCurr}的价格{action}{amount}{tradeCurr}',
'spot.orders.cancelExplanation0': '委托超时撤单',
'spot.orders.cancelExplanation1': '用户手动撤单',
'spot.orders.cancelExplanation3': '下单失败撤单',
'spot.orders.actionBuy': '买入',
'spot.orders.actionSell': '卖出',
'spot.orders.triggerPop': '当市场最新成交价达到您设置的触发价格时,系统将自动按您设置的委托价格和数量下达限价委托单。',
'spot.orders.triggerPopPlanOrder': '计划委托是指用户预先设置好委托单和委托单触发价格,当市场的最新成交价达到设置的触发价格时,系统即会将用户事先设置的委托单送入市场的交易策略。',
'spot.orders.triggerPopDetail': '更多详情',
'spot.orders.triggerPopLimitOrder': '限价单是指用户设置委托数量以及可接受的最高买价或最低卖价,当市场价格符合用户预期时,系统会以限价范围内的最优价格进行成交。',
'spot.orders.triggerPopMarketOrder': '市价单是指用户以当前市场最优价格立即执行买入或者卖出。',
'spot.orders.triggerPopTrackOrder': '跟踪委托无数量限制,跟踪委托被触发时下达的',
'spot.orders.triggerPopTrackOrder2': '委托单数量以当时用户可下达的最大数量与用户跟踪委托设置的委托数量,两者中小者为准。',
'spot.orders.triggerPopIcebergOrder': '冰山委托无数量限制,当冰⼭委托在委托时的可下单数量为0时,则冰山委托将被撤销。每个⽤户最多可同时持有6笔冰山委托。',
'spot.orders.triggerPopTimeWeightOrder': '时间加权委托无数量限制,当时间加权委托在委托时的可下单数量为0时,则时间加权委托将被撤销。每个用户最多同时持有6笔时间加权委托。',
'spot.orders.priceVariance': '委托深度',
'spot.orders.priceVarianceExplain': '买单时,系统将以下达限价单时的买一价 * (1-委托深度)作为限价单的价格。卖单时,系统将以下达限价单时的卖一价 * (1+委托深度)作为限价单的价格。',
'spot.orders.totalAmount': '委托总数',
'spot.orders.totalAmountExplain': '您希望买入或卖出的总数量。',
'spot.orders.avgAmount': '单笔均值',
'spot.orders.avgAmountExplain': '系统将在您设置的数量的范围内,设定每次限价单的数量。',
'spot.orders.priceLimit': '价格限制',
'spot.orders.priceLimitExplain': '买单时,当最新成交价大于您设置的价格限制后,该冰山委托将暂停;卖单时,当最新成交价小于您设置的价格限制后,该冰山委托将暂停。',
'spot.orders.filledCount': '已成交量',
'spot.orders.entrustedCount': '已委托量',
'spot.orders.partialStatus': '部分生效',
'spot.orders.pausedStatus': '暂停生效',
/* spot.trade */
'spot.trade': '交易',
'spot.menu.orders': '币币委托',
'spot.app': 'app',
'spot.ios': 'ios',
'spot.web': '网页',
'spot.android': '安卓',
'spot.bid': '买',
'spot.ask': '卖',
'spot.amount': '数量',
'spot.group': '深度合并',
'spot.xDecimal': '位小数',
'spot.singleDecimal': '位小数',
'spot.10Decimal': '十位整数',
'spot.100Decimal': '百位整数',
'spot.1000Decimal': '千位整数',
'spot.10000Decimal': '萬位整数',
'spot.price': '价格',
'spot.total': '金额',
'spot.placeorder.pleaseEnter': '请输入',
'spot.pwd': '<PASSWORD>',
'spot.orderType': '委托类型',
'spot.type': '类型',
'spot.depth.amount': '数量',
'spot.depth.sum': '累计',
'spot.depth.backToCenter': '返回盘口',
'spot.FullLimitOrder': '限价委托',
'spot.limitOrder': '限价单',
'spot.marketOrder': '市价单',
'spot.planOrder': '计划委托',
'spot.trackOrder': '跟踪委托',
'spot.icebergOrder': '冰山委托',
'spot.timeWeightOrder': '时间加权委托',
'spot.shortLimitOrder': '限价',
'spot.shortMarketOrder': '市价',
'spot.market': '市价',
'spot.buy': '买入',
'spot.sell': '卖出',
'spot.buyAndSell': '买&卖',
'spot.buyin': '买入{currency}',
'spot.sellout': '卖出{currency}',
'spot.fee': '费率标准',
'spot.fee.broker': '当前手续费费率:',
'spot.fee.brokerMT': '挂单成交{maker}%,吃单成交{taker}%',
'spot.submit.loading': '正在提交...',
'spot.ava.buy': '可买',
'spot.ava.sell': '可卖',
'spot.callmarket.title': '价格发现',
'spot.callmarket.title.all': '价格发现-第N阶段',
'spot.callmarket.session': '第N阶段',
'spot.callmarket.desc1': '只能下限价单,可以撤单',
'spot.callmarket.desc2': '只能下限价单,不可以撤单',
'spot.callmarket.ended': '已结束',
'spot.callmarket.endedin': '距结束',
'spot.callmarket.startedin': '距开始',
'spot.callmarket.open': '预计开盘价',
'spot.callmarket.matched': '申报匹配量',
'spot.callmarket.unmatched': '申报未匹配量',
'spot.callmarket.startingsoon': '暂未开始',
'spot.place.tips.price': '请输入交易价格',
'spot.place.tips.amount': '请输入交易数量',
'spot.place.tips.total': '请输入交易总金额',
'spot.place.tips.triggerPrice': '触发价格不能为空',
'spot.place.tips.range': '回调幅度不能为空',
'spot.place.tips.activatePrice': '激活价格不能为空',
'spot.place.tips.orderPrice': '委托价格不能为空',
'spot.place.tips.money2': '您的余额不足,请先充值',
'spot.place.tips.minsize': '最小交易数量是',
'spot.place.tips.greaterthan0': '总金额必须大于0',
'spot.place.tips.minbuy': '最小买入',
'spot.place.tips.minsell': '最小卖出',
'spot.place.tips.pwd': '<PASSWORD>',
'spot.place.tips.must': '必须',
'spot.place.tips.multiple': '的整数倍',
'spot.place.tips.margin': '杠杆交易存在爆仓风险,请注意理性投资',
'spot.place.tips.priceVariance': '委托深度不能为空',
'spot.place.tips.totalAmount': '委托总数不能为空',
'spot.place.tips.avgAmount': '单笔均值不能为空',
'spot.place.tips.avgAmountLessThanMin': '单笔均值不能低于委托总数的千分之⼀',
'spot.place.tips.avgAmountLargerThanMax': '单笔均值不能超过委托总数',
'spot.place.tips.priceLimit': '价格限制不能为空',
'spot.place.tips.priceVarianceNotGreaterThan': '委托深度不能大于{max}%',
'spot.place.tips.timeWeight.priceVariance': '扫单范围不能为空',
'spot.place.tips.timeWeight.priceVarianceNotGreaterThan': '扫单范围不能超过{max}%',
'spot.place.tips.timeWeight.sweepRatio': '扫单比例不能为空',
'spot.place.tips.timeWeight.sweepRatioNotGreaterThan': '扫单比例不能超过{max}%',
'spot.place.tips.timeWeight.totalAmount': '委托总数不能为空',
'spot.place.tips.timeWeight.priceLimitTrade': '单笔上限不能为空',
'spot.place.tips.timeWeight.priceLimitTradeLessThanMin': '单笔上限不能小于委托总数千分之一',
'spot.place.tips.timeWeight.priceLimitTradeLargerThanMax': '单笔上限不能大于委托总数',
'spot.place.tips.timeWeight.priceLimitBase': '价格限制不能为空',
'spot.place.tips.timeWeight.timeInterval': '委托间隔不能为空',
'spot.place.tips.timeWeight.timeIntervalRange': '委托间隔不能小于{min}秒大于{max}秒',
'spot.place.confirm.buy': '确认买入',
'spot.place.confirm.sell': '确认卖出',
'spot.place.confirm.normalTrade.buy': '输入资金密码',
'spot.place.marketPrice': '按市场最优价格成交',
'spot.place.forgetPwd': '<PASSWORD>',
'spot.place.nopwd': '<PASSWORD>',
'spot.place.autoBorrowWarn': '完成此次交易您需借币',
'spot.place.forcePrice': '预估爆仓价格',
'spot.place.noWarn': '下次不再提醒',
'spot.place.kline': 'K线',
'spot.place.kline.title': '实时行情',
'spot.place.kline.more': '更多',
'spot.kline.noInfo': '暂无信息',
'spot.place.fullScreen': '全屏交易',
'spot.ticker.legal': '人民币价格',
'spot.ticker.legal.new': '{currency}价格',
'spot.ticker.legal.unit': '计价单位',
'spot.ticker.highest': '24h最高价',
'spot.ticker.lowest': '24h最低价',
'spot.ticker.volume': '24h成交量',
'spot.ticker.inflows': '24h资金流入',
'spot.ticker.outflows': '24h资金流出',
'spot.ticker.inflowTips': '过去24小时主动买入成交量',
'spot.ticker.outflowTips': '过去24小时主动卖出成交量',
'spot.deals.title': '最新交易',
'spot.deals.price': '价格(-)',
'spot.deals.amount': '数量(-)',
'spot.deals.time': '时间',
'spot.deals.no': '暂时没有最新成交',
'spot.ticker.introduce.releaseTime': '发行时间',
'spot.ticker.introduce.distributionAmount': '发行总量',
'spot.ticker.introduce.circulationAmount': '流通总量',
'spot.ticker.introduce.crowdfunding': '众筹价格',
'spot.ticker.introduce.website': '官网',
'spot.ticker.introduce.whitePaper': '白皮书',
'spot.ticker.introduce.introduction': '介绍',
'spot.kline.price': '成交价',
'spot.kline.tabs[0]': '行情',
'spot.kline.tabs[1]': '介绍',
'spot.kline.tabs[2]': '公告',
'spot.kline.tabs[3]': '评级报告',
'spot.kline.tabs[2].more': '全部公告',
'spot.kline.tabs[3].more': '全部评级报告',
'spot.kline.tabs.news': '相关资讯',
'spot.kline.tabs.news.more': '全部资讯',
'spot.page.title': '- 全球领先的比特币/数字货币交易平台 |',
'spot.page.title.tokens': '币币委托 ',
/* 未登录 */
'spot.notlogin.tradenow': '立即开始交易',
'spot.notlogin.preview': '此页面为{site}交易的预览,所有信息均为实时数据',
'spot.notlogin.logintoview1': '您必须',
'spot.notlogin.logintoview2': '登录',
'spot.notlogin.logintoview3': '才可看到此信息',
/* 专业版 */
'spot.all.bills': '全部账单',
'spot.all.history': '全部借币历史记录',
'spot.all.force': '全部爆仓订单',
'spot.all.risk': '全部风险准备金',
/* 公告类别 */
'notice.category.week': '周报',
'notice.category.month': '月报',
'notice.category.news': '快讯',
'notice.category.act': '活动',
'notice.category.treasure': '财报',
'notice.category.rate': '评级报告',
/* 项目披露 */
'spot.project.info': '项目披露',
/* 高阶限价单 */
'spot.advancedLimitOrder': '高级限价委托',
'spot.orders.triggerPopAdvancedLimitOrder': '高级限价委托相对于普通限价委托可选择三种生效机制,“只做Maker(Post only)”、“全部成交或立即取消(FillOrKill)”、“立即成交并取消剩余(ImmediatelOrCancel)”;而普通限价委托的生效机制默认是“一直有效”。',
'spot.orders.orderType': '生效机制',
'spot.orders.orderType.postOnly': '只做Maker(Post only)',
'spot.orders.orderType.FOK': '全部成交或立即取消(FillOrKill)',
'spot.orders.orderType.FAK': '立即成交并取消剩余(ImmediateOrCancel)',
'spot.orders.orderTypeShort.always': '一直有效',
'spot.orders.orderTypeShort.postOnly': 'Post only',
'spot.orders.orderTypeShort.FOK': 'FillOrKill',
'spot.orders.orderTypeShort.FAK': 'ImmediateOrCancel',
'spot.place.tips.orderType': '该委托的生效机制。默认是“只做Maker(Post only)”,不会立刻在市场成交,保证用户始终为Maker;如果委托会立即与已有委托成交,那么该委托会被取消。如果你的委托被设置为“全部成交或立即取消(FillOrKill)”,该委托只会立即全部成交,否则将被取消。如果你的委托被设置为“立即成交并取消剩余(ImmediatelOrCancel)”,任何未被成交的部分将被立即取消。',
'spot.orders.actionBuyMargin': '买入(做多)',
'spot.orders.actionSellMargin': '卖出(做空)',
/* 深度tooltip */
'spot.depth.tooltip.sumTrade': '合计{trade}',
'spot.depth.tooltip.sumBase': '合计{base}',
'spot.depth.tooltip.avgPrice': '均价',
// 通用
all: '全部',
go_back: '返回',
next_step: '下一步',
prev_step: '上一步',
ensure: '确认',
OK: '确定',
please_select: '请选择',
please_input_pwd: '<PASSWORD>',
pwd_error: '<PASSWORD>',
valuation: '估值',
link_to_all: '点击查看全部<<',
// 钱包
// 创建钱包
wallet_create_step1: '创建钱包',
wallet_setPassword: '<PASSWORD>',
wallet_password_placeholder: '请输入至少10位,包含大小写字母和数字的密码',
wallet_password_lengthValidate: '至少10位字符',
wallet_password_chartValidate: '必须包含数字、大小写字母',
wallet_twicePassword: '<PASSWORD>',
wallet_passwordNotSame: '两次密码输入不一致',
wallet_unsaveTip: '我确认DEX不会保存我的任何密码/助记词/Keystore/私钥',
wallet_hadWallet: '已有钱包.',
wallet_importNow: '立即导入>>',
wallet_nextStep: '下一步',
// safetip 安全提示
wallet_safeTip_title: '安全提示',
wallet_safeTip_beforeKeystore: '请在安全环境下,下载',
wallet_safeTip_afterKeystore: '文件,并记录您的助记词,为避免泄漏,请勿拍照或截屏',
wallet_known: '知道了',
// step2 备份助记词
wallet_create_step2: '备份助记词',
wallet_create_backupMnemonic: '请将下列助记词按顺序进行备份',
wallet_create_backupMnemonic_error: '未通过验证,请重新备份',
wallet_create_beginValidate: '我已抄写完,开始验证',
wallet_create_step3: '验证助记词',
wallet_choiceMnemonicPre: '请选择编号为',
wallet_choiceMnemonicSuf: '所对应的助记词',
wallet_ensure: '确定',
wallet_confirm: '确认',
wallet_create_step4: '验证成功',
wallet_mnemonicSuccess: '恭喜您,助记词已验证成功,请妥善保管!',
wallet_toTrade: '立即开始交易',
wallet_seePrivate: '查看私钥',
wallet_privateKey: '私钥',
// 导入钱包
wallet_import: '导入钱包',
wallet_import_mnemonic: '助记词导入',
// keystore导入
wallet_import_upload_todo: '上传Keystore文件,可直接拖动至此',
wallet_import_upload_doing: '上传中',
wallet_import_upload_retry: '重新上传',
wallet_import_passwordTip: '该密码为生成Keystore文件时设置的密码,若丢失则无法导入钱包',
wallet_import_enterPassword: '<PASSWORD>',
wallet_import_fileError: '文件格式错误/文件内容不合法',
wallet_import_noFile: '请先上传Keystore文件',
wallet_import_passwordError: '钱包密码错误',
// 助记词导入
wallet_import_mnemonic_enter: '请输入助记词',
wallet_import_mnemonic_splitTip: '不同单词请用空格分隔',
wallet_import_mnemonic_error: '助记词非法',
wallet_import_mnemonic_sessionPassword: '<PASSWORD>',
wallet_import_mnemonic_none: '助记词不能为空',
// 私钥导入
wallet_import_private_enter: '请输入钱包私钥',
wallet_import_password_placeholder: '<PASSWORD>',
wallet_import_private_error: '私钥非法',
wallet_import_private_none: '私钥不能为空',
wallet_import_sessionPasswordTip: '该密码只对本次登录有效,与其他场景下设置的密码无关',
// Header
header_menu_trade: '交易',
header_menu_order: '订单',
header_menu_create_wallet: '创建钱包',
header_menu_import_wallet: '导入钱包',
header_menu_current_entrust: '当前委托',
header_menu_history_entrust: '历史委托',
header_menu_deal_entrust: '成交明细',
header_menu_wallet: '链上钱包',
header_menu_assets: '资产余额',
header_menu_down_keystore: '下载keystore文件',
header_menu_logout: '退出钱包',
header_menu_logout1: '确定要退出当前钱包',
header_menu_help: '帮助',
header_menu_instructions: '说明文档',
header_menu_draw_omdex: '领取测试币',
header_menu_item_address: '地址',
header_menu_explorer_omchain: '浏览器',
footer_standard_rates: '费率标准',
// 首页
home_banner_title: 'OMEx DEX',
home_banner_subtitle: '无边界去中心化交易平台',
home_banner_btn_trade: '开始交易',
home_adv_title: '产品优势',
home_adv_item0_title: '安全可靠',
home_adv_item0_content: '依靠Secp256k1椭圆曲线算法,用户数字资产存放在自己的钱包中,无需托管即可交易',
home_adv_item1_title: '快捷便利',
home_adv_item1_content: 'OMEx DEX严格审核链上资产,以价值稳定数字资产作为计价货币,提供多种交易选择',
home_adv_item2_title: '持续迭代',
home_adv_item2_content: 'OMEx DEX会第一时间支持OMChain的各项新功能,提供更优的交易体验',
home_exp_title: '体验模拟交易',
home_exp_content: '已经创建过OMChain钱包的OMEx用户,我们将会为您发放一定数量的测试币,数量有限,先到先得。',
home_steps_title: '快速开始',
home_steps_item0_title: '1.创建OMChain钱包',
home_steps_item0_content: 'DEX不会保存您链上钱包的任何信息;助记词和keystore文件是您拥有个人资产的唯一凭证,请妥善保管,若已经创建完成,您可以直接导入钱包。',
home_steps_item0_button: '创建钱包',
home_steps_item1_title: '2.钱包充值',
home_steps_item1_content: '登录OMChain链上钱包,进入资产管理,获得OMChain链上地址;测试网可以通过领取测试币直接参与DEX交易;到账记录可在链上钱包——资产记录里面查看。',
home_steps_item1_button: '领取测试币',
home_steps_item2_title: '3.去交易',
home_steps_item2_content: '使用领取的测试币在任意交易对进行交易;您的每次下单、撤单操作都会生成一个哈希值,被广播至区块链网络。',
home_steps_item2_button: '立即交易',
home_steps_item3_title: '4.查看交易信息',
home_steps_item3_content: '每一笔交易、转账都可以通过交易哈希值、地址等在区块链浏览器中查询相应信息。',
home_steps_item3_button: '查看区块数据',
home_steps_item0_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/5BBC703C1C9BF16E9B3DBE44E9306EBD.png',
home_steps_item1_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/EA5B9697721EAAE780B6A0D18D5F6DE5.png',
home_steps_item2_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/0A848CAA0FA942D868854F6F469ADEC1.png',
home_steps_item3_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/F497569D03E57047301DAC9E4CB05207.png',
home_exp_more: '想要进一步了解「DEX、OMChain详细设计规则」',
home_exp_img: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/3AF196CA9B03F9FFAE8A519469FBB6AD.png',
home_subtitle: 'OMChain测试网上线,所有交易记录链上可查',
home_receive_coin: '领取测试币',
home_step5_title: '帮助文档',
// 资产余额
assets_tab_accounts: '资产余额',
assets_tab_transactions: '交易记录',
assets_address: '地址:',
assets_product_search: '币种搜索',
assets_hide_zero: '隐藏零余额资产',
assets_empty: '暂无资产',
assets_column_assets: '资产',
assets_column_total: '总量',
assets_column_balance: '可用',
assets_column_freeze: '冻结',
assets_column_list: '挂单',
assets_trans_btn: '转账',
assets_copy_success: '复制成功',
// 交易记录
trade_query_begin: '起始时间',
trade_query_end: '截止时间',
trade_query_order_type: '订单类型',
trade_query_more: '更多交易记录请在区块链浏览器查看',
trade_query_search: '查询',
trade_emtpy: '暂无交易记录',
trade_column_hash: '交易哈希',
trade_column_time: '时间',
trade_column_assets: '资产',
trade_column_type: '交易类型',
trade_column_direction: '方向',
trade_column_amount: '金额',
trade_column_fee: '手续费',
trade_type_order: '下单',
trade_type_cancle: '撤单',
trade_type_trans: '转账',
trade_type_receive: '收款',
trade_type_pay: '付款',
trade_type_buy: '买',
trade_type_sell: '卖',
// 转账
trans_address: '转账地址',
trans_step_1: '转账',
trans_step_2: '请确认交易信息',
trans_choose_token: '选择币种',
trans_no_token_found: '搜索不到币种',
trans_err_addr_format: '地址格式错误',
trans_err_addr_same: '不能给自己转账',
trans_amount: '转账数量',
trans_available: '可转账数量:',
trans_available_not_enough: '余额不足',
trans_fee: '手续费',
trans_fee_not_enough: '手续费不足',
trans_note: '备注',
trans_middle_step_show_token: '选择币种',
trans_middle_step_show_sender: '我的地址',
trans_middle_step_show_taker: '收款地址',
trans_middle_step_show_amount: '转账数量',
trans_middle_step_show_fee: '手续费',
trans_middle_step_show_note: '备注',
trans_err_pwd: '<PASSWORD>',
trans_success: '转账成功',
trans_fail: '转账失败',
group_hot: '热门榜',
group_new: '打新榜',
// desktop新增
'node.main.title': 'Node settings',
'node.active.title': 'Active Node',
'node.delay.type.low': 'Low latency',
'node.delay.type.high': 'High latency',
'node.delay.type.unreachable': 'Unreachable',
'node.tab.wellenow': 'WELLENOW',
'node.tab.local': 'Local',
'node.tab.customerlize': 'CUSTOMERLIZE',
'dex.help.title': 'Is there a problem in DEX operator',
'dex.help.item1': '- DEX Operators Overview',
'dex.help.item2': '- DEX Operators Guide (CLI)',
'dex.help.item3': '- DEX Operators FAQ',
'register.website.label': 'Website',
'register.website.hint': 'Other partners in the ecosystem can get more information through websita. Such as logo, community contact information, etc.',
'register.feeAddress.label': 'HandlingFeeAddress',
'register.feeAddress.hint': 'For security reasons, you can designate another address to collect handling fees.',
'issueToken.symbol.label': 'Symbol',
'issueToken.symbol.hint': 'symbol is a non-case-sensitive token ticker limited to 6 alphanumeric characters, but the first character cannot be a number, eg. “bcoin” since the system will automatically add 3 random characters, such as “bcoin-gf6”',
'issueToken.wholename.label': 'Wholename',
'issueToken.totalSupply.label': 'TotalSupply',
'issueToken.desc.label': 'Desc',
'issueToken.mintable.label': 'Mintable',
'issueToken.issue.btn': 'Issue',
'listToken.label': 'BaseAsset/QuoteAsset',
'listToken.list.btn': 'List',
'listToken.hint': 'Not yet the DEX operation?',
'listToken.hint.register': 'Register',
'listToken.initPrice.label': 'Init-price',
'productList.favorite': '我的关注',
'productList.owner': '按运营方查询',
'productList.token': '按交易对查询',
'productList.noFavorite': '暂无关注',
'productList.noResult': 'No Results Found',
'productList.item.pair': '交易对',
'productList.item.change': '涨幅',
'productList.item.owner': '运营商',
'productList.item.deposit': '撮合金',
'linkMenu.Dashboard': 'Dashboard',
'linkMenu.Token': 'Token',
'linkMenu.operator': 'DEX Operator',
'linkMenu.version': 'Version',
'linkMenu.register': 'Register',
'linkMenu.tokenPair': 'List TokenPair',
'linkMenu.deposits': 'Add Deposits',
'linkMenu.handlingFee': 'HandlingFee',
'linkMenu.issue': 'Issue',
'linkMenu.mintBurn': 'Mint&Burn',
'nodeMenu.remote': 'Remote Node',
'nodeMenu.block': 'Block',
'nodeMenu.latency': 'Latency',
'nodeMenu.local': 'Local Node',
'nodeMenu.more': 'more',
'node.stopped': 'Stopped',
tokenPair_emtpy: 'No TokenPair',
issue_empty: 'No Issue',
dashboard_more: 'More',
dashboard_asset_title: 'My Asset',
dashboard_tokenPair_title: 'My List TokenPair',
tokenPair_column_tokenPair: 'TokenPair',
tokenPair_column_birth: 'BirthDay',
tokenPair_column_deposit: 'Deposits',
tokenPair_column_rank: 'Rank',
tokenPair_cell_add: 'Add Deposits',
dashboard_issue_title: 'My Issue',
issue_cell_mint: 'Mint',
issue_cell_burn: 'Burn',
issue_column_token: 'Token',
issue_column_mintable: 'Mintable',
issue_column_original: 'Original totalsupply',
issue_column_total: 'Totalsupply',
dashboard_transaction_title: 'Transaction',
};
export default zhCN;
<file_sep>import { toLocale } from '_src/locale/react-locale';
import { calc } from '_component/omit';
import util from '../utils/util';
import Enum from './Enum';
const FormatAsset = {
// 获取现货交易资产(币币交易资产)
getSpotData(product, account, productConfig) {
if (!product || !productConfig) {
return null;
}
// 两种精度可能为0,所以用undefined进行判断
const sizeTruncate = typeof productConfig.max_size_digit !== 'undefined' ? productConfig.max_size_digit : 4;
const quoteSizeTruncate = typeof productConfig.quotePrecision !== 'undefined' ? productConfig.quotePrecision : 4;
// 交易货币信息
const baseCurr = product.indexOf('_') > -1 ? product.split('_')[0].toUpperCase() : '-';
const baseCurrAccount = account[baseCurr.toLowerCase()];
const baseCurrAvail = baseCurrAccount ?
calc.showFloorTruncation(baseCurrAccount.available, sizeTruncate)
:
calc.showFloorTruncation(0, sizeTruncate);
const baseCurrFreeze = baseCurrAccount ?
calc.showFloorTruncation(baseCurrAccount.locked, sizeTruncate)
:
calc.showFloorTruncation(0, sizeTruncate);
// 计价货币信息
const quoteCurr = product.indexOf('_') > -1 ? product.split('_')[1].toUpperCase() : '-';
const quoteCurrAccount = account[quoteCurr.toLowerCase()];
const quoteCurrAvail = quoteCurrAccount ?
calc.showFloorTruncation(quoteCurrAccount.available, quoteSizeTruncate)
:
calc.showFloorTruncation(0, quoteSizeTruncate);
const quoteCurrFreeze = quoteCurrAccount ?
calc.showFloorTruncation(quoteCurrAccount.locked, quoteSizeTruncate)
:
calc.showFloorTruncation(0, quoteSizeTruncate);
return [{
currencyName: baseCurr,
available: baseCurrAvail,
locked: baseCurrFreeze
}, {
currencyName: quoteCurr,
available: quoteCurrAvail,
locked: quoteCurrFreeze
}];
},
// 获取现货交易资产(币币交易资产) - 非登录下
getSpotDataNotLogin(product) {
const { productConfig } = window.OM_GLOBAL;
if (!product || !productConfig) {
return undefined;
}
// 两种精度可能为0,所以用undefined进行判断
const sizeTruncate = typeof productConfig.max_size_digit !== 'undefined' ? productConfig.max_size_digit : 4;
const quoteSizeTruncate = typeof productConfig.quotePrecision !== 'undefined' ? productConfig.quotePrecision : 4;
// 计价货币信息
const quoteCurr = product.indexOf('_') > -1 ? product.split('_')[1].toUpperCase() : '-';
// 交易货币信息
const baseCurr = product.indexOf('_') > -1 ? product.split('_')[0].toUpperCase() : '-';
return [{
currencyName: baseCurr,
available: calc.showFloorTruncation(0, sizeTruncate),
locked: calc.showFloorTruncation(0, sizeTruncate)
}, {
currencyName: quoteCurr,
available: calc.showFloorTruncation(0, quoteSizeTruncate),
locked: calc.showFloorTruncation(0, quoteSizeTruncate)
}];
}
};
export default FormatAsset;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import InputNum from '_component/InputNum';
import { toLocale } from '_src/locale/react-locale';
import { calc } from '_component/omit';
import Enum from '../../utils/Enum';
import FormatNum from '../../utils/FormatNum';
import util from '../../utils/util';
import StrategyTypeSelect from '../placeOrders/StrategyTypeSelect';
import TradeSliderBar from '../../component/TradeSliderBar';
import Available from '../../component/placeOrder/Available';
import SubmitButton from '../../component/placeOrder/SubmitButton';
import URL from '../../constants/URL';
function mapStateToProps(state) { // 绑定redux中相关state
const { SpotTrade } = state;
const {
currencyTicker, isShowTradePwd, symbol,
} = SpotTrade;
const currencyPrice = currencyTicker.price;
return {
symbol,
currencyTicker,
currencyPrice,
isShowTradePwd,
};
}
function mapDispatchToProps() {
return {};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
export default class MarketForm extends React.Component {
constructor(props) {
super(props);
this.state = {
inputObj: { // 下单的input值(由原来的reducer移动到这里)
price: '',
amount: '',
total: ''
},
isLoading: false, // 下单按钮loading状态
warning: '', // 错误信息
};
this.formParam = {}; // 表单参数
}
componentDidMount() {
const { currencyPrice } = this.props;
this.updateInput({
price: currencyPrice
});
}
componentWillReceiveProps(nextProps) {
const {
symbol, currencyTicker, type, asset
} = nextProps;
if (this.props.symbol !== symbol || this.props.asset.isMargin !== asset.isMargin) { // 切换币对
this.clearForm();
this.updateWarning();
this.updateInput({
price: currencyTicker.price
});
}
if (this.props.type !== type) {
this.clearForm();
}
}
// 输入框 keyup
onInputKeyUp = (key) => {
return (value, e) => {
const config = window.OM_GLOBAL.productConfig;
const { inputObj } = this.state;
const priceTruncate = config.max_price_digit;
const sizeTruncate = config.max_size_digit;
if (util.ctrlAorTab(e)) {
return;
}
const input = { ...inputObj };
let inputValue = value;
inputValue = inputValue.replace(/\s+/g, '');
/* 清空操作 */
if (!inputValue.length) {
input[key] = '';
this.updateInput(input);
return;
}
/* 非清空操作 */
// 总金额小数位操作
if (['total'].indexOf(key) > -1) {
inputValue = FormatNum.CheckInputNumber(inputValue, priceTruncate);
} else if (['amount'].indexOf(key) > -1) {
// 数量操作
// 保留小数位操作
inputValue = FormatNum.CheckInputNumber(inputValue, sizeTruncate);
}
input[key] = inputValue;
this.updateInput(input);
};
};
// 输入改变
onInputChange = (key) => {
return (inputValue) => {
const { inputObj } = this.state;
const { productConfig } = window.OM_GLOBAL;
const input = { ...inputObj };
const priceTruncate = productConfig.max_price_digit;
const sizeTruncate = productConfig.max_size_digit;
// 非pwd输入,当输入只有.的时候,切换为空
const value = inputValue === '.' ? '' : inputValue;
if (key === 'total') {
// 输入总金额
input[key] = FormatNum.CheckInputNumber(value, priceTruncate);
} else if (key === 'amount') {
// 输入数量
input[key] = FormatNum.CheckInputNumber(value, sizeTruncate);
}
this.updateWarning(''); // 清空错误提示
this.updateInput(input); // 更新input值
};
};
// 拖动百分比sliderBar
onTradeSliderBarChange = (value) => {
const { productConfig } = window.OM_GLOBAL;
const { asset, type } = this.props;
const { baseAvailable, tradeAvailable } = asset;
const { inputObj } = this.state;
const newInputObj = { ...inputObj };
const barValue = value * 0.01;
// 精度有可能是0
const priceTruncate = 'max_price_digit' in productConfig ? productConfig.max_price_digit : 2;
const sizeTruncate = 'max_size_digit' in productConfig ? productConfig.max_size_digit : 2;
if (type === Enum.placeOrder.type.buy) { // 买单
if (Number(baseAvailable) === 0) {
return false;
}
newInputObj.total = calc.floorMul(baseAvailable, barValue, priceTruncate);
} else { // 卖单
if (Number(tradeAvailable) === 0) {
return false;
}
newInputObj.amount = calc.floorMul(tradeAvailable, barValue, sizeTruncate);
}
newInputObj.total = newInputObj.total > 0 ? newInputObj.total : '';
newInputObj.amount = newInputObj.amount > 0 ? newInputObj.amount : '';
return this.updateInput(newInputObj);
};
// 提交表单
onOrderSubmit = () => {
const {
type, asset, currencyPrice
} = this.props;
const { updateWarning } = this;
const { inputObj } = this.state;
const {
isMargin, baseAvailable,
tradeAvailable,
tradeCurr
} = asset;
const { productConfig } = window.OM_GLOBAL;
const min_trade_size = productConfig.min_trade_size;
const tradePrice = inputObj.price;
const tradeAmount = inputObj.amount;
const totalMoney = inputObj.total;
const tempParams = {
price: tradePrice,
size: tradeAmount,
quoteSize: totalMoney
};
let userBalance = 0;
if (type === Enum.placeOrder.type.buy) {
userBalance = Number(baseAvailable);
}
if (type === Enum.placeOrder.type.sell) {
userBalance = Number(tradeAvailable);
}
// 市价单 只做余额判断
if (type === Enum.placeOrder.type.buy) { // 买
// 检查 下单金额比当前价格的最小购买单位还少
if (Number(totalMoney) < Number(calc.mul(currencyPrice, min_trade_size))) {
updateWarning(toLocale('spot.place.tips.minbuy') + min_trade_size + tradeCurr);
return false;
}
// 计价货币余额不足
if (Number(userBalance) < Number(totalMoney)) {
updateWarning(toLocale('spot.place.tips.money2'));
return false;
}
tempParams.price = totalMoney;
} else if (type === Enum.placeOrder.type.sell) { // 卖
// 检查 交易金额小于当前币种 的最小购买单位,无法卖出
if (Number(tradeAmount) < Number(min_trade_size)) {
updateWarning(toLocale('spot.place.tips.minsell') + min_trade_size + tradeCurr);
return false;
}
// 交易货币余额不足
if (Number(userBalance) < Number(tradeAmount)) {
updateWarning(toLocale('spot.place.tips.money2'));
return false;
}
tempParams.size = tradeAmount;
}
this.formParam = {
postUrl: URL.POST_SUBMIT_ORDER,
side: type,
price: tempParams.price,
size: tempParams.size,
systemType: isMargin ? Enum.spotOrMargin.margin : Enum.spotOrMargin.spot,
quoteSize: tempParams.quoteSize,
orderType: 1
};
updateWarning('');
this.setLoading(true);
return this.props.onSubmit(this.formParam, () => {
this.clearForm();
this.setLoading(false);
}, (res) => {
if (res && res.msg) {
this.updateWarning(res.msg);
}
this.setLoading(false);
});
};
// 获取sliderBar当前percent
getPercent = (baseAvailable, tradeAvailable) => {
let percent = 0;
const { productConfig } = window.OM_GLOBAL;
const { type } = this.props;
const { inputObj } = this.state;
const { total, amount } = inputObj;
const priceTruncate = 'max_price_digit' in productConfig ? productConfig.max_price_digit : 2;
const sizeTruncate = 'max_size_digit' in productConfig ? productConfig.max_size_digit : 2;
if (type === Enum.placeOrder.type.buy) { // 买单,根据总金额计算百分比
percent = baseAvailable === 0 ? 0 : calc.div(Number(total), calc.floorTruncate(baseAvailable, priceTruncate));
} else { // 卖单,根据数量计算百分比
percent = tradeAvailable === 0 ? 0 : calc.div(Number(amount), calc.floorTruncate(tradeAvailable, sizeTruncate));
}
percent = percent > 1 ? 1 : percent;
return Number((percent * 100).toFixed(2));
};
setLoading = (isLoading = false) => {
this.setState({ isLoading });
};
updateInput = (inputObj) => {
this.setState(Object.assign(this.state.inputObj, inputObj));
};
updateWarning = (warning = '') => {
this.setState({ warning });
};
clearForm = () => {
this.setState(Object.assign(this.state.inputObj, {
amount: '',
total: ''
}));
};
// 价格
renderPrice = () => {
const { tradeType } = window.OM_GLOBAL;
if (tradeType === Enum.tradeType.normalTrade) {
return null;
}
return (
<span
style={{
color: 'rgba(255,255,255,0.3)',
marginLeft: '20px'
}}
className="flex-row vertical-middle"
>
{toLocale('spot.place.marketPrice')}
</span>
);
};
// 滑动条
renderSliderBar = () => {
const { asset, type } = this.props;
const { baseAvailable, tradeAvailable } = asset;
const isFullTrade = window.OM_GLOBAL.tradeType === Enum.tradeType.fullTrade;
const sliderType = type === Enum.placeOrder.type.buy ? 'green' : 'red';
const percent = this.getPercent(baseAvailable, tradeAvailable);
return (
<TradeSliderBar
value={percent}
color={sliderType}
theme={isFullTrade ? 'dark' : 'light'}
onChange={this.onTradeSliderBarChange}
/>
);
};
// 买入只显示总金额
renderTotal = () => {
const { tradeType } = window.OM_GLOBAL;
const { asset, type } = this.props;
const { inputObj } = this.state;
const { baseCurr } = asset;
if (type === Enum.placeOrder.type.buy) {
return (
<div className="input-container">
{tradeType === Enum.tradeType.normalTrade ?
<span className="input-title">
{toLocale('spot.total')} ({baseCurr})
</span>
:
null
}
<InputNum
type="text"
onKeyUp={this.onInputKeyUp('total')}
onChange={this.onInputChange('total')}
autoComplete="off"
value={inputObj.total}
className="input-theme-controls"
placeholder={tradeType === Enum.tradeType.normalTrade ? null : `${toLocale('spot.placeorder.pleaseEnter') + toLocale('spot.total')} (${baseCurr})`}
/>
</div>
);
}
return null;
};
// 卖出只显示数量
renderAmount = () => {
const { tradeType, productConfig } = window.OM_GLOBAL;
const { asset, type } = this.props;
const { inputObj } = this.state;
const { tradeCurr } = asset;
let placeholder = `${toLocale('spot.placeorder.pleaseEnter')
+ toLocale('spot.amount')} (${tradeCurr})`;
if (tradeType === Enum.tradeType.normalTrade) {
// 非全屏模式
placeholder = `${toLocale('spot.place.tips.minsize')}${productConfig.min_trade_size}${tradeCurr}`;
}
if (type === Enum.placeOrder.type.sell) {
return (
<div className="input-container">
{tradeType === Enum.tradeType.normalTrade ?
<span className="input-title">
{toLocale('spot.amount')} ({tradeCurr})
</span> : null}
<InputNum
type="text"
onKeyUp={this.onInputKeyUp('amount')}
onChange={this.onInputChange('amount')}
value={inputObj.amount}
className="input-theme-controls"
placeholder={placeholder}
/>
</div>
);
}
return null;
};
render() {
const { tradeType } = window.OM_GLOBAL;
const { needWarning, asset, type } = this.props;
const { warning, isLoading } = this.state;
const isFullTrade = tradeType === Enum.tradeType.fullTrade;
return (
<div className="spot-trade-market">
<div className={isFullTrade ? 'flex-row mar-bot8' : ''}>
<StrategyTypeSelect strategyType={Enum.placeOrder.strategyType.market} />
{this.renderPrice()}
</div>
{this.renderSliderBar()}
{this.renderTotal()}
{this.renderAmount()}
<Available asset={asset} type={type} />
<SubmitButton
type={type}
unit={asset.tradeCurr}
isMargin={asset.isMargin}
isLoading={isLoading}
onClick={this.onOrderSubmit}
warning={needWarning ? warning : ''}
/>
</div>
);
}
}
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import PageURL from '../constants/PageURL';
import * as SpotActions from '../redux/actions/SpotAction';
function mapStateToProps(state) { // 绑定redux中相关state
return {
productList: state.SpotTrade.productList,
activeMarket: state.Spot.activeMarket
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch)
};
}
const TradeAreaWrapper = (Component) => {
@withRouter
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class TradeArea extends React.Component {
// 改变交易区
onTabChange = (key) => {
return () => {
const { productList } = this.props;
// const { pathname } = window.location;
const pathname = window.OM_GLOBAL.isMarginType ? PageURL.spotMarginTradePage : PageURL.spotTradePage;
let product = '';
let newHash = '';
if (Number(key) === 1) { // 自选
const collectList = productList.filter((product) => {
return +product.collect === 1;
});
product = collectList.length > 0 ? collectList[0].product : productList[0].product;
newHash = `#product=${product.toLowerCase()}&favorites=1`;
} else { // 其他交易区
// forEach方法不能break,故用some方法
productList.some((item) => {
const thisMarket = item.product.split('_')[1];
if (key === thisMarket) {
// 选中交易区的第一个(非隐藏)币对
product = item.product;
newHash = `#product=${product.toLowerCase()}`;
return true;
}
return false;
});
}
this.props.history.replace(pathname + newHash);
const { spotActions } = this.props;
spotActions.updateSearch('');
spotActions.updateActiveMarket(key);
spotActions.updateProduct(product);
};
};
render() {
const { productList } = this.props;
let marketFlag = '';
const markets = [];
productList.forEach((product) => {
const thisMarket = product.product.split('_')[1];
if (marketFlag !== thisMarket) {
marketFlag = thisMarket;
markets.push(marketFlag);
}
});
return (
<Component
{...this.props}
markets={markets}
onAreaChange={this.onTabChange}
/>
);
}
}
return TradeArea;
};
export default TradeAreaWrapper;
<file_sep>import React from 'react';
import { withRouter } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import DatePicker from '_component/ReactDatepicker';
import Select from '_component/ReactSelect';
import 'react-datepicker/dist/react-datepicker.css';
import { toLocale } from '_src/locale/react-locale';
import Message from '_src/component/Message';
import { Dialog } from '_component/Dialog';
import Icon from '_src/component/IconLite';
import Checkbox from 'rc-checkbox';
import moment from 'moment';
import Cookies from 'js-cookie';
import Loading from '_component/Loading';
import RouterCredential from '../../RouterCredential';
import ont from '../../utils/dataProxy';
import DexTable from '../../component/DexTable';
import URL from '../../constants/URL';
import * as SpotActions from '../../redux/actions/SpotAction';
import * as OrderActions from '../../redux/actions/OrderAction';
import Enum from '../../utils/Enum';
import orderUtil from './orderUtil';
import PasswordDialog from '../../component/PasswordDialog';
import './OrderList.less';
import { Button } from '_component/Button';
import normalColumns from '../spotOrders/normalColumns';
import commonUtil from '../spotOrders/commonUtil';
import * as CommonAction from '../../redux/actions/CommonAction';
import * as FormAction from '../../redux/actions/FormAction';
import Config from '../../constants/Config';
import util from '../../utils/util';
function mapStateToProps(state) { // 绑定redux中相关state'
const { product, productList, productObj } = state.SpotTrade;
const { data } = state.OrderStore;
const { theme } = state.Spot;
const { privateKey } = state.Common;
const { FormStore } = state;
return {
product, productList, productObj, data, theme, privateKey, FormStore
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
commonAction: bindActionCreators(CommonAction, dispatch),
formActions: bindActionCreators(FormAction, dispatch),
spotActions: bindActionCreators(SpotActions, dispatch),
orderActions: bindActionCreators(OrderActions, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class OpenList extends RouterCredential {
constructor(props, context) {
super(props, context);
this.threeDaysAgo = moment().subtract(3, 'days').endOf('day');
this.todayAgo = moment().subtract(0, 'days').endOf('day');
this.minDate = moment().subtract(3, 'month');
this.maxDate = moment();
this.state = {
isLoading: false,
isShowPwdDialog: false, // 资金密码弹窗
cancelLoading: false, // 取消订单期间的loading状态
product: 'all',
side: 'all',
start: this.threeDaysAgo,
end: this.todayAgo
};
this.targetNode = null;
}
componentWillMount() {
const { orderActions } = this.props;
orderActions.resetData();
if (this.props.location.state && this.props.location.state.product) {
this.setState({
product: this.props.location.state.product
});
}
if (this.props.location.state && this.props.location.state.period) {
let interval = 1;
const period = this.props.location.state.period;
if (period === 'oneWeek') {
interval = 7;
} else if (period === 'oneMonth') {
interval = 30;
} else if (period === 'threeMonth') {
interval = 90;
}
const start = moment().subtract(interval, 'days').endOf('day');
const end = moment().subtract(0, 'days').endOf('day');
this.setState({
start,
end
});
}
}
componentDidMount() {
// 初始化omchain客户端。原因是交易页、未成交委托页撤单和资产页转账都需要
this.props.commonAction.initOMChainClient();
const { spotActions, orderActions } = this.props;
spotActions.fetchProducts();
const { webType } = window.OM_GLOBAL;
document.title = toLocale('spot.orders.openOrders') + toLocale('spot.page.title');
// orderActions.getNoDealList();
this.onSearch();
}
componentWillReceiveProps(nextProps) {
}
componentWillUnmount() {
const { orderActions } = this.props;
orderActions.resetData();
}
// 撤销订单
onCancelOrder = (order) => {
return (e) => {
e.persist(); // 移出事件池从而保留事件对象
// 2019-08-13 增加用户清空全部缓存的判断
if (!util.isLogined()) {
window.location.reload();
}
// this.formParam = { product, order_id };
// // 检查私钥,如果未过期直接取私钥,如果过期显示弹窗
// const expiredTime = localStorage.getItem('pExpiredTime') || 0;
// // 小于30分钟,且privateKey,(true时),不需要输入密码,直接提交
// if ((new Date().getTime() < +expiredTime) && this.props.privateKey) {
// const param = { ...this.formParam, pk: this.props.privateKey };
// return this.props.orderActions.cancelOrder(param, this.successToast, this.onSubmitErr);
// }
// return this.onPwdOpen();
const order_id = order.order_id;
let title = toLocale('spot.myOrder.cancelPartDealTip');
if ((order.quantity - order.remain_quantity) === 0) { // 未成交
title = toLocale('spot.myOrder.cancelNoDealTip');
}
const _this = this;
const dialog = Dialog.confirm({
title,
confirmText: toLocale('ensure'),
cancelText: toLocale('cancel'),
theme: 'dark',
dialogId: 'omdex-confirm',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
dialog.destroy();
if (Number(e.target.getAttribute('canceling'))) {
return;
}
e.target.setAttribute('canceling', 1);
this.targetNode = e.target;
this.formParam = { order_id, start: Math.floor(_this.state.start.valueOf() / 1000 - 86400), end: Math.floor(_this.state.end.valueOf() / 1000) };
if (_this.state.product !== 'all') {
this.formParam = { ...this.formParam, product: _this.state.product };
}
if (_this.state.side !== 'all') {
this.formParam = { ...this.formParam, side: _this.state.side };
}
// 检查私钥,如果未过期直接取私钥,如果过期显示弹窗
const expiredTime = window.localStorage.getItem('pExpiredTime') || 0;
// 小于30分钟,且privateKey,(true时),不需要输入密码,直接提交
if ((new Date().getTime() < +expiredTime) && this.props.privateKey) {
const param = { ...this.formParam, pk: this.props.privateKey };
this.setState({
isShowPwdDialog: false,
cancelLoading: true,
}, () => {
e.target.setAttribute('canceling', 0);
this.props.orderActions.cancelOrder(param, this.successToast, this.onSubmitErr);
});
} else {
e.target.setAttribute('canceling', 0);
this.onPwdOpen();
}
},
});
};
};
// 查询
onBtnSearch = () => {
this.onSearch({ page: 1 });
};
onSearch = (param) => {
const { orderActions } = this.props;
const { start, end } = this.state;
const params = {
product: this.state.product,
start: this.state.start,
end: this.state.end,
side: this.state.side,
...param
};
params.start = Math.floor(start.valueOf() / 1000) - 86400;
params.end = Math.floor(end.valueOf() / 1000);
if (params.start >= params.end) {
Message.warn({ content: toLocale('spot.orders.tips.dateRange') });
return false;
}
params.from = 'IndependentPage';
orderActions.getNoDealList(params);
};
// 币对改变
onProductsChange = (obj) => {
const value = obj.value;
if (value.length > 0) {
this.setState({
product: value
}, () => {
this.onSearch({ page: 1 });
});
}
};
// 买卖筛选的改版
onSideChange = (obj) => {
const value = obj.value;
let side = 'all';
if (+value === 1) {
side = 'BUY';
} else if (+value === 2) {
side = 'SELL';
}
this.setState({
side
}, () => {
this.onSearch({ page: 1 });
});
};
// 设置日期
onDatePickerChange(key) {
return (date) => {
this.setState({
[key]: date
}, () => {
this.onSearch({ page: 1 });
});
};
}
// 页码变化
onPageChange = (page) => {
this.onSearch({ page });
};
handleDateChangeRaw = (e) => {
e.preventDefault();
};
// 渲染查询条件行
renderQuery = () => {
const { productList } = this.props;
const sortProductList = productList.sort((a, b) => { return (a.base_asset_symbol).localeCompare(b.base_asset_symbol); });
const newProductList = sortProductList.map((obj) => {
return {
value: obj.product,
label: obj.product.replace('_', '/').toUpperCase()
};
});
const {
product, side, start, end
} = this.state;
newProductList.unshift({ value: 'all', label: toLocale('spot.orders.allProduct') });
return (
<div className="query-container">
<div className="sub-query">
<span>{toLocale('spot.orders.symbol')}</span>
<Select
clearable={false}
searchable={false}
small
theme="dark"
name="form-field-name"
value={product}
onChange={this.onProductsChange}
options={newProductList}
style={{ width: 160 }}
/>
<span>{toLocale('spot.myOrder.direction')}</span>
<Select
clearable={false}
searchable={false}
small
theme="dark"
name="form-field-name"
value={side === 'all' ? 0 : (side === 'BUY' ? 1 : 2)}
onChange={this.onSideChange}
options={orderUtil.sideList()}
className="select-theme-controls mar-rig16 select-container"
style={{ width: 160 }}
/>
<span />
<DatePicker
small
selectsStart
theme="dark"
placeholderText="起始时间"
selected={start || null}
startDate={start || null}
endDate={end || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={this.minDate}
maxDate={end || this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('start')}
/>
<div className="dash" />
<DatePicker
small
selectsEnd
theme="dark"
placeholderText="截止时间"
selected={end || null}
startDate={start || null}
endDate={end || null}
dateFormat="YYYY-MM-DD"
onChangeRaw={this.handleDateChangeRaw}
minDate={start || this.minDate}
maxDate={this.maxDate}
locale={util.getSupportLocale(Cookies.get('locale') || 'en_US').toLocaleLowerCase()}
onChange={this.onDatePickerChange('end')}
/>
<Button
className="btn"
size={Button.size.small}
type={Button.btnType.primary}
onClick={this.onBtnSearch}
>
{toLocale('spot.search')}
</Button>
</div>
</div>
);
};
// 下单成功提示
successToast = () => {
this.successCallback && this.successCallback();
// setTimeout(() => {
// this.setState({cancelLoading: false});
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_success" isColor />{toLocale('spot.myOrder.cancelSuccessed')}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
this.setState({ cancelLoading: false });
Message.success({ content: toLocale('spot.myOrder.cancelSuccessed'), duration: 3 });
};
// 后端返回失败时
onSubmitErr = (err) => {
this.onPwdClose();
this.targetNode.removeAttribute('canceling');
this.errorCallback && this.errorCallback(err);
// setTimeout(() => {
// this.setState({cancelLoading: false});
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_fail" isColor />{toLocale('spot.myOrder.cancelFailed')}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
this.setState({ cancelLoading: false });
Message.error({ content: toLocale('spot.myOrder.cancelFailed'), duration: 3 });
};
// 开启资金密码弹窗
onPwdOpen = () => {
this.setState({
isShowPwdDialog: true
}, () => {
const o = window.document.getElementsByClassName('pwd-input');
if (o && o[0] && o[0].focus) {
o[0].focus();
}
});
};
// 关闭资金密码弹窗
onPwdClose = () => {
this.setState({
isLoading: false,
isShowPwdDialog: false
}, () => {
this.errorCallback && this.errorCallback();
});
};
// 资金密码弹窗点击提交
onPwdEnter = (password) => {
const { formActions, orderActions, commonAction } = this.props;
if (password.trim() === '') {
return formActions.updateWarning(toLocale('spot.place.tips.pwd'));
}
formActions.updateWarning('');
this.setState({
isLoading: true
}, () => {
setTimeout(() => {
commonAction.validatePassword(password, (pk) => {
const param = { ...this.formParam, pk };
this.setState({
isShowPwdDialog: false,
cancelLoading: true
}, () => {
orderActions.cancelOrder(param, () => {
this.successToast();
this.onPwdClose();
}, this.onSubmitErr);
});
}, () => {
this.setState({
isLoading: false
});
});
}, Config.validatePwdDeferSecond);
});
return false;
};
// 资金密码弹窗
renderPwdDialog = () => {
const { isLoading, isShowPwdDialog } = this.state;
const { warning } = this.props.FormStore;
const title = toLocale('please_input_pwd');
return (
<PasswordDialog
title={title}
btnLoading={isLoading}
warning={warning}
isShow={isShowPwdDialog}
updateWarning={this.props.formActions.updateWarning}
onEnter={this.onPwdEnter}
onClose={this.onPwdClose}
/>
);
};
render() {
const { theme, productObj, data } = this.props;
const { orderList, isLoading, page } = data;
const themeColor = (theme === Enum.themes.theme2) ? 'dark' : '';
let newList = orderList;
if (orderList.length && orderList[0].uniqueKey) {
newList = [];
}
return (
<div className="spot-orders flex10">
<div className="title">{toLocale('spot.orders.openOrders')}</div>
{this.renderQuery()}
<DexTable
columns={normalColumns.noDealColumns(this.onCancelOrder)}
dataSource={commonUtil.formatOpenData(newList, productObj)}
empty={orderUtil.getEmptyContent()}
rowKey="order_id"
style={{ clear: 'both', zIndex: 0 }}
isLoading={isLoading}
theme={themeColor}
pagination={page}
onPageChange={this.onPageChange}
/>
<p className="spot-orders-utips c-disabled" style={{ display: 'none' }}>
{toLocale('spot.bills.clearTips')}
</p>
<div className={`wait-loading ${this.state.cancelLoading ? '' : 'hide'}`} >
<div className="loading-icon"><Icon className="icon-loadingCopy" isColor /></div>
</div>
{this.renderPwdDialog()}
</div>
);
}
}
export default OpenList;
<file_sep>// const koKR = {
// 'borrow': '대출',
// 'repay': '상환',
// 'ensure': '확인',
// 'cancel': '취소',
// 'search':'검색',
// 'pair':'코인',
// 'change':'정렬',
// 'spot.noData': '데이터가 없습니다.',
// /* spot */
// 'spot.all': '전체',
// 'spot.asset': '자산',
// 'spot.asset.marginTrade': 'X 마진거래',
// 'spot.asset.spotTrade': '일반거래',
// 'spot.asset.futureTrade': '계약',
// 'spot.asset.ava': '거래가능',
// 'spot.asset.borrow': '대출',
// 'spot.asset.freeze': '거래중',
// 'spot.asset.risk': '위험율',
// 'spot.asset.forceClose': '강제청산',
// 'spot.asset.interest': '이자',
// 'spot.asset.deposit': '입금',
// 'spot.asset.transfer': '내부송금',
// 'spot.asset.transferSuccess': '송금성공',
// 'spot.asset.borrowBill': '대출',
// 'spot.asset.goBorrow': '대출하러 가기',
// 'spot.asset.borrowBillSuccess': '대출성공',
// 'spot.asset.repayBill': '상환',
// 'spot.asset.repayBillSuccess': '상환성공',
// /* spot.bills */
// 'spot.bills.coin': '종류',
// 'spot.bills.tradeDate': '거래일자',
// 'spot.bills.tradeType': '유형',
// 'spot.bills.tradeAmount': '금액',
// 'spot.bills.balance': '잔액',
// 'spot.bills.fee': '수수료',
// 'spot.bills.clearTips': '최고의 시스템 성능을 유지하기 위하여 OMCOIN은 정기적으로 3개월 이전의 데이터를 삭제합니다.',
// 'spot.coin': '종류',
// 'spot.marketDict': '시장',
// 'spot.favorites': '즐겨찾기',
// /* spot.margin */
// 'spot.margin.marginTips1': '마진거래는 투자자로 하여금 더 큰 자산을 운용할 수 있게 합니다. 하지만 기대수익과 리스크가 동반되기 때문에 자산 손실 및 강제 청산으로 인한 리스크가 늘 존재합니다. 투자자들은 반드시 리스크에 대해 인지하시고 신중하게 투자하시기 바랍니다.',
// 'spot.margin.marginTips2': '나는 OMCOIN의 ',
// 'spot.margin.marginTips2-2': ' ',
// 'spot.margin.marginTips3': '<마진거래 이용 동의서>',
// 'spot.margin.marginTips4': '를 읽고 이 내용에 동의합니다. 나는 마진거래를 위한 계좌 개설에 동의하며 계좌 개설 및 실제 거래에서 발생하는 위험에 대해 충분히 인지하고 있습니다.',
// 'spot.margin.safe':'안전',
// 'spot.margin.risk':'위험',
// 'spot.margin.forceliq':'청산완료',
// 'spot.margin.activate':'마진거래 약관 보기',
// 'spot.margin.borrow': '대출',
// 'spot.margin.repay': '상환',
// 'spot.margin.long': '롱',
// 'spot.margin.short': '숏',
// 'spot.margin.marginBorrow': 'X 레버리지 가능',
// 'spot.margin.dailyRate': '<NAME>',
// 'spot.margin.borrowAmount': '대출수량',
// 'spot.margin.repayAmount': '상환수량',
// 'spot.margin.loanAmount': '대출수량',
// 'spot.maring.interest': '이자',
// 'spot.margin.amountRepay': '상환수량',
// 'spot.margin.avaRepay': '상환가능',
// 'spot.margin.repayAll': '모두 상환',
// 'spot.margin.noLoanTips': '대출수량은 대출가능수량보다 클 수 없습니다.',
// 'spot.margin.noBorrowAmountTips': '대출수량을 입력해주세요.',
// 'spot.margin.borrowLessThanTips': '대출수량은 0보다 커야 합니다.',
// 'spot.margin.noRepayAmountTips': '상환수량을 입력해주세요.',
// 'spot.margin.repayLessThanTips': '상환수량은 상환가능수량보다 클 수 없습니다.',
// 'spot.margin.transferBalanceTip':'{symbol} 마진 거래 계정의 잔액이 부족합니다. 마진 거래를 원하시면 거래를 위한 금액을 이체해주세요. ',
// 'spot.margin.transferRiskTip':'{symbol} 마진 거래 계정의 위험율이 너무 낮습니다. 위험을 줄이기 위해 자산 계정으로 이체해주세요. ',
// 'spot.margin.needMore':'더 많은 레버리지 거래를 원하실 경우, 대출을 먼저 완료하시기 바랍니다.',
// 'spot.margin.borrowAction':'대출',
// 'spot.margin.borrowAvailable':'대출가능',
// 'spot.margin.borrowAll':'전부 대출',
// /*spot.market*/
// 'spot.market.more': '전체 보기',
// 'spot.market.orders': '주문정보',
// 'spot.menu.market.orders': '주문기록',
// 'spot.menu.market.bills': '거래내역',
// 'spot.menu.market.currencyIntro': '암호화폐 가이드',
// 'spot.menu.market.marginIntro': '마진거래 가이드',
// 'spot.menu.market.history': '대출 기록',
// 'spot.menu.market.strategy': '조건주문 가이드',
// /* spot.orders */
// 'spot.bills.spot': '거래내역',
// 'spot.bills.margin': '마진거래내역',
// 'spot.orders.currencies': '종류',
// 'spot.orders.types': '유형',
// 'spot.orders.last2': '최근 2일',
// 'spot.orders.2daysago': ' 최근 2일 이전',
// 'spot.search': '검색',
// 'spot.orders.allOrders': '전체 주문',
// 'spot.orders.amount': '주문 수량',
// 'spot.orders.averPrice': '평균 체결 가격',
// 'spot.orders.cancel': '주문 취소',
// 'spot.orders.cancelled': '취소',
// 'spot.orders.canceling': '취소중',
// 'spot.orders.cancelAll': '모두 취소',
// 'spot.orders.date': '주문 시간',
// 'spot.orders.filled': '체결수량 ',
// 'spot.orders.completeFilled': '체결',
// 'spot.orders.noorders': '미체결 주문이 없습니다. (최근 10건만 노출됩니다.)',
// 'spot.orders.noorders2day': '최근 2일동안 주문 기록이 없습니다.',
// 'spot.orders.noorders2dayago': '최근 3개월동안 주문 기록이 없습니다.',
// 'spot.orders.more': '전체 보기',
// 'spot.orders.open': '미체결',
// 'spot.orders.openOrders': '미체결 주문 10건',
// 'spot.orders.unfinished': '미체결',
// 'spot.orders.orderHistory':'주문 기록',
// 'spot.orders.partialFilled': '부분 체결',
// 'spot.orders.price': '주문 가격',
// 'spot.orders.side': '주문 유형 ',
// 'spot.orders.side.spot': '일반',
// 'spot.orders.side.margin': '마진',
// 'spot.orders.source': '주문 출처',
// 'spot.orders.status': '상태',
// 'spot.orders.operation': '작업',
// 'spot.orders.tips.datepicker': '시작 날짜와 종료 날짜를 선택하세요.',
// 'spot.orders.tips.dateRange': '종료 날짜는 시작 날짜 이후여야 합니다.',
// 'spot.orders.title':'주문',
// 'spot.orders.total': '총액',
// 'spot.orders.type': '유형',
// 'spot.orders.symbol': '종류',
// 'spot.orders.side2': '주문',
// 'spot.orders.toast.unhis': '현재 기존 거래내역에 대한 통합 검색은 지원되지 않습니다. 조회하고자 하는 암호화폐를 선택한 후 다시 조회해주세요.',
// 'spot.orders.download': '다운로드',
// 'spot.orders.borrowedId': '대출ID',
// 'spot.orders.accountBorrowedToken': '대출계정',
// 'spot.orders.borrowedPair': '대출화폐명',
// 'spot.orders.borrowedTime': '대출시간',
// 'spot.orders.borrowedQuantity': '대출수량',
// 'spot.orders.dailyRate': '이율',
// 'spot.orders.timeUnit': '일간',
// 'spot.orders.interestTime': '이자기간',
// 'spot.orders.totalInterest': '이자',
// 'spot.orders.outstandingLoans': '잔여대출금',
// 'spot.orders.statusOnly': '상태',
// 'spot.orders.operationOnly': '작업',
// 'spot.orders.loansRepay': '상환',
// 'spot.orders.borrowing': '대출중',
// 'spot.orders.loansRepaid': '청산',
// 'spot.orders.historyRecord':'다른 종목 숨기기',
// 'spot.orders.dealAveragePrice':'평균체결가',
// 'spot.orders.dealt':'체결완료',
// 'spot.orders.entrustMoney':'주문금액',
// 'spot.orders.entrustPrice':'주문가격',
// 'spot.orders.entrustMount':'주문수량',
// 'spot.orders.direction':'매수/매도',
// 'spot.orders.myDealList':'미체결 주문 보기',
// 'spot.orders.noOrders': '미체결된 주문이 없습니다.',
// 'spot.orders.noHistory': '최근 2일동안 주문 기록이 없습니다.',
// 'spot.orders.noData':'조회된 내용이 없습니다.',
// 'spot.order.noSpotBills': '거래내역이 없습니다.',
// 'spot.order.noMarginBills': '마진 거래내역이 없습니다.',
// 'spot.order.noBorrowOrder': '대출 내역이 없습니다.',
// 'spot.order.noPayoffOrder': '상환 내역이 없습니다.',
// 'spot.orders.normalSell':'일반주문',
// 'spot.orders.planSell':'조건주문',
// 'spot.orders.triggerPrice':'조건가격',
// 'spot.orders.orderPrice':'주문가격',
// 'spot.orders.orderSuccess':'주문에 성공했습니다.',
// 'spot.orders.orderError':'주문에 실패했습니다. 다시 시도해주세요.',
// 'spot.orders.status1':'조건대기중',
// 'spot.orders.status2':'주문완료',
// 'spot.orders.status3':'취소됨',
// 'spot.orders.rise':'상승',
// 'spot.orders.fall':'하락',
// 'spot.orders.higher':'높아',
// 'spot.orders.lower':'낮아',
// 'spot.orders.entrustWords':'현재의 가격이 {direction}하여 {triggerPrice}{baseCurr}에 도달하거나 더 {comparation}질 경우, {orderPrice}{baseCurr}의 가격으로 {amount}{tradeCurr} {action} 주문을 발동합니다.',
// 'spot.orders.cancelExplaination0':'시간초과 취소',
// 'spot.orders.cancelExplaination1':'사용자 직접 취소',
// 'spot.orders.cancelExplaination3':'잔고부족 취소',
// 'spot.orders.actionBuy':'매수',
// 'spot.orders.actionSell':'매도',
// 'spot.orders.triggerPop':'시장의 최신 거래 가격이 설정한 조건가격에 도달할 경우, 미리 설정한 주문가격 및 수량에 따라 자동으로 지정가 주문을 등록합니다. 주문을 실제로 발동시키는 가격이 되므로 유의하세요.',
// 'spot.orders.triggerPop2':'조건주문이란, 고객이 특정 조건에 주문을 낼 수 있도록 미리 설정하는 주문 방식입니다. 시장의 최신 거래 가격이 사전에 설정한 조건가격에 도달할 경우, 미리 설정한 주문가격 및 수량에 따라 자동으로 지정가 주문을 등록합니다. 해당 호가에 충분한 수량이 없을 경우 모두 체결되지 않을 수 있으니 유의하세요.',
// 'spot.orders.triggerPopDetail':'더보기',
// 'spot.orders.triggerPopLimitOrder': '지정가 주문은 사용자가 주문 수량 또한 최고 매입가 혹은 매도가를 설정하는 거래 방식입니다. 사용자가 설정한 가격에 도달되면 시스템은 자동으로 최적의 가격으로 체결 시킵니다.',
// 'spot.orders.triggerPopMarketOrder': '시장가 주문은 사용자가 최적의 가격으로 즉시 매도 혹은 매수를 실행하는 주문 방식입니다.',
// /*spot.trade*/
// 'spot.trade': '거래',
// 'spot.trade.title': '거래',
// 'spot.menu.orders': '주문 기록',
// 'spot.app': 'App',
// 'spot.ios': 'iOS',
// 'spot.web': '웹',
// 'spot.android': 'Android',
// 'spot.bid': ' 매수',
// 'spot.ask': ' 매도',
// 'spot.amount': '수량',
// 'spot.group': '호가단위',
// 'spot.xDecimal': '단위',
// 'spot.10Decimal': '10단위',
// 'spot.100Decimal': '100단위',
// 'spot.1000Decimal': '1000단위',
// 'spot.10000Decimal': '10000단위',
// 'spot.price': '가격',
// 'spot.total': '금액',
// 'spot.pwd': '<PASSWORD>',
// 'spot.orderType': '주문 유형',
// 'spot.type': '유형',
// 'spot.depth.amount':'주문',
// 'spot.depth.backToCenter': '모두 보기',
// 'spot.limitOrder': '지정가 주문',
// 'spot.marketOrder': '시장가 주문',
// 'spot.triggerOrder':'조건 주문',
// 'spot.shortLimitOrder': '지정가',
// 'spot.shortMarketOrder': '시장가',
// 'spot.market': '시장가',
// 'spot.buy': '매수',
// 'spot.sell': '매도',
// 'spot.buyin': '매수',
// 'spot.sellout': '매도',
// 'spot.fee': '수수료 안내',
// 'spot.submit.loading': '진행중입니다...',
// 'spot.ava.buy': '매수가능 ',
// 'spot.ava.sell': '매도가능 ',
// 'spot.place.tips.price': '거래 가격을 입력하세요.',
// 'spot.place.tips.amount': '거래 수량을 입력하세요.',
// 'spot.place.tips.total': '총 거래 금액을 입력하세요.',
// 'spot.place.tips.triggerPrice': '조건가격을 입력하세요.',
// 'spot.place.tips.orderPrice': '주문가격을 입력하세요.',
// 'spot.place.tips.money2': '잔고가 부족합니다. 입금 후 다시 시도해주세요.',
// 'spot.place.tips.minsize': '최소 거래 수량보다 작습니다. 최소 거래 수량 : ',
// 'spot.place.tips.greaterthan0': '매매 가격은 0보다 커야 합니다.',
// 'spot.place.tips.minbuy': '최소 매수 수량보다 작습니다. 최소 매수 수량 : ',
// 'spot.place.tips.minsell': '최소 매도 수량보다 작습니다. 최소 매도 수량 : ',
// 'spot.place.tips.pwd': '보안비밀번호를 입력하세요.',
// 'spot.place.tips.must': '최소 호가단위 : ',
// 'spot.place.tips.multiple': '원',
// 'spot.place.confirm.buy':'매수 확인',
// 'spot.place.confirm.sell':'매도 확인',
// 'spot.place.marketPrice':'시장 가격으로 체결되며, 수량 부족시 이후 호가로 체결',
// 'spot.place.forgetPwd':'보안 비밀번호 찾기',
// 'spot.place.nopwd':'보안설정',
// 'spot.place.kline':'차트 보기',
// 'spot.place.kline.title':'실시간 차트',
// 'spot.place.kline.more':'더보기',
// 'spot.kline.noInfo':'정보가 없습니다.',
// 'spot.place.fullScreen': '전체 화면',
// 'spot.callmarket.title':'동시호가',
// 'spot.callmarket.title.all':'동시호가-N단계',
// 'spot.callmarket.session':'N단계',
// 'spot.callmarket.desc1':'지정가 주문만 가능,취소가능',
// 'spot.callmarket.desc2':'지정가 주문만 가능,취소불가',
// 'spot.callmarket.ended':'종료',
// 'spot.callmarket.endedin':'종료까지 : ',
// 'spot.callmarket.startedin':'시작까지 : ',
// 'spot.callmarket.open':'예상 시초가',
// 'spot.callmarket.matched':'체결 수량',
// 'spot.callmarket.unmatched':'미체결 수량 ',
// 'spot.callmarket.startingsoon':'곧 시작됩니다.',
// 'spot.ticker.legal': '원화가격',
// 'spot.ticker.highest': '24시간 최고 가격',
// 'spot.ticker.lowest': '24시간 최저 가격',
// 'spot.ticker.volume': '24시간 거래량',
// 'spot.ticker.inflows': '24 시간 자금 을 유입 하다',
// 'spot.ticker.outflows': '24 시간 자금 유출',
// 'spot.kline.price': '거래가',
// 'spot.kline.tabs[0]':'차트',
// 'spot.kline.tabs[1]':'정보',
// 'spot.page.title':'- 서버 OK! 수수료 OK! |',
// 'spot.page.title.tokens':'주문 기록',
// 'spot.page.title.bills':'거래 내역',
// 'spot.page.title.marginHistory':'마진거래 내역',
// 'spot.deals.title':'최근 체결',
// 'spot.deals.price':'거래 가격(-)',
// 'spot.deals.amount':'거래량(-)',
// 'spot.deals.time':'거래시간',
// 'spot.deals.no':'데이터가 없습니다.',
// 'spot.ticker.introduce.releaseTime':'발생시점',
// 'spot.ticker.introduce.distributionAmount':'발행총량',
// 'spot.ticker.introduce.circulationAmount':'거래총량',
// 'spot.ticker.introduce.crowdfunding':'ICO 가격',
// 'spot.ticker.introduce.website':'웹사이트',
// 'spot.ticker.introduce.whitePaper':'백서',
// 'spot.ticker.introduce.introduction':'소개'
// };
// export default koKR;
<file_sep>import React, { Component } from 'react';
import Icon from '_src/component/IconLite';
import './index.less';
class DexDesktopInput extends Component {
constructor() {
super();
this.state = {};
}
render() {
const {
value, onChange, hint, label, multiple
} = this.props;
return (
<div className="dex-desktop-input-container">
<div className="desktop-input-title-row">
<label className="desktop-input-label" htmlFor="">{label}</label>
{
hint && (
<div className="desktop-input-icon">
<Icon className="icon-system_doubt" />
<div className="desktop-input-hint">{hint}</div>
</div>
)
}
</div>
{
multiple ? (
<textarea
className="desktop-input"
value={value}
onChange={onChange}
rows="2"
/>
) : (
<input
className="desktop-input"
value={value}
onChange={onChange}
/>
)
}
</div>
);
}
}
export default DexDesktopInput;
<file_sep>const path = require('path');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const base = require('./webpack.config.base');
base.output.publicPath = 'file:./';
base.output.path = path.resolve(__dirname, '../bundle');
// 增加block strip能力
base.module.rules.forEach((item) => {
if (item.use && item.use[0] === 'eslint-loader') {
item.use.unshift('@ok/strip-block-loader');
item.use.unshift('@ok/strap-react-hot-loader');
}
});
base.plugins.unshift(
new CleanWebpackPlugin([path.resolve(__dirname, '../bundle')], {
root: path.resolve(__dirname, '../')
}),
new webpack.DefinePlugin({ 'process.env.ROUTE_TYPE': JSON.stringify('hash') }),
new HtmlWebpackPlugin({
template: path.resolve(path.resolve(__dirname, '../src'), 'desktop.html'),
filename: 'index.html'
}),
);
base.devtool = 'source-map';
base.mode = 'production';
module.exports = Object.assign(base, {
mode: 'production',
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
}),
new OptimizeCSSAssetsPlugin({})
]
}
});
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import commonUtil from './commonUtil';
import { OrderStatus } from '../../constants/OrderStatus';
import util from '../../utils/util';
import FormatNum from '../../utils/FormatNum';
export default {
noDealColumns: (onCancelOrder, onClickProduct) => {
const commonCols = commonUtil.getCommonColumns(onClickProduct);
const normalCols = [{ // 操作(未成交)
title: toLocale('spot.orders.operation'),
key: 'operation',
render: (text, record) => {
return (
<div>
<a
className="order-cancel"
onClick={onCancelOrder(record)}
>
{toLocale('spot.orders.cancel')}
</a>
</div>
);
}
}];
return commonCols.concat(normalCols);
},
historyColumns: (onClickSymbol) => {
const commonCols = commonUtil.getCommonColumns(onClickSymbol);
const historyCols = [];
/*
const historyCols = [{ // 成交均价
title: (
<span>
{toLocale('spot.myOrder.filledPrice')}
</span>
),
key: 'filled_avg_price',
render: (text) => {
return (<div>{text}</div>);
}
}, { // 委托量
title: (
<span>
{toLocale('spot.myOrder.amount')}
</span>
),
key: 'quantity',
render: (text) => {
return (<div>{text}</div>);
}
}, { // 成交量
title: (
<span>
{toLocale('spot.myOrder.filledAmount')}
</span>
),
key: 'remain_quantity',
render: (text, data) => {
return (<div>{data.filledQuantity}</div>);
}
}, { // 成交状态
title: toLocale('spot.myOrder.filledStatus'),
key: 'status',
render: (text) => {
return (
<span>{text}</span>
);
}
}]; */
return commonCols.concat(historyCols);
},
detailColumns: () => {
const detailCols = [{ // 区块高度订单号
title: toLocale('spot.myOrder.height'),
key: 'block_height',
render: (text) => { // className="can-click"
return (
<span>
{text}
</span>
);
}
}, { // 时间
title: toLocale('spot.myOrder.date'),
key: 'timestamp',
render: (text) => {
const d = text.split(' ')[0];
const t = text.split(' ')[1];
return (
<span>{d}<br />{t}</span>
); // return (<span>{text}</span>);
}
}, { // 订单号
title: toLocale('spot.myOrder.id'),
key: 'order_id',
render: (text) => { // className="can-click"
return (
<span>
{text}
</span>
);
}
}, { // 交易对
title: toLocale('spot.myOrder.product'),
key: 'product',
render: (text) => {
return (
<span>
{text}
</span>
);
}
}, { // 方向
title: toLocale('spot.myOrder.direction'),
key: 'side',
render: (text, data) => {
return <div className={data.sideClass}>{text}</div>;
}
}, { // 成交均价
title: toLocale('spot.myOrder.filledPrice'),
key: 'price',
render: (text) => {
return (<div>{text}</div>);
}
}, { // 成交量
title: toLocale('spot.myOrder.filledAmount'),
key: 'volume',
render: (text) => {
return (<div>{text}</div>);
}
}, { // 成交额
title: toLocale('spot.myOrder.filledMoney'),
key: 'total',
render: (text, data) => {
return (<span>{data.money}</span>);
}
}, { // 手续费(OMB)
title: toLocale('spot.myOrder.fee'),
key: 'fee',
render: (text) => {
let txt = '';
if (text) {
txt = text.split('-')[0];
}
return FormatNum.formatFeeStr(txt.toUpperCase());
}
}];
return detailCols;
}
};
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import Icon from '_src/component/IconLite';
import PageURL from '_src/constants/PageURL';
import Config from '_src/constants/Config';
import './index.less';
const index = () => {
return (
<div className="home-container-inner">
<div className="home-header">
<div className="home-header-right">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/AD222BAF06543BE0DB6E0A96DDC583F7.png"
width={844}
height={400}
/>
</div>
<div className="home-header-left">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/D4592142474E53DC42541273C4DDA1B5.png"
width={300}
height={286}
/>
</div>
<h1>{toLocale('home_title')}</h1>
<h3>{toLocale('home_subtitle')}</h3>
<div className="home-btn-group">
<a href={PageURL.spotFullPage} target="_blank" rel="noopener noreferrer">
<span>
<Icon className="icon-trade" />
<span>{toLocale('home_begin_trade_btn')}</span>
</span>
<Icon className="icon-go" />
</a>
<a className="div2" href={PageURL.walletCreate} target="_blank" rel="noopener noreferrer">
<span>
<Icon className="icon-create" />
<span>{toLocale('home_create_wallet_btn')}</span>
</span>
<Icon className="icon-go" />
</a>
<a className="div2" href={PageURL.walletImport} target="_blank" rel="noopener noreferrer">
<span>
<Icon className="icon-wallet1" />
<span>{toLocale('home_import_wallet_btn')}</span>
</span>
<Icon className="icon-go" />
</a>
<a className="div2" href={Config.omchain.browserUrl} target="_blank" rel="noopener noreferrer">
<span>
<Icon className="icon-Browser" />
<span>{toLocale('home_browser')}</span>
</span>
<Icon className="icon-go" />
</a>
<a className="div3" href={Config.omchain.docUrl} target="_blank" rel="noopener noreferrer">
<span>
<Icon className="icon-help" />
<span href={Config.omchain.docUrl}>{toLocale('home_instructions')}</span>
</span>
<Icon className="icon-go" />
</a>
</div>
</div>
<div className="home-body">
<h2>{toLocale('home_how_use')}</h2>
<div className="how-to-container">
<div className="step-container">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/382EC444F5ED5F9C50DD06A6D65ED150.png"
alt="num-1"
width={48}
height={48}
/>
<span>{toLocale('home_step1_title')}</span>
</div>
<div className="desc-container">
<ul>
<li>{toLocale('home_step1_li1')}</li>
<li>{toLocale('home_step1_li2')}</li>
<li>{toLocale('home_step1_li3')}</li>
</ul>
<a href={PageURL.walletCreate} target="_blank" rel="noopener noreferrer">{toLocale('home_step1_btn')}
<img src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/130407AC319D1D7DB4B7EAD09D83016C.png" />
</a>
</div>
</div>
<div className="how-to-container">
<div className="step-container">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/754582E0858D40E1AA5541F4AC50BF85.png"
alt="num-2"
width={48}
height={48}
/>
<span>{toLocale('home_step2_title')}</span>
</div>
<div className="desc-container">
<ul>
<li>{toLocale('home_step2_li1')}</li>
<li>{toLocale('home_step2_li2')}</li>
<li>{toLocale('home_step2_li3')}</li>
</ul>
<a href={Config.omchain.receiveCoinUrl} target="_blank" rel="noopener noreferrer">{toLocale('home_step2_btn')}
<img src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/130407AC319D1D7DB4B7EAD09D83016C.png" />
</a>
</div>
</div>
<div className="how-to-container">
<div className="step-container">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/92C0DA26E463944FEE42BA6930AE8BCD.png"
alt="num-3"
width={48}
height={48}
/>
<span>{toLocale('home_step3_title')}</span>
</div>
<div className="desc-container">
<ul>
<li>{toLocale('home_step3_li1')}</li>
<li>{toLocale('home_step3_li2')}</li>
</ul>
<a href={PageURL.spotFullPage} target="_blank" rel="noopener noreferrer">{toLocale('home_step3_btn')}
<img src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/130407AC319D1D7DB4B7EAD09D83016C.png" />
</a>
</div>
</div>
<div className="how-to-container">
<div className="step-container">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/831414284D0C7E47AF223D99E574458F.png"
alt="num-4"
width={48}
height={48}
/>
<span>{toLocale('home_step4_title')}</span>
</div>
<div className="desc-container">
<ul>
<li>{toLocale('home_step4_li1')}</li>
</ul>
<a href={Config.omchain.browserUrl} target="_blank" rel="noopener noreferrer">{toLocale('home_step4_btn')}
<img src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/130407AC319D1D7DB4B7EAD09D83016C.png" />
</a>
</div>
</div>
<div className="how-to-container">
<div className="step-container">
<img
src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/F40D61AE8D4EDF6B5440F74FC759F37E.png"
alt="num-5"
width={48}
height={48}
/>
<span>{toLocale('home_step5_title')}</span>
</div>
<div className="desc-container">
<ul>
<li>{toLocale('home_step5_li1')}</li>
</ul>
<a href={Config.omchain.docUrl} target="_blank" rel="noopener noreferrer">{toLocale('home_step5_btn')}
<img src="https://img.bafang.com/cdn/assets/imgs/MjAxOTEx/130407AC319D1D7DB4B7EAD09D83016C.png" />
</a>
</div>
</div>
</div>
<div className="omex-logo">
<Icon className="icon-testcoin" isColor />
<a target="_blank" rel="noopener noreferrer" href={Config.omchain.receiveCoinUrl}>{toLocale('home_receive_coin')} >></a>
</div>
</div>
);
};
export default index;
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import LeftMenu from '../../component/leftMenu';
import ProductListWrapper from '../../wrapper/ProductListWrapper';
const ProductListMenu = (props) => {
const {
dataSource, activeId, searchText, onSearch, onSelect, onClickStar
} = props;
const listEmpty = toLocale('spot.noData');
return (
<LeftMenu
searchBar
searchPlaceholder={toLocale('search')}
searchText={searchText}
subTitle={[toLocale('pair'), toLocale('change')]}
menuList={dataSource}
listHeight={324}
listEmpty={listEmpty}
activeId={activeId}
canStar
onSearch={onSearch}
onSelect={onSelect}
onClickStar={onClickStar}
/>
);
};
export default ProductListWrapper(ProductListMenu);
<file_sep>import { storage } from '_component/omit';
import ActionTypes from '../actionTypes/SpotActionType';
let activeMarket = {};
try {
activeMarket = JSON.parse(storage.get('activeMarket') || '{}');
if (!activeMarket.groupId) {
activeMarket = {
filterWord: ['tusdk'],
groupId: 1,
groupName: 'TUSDK',
};
}
} catch (e) {
console.warn(e); // eslint-disable-line
}
const initialState = {
wsIsOnlineV3: false, // ws连接状态v3
wsErrCounterV3: 0, // ws断线重连计数器v3
wsIsDelayLogin: false, // 获取tomen时间是否晚于页面执行推送连接
valuationToken: 'tomt', // OMChain计价通证 tomt
activeMarket, // 当前交易区 原来是1
searchText: '', // 币对搜索input
billMenuActive: '', // 左侧菜单激活Id
hasOpenMargin: false, // 币对中是否存在 杠杠
tickers: {}, // 所有币对行情
cnyRate: 0, // 人民币对美元汇率
theme: localStorage.getItem('theme') || 'theme-1', // 白天 or 夜间模式
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case ActionTypes.UPDATE_HAS_OPEN_MARGIN:
return {
...state,
hasOpenMargin: action.data
};
case ActionTypes.UPDATE_WS_STATUS_V3:
return {
...state,
wsIsOnlineV3: action.data
};
case ActionTypes.UPDATE_WS_ERR_COUNTER_V3:
return {
...state,
wsErrCounterV3: action.data
};
case ActionTypes.UPDATE_WS_IS_DELAY:
return {
...state,
wsIsDelayLogin: action.data
};
// 更新tickers,通过api
case ActionTypes.FETCH_SUCCESS_TICKERS:
return {
...state,
tickers: action.data
};
// 更新tickers,通过推送
case ActionTypes.UPDATE_TICKERS:
return {
...state,
tickers: action.data
};
case ActionTypes.UPDATE_ACTIVE_MARKET:
return {
...state,
activeMarket: action.data
};
case ActionTypes.UPDATE_SEARCH:
return {
...state,
searchText: action.data
};
case ActionTypes.UPDATE_BILL_MENU:
return {
...state,
billMenuActive: action.data
};
case ActionTypes.UPDATE_THEME:
return {
...state,
theme: action.data
};
case ActionTypes.UPDATE_CNY_RATE:
return {
...state,
cnyRate: action.data
};
default:
return state;
}
}
<file_sep>import React from 'react';
import PropType from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import config from '_src/constants/Config';
import TickerWrapper from '../../wrapper/TickerWrapper';
import './FullTradeTicker.less';
const FullTradeTicker = (props) => {
const { dataSource } = props;
const {
price, change, changePercentage, legalCurrency, legalPrice, dayHigh, volume, dayLow
} = dataSource;
const isFall = change.toString().indexOf('-') > -1;
return (
<div className="full-ticker">
<div className="seg-line" />
<div className="ticker-main">
<span className={`${isFall ? 'primary-red' : 'primary-green'} price`}>
{price}
</span>
<span className={`${isFall ? 'primary-red' : 'primary-green'} change`}>
{changePercentage}
</span>
</div>
<div className="ticker-units">
{
config.needLegalPrice ?
<div className="ticker-unit">
<div className="title">
{toLocale('spot.ticker.legal.new', { currency: legalCurrency })}
</div>
<div className="value">
{legalPrice}
</div>
</div> : null
}
<div className="ticker-unit">
<div className="title">
{toLocale('spot.ticker.lowest')}
</div>
<div className="value">
{dayLow}
</div>
</div>
<div className="ticker-unit">
<div className="title">
{toLocale('spot.ticker.highest')}
</div>
<div className="value">
{dayHigh}
</div>
</div>
<div className="ticker-unit">
<div className="title">
{toLocale('spot.ticker.volume')}
</div>
<div className="value">
{volume}
</div>
</div>
</div>
</div>
);
};
FullTradeTicker.propTypes = {
dataSource: PropType.object
};
FullTradeTicker.defaultProps = {
dataSource: {
price: '--', // 最新价格
change: '--', // 涨幅
changePercentage: '--', // 涨跌幅百分比
legalPrice: '--', // 法币价格
dayHigh: '--', // 24小时最高价
dayLow: '--', // 24小时最低价
volume: '--', // 24小时成交量
unit: '--', // 币种
inflows: '--', // 24小时资金流入,
outflows: '--', // 24小时资金流出,
legalCurrency: '--',
// tips: { toLocale('spot.ticker.inflowTips'), toLocale('spot.ticker.outflowTips')
}
};
export default TickerWrapper(FullTradeTicker);
<file_sep>import React from 'react';
import AssetSpot from '../../component/asset/AssetSpot';
import SpotAssetWrapper from '../../wrapper/SpotAssetWrapper';
import './SpotAsset.less';
const AssetWrapper = (Component) => {
return (props) => {
return (
<div className="spot-asset">
<Component {...props} />
</div>
);
};
};
export default SpotAssetWrapper(AssetWrapper(AssetSpot));
<file_sep>import React, { Fragment } from 'react';
import { toLocale } from '_src/locale/react-locale';
import Image from '../image';
import './index.less';
import './index-md.less';
import './index-lg.less';
import './index-xl.less';
const AdvantageItem = (props) => {
const { img, title, content } = props.data;
return (
<div className="item-container">
<img
className="item-img"
src={img}
alt={toLocale(title)}
/>
<h3 className="item-title">{toLocale(title)}</h3>
<p className="item-content">{toLocale(content)}</p>
</div>
);
};
const itemList = [
{
img: Image.adv_item0,
title: 'home_adv_item0_title',
content: 'home_adv_item0_content'
},
{
img: Image.adv_item1,
title: 'home_adv_item1_title',
content: 'home_adv_item1_content'
},
{
img: Image.adv_item2,
title: 'home_adv_item2_title',
content: 'home_adv_item2_content'
}
];
const Advantage = () => {
return (
<article className="advantage-container">
<div className="advantage-grid">
<h2 className="advantage-title">{toLocale('home_adv_title')}</h2>
<div className="advantage-list">
{
itemList.map((item) => {
return <AdvantageItem data={item} key={item.title} />;
})
}
</div>
</div>
</article>
);
};
export default Advantage;
<file_sep>/**
* 交易相关金额、数量、价格输入框
* Created by wenqiang.li on 2018/3/27.
*
* 输入后自动加千分逗号,传出时去掉逗号
*/
import React from 'react';
export default class InputNum extends React.Component {
constructor(props) {
super(props);
}
onBlur = (e) => {
const {onBlur} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onBlur !== 'undefined') {
onBlur(inpNumber, e);
}
}
onClick = (e) => {
const {onClick} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onClick !== 'undefined') {
onClick(inpNumber, e);
}
}
onCut = (e) => {
const {onCut} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onCut !== 'undefined') {
onCut(inpNumber, e);
}
}
onCopy = (e) => {
const {onCopy} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onCopy !== 'undefined') {
onCopy(inpNumber, e);
}
}
onDoubleClick = (e) => {
const {onDoubleClick} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onDoubleClick !== 'undefined') {
onDoubleClick(inpNumber, e);
}
}
onFocus = (e) => {
const {onFocus} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onFocus !== 'undefined') {
onFocus(inpNumber, e);
}
}
onKeyDown = (e) => {
const {onKeyDown} = this.props;
//清除无效字符
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onKeyDown !== 'undefined') {
onKeyDown(inpNumber, e);
}
}
onChange = (e) => {
const {onChange} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onChange !== 'undefined') {
onChange(inpNumber, e);
}
}
onKeyUp = (e) => {
const {onKeyUp} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onKeyUp !== 'undefined') {
onKeyUp(inpNumber, e);
}
}
onKeyPress = (e) => {
const {onKeyPress} = this.props;
let inpNumber = this.checkInpNumber(e.target.value);
if (typeof onKeyPress !== 'undefined') {
onKeyPress(inpNumber, e);
}
}
checkInpNumber = (inputValue, num) => {
let inps = inputValue.split('.');
if (inps.length > 1) {
if (typeof num != 'undefined' || num === -1) {
return inps[0].replace(/\D/g, '') + '.' + inps[1].replace(/\D/g, '');
}
else {
return inps[0].replace(/\D/g, '') + '.' + inps[1].replace(/\D/g, '').slice(0, num);
}
} else {
return inps[0].replace(/\D/g, '');
}
};
removeDot = (value) => {
if (typeof value != 'number' && typeof value != 'string') {
return value;
}
let newValue = String(value).replace(/,/g, '');
return newValue;
}
addDot = (value) => {
if (typeof value != 'number' && typeof value != 'string') {
return value;
}
if (Math.abs(value) < 1000) {
return value;
}
let newValue = String(value).replace(/,/g, '');
let inpArr = newValue.split('.');
let l = inpArr[0].split("").reverse(), t = '';
for (let i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
if (inpArr.length == 2) {
return t.split("").reverse().join("") + "." + inpArr[1];
}
else {
return t.split("").reverse().join("");
}
return newValue;
}
render() {
const {value} = this.props;
let newValue = this.removeDot(value);
newValue = this.addDot(newValue);
return <input {...this.props} type="text"
onCopy={this.onCopy}
onBlur={this.onBlur}
onClick={this.onClick}
onChange={this.onChange}
onCut={this.onCut}
onDoubleClick={this.onDoubleClick}
onFocus={this.onFocus}
onKeyUp={this.onKeyUp}
onKeyDown={this.onKeyDown}
onKeyPress={this.onKeyPress}
value={newValue}
/>
}
}<file_sep>export const NODE_TYPE = {
LOW: 'low',
HIGH: 'high',
UNREACHABLE: 'unreachable',
};
export const MAX_LATENCY = 2147483647; // -1 >>> 1
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ItemGroup as RcItemGroup } from 'rc-menu';
class ItemGroup extends Component {
static propTypes = {
/** 分组标题 */
title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 分组的菜单项 Array<MenuItem> */
children: PropTypes.array,
};
static defaultProps = {
title: '',
children: [],
};
render() {
return (
<RcItemGroup
{...this.props}
/>
);
}
}
export default ItemGroup;
<file_sep>/**
* 基础弹框
* Created by yuxin.zhang on 2018/9/1.
*/
import React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import BaseDialog from './BaseDialog';
import ActionButton from './ActionButton';
import './Dialog.less';
export default function Dialog(props) {
const {
openWhen, visible, children, btnList, onClose,
...attr
} = props;
const dialogVisible = Object.prototype.hasOwnProperty.call(props, 'openWhen') ? openWhen : visible;
const {
confirmText, cancelText, onConfirm, onCancel, confirmDisabled, confirmLoading, theme
} = props;
// 当存在对应的按钮文案时,会显示对应的按钮
const hasConfirmBtn = confirmText !== null && confirmText !== undefined;
const hasCancelBtn = cancelText !== null && cancelText !== undefined;
let newBtnList = [];
hasCancelBtn && newBtnList.push({
text: cancelText,
type: ActionButton.btnType.default,
onClick: onCancel || onClose
});
hasConfirmBtn && newBtnList.push({
text: confirmText,
type: ActionButton.btnType.primary,
onClick: onConfirm,
loading: confirmLoading,
disabled: confirmDisabled,
closeDialog: onClose,
});
// 当外部没有按钮列表时 使用内部列表
newBtnList = btnList && btnList.length !== 0 ? btnList : newBtnList || [];
return (
<BaseDialog
{...attr}
visible={dialogVisible}
onClose={onClose}
>
{children}
{
newBtnList.length > 0 &&
<div className="btn-box">
{
newBtnList.map((item, index) => {
const {
text, type, disabled, loading, onClick, closeDialog
} = item;
return (
<ActionButton
key={`dialogBtn${index}`}
type={type}
disabled={disabled}
className="dialog-btn"
loading={loading}
onClick={onClick}
closeDialog={closeDialog}
theme={theme}
>{text}
</ActionButton>
);
})
}
</div>
}
</BaseDialog>
);
}
Dialog.defaultProps = {
confirmText: null,
cancelText: null,
confirmDisabled: false,
confirmLoading: false,
onConfirm: null,
onCancel: null
};
Dialog.propTypes = {
/** 确认按钮文案 当该参数不为 null/undefined 时,会出现确认按钮 */
confirmText: PropTypes.string,
/** 取消按钮文案 当该参数不为 null/undefined 时,会出现取消按钮 */
cancelText: PropTypes.string,
/** 确认按钮禁止 */
confirmDisabled: PropTypes.bool,
/** 确认按钮loading */
confirmLoading: PropTypes.bool,
/** 确认按钮回调 */
onConfirm: PropTypes.func,
/** 取消按钮回调 可以不传 不传时会调用onClose */
onCancel: PropTypes.func
};
function create(config) {
const div = document.createElement('div');
let parentContainer = document.body;
const { parentSelector } = config;
// 如果 指定了父容器且存在 则挂载到父容器上 默认挂载到body
if (parentSelector && document.querySelector(parentSelector)) {
parentContainer = document.querySelector(parentSelector);
}
parentContainer.appendChild(div);
function destroy() {
const unmountResult = ReactDOM.unmountComponentAtNode(div);
if (unmountResult && div.parentNode) {
div.parentNode.removeChild(div);
}
}
function close() {
destroy();
if (config.onClose) {
config.onClose();
}
}
let currentConfig = {
...config, visible: true, onClose: close
};
function render(props) {
ReactDOM.render(<Dialog {...props} />, div);
}
function update(newConfig) {
currentConfig = {
...currentConfig,
...newConfig,
};
render(currentConfig);
}
render(currentConfig);
return {
destroy,
update
};
}
Dialog.create = create;
<file_sep>import React from 'react';
import Icon from '_src/component/IconLite';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import util from '_src/utils/util';
import './FullTradeProduct.less';
import * as SpotActions from '../../redux/actions/SpotAction';
import Introduce from '../../component/kline/Introduce';
function mapStateToProps(state) { // 绑定redux中相关state
const { product } = state.SpotTrade;
return {
product
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
export default class FullTradeProduct extends React.Component {
constructor(props) {
super(props);
this.state = {
isShowProduction: false
};
}
// 显示币种介绍
showProduction = () => {
this.setState({
isShowProduction: true
});
};
// 隐藏币种介绍
hideProduction = () => {
this.setState({
isShowProduction: false
});
};
render() {
const { product } = this.props;
const {
isShowProduction
} = this.state;
return (
<div className="full-product-list">
<span>
<em>{util.getShortName(product)}</em>
</span>
<span
onMouseEnter={this.showProduction}
onMouseLeave={this.hideProduction}
style={{ position: 'relative' }}
>
<Icon
className="icon-annotation-night"
isColor
style={{ width: '16px', height: '16px', marginBottom: '-3px' }}
/>
<div
className="production-container"
style={{ display: isShowProduction ? 'block' : 'none' }}
>
<Introduce />
</div>
</span>
</div>);
}
}
<file_sep>import React, { Component } from 'react';
// import PropTypes from 'prop-types';
import { Item } from 'rc-menu';
class MenuItem extends Component {
// static propTypes = {
// /** item 的唯一标志 */
// key: PropTypes.object,
// };
// static defaultProps = {
// key: '',
// };
render() {
return (
<Item {...this.props} />
);
}
}
export default MenuItem;
<file_sep>import { storage } from '_component/omit';
import { settingsAPIs } from '_constants/apiConfig';
import { MAX_LATENCY } from '_constants/Node';
import ActionTypes from '../actionTypes/NodeActionType';
const getRenderRemoteList = () => {
const nodeList = settingsAPIs.NODE_LIST;
return nodeList.map((node) => {
return {
...node,
latency: MAX_LATENCY,
};
});
};
const initialState = {
remoteList: getRenderRemoteList(),
currentNode: storage.get('currentNode') || {
...settingsAPIs.DEFAULT_NODE,
latency: MAX_LATENCY,
},
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case ActionTypes.UPDATE_CURRENT_NODE:
return {
...state,
currentNode: action.data,
};
case ActionTypes.UPDATE_REMOTE_LIST:
return {
...state,
remoteList: action.data,
};
default:
return state;
}
}
<file_sep>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { toLocale } from '_src/locale/react-locale';
// import { calc } from '_component/omit';
import Message from '_src/component/Message';
// import Dialog from '_component/Dialog/src/Dialog';
import { Dialog } from '_component/Dialog';
import Icon from '_src/component/IconLite';
import util from '../../utils/util';
import Enum from '../../utils/Enum';
import './SpotPlaceOrder.less';
import * as FormAction from '../../redux/actions/FormAction';
import * as SpotAction from '../../redux/actions/SpotTradeAction';
import * as CommonAction from '../../redux/actions/CommonAction';
import LimitForm from '../placeOrders/LimitForm';
import PasswordDialog from '../../component/PasswordDialog';
import Config from '../../constants/Config';
function mapStateToProps(state) { // 绑定redux中相关state
const { SpotTrade, FormStore, Common } = state;
const {
product, currencyObjByName, currencyTicker, account
} = SpotTrade;
const { privateKey } = Common;
return {
product,
currencyObjByName, // 获取杠杆资产日利率
account,
currencyTicker, // 切换币对时,重置默认价格
FormStore,
privateKey
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
commonAction: bindActionCreators(CommonAction, dispatch),
formAction: bindActionCreators(FormAction, dispatch),
spotAction: bindActionCreators(SpotAction, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class SpotPlaceOrder extends React.Component {
constructor(props) {
super(props);
this.asset = {}; // 资产-各种表单都需要
this.formParam = {}; // 表单提交参数
this.state = {
isLoading: false,
isShowPwdDialog: false, // 资金密码弹窗
type: Enum.placeOrder.type.buy, // 买或卖
};
this.successCallback = null;
this.errorCallback = null;
}
componentDidMount() {
const { formAction, currencyTicker } = this.props;
formAction.updateInput({
price: (currencyTicker && currencyTicker.price)
});
}
componentWillReceiveProps(nextProps) {
const { product, currencyTicker } = nextProps;
if (this.props.product !== product) { // 切换币对
const { formAction } = this.props;
formAction.clearForm();
formAction.updateWarning();
formAction.updateInput({
price: (currencyTicker && currencyTicker.price)
});
}
}
// 买卖切换
onChangeType = (type) => {
return () => {
this.setState({
type
});
const { formAction } = this.props;
// 切换买卖类型
formAction.updateType(type);
// 清空下单报错
formAction.updateWarning();
};
};
// 资金密码弹窗点击提交
onPwdEnter = (password) => {
const { formAction, commonAction } = this.props;
if (password.trim() === '') {
return formAction.updateWarning(toLocale('spot.place.tips.pwd'));
}
formAction.updateWarning('');
this.setState({
isLoading: true,
}, () => {
setTimeout(() => {
commonAction.validatePassword(password, (pk) => {
const param = { ...this.formParam, pk };
formAction.submitOrder(param, () => {
this.successToast();
this.onPwdClose();
}, this.onSubmitErr);
}, () => {
this.setState({
isLoading: false,
});
});
}, Config.validatePwdDeferSecond);
});
return false;
};
// 开启资金密码弹窗
onPwdOpen = () => {
this.setState({
isShowPwdDialog: true
}, () => {
const o = window.document.getElementsByClassName('pwd-input');
if (o && o[0] && o[0].focus) {
o[0].focus();
}
});
};
// 关闭资金密码弹窗
onPwdClose = () => {
this.setState({
isShowPwdDialog: false,
isLoading: false,
}, () => {
this.errorCallback && this.errorCallback();
});
};
// 后端返回失败时
onSubmitErr = (err) => {
this.onPwdClose();
const { type } = this.state;
const msg = (type === Enum.placeOrder.type.buy) ? toLocale('spot.orders.buyFail') : toLocale('spot.orders.sellFail');
// setTimeout(() => {
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_fail" isColor />{msg}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
Message.error({ content: msg, duration: 3 });
};
// 资金划转
onTransfer = () => {
const { spotAction } = this.props;
spotAction.updateMarginTransfer(true);
};
// 获取baseCurr和tradeCurr及对应额度
getAvailables = () => {
const {
product, account
} = this.props;
const tradeCurr = (product && product.includes('_')) ? product.split('_')[0].toUpperCase() : '';
const baseCurr = (product && product.includes('_')) ? product.split('_')[1].toUpperCase() : '';
// let baseAvailable = 0;
// let tradeAvailable = 0;
const tradeAccount = account[tradeCurr.toLowerCase()];
const baseAccount = account[baseCurr.toLowerCase()];
// if (tradeAccount && baseAccount) {
// tradeAvailable = Number(tradeAccount.available);
// baseAvailable = Number(baseAccount.available);
// }
const tradeAvailable = tradeAccount ? Number(tradeAccount.available) : 0;
const baseAvailable = baseAccount ? Number(baseAccount.available) : 0;
return {
baseCurr,
baseAvailable,
tradeCurr,
tradeAvailable
};
};
// 获取不同策略委托表单
getStrategyForm = (strategyType) => {
const { asset } = this;
const { isShowPwdDialog, type } = this.state;
/*
* 子表单通用props
* asset:资产
* onSubmit:提交按钮钩子
* needWarning: 是否显示错误提示
* */
const commonProps = {
asset,
type,
onSubmit: this.handleSubmit,
needWarning: !isShowPwdDialog
};
switch (strategyType) {
case Enum.placeOrder.strategyType.limit:
return <LimitForm {...commonProps} />;
default:
return <LimitForm {...commonProps} />;
}
};
// 下单成功提示
successToast = () => {
const { formAction } = this.props;
formAction.clearForm();
this.successCallback && this.successCallback();
const { type } = this.state;
const msg = (type === Enum.placeOrder.type.buy) ? toLocale('spot.orders.buySuccess') : toLocale('spot.orders.sellSuccess');
// setTimeout(() => {
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_success" isColor />{msg}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
Message.success({ content: msg, duration: 2 });
};
// 子表单点击提交
handleSubmit = (formParam, successCallback, errorCallback) => {
this.successCallback = successCallback;
this.errorCallback = errorCallback;
const { formAction } = this.props;
formAction.updateWarning('');
// 2019-08-13 增加用户清空全部缓存的判断
if (!util.isLogined()) {
window.location.reload();
}
this.formParam = { ...formParam, product: this.props.product };
// 检查私钥,如果未过期直接取私钥,如果过期显示弹窗
const expiredTime = window.localStorage.getItem('pExpiredTime') || 0;
// 小于30分钟,且privateKey,(true时),不需要输入密码,直接提交
if ((new Date().getTime() < +expiredTime) && this.props.privateKey) {
const param = { ...this.formParam, pk: this.props.privateKey };
return formAction.submitOrder(param, this.successToast, this.onSubmitErr);
}
return this.onPwdOpen();
};
// 买卖title
renderTitle = () => {
const { product } = this.props;
const { type } = this.state;
const tradeCurr = util.getSymbolShortName(product.split('_')[0].toUpperCase());
const buyInTitle = toLocale('spot.buyin', { currency: tradeCurr });
const sellTitle = toLocale('spot.sellout', { currency: tradeCurr });
return (
<ul className="spot-tab-heads">
<li
className={type === Enum.placeOrder.type.buy ? 'active' : ''}
onClick={this.onChangeType(Enum.placeOrder.type.buy)}
>
{buyInTitle}
</li>
<li
className={type === Enum.placeOrder.type.sell ? 'active' : ''}
onClick={this.onChangeType(Enum.placeOrder.type.sell)}
>
{sellTitle}
</li>
</ul>
);
};
// 资金密码弹窗
renderPwdDialog = () => {
const { isShowPwdDialog, isLoading } = this.state;
const { formAction, FormStore } = this.props;
const { warning } = FormStore;
const title = toLocale('please_input_pwd');
return (
<PasswordDialog
title={title}
btnLoading={isLoading}
warning={warning}
isShow={isShowPwdDialog}
onEnter={this.onPwdEnter}
onClose={this.onPwdClose}
updateWarning={formAction.updateWarning}
/>
);
};
render() {
const { tradeType } = window.OM_GLOBAL;
const { strategyType } = this.props.FormStore;
const extraClassName = tradeType === Enum.tradeType.normalTrade ? 'flex10' : 'auto-stretch';
this.asset = this.getAvailables();
return (
<div className={`spot-place-order-container ${extraClassName}`}>
{this.renderTitle()}
<div className={`spot-trade type-${strategyType}`}>
{this.getStrategyForm(strategyType)}
{this.renderPwdDialog()}
</div>
</div>
);
}
}
export default SpotPlaceOrder;
<file_sep>import commonZhCN from '../language/zh';
import commonEnUS from '../language/en';
import commonZhHK from '../language/hk';
import commonKoKR from '../language/ko';
import zhCN from './zh';
import enUS from './en';
import zhHK from './hk';
import koKR from './ko';
export default (language) => {
let messages = null;
if (language === 'zh_CN') { // 简体中文
messages = { ...commonZhCN, ...zhCN };
} else if (language === 'en_US') { // 英文
messages = { ...commonEnUS, ...enUS };
} else if (language === 'zh_HK') { // 繁体中文
messages = { ...commonZhHK, ...zhHK };
} else if (language === 'ko_KR') { // 韩文
messages = { ...commonKoKR, ...koKR };
}
return messages;
};
<file_sep>import React, { Component } from 'react';
import { calc } from '_component/omit';
import ont from '_src/utils/dataProxy';
import URL from '_constants/URL';
import { toLocale } from '_src/locale/react-locale';
import util from '_src/utils/util';
import DashboardSection from './DashboardSection';
const depositCols = [
{
title: toLocale('tokenPair_column_tokenPair'),
key: 'product',
render: (text) => {
return util.getShortName(text);
}
},
{
title: toLocale('tokenPair_column_birth'),
key: 'block_height',
},
{
title: toLocale('tokenPair_column_deposit'),
key: 'deposits',
render: (text) => {
return calc.showFloorTruncation(text.amount, 8, false);
}
},
{
title: toLocale('tokenPair_column_rank'),
key: 'rank',
},
{
title: '',
key: 'add',
render: (text, data) => {
return (
<span
className="td-action"
>
{toLocale('tokenPair_cell_add')}
</span>
);
}
}
];
class DashboardTokenpair extends Component {
constructor() {
super();
this.state = {
loading: false,
deposits: [],
};
this.addr = window.OM_GLOBAL.senderAddr;
}
componentDidMount() {
if (this.addr) {
this.fetchAccountDeposit();
}
}
fetchAccountDeposit = () => {
const page = 1;
const address = this.addr;
const params = {
page,
per_page: 3,
};
this.setState({ loading: true });
ont.get(`${URL.GET_ACCOUNT_DEPOSIT}/${address}`, { params }).then(({ data }) => {
this.setState({ loading: false, deposits: data });
}).catch((err) => {
console.log(err);
});
}
render() {
const { loading, deposits } = this.state;
return (
<DashboardSection
title={toLocale('dashboard_tokenPair_title')}
columns={depositCols}
dataSource={deposits}
rowKey="product"
isLoading={loading}
empty={toLocale('tokenPair_emtpy')}
/>
);
}
}
export default DashboardTokenpair;
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import { Button } from '_component/Button';
import navigation from '../../utils/navigation';
import Enum from '../../utils/Enum';
import './NotLogin.less';
export default () => {
const { tradeType } = window.OM_GLOBAL;
return (
<div className={`place-order-not-login ${tradeType === Enum.tradeType.fullTrade ? 'dark' : 'flex10'}`}>
<div className="header">{toLocale('spot.notlogin.tradenow')}</div>
<div className="main">
{/* site以前传omex or omcoin,但是为了兼容各种券商,去掉站点名称 */}
<p>{toLocale('spot.notlogin.preview', { site: '' })}</p>
<div className="btns">
<Button
type={Button.btnType.primary}
size={Button.size.large}
circle
onClick={() => { navigation.login(); }}
>
{toLocale('login')}
</Button>
<Button
type={Button.btnType.default}
size={Button.size.large}
circle
onClick={() => { navigation.register(); }}
style={{ background: 'none' }}
>
{toLocale('signUp')}
</Button>
</div>
</div>
</div>
);
};
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Tabs, { TabPane } from 'rc-tabs';
import { toLocale } from '_src/locale/react-locale';
import * as NodeActions from '_src/redux/actions/NodeAction';
import { getNodeLatency } from '_src/utils/node';
import NodeItem from './NodeItem';
import NodeList from './NodeList';
import TabLocal from './TabLocal';
import TabCustomerlize from './TabCustomerlize';
import './index.less';
const loopTime = 10000;
function mapStateToProps(state) { // 绑定redux中相关state
const {
currentNode, remoteList,
} = state.NodeStore;
return {
currentNode,
remoteList,
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
nodeActions: bindActionCreators(NodeActions, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class NodeSetting extends Component {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
const fetchNodesLatency = () => {
const { remoteList } = this.props;
remoteList.forEach((node) => {
getNodeLatency(node).then((latency) => {
const newList = this.props.remoteList.slice();
for (let i = 0; i < newList.length; i++) {
if (newList[i].wsUrl === node.wsUrl) {
newList[i].latency = latency;
break;
}
}
this.props.nodeActions.updateRemoteList(newList);
const { currentNode } = this.props;
if (currentNode.wsUrl === node.wsUrl) {
this.props.nodeActions.updateCurrenntNode({ ...currentNode, latency });
}
});
});
};
fetchNodesLatency();
this.timer = setInterval(fetchNodesLatency, loopTime);
}
componentWillUnmount() {
this.timer && clearInterval(this.timer);
}
render() {
const { currentNode } = this.props;
const {
region, country, location, wsUrl, latency
} = currentNode;
return (
<div className="node-container">
<h1 className="node-title">{toLocale('node.main.title')}</h1>
<div className="node-active-container">
<h2 className="node-active-title">{toLocale('node.active.title')}</h2>
<NodeItem
name={`${region} - ${country} - ${location}`}
ws={wsUrl}
http="https://www.omlink.com/omchain/v1"
delayTime={latency}
disabled
/>
</div>
<div className="node-select-container">
<Tabs defaultActiveKey="1" prefixCls="node-select">
<TabPane tab={toLocale('node.tab.wellenow')} key="1">
<NodeList />
</TabPane>
<TabPane tab={toLocale('node.tab.local')} key="2">
<TabLocal />
</TabPane>
<TabPane tab={toLocale('node.tab.customerlize')} key="3">
<TabCustomerlize />
</TabPane>
</Tabs>
</div>
</div>
);
}
}
export default NodeSetting;
<file_sep>import React from 'react';
import Tooltip from 'rc-tooltip';
import './index.less';
const index = ({
isHTML = false, overlay = '', maxWidth, children, noUnderline,
style = {}, className = '',
hasArrow = false, noWrapper = false, hasShadow = false,
...props
}) => {
let overlayDiv = null;
const overlayProps = {
className: 'om-tooltip-inner',
style: { maxWidth }
};
if (isHTML && typeof overlay === 'string') {
overlayDiv = (
<div {...overlayProps} dangerouslySetInnerHTML={{ __html: overlay }} />
);
} else {
overlayDiv = (
<div {...overlayProps}>
{overlay}
</div>
);
}
let inner = null;
if (noWrapper) {
inner = children;
} else {
inner = <span className={`${className} ${noUnderline ? '' : 'has-tooltip'}`} style={style}>{children}</span>;
}
return (
<Tooltip
{...props}
overlay={overlayDiv}
overlayClassName={`om-tooltip ${maxWidth ? 'no-default-max' : ''} ${hasArrow ? 'has-arrow' : ''} ${hasShadow ? 'has-shadow' : ''}`}
>
{inner}
</Tooltip>
);
};
export default index;
<file_sep>import React from 'react';
// import '@babel/polyfill';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import { LocaleProvider } from '_src/locale/react-locale';
import { storage } from '_component/omit';
import Cookies from 'js-cookie';
import configureStore from './redux/store';
import App from './container/App';
import './index.less';
import './assets/fonts/iconfont.css';
import './assets/fonts/iconfont';
import util from './utils/util';
// x
// 是否开放交易所,来自javaWeb工程注入
// window.isBroker = true;
// window.brokerObj = {
// logo: ''
// };
window.OM_GLOBAL = {
webTypes: { OMEx: 'OMEx', DEX: 'DEX' }, // 站点列表
webType: 'DEX', // 站点标示
ws: undefined, // websocket实例
tradeType: undefined, // 交易模式(全屏/非全屏)
isMarginType: false, // 杠杠模式(是否开启杠杠模式 false不开启,true开启)
productObj: undefined, // 所有币对配置
productConfig: {
// max_price_digit: '',
// max_size_digit: '',
min_trade_size: ''
}, // 当前币对配置
isLogin: undefined,
};
// const language = 'zh_CN';
// 多语言配置
const language = util.getSupportLocale(Cookies.get('locale') || 'en_US');
const languageType = 2; // 1远程,2本地
let localProviderProps = {};
const store = configureStore();
const renderDom = () => {
render(
<LocaleProvider {...localProviderProps} >
<Provider store={store}>
<App />
</Provider>
</LocaleProvider>,
document.querySelector('#app')
);
};
if (languageType === 2) {
import('./locale').then((localeMessage) => {
localProviderProps = {
localeData: localeMessage.default(language)
};
renderDom();
});
} else {
const fetchConfig = {
site: 'omex',
project: 'spot',
locale: language,
needParts: ['transfer']
};
localProviderProps = { fetchConfig };
renderDom();
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import Fee from './Fee';
import Enum from '../../utils/Enum';
import util from '../../utils/util';
const SubmitButton = (props) => {
const { webType, webTypes, tradeType } = window.OM_GLOBAL;
const {
type, isLoading, canSubmit, warning, unit, onClick, isMargin
} = props;
const extra = isMargin ? 'Margin' : '';
let intlId = `spot.orders.actionBuy${extra}`;
let classFix = 'buy';
if (type === Enum.placeOrder.type.sell) {
intlId = `spot.orders.actionSell${extra}`;
classFix = 'sell';
}
let btnContent = `${toLocale(intlId) } ${ unit}`;
if (webType === webTypes.OMKr) {
btnContent = unit + toLocale(intlId);
}
// 修改文案
if (!util.isLogined()) {
btnContent = `${toLocale('header_menu_create_wallet') } / ${ toLocale('header_menu_import_wallet')}`;
}
const isFullTrade = tradeType === Enum.tradeType.fullTrade;
const hasWarn = warning.trim() !== '';
const isDisabled = isLoading || !canSubmit;
return (
<div className="spot-submit">
<button
className={isDisabled ? 'spot-disabled-btn' : `spot-submit-${classFix}`}
onClick={util.debounce(onClick, 100)}
>
{isLoading ? toLocale('spot.submit.loading') : btnContent}
</button>
<div className="mar-top5 fz12" style={{ display: hasWarn ? 'block' : 'none', height: '13px' }}>
{window.isBroker && !isFullTrade && !hasWarn ? <Fee /> : null}
{hasWarn ? <div className="spot-err-tips">{warning}</div> : null}
</div>
</div>
);
};
SubmitButton.propTypes = {
type: PropTypes.number,
unit: PropTypes.string,
canSubmit: PropTypes.bool,
isLoading: PropTypes.bool,
warning: PropTypes.string,
onClick: PropTypes.func,
isMargin: PropTypes.bool,
};
SubmitButton.defaultProps = {
type: 1,
unit: '',
canSubmit: true,
isLoading: false,
warning: '',
isMargin: false,
onClick: () => {
}
};
export default SubmitButton;
<file_sep>import React, { Component } from 'react';
import DexDesktopContainer from '_component/DexDesktopContainer';
import DexDesktopInput from '_component/DexDesktopInput';
import DexDesktopCheckbox from '_component/DexDesktopCheckbox';
import { toLocale } from '_src/locale/react-locale';
import PasswordDialog from '_component/PasswordDialog';
import { Dialog } from '_component/Dialog';
import Message from '_src/component/Message';
import ClientWrapper from '_src/wrapper/ClientWrapper';
import util from '_src/utils/util';
import Config from '_constants/Config';
import './index.less';
const showError = () => {
Message.error({
content: '服务端异常,请稍后重试'
});
};
@ClientWrapper
class IssueToken extends Component {
constructor() {
super();
this.state = {
symbol: '',
wholename: '',
totalSupply: '',
mintable: 0,
desc: '',
isActionLoading: false,
};
}
onSymbolChange = (e) => {
this.setState({
symbol: e.target.value
});
}
onWholenameChange = (e) => {
this.setState({
wholename: e.target.value
});
}
onTotalSupplyChange = (e) => {
this.setState({
totalSupply: e.target.value
});
}
onMintableChange = (e) => {
this.setState({
mintable: e.target.checked ? 1 : 0
});
}
onDescChange = (e) => {
this.setState({
desc: e.target.value
});
}
onIssue = () => {
this.setState({ isActionLoading: true });
const {
symbol, wholename, totalSupply, mintable, desc
} = this.state;
const { omchainClient } = this.props;
const fSymbol = symbol.toLowerCase();
const fTotal = util.precisionInput(totalSupply);
const fMintable = mintable === 1;
omchainClient.sendTokenIssueTransaction(fSymbol, wholename, fTotal, fMintable, desc).then((res) => {
this.setState({ isActionLoading: false });
const { result, status } = res;
const { txhash } = result;
const log = JSON.parse(result.raw_log);
if (status !== 200 || (log && log.code)) {
showError();
} else {
const dialog = Dialog.success({
className: 'desktop-success-dialog',
confirmText: 'Get Detail',
theme: 'dark',
title: 'Issue success!',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
window.open(`${Config.omchain.browserUrl}/tx/${txhash}`);
dialog.destroy();
},
});
}
}).catch((err) => {
console.log(err);
this.setState({ isActionLoading: false });
showError();
});
}
onPwdEnter = (password) => {
this.props.onPwdEnter(password, this.onIssue);
}
handleIssue = () => {
this.props.checkPK(this.onIssue);
}
render() {
const {
symbol, wholename, totalSupply, desc, mintable, isActionLoading
} = this.state;
const { isShowPwdDialog, isLoading, warning } = this.props;
return (
<DexDesktopContainer
isShowHelp
isShowAddress
needLogin
loading={isActionLoading}
>
<div className="issue-token-container">
<DexDesktopInput
label={toLocale('issueToken.symbol.label')}
value={symbol}
onChange={this.onSymbolChange}
hint={toLocale('issueToken.symbol.hint')}
/>
<DexDesktopInput
label={toLocale('issueToken.wholename.label')}
value={wholename}
onChange={this.onWholenameChange}
/>
<DexDesktopInput
label={toLocale('issueToken.totalSupply.label')}
value={totalSupply}
onChange={this.onTotalSupplyChange}
/>
<DexDesktopCheckbox
label={toLocale('issueToken.mintable.label')}
checked={mintable === 1}
onChange={this.onMintableChange}
/>
<DexDesktopInput
label={toLocale('issueToken.desc.label')}
value={desc}
onChange={this.onDescChange}
multiple
/>
<button
className="dex-desktop-btn issue-token-btn"
onClick={this.handleIssue}
>
{toLocale('issueToken.issue.btn')}
</button>
</div>
<PasswordDialog
btnLoading={isLoading}
warning={warning}
isShow={isShowPwdDialog}
updateWarning={this.props.updateWarning}
onEnter={this.onPwdEnter}
onClose={this.props.onPwdClose}
/>
</DexDesktopContainer>
);
}
}
export default IssueToken;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './Tabs.less';
export default class TabPane extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="om-Tabpane" style={{ display: this.props.display, ...this.props.style }}>
{this.props.children}
</div>
);
}
}
TabPane.propTypes = {
// label: PropTypes.oneOfType([
// PropTypes.object,
// PropTypes.string
// ]),
display: PropTypes.string,
// tabBarExtraContent: PropTypes.oneOfType([
// PropTypes.object,
// PropTypes.string
// ])
};
TabPane.defaultProps = {
// label: '- -',
display: 'block',
// tabBarExtraContent: null
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Icon from '../IconLite';
import './BaseButton.less';
import BaseButton from './BaseButton';
const ButtonSize = {
mini: 'mini',
small: 'small',
large: 'large',
default: 'default'
};
export default class Button extends React.PureComponent {
static propTypes = {
/** 设置按钮载入状态 */
loading: PropTypes.bool,
/** 设置按钮形状,可选值为 circle */
shape: PropTypes.string,
/** 设置按钮的图标类型 */
icon: PropTypes.string,
/** 外部传入类 */
className: PropTypes.string,
/** 设置按钮大小,可选值为 small large 或者不设 */
size: PropTypes.string,
/** 将按钮宽度调整为其父宽度的选项 */
block: PropTypes.bool,
/** 点击跳转的地址,指定此属性 button 的行为和 a 链接一致 */
href: PropTypes.string,
/** 相当于 a 链接的 target 属性,href 存在时生效 */
target: PropTypes.string,
};
static defaultProps = {
loading: false,
shape: '',
icon: '',
className: '',
size: ButtonSize.default,
block: false,
href: '',
target: '',
};
render() {
const {
loading, shape, icon, className, size, block, href, target, children, ...attr
} = this.props;
return (
<BaseButton
{...attr}
>
{
icon && icon.length !== 0 && !loading &&
<Icon className="icon-Loading loading-icon" />
}
{
// loading &&
<Icon className="icon-Loading loading-icon" />
}
{children}
</BaseButton>
);
}
}
Button.btnType = BaseButton.btnType;
<file_sep>/* eslint-disable camelcase */
import { calc } from '_component/omit';
// yao 格式化深度asks/bids数据 两个格式逻辑是一样的因此提取出函数
import util from './util';
const formatDepthArr = (arr) => {
return {
price: arr[0],
quantity: arr[1],
};
};
const formatProduct = (product) => {
return product;
// return symbol.toLowerCase().replace('-', '_');
};
const instrumentId2Product = (instrument_id) => {
return instrument_id.toLowerCase().split('_');
};
const formatters = {
account: (data) => { // 币币账户
return data;
},
// 用户交易数据
order([resData]) {
return resData;
},
kline: (data) => { // k线
return data.map(({ instrument_id, candle: [timestamp, open, high, low, close, volume] }) => {
return {
open,
high,
low,
close,
volume,
symbol: instrument_id.replace('-', '_').toLowerCase(),
createdDate: new Date(timestamp).getTime(),
};
});
},
ticker([resData]) {
return {
high: +resData.high,
low: +resData.low,
open: +resData.open,
volume: +resData.volume,
price: +resData.price,
product: formatProduct(resData.product),
change: resData.price - resData.open,
changePercentage: util.getChangePercentage(resData),
last: +resData.price,
};
},
allTickers: (data) => { // 所有币对ticker
return data.map((resData) => {
const open = resData.o;
let changePercent = '0.00';
if (open && (+resData.p !== -1)) {
changePercent = calc.floorDiv(calc.sub(resData.p, open) * 100, open, 2);
}
// 如果数值是负数 则自带负号
const changeSignStr = changePercent >= 0 ? '+' : '';
return {
high: +resData.h,
low: +resData.l,
open: +resData.o,
volume: +resData.v,
price: +resData.p,
product: formatProduct(resData.id),
change: resData.p - resData.o,
changePercentage: `${changeSignStr}${changePercent}%`,
last: +resData.p,
};
});
},
// 深度
depth: ({ data, action }) => {
const [resData] = data;
const [base, quote] = instrumentId2Product(resData.instrument_id);
return {
base,
quote,
action,
data: {
asks: resData.asks.map(formatDepthArr),
bids: resData.bids.map(formatDepthArr),
}
};
},
// 成交的数据
matches: (data) => {
return data;
},
};
export default formatters;
<file_sep>import { PureComponent } from 'react'; // eslint-disable-line
import PropTypes from 'prop-types';
import { getMedia, WatchMedia } from '../index';
class MediaQuery extends PureComponent {
constructor(props) {
super(props);
const media = getMedia().media;
this.state = {
media
};
// 监听媒体类型
this.watchMedia = new WatchMedia();
this.watchMedia.watch((mediaConfig) => {
this.setState({
media: mediaConfig.media
});
}, { runNow: false });
}
componentWillUnmount() {
this.watchMedia.destroy();
}
// 根据当前媒体获取需要选项的组件
getCurrentComponent = () => {
const {
sm, md, lg, xl
} = this.props;
this.components = {
sm, md, lg, xl
};
// 寻找最近一层,props存在的组件
if (!md) {
this.components.md = this.components.sm;
}
if (!lg) {
this.components.lg = this.components.md;
}
if (!xl) {
this.components.xl = this.components.lg;
}
const currentMedia = this.state.media;
return this.components[currentMedia];
}
render() {
// 业务层SM组件的props变化时,需要重新赋值this.components,所以在render时重新计算
const CurrentComponent = this.getCurrentComponent();
return CurrentComponent;
}
}
MediaQuery.propTypes = {
sm: PropTypes.element.isRequired,
md: PropTypes.element,
lg: PropTypes.element,
xl: PropTypes.element
};
MediaQuery.defaultProps = {
md: null,
lg: null,
xl: null
};
export default MediaQuery;
<file_sep>import { createBrowserHistory, createHashHistory } from 'history';
let Router = createBrowserHistory();
if (process.env.ROUTE_TYPE === 'hash') {
Router = createHashHistory();
}
const proxy = new Proxy(Router, {
get(target, key) {
return target[key];
},
set(target, key, value) {
target[key] = value; // eslint-disable-line
}
});
export default proxy;
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button } from '_component/Button';
import WalletLeft from '_component/WalletLeft';
import WalletRight from '_component/WalletRight';
import * as walletActions from '_src/redux/actions/WalletAction';
import questionGenerator from './questionGenerator';
import './Step.less';
import './Step3.less';
import { toLocale } from '_src/locale/react-locale';
function mapStateToProps(state) {
const { mnemonic } = state.WalletStore;
return { mnemonic };
}
function mapDispatchToProps(dispatch) {
return {
walletAction: bindActionCreators(walletActions, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps)
class Step3 extends Component {
constructor(props) {
super(props);
this.questions = questionGenerator.getQuestions(props.mnemonic.split(' '));
this.state = {
selectArr: []
};
}
selectOption = (questionNo, selectedIndex) => {
return () => {
const { selectArr } = this.state;
const selectArrTemp = [...selectArr];
selectArrTemp[questionNo] = selectedIndex;
this.setState({
selectArr: selectArrTemp
});
};
}
// 返回上一步
handlePrevStep = () => {
const { walletAction } = this.props;
walletAction.updateIsPass(true);
walletAction.updateCreateStep(2);
}
// 点击确定
handleEnsure = () => {
const { selectArr } = this.state;
const { questions } = this;
const { walletAction } = this.props;
const isPass = questions.every((item, index) => {
return item.answer === selectArr[index];
});
if (!isPass) {
walletAction.updateIsPass(false);
walletAction.updateCreateStep(2);
} else {
walletAction.updateCreateStep(4);
}
}
renderQuestion = (question, selectedOption) => {
const { no, title } = question;
return (
<div className="question-item" key={`question${no}`}>
<div className="question-title">
{no + 1})
{toLocale('wallet_choiceMnemonicPre')}
<span style={{ color: '#3075EE', margin: '0 3px' }}>
{title}
</span>
{toLocale('wallet_choiceMnemonicSuf')}
</div>
<div className="options-container">
{
question.options.map((optionItem, optionIndex) => {
const isActive = selectedOption === optionIndex;
const clsName = `option-item ${isActive ? 'active' : ''}`;
return (
<div
className={clsName}
key={`question${no}-option${optionIndex}`}
onClick={this.selectOption(no, optionIndex)}
>
{optionItem}
</div>
);
})
}
</div>
</div>
);
}
render() {
const { selectArr } = this.state;
return (
<div>
<div className="create-wallet-step3 wallet-step-dialog">
<WalletLeft
stepNo={3}
stepName={toLocale('wallet_create_step3')}
imgUrl="https://static.bafang.com/cdn/assets/imgs/MjAxOTQ/355F3AD5BD296D7EEA40263B0F98E4F3.png"
/>
<WalletRight>
<div className="questions-container">
{
this.questions.map((questionItem, questionIndex) => {
return this.renderQuestion(questionItem, selectArr[questionIndex]);
})
}
</div>
<div className="next-row">
<Button type="primary" className="prev-btn" onClick={this.handlePrevStep}>
{toLocale('prev_step')}
</Button>
<Button type="primary" onClick={this.handleEnsure}>
{toLocale('wallet_confirm')}
</Button>
</div>
</WalletRight>
</div>
</div>
);
}
}
export default Step3;
<file_sep>import React, { Component } from 'react';
import { toLocale } from '_src/locale/react-locale';
import QRCode from 'qrcode.react';
import Icon from '_src/component/IconLite';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import './index.less';
class WalletAddress extends Component {
constructor() {
super();
this.state = {
copySuccess: false,
};
}
onCopy = () => {
if (this.state.copySuccess) return;
this.setState({ copySuccess: true });
clearTimeout(this.copyTimer);
this.copyTimer = setTimeout(() => {
this.setState({ copySuccess: false });
}, 1000);
};
render() {
const { senderAddr } = window.OM_GLOBAL || {};
const { copySuccess } = this.state;
return (
<div className="my-address">
<span>{toLocale('assets_address')}{senderAddr}</span>
<div className="qr-container">
<Icon className="icon-icon_erweima" />
<div className="qr-pic">
<QRCode value={senderAddr || ''} size={75} />
</div>
</div>
<CopyToClipboard text={senderAddr} onCopy={this.onCopy}>
<Icon className={copySuccess ? 'icon-icon_success' : 'icon-icon_copy'} isColor />
</CopyToClipboard>
</div>
);
}
}
export default WalletAddress;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { calc } from '_component/omit';
import { toLocale } from '_src/locale/react-locale';
import Icon from '_src/component/IconLite';
import { NODE_TYPE, MAX_LATENCY } from '_constants/Node';
import { getDelayType } from '_src/utils/node';
import './NodeItem.less';
const timeUnit = (time) => {
if (!time || time === MAX_LATENCY) {
return '- -';
}
const suffix = ['ms', 's'];
const carry = 1000;
let index = 0;
while (time >= carry && index < suffix.length - 1) {
time = calc.div(time, carry);
index++;
}
return `${time}${suffix[index]}`;
};
class NodeItem extends Component {
static propTypes = {
name: PropTypes.string,
ws: PropTypes.string,
http: PropTypes.string,
delayTime: PropTypes.number,
onClick: PropTypes.func,
disabled: PropTypes.bool,
};
static defaultProps = {
name: '',
ws: '',
http: '',
delayTime: MAX_LATENCY,
onClick: () => {},
disabled: false,
};
constructor() {
super();
this.state = {};
}
handleClick = () => {
const { onClick, disabled } = this.props;
if (!disabled) {
onClick && onClick();
}
}
render() {
const {
name, ws, http, delayTime, disabled
} = this.props;
const delayType = getDelayType(delayTime);
const delayCls = `node-delay node-delay-${delayType}`;
const delayTypeTxt = toLocale(`node.delay.type.${delayType}`);
return (
<div className="node-set-item">
<div className="node-name">{name}</div>
<div className="node-link">
<div className="node-link-item one-line">{ws}</div>
<div className="node-link-item one-line">{http}</div>
</div>
<div className={delayCls}>
<div className="node-delay-type">{delayTypeTxt}</div>
<div className="node-delay-time">{timeUnit(delayTime)}</div>
</div>
<div className="node-icon" onClick={this.handleClick} style={{ cursor: disabled ? 'normal' : 'pointer' }}>
<Icon className={`icon-node color-${delayType}`} />
</div>
</div>
);
}
}
NodeItem.NODE_TYPE = NODE_TYPE;
export default NodeItem;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { calc } from '_component/omit';
function mapStateToProps(state) { // 绑定redux中相关state
const { tickers } = state.Spot;
const { legalObj } = state.Common;
return { tickers, legalObj };
}
function mapDispatchToProps() { // 绑定action,以便向redux发送action
return {};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class LegalPrice extends React.Component {
static propTypes = {
currency: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};
static defaultProps = {
currency: '',
value: 0
};
render() {
const {
tickers, currency, value, legalObj
} = this.props;
// 计算人民币价格
let legalPrice = '';
if (tickers) {
// btc_usdt、eth_usdt等,usdt_usdt不存在,取1
// const tradeCurr = currency.toLowerCase();
// const { price } = tickers[`${tradeCurr}_omb`] || { price: tradeCurr === 'omb' ? 1 : 0 };
// const price = tickers[`${tradeCurr}_omb`] ? 1 : 0;
const { rate, symbol, precision } = legalObj;
if (value && rate) {
const digit = precision || 0;
const finalPrice = (calc.mul(calc.mul(value || 0, rate), 1) || 0).toFixed(digit);
legalPrice = `≈${symbol || ''}${(calc.showFloorTruncation(finalPrice, digit))}`;
}
}
return <span className="legal-price c-disabled fz12">{legalPrice}</span>;
}
}
export default LegalPrice;
<file_sep>const SpotActionType = {
FETCH_SUCCESS_CURRENCY_LIST: 'FETCH_SUCCESS_CURRENCY_LIST', // 获取所有币种-成功
FETCH_ERROR_CURRENCY_LIST: 'FETCH_ERROR_CURRENCY_LIST', // 获取所有币种-失败
UPDATE_WS_STATUS_V3: 'UPDATE_WS_STATUS_V3', // 更新ws连接状态 v3
UPDATE_WS_ERR_COUNTER_V3: 'UPDATE_WS_ERR_COUNTER_V3', // 更新ws连接状态-失败计数器次数 v3
UPDATE_WS_IS_DELAY: 'UPDATE_WS_IS_DELAY', // 更新ws登录是否延迟
FETCH_SUCCESS_TICKERS: 'FETCH_SUCCESS_TICKERS', // 获取所有tickers-成功
UPDATE_TICKERS: 'UPDATE_TICKERS', // 批量更新tickers
FETCH_SUCCESS_INDEX_ALL: 'FETCH_SUCCESS_INDEX_ALL', // 获取所有index-成功
UPDATE_ACTIVE_MARKET: 'UPDATE_ACTIVE_MARKET', // 更改交易区
UPDATE_SEARCH: 'UPDATE_SEARCH', // 更改搜索条件
UPDATE_SYMBOL: 'UPDATE_SYMBOL', // 更改当前币对
COLLECT_PRODUCT: 'COLLECT_PRODUCT', // 收藏-取消收藏币对
UPDATE_BILL_MENU: 'UPDATE_BILL_MENU', // 更新账单菜单的选中项
UPDATE_THEME: 'UPDATE_THEME', // 更新主题
UPDATE_CNY_RATE: 'UPDATE_CNY_RATE', // 人民币汇率
UPDATE_HAS_OPEN_MARGIN: 'UPDATE_HAS_OPEN_MARGIN', // 币对中是否存在 杠杠
};
export default SpotActionType;
<file_sep>import React, { Component } from 'react';
import { toLocale } from '_src/locale/react-locale';
import { withRouter } from 'react-router-dom';
import Icon from '_component/IconLite';
import PageURL from '_constants/PageURL';
import config from '../../../package.json';
import './index.less';
@withRouter
class DesktopLinkMenu extends Component {
constructor() {
super();
this.state = {
isMenuShow: false
};
}
showMenu = () => {
this.setState({ isMenuShow: true });
}
hideMenu = () => {
this.setState({ isMenuShow: false });
}
toRoute = (route) => {
return () => {
this.props.history.push(route);
this.hideMenu();
};
}
render() {
const { isMenuShow } = this.state;
const { version } = config;
return (
<div
className="desktop-setting-container"
onMouseEnter={this.showMenu}
onMouseLeave={this.hideMenu}
>
<Icon className="icon-icon_hambergur" />
<div
className="desktop-link-menu-wrapper"
style={{ display: isMenuShow ? 'block' : 'none' }}
>
<div className="desktop-link-menu-conntainer">
<div className="link-menu-item-container">
<div className="link-menu-item" onClick={this.toRoute(PageURL.dashboardPage)}>{toLocale('linkMenu.Dashboard')}</div>
</div>
<div className="link-menu-item-container link-token-container">
<div className="link-menu-item">
{toLocale('linkMenu.Token')}
<Icon className="icon-retract" />
<div className="link-sub-menu">
<div className="link-submenu-item" onClick={this.toRoute(PageURL.issueTokenPage)}>{toLocale('linkMenu.issue')}</div>
<a href="" className="link-submenu-item">{toLocale('linkMenu.mintBurn')}</a>
</div>
</div>
</div>
<div className="link-menu-item-container link-operator-container">
<div className="link-menu-item">
{toLocale('linkMenu.operator')}
<Icon className="icon-retract" />
<div className="link-sub-menu">
<div className="link-submenu-item" onClick={this.toRoute(PageURL.registerPage)}>{toLocale('linkMenu.register')}</div>
<div className="link-submenu-item" onClick={this.toRoute(PageURL.listTokenpairPage)}>{toLocale('linkMenu.tokenPair')}</div>
<a href="" className="link-submenu-item">{toLocale('linkMenu.deposits')}</a>
<a href="" className="link-submenu-item">{toLocale('linkMenu.handlingFee')}</a>
</div>
</div>
</div>
<div className="link-menu-item-container">
<div className="link-menu-version">{toLocale('linkMenu.version')}</div>
<div className="link-menu-version-detail">OPENDEX {version}</div>
</div>
</div>
</div>
</div>
);
}
}
export default DesktopLinkMenu;
<file_sep>import Config from './Config';
// function getContextPath() {
// const pathName = document.location.pathname;
// const index = pathName.substr(1).indexOf('/');
// const result = pathName.substr(0, index + 1);
// return result;
// }
// var OMEX_BASE_URL = location.protocol + '//' + location.host + getContextPath() + PROJECT_PRXFIX_URL;
const OMDEX_BASE_URL = '{domain}/omchain/v1';
/*
* URL统一管理
*/
const URL = {
GET_ORDER_OPEN: `${OMDEX_BASE_URL}/order/list/open`,
GET_ORDER_CLOSED: `${OMDEX_BASE_URL}/order/list/closed`,
GET_PRODUCT_DEALS: `${OMDEX_BASE_URL}/deals`,
GET_LATEST_MATCHES: `${OMDEX_BASE_URL}/matches`,
GET_PRODUCT_TICKERS: `${OMDEX_BASE_URL}/tickers`,
GET_PRODUCTS: `${OMDEX_BASE_URL}/products`, // `${OMDEX_BASE_URL}/products` 原:`${OMDEX_SUPPORT_ROOT}/omchain/product/list`
GET_TOKENS: `${OMDEX_BASE_URL}/tokens`,
GET_DEPTH_BOOK: `${OMDEX_BASE_URL}/order/depthbook`,
GET_CANDLES: `${OMDEX_BASE_URL}/candles`,
GET_ACCOUNTS: `${OMDEX_BASE_URL}/accounts`, // 所有账户
GET_TRANSACTIONS: `${OMDEX_BASE_URL}/transactions`, // 交易记录
GET_LATEST_HEIGHT: `${OMDEX_BASE_URL}/latestheight`, // 查询最新高度
GET_ACCOUNT_DEPOSIT: `${OMDEX_BASE_URL}/dex/deposits`, // 查询对应地址的币对
};
export default URL;
<file_sep>import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../IconLite';
import OmPagination from './OmPagination';
function noop() {
}
export default class Pagination extends React.Component {
static propTypes = {
current: PropTypes.number,
defaultCurrent: PropTypes.number,
total: PropTypes.number,
pageSize: PropTypes.number,
defaultPageSize: PropTypes.number,
onChange: PropTypes.func,
hideOnSinglePage: PropTypes.bool,
showQuickJumper: PropTypes.bool,
showTotal: PropTypes.func,
/** (page: number, type: 'page' | 'prev' | 'next' | 'jump-prev' | 'jump-next') => React.ReactNode
* 用于自定义页码的结构,可用于优化 SEO
* */
itemRender: PropTypes.func,
size: PropTypes.string,
dark: PropTypes.bool,
// 兼容老版本
totalPage: PropTypes.number,
};
static defaultProps = {
prefixCls: 'om-ui-pagination',
current: 1,
defaultCurrent: 1,
total: 100,
pageSize: 10,
defaultPageSize: 10,
onChange: noop,
hideOnSinglePage: true,
showQuickJumper: false,
showTotal: noop,
dark: false,
size: '',
};
getIconsProps = () => {
const { prefixCls } = this.props;
const prevIcon = (
<a className={`${prefixCls}-item-link`}>
<Icon type="left" />
</a>
);
const nextIcon = (
<a className={`${prefixCls}-item-link`}>
<Icon type="right" />
</a>
);
const jumpPrevIcon = (
<a className={`${prefixCls}-item-link`}>
<div className={`${prefixCls}-item-container`}>
<Icon
className={`${prefixCls}-item-link-icon`}
type="double-left"
/>
<span className={`${prefixCls}-item-ellipsis`}>•••</span>
</div>
</a>
);
const jumpNextIcon = (
<a className={`${prefixCls}-item-link`}>
<div className={`${prefixCls}-item-container`}>
<Icon
className={`${prefixCls}-item-link-icon`}
type="double-right"
/>
<span className={`${prefixCls}-item-ellipsis`}>•••</span>
</div>
</a>
);
return {
prevIcon,
nextIcon,
jumpPrevIcon,
jumpNextIcon,
};
};
render() {
const {
className, size, locale, ...restProps
} = this.props;
const isSmall = size === 'small';
return (
<OmPagination
{...restProps}
{...this.getIconsProps()}
className={classNames(className, { mini: isSmall })}
locale={locale}
/>
);
}
}
<file_sep>import LoggedMenu from './LoggedMenu';
import LoginMenu from './LoginMenu';
export default { LoggedMenu, LoginMenu };
export { LoggedMenu };
export { LoginMenu };
<file_sep>// 全屏深度背景条
const DepthBar = {
sort(depth) {
depth.sort((a, b) => { return a.amount.replace(/,/g, '') - b.amount.replace(/,/g, ''); });
return depth;
},
median(depth) {
const i = Math.floor(depth.length * 2 / 3);
if (!depth[i]) {
return 1;
}
const result = depth[i].amount.replace(/,/g, '');
return Math.max(1, result);
},
medianUnit(bids, asks) {
return this.median(this.sort(bids.concat(asks)));
},
width(amount, medianUnit) {
if (Number(medianUnit) === 0) {
return 1;
}
// (数量/平均数量) * 总长度的50%
return Math.round(amount.replace(/,/g, '') / medianUnit * 50);
}
};
export default DepthBar;
<file_sep>const Image = {
banner_sm: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/DDE07490AE187611948CB9F15BE41793.png',
// 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/410648F9E8DB41A5152E0908A3D7E204.png',
banner_md: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/55C3FCBAC71BE1055775F873E22D092E.png',
banner_lg: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/EBA101812FE23E98F37D7EC1F204FC74.png',
banner_xl: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/25FA1E9B5E49AEBD7CFA3F51816630B6.png',
adv_item0: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/81B03C0DA3BCB843CF579606BD54DC06.png',
adv_item1: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/5C672F9A3D83697712651260658811DA.png',
adv_item2: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/1DEDBB0D47FE70AC39E446D8B9AB6FCE.png',
exp: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/3AF196CA9B03F9FFAE8A519469FBB6AD.png',
step0: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/5BBC703C1C9BF16E9B3DBE44E9306EBD.png',
step1: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/EA5B9697721EAAE780B6A0D18D5F6DE5.png',
step2: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/0A848CAA0FA942D868854F6F469ADEC1.png',
step3: 'https://static.bafang.com/cdn/assets/imgs/MjAyMDQ/F497569D03E57047301DAC9E4CB05207.png',
};
export default Image;
<file_sep>import { Component } from 'react';
import util from './utils/util';
export default class RouterCredential extends Component {
// constructor(props) {
// super(props);
// }
componentWillMount() {
// this.requireCredential();
}
// 路由校验
requireCredential() {
this.subAccountEmailCheck();
const { location, localStorage } = window;
if (util.lessThanIE11()) {
location.href = '/pages/products/browserUpdate.html';
}
const token = localStorage.getItem('dex_token');
// 已经有用户信息,直接展示,这种情况对应用户非首次打开页面
if (token) {
// 页面统计
util.logRecord();
}
}
// 资金管理要求加的子账户检查
subAccountEmailCheck = () => {
const { location, localStorage } = window;
const subAccountUnBindEmail = (localStorage.getItem('subAccountUnBindEmail') === '1');
const currentIsSub = (localStorage.getItem('currentIsSub') === '1');
if (currentIsSub && subAccountUnBindEmail) {
location.href = `/dex/account/users/security/subBindEmail/20?forward=${location.pathname}${location.search}`;
}
};
}
<file_sep>/**
* Created by omer on 2018/1/24.
*/
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Cookies from 'js-cookie';
import echarts from '@okfe/echarts/lib/echarts';
import '@okfe/echarts/lib/chart/line';
import '@okfe/echarts/lib/component/tooltip';
import Colors from '../../utils/Colors';
import Enum from '../../utils/Enum';
export default class Kline extends React.Component {
// constructor(props) {
// super(props);
// }
componentDidMount() {
const { dataSource, theme } = this.props;
this.echartMain = echarts.init(this.chartDom, undefined, {
animationLoopDelta: 64
});
let localeText = {
time: '时间',
price: '价格'
};
const language = Cookies.get('locale') || (navigator.languages && navigator.languages[0]) || navigator.language;
let axisLineColor = Colors.blackRGB(0.1);
let axisTextColor = Colors.blackRGB(0.25);
if (theme === Enum.themes.theme2) {
axisLineColor = Colors.whiteRGB(0.1);
axisTextColor = Colors.whiteRGB(0.25);
}
switch (language) {
case 'en_US':
localeText = {
time: 'time',
price: 'price'
};
break;
case 'zh_HK':
localeText = {
time: '時間',
price: '價咯'
};
break;
case 'ko_KR':
localeText = {
time: '시간',
price: '가격'
};
break;
default:
break;
}
const options = {
grid: {
left: 0,
right: 0,
top: 10,
bottom: 0,
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'line',
},
backgroundColor: Colors.blueRGB(0.1),
padding: 8,
textStyle: {
color: Colors.blue,
fontSize: 12,
lineHeight: 18,
},
formatter: (param) => {
const item = param[0];
return `${localeText.time} : ${item.name}` +
`<br/> ${localeText.price} : ${item.data}`;
}
// position: (point, params, dom, rect, size) => {
// // 固定在顶部
// return [point[0] - (size.contentSize[0] / 2), point[1] - 80];
// }
},
axisPointer: {
// link: { xAxisIndex: 'all' },
lineStyle: {
color: axisLineColor
},
// splitLine: {
// show: true,
// },
// label: {
// backgroundColor: '#777'
// }
},
xAxis: [
{
type: 'category', // time类型的不太靠谱,xAxis的data传啥都不对
axisLine: {
lineStyle: {
color: axisLineColor
}
},
axisLabel: {
textStyle: {
color: axisTextColor
},
},
axisTick: {
show: false
},
// axisPointer: {
// z: 100,
// label: {
// margin: 0,
// color: 'red'
// }
// }
}
],
yAxis: [
{
type: 'value',
show: true,
axisPointer: {
show: false
},
axisLabel: {
textStyle: {
color: axisTextColor
},
},
axisLine: {
show: false
},
splitLine: {
show: false,
},
axisTick: {
show: false,
},
splitNumber: 3,
scale: true,
}
],
series: [
{
name: 'price',
type: 'line',
smooth: true,
symbol: 'circle',
showSymbol: false,
itemStyle: {
color: Colors.blue,
borderWidth: 2,
borderColor: '#fff',
shadowColor: 'rgba(0, 0, 0, 0.15)',
shadowBlur: 9,
shadowOffsetY: 2,
},
lineStyle: {
color: '#5795F1',
width: 1
},
}
]
};
this.echartMain.setOption(options);
this.renderChart(dataSource);
}
componentWillReceiveProps(nextProps) {
this.renderChart(nextProps.dataSource, nextProps.theme);
}
renderChart = (dataSource, theme) => {
if (this.echartMain) {
let axisLineColor = Colors.blackRGB(0.1);
let axisTextColor = Colors.blackRGB(0.25);
if (theme === Enum.themes.theme2) {
axisLineColor = Colors.whiteRGB(0.1);
axisTextColor = Colors.whiteRGB(0.25);
}
const chartData = {
time: [],
price: []
};
let min = 0;
let max = 0;
dataSource.forEach((obj, i) => {
const currClose = obj.close;
if (i == 0) {
min = Number(currClose);
max = Number(currClose);
}
if (Number(currClose) > max) {
max = Number(currClose);
}
if (Number(currClose) < min) {
min = Number(currClose);
}
chartData.time.push(moment(obj.createdDate).format('HH:mm'));
chartData.price.push(currClose);
});
this.echartMain.setOption({
xAxis: [{
data: chartData.time,
axisLabel: {
interval: (index, value) => { return /(.*)(:30|:00)+(.*)/.test(value); }, // 仅展示整点或者半点的刻度
textStyle: {
color: axisTextColor
},
},
axisLine: {
lineStyle: {
color: axisLineColor
}
}
}],
axisPointer: {
lineStyle: {
color: axisLineColor
},
},
yAxis: [{
// min: min * 0.99,
// max: max * 1,
axisLabel: {
textStyle: {
color: axisTextColor
},
},
}],
series: [{
data: chartData.price
}]
});
}
};
render() {
const { style } = this.props;
return (
<div
style={{ ...style, height: '220px' }}
ref={(chartDom) => {
this.chartDom = chartDom;
}}
/>
);
}
}
Kline.defaultProps = {
style: {},
dataSource: []
};
Kline.propTypes = {
style: PropTypes.object,
dataSource: PropTypes.array
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Icon from '_src/component/IconLite';
import { toLocale } from '_src/locale/react-locale';
import util from '_src/utils/util';
import './FullLeftMenu.less';
import ProductListWrapper from '../../wrapper/ProductListWrapper';
const SortTypes = {
noSort: 'noSort',
asc: 'asc',
des: 'des'
};
const FullLeftMenu = class LeftMenu extends React.Component {
static propTypes = {
searchBar: PropTypes.bool,
theme: PropTypes.string,
canStar: PropTypes.bool,
};
static defaultProps = {
searchBar: true, // 修改默认false
theme: '',
canStar: false,
};
constructor(props) {
super(props);
this.state = {
menuList: props.dataSource,
sortType: SortTypes.noSort,
activeId: props.activeId,
};
this.addr = window.OM_GLOBAL.senderAddr;
}
componentWillReceiveProps(nextProps) {
const { sortType } = this.state;
const { dataSource, activeId } = nextProps;
const newList = [...dataSource];
if (sortType === SortTypes.noSort) {
newList.sort((a, b) => { return (a.text).localeCompare(b.text); });
} else if (sortType === SortTypes.asc) {
newList.sort((a, b) => { return parseFloat(a.change) - parseFloat(b.change); });
} else if (sortType === SortTypes.des) {
newList.sort((a, b) => { return parseFloat(b.change) - parseFloat(a.change); });
}
this.setState({
menuList: newList,
activeId
});
}
// 模糊搜索
handleSearchChange = (e) => {
const args = e.target.value;
if (this.props.onSearch) {
this.props.onSearch(args);
return false;
}
const allList = this.props.dataSource;
const filterList = allList.filter((item) => {
return [args.toLowerCase(), args.toUpperCase()].includes(item.text);
});
this.setState({
menuList: filterList
});
return false;
};
// 排序
handleSort = () => {
const { sortType, menuList } = this.state;
const newList = [...menuList];
let newSortType = SortTypes.noSort;
if (sortType === SortTypes.asc) { // 升序切换为降序
newList.sort((a, b) => { return parseFloat(b.change) - parseFloat(a.change); });
newSortType = SortTypes.des;
} else if (sortType === SortTypes.des) { // 降序切换为默认
newList.sort((a, b) => { return (a.text).localeCompare(b.text); });
newSortType = SortTypes.noSort;
} else { // 默认切换为升序
newList.sort((a, b) => { return parseFloat(a.change) - parseFloat(b.change); });
newSortType = SortTypes.asc;
}
this.setState({
sortType: newSortType,
menuList: newList
});
};
// 收藏/取消收藏
handleStar = (item) => {
return (e) => {
e.preventDefault();
e.stopPropagation();
const { onClickStar } = this.props;
if (onClickStar) {
onClickStar(!item.stared, item);
}
};
};
// 选中菜单项
handleSelect = (item) => {
return () => {
const { onSelect } = this.props;
if (onSelect) {
onSelect(item);
}
};
};
// 渲染list
renderList = (menuList) => {
const { canStar } = this.props;
const { activeId } = this.state;
return (
<div>
{
menuList.map((item, index) => {
const {
id, text, change, changePercentage, price
} = item;
let { stared, lever } = item;
lever = null;
stared = false;
const color = change.toString().indexOf('-') > -1 ? 'red' : 'green';
return (
<li
key={index}
className={id === activeId ? 'active' : ''}
onClick={this.handleSelect(item)}
>
{/*
<span
style={{ visibility: canStar ? 'visible' : 'hidden' }}
onClick={this.handleStar(item)}
>
<Icon className={stared ? 'icon-Star' : 'icon-Star-o'} />
</span> */}
<span className="pair" title={text}>{util.getShortName(text)}</span>
{lever ? <span className="lever"><span>{lever}X</span></span> : null}
<span className="pair">{price}</span>
<span className={`change change-${color}`}>{changePercentage}</span>
</li>
);
})
}
</div>
);
};
renderEmpty = () => {
const listEmpty = toLocale('spot.noData');
return (
<div className="empty-container">
{listEmpty}
</div>
);
};
render() {
const {
searchBar, style,
searchText, theme
} = this.props;
const { menuList, sortType } = this.state;
const ascSort = sortType === SortTypes.asc;
const desSort = sortType === SortTypes.des;
const haveData = menuList && menuList.length > 0;
const themeClass = theme || '';
return (
<div className={`om-left-menu ${themeClass}`} style={style}>
{searchBar ?
<div className="list-search">
<div className="search-wrap">
{/* debug-chrome自动记住用户名 */}
<input type="text" style={{ display: 'none' }} />
<input
type="text"
autoComplete="off"
value={searchText}
placeholder={toLocale('search')}
onChange={this.handleSearchChange}
className="input-theme-controls input-query-product"
/>
<Icon className="icon-search" />
</div>
</div> : null
}
<div className="list-head">
<div>{toLocale('pair')}</div>
<div>{toLocale('price')}</div>
<div className="head-percentage">
<div className="head-right" onClick={this.handleSort}>
<span>{toLocale('change')}</span>
<span className="change-icons">
<Icon className={`${ascSort ? 'active' : ''} icon-retract`} />
<Icon className={`${desSort ? 'active' : ''} icon-spread`} />
</span>
</div>
</div>
</div>
<ul className="list-main">{/* style={{ height: 324 }} */}
{haveData ? this.renderList(menuList) : this.renderEmpty()}
</ul>
</div>
);
}
};
export default ProductListWrapper(FullLeftMenu);
<file_sep>import React from 'react';
import Loadable from 'react-loadable';
import Loading from '_component/Loading';
import { toLocale } from '_src/locale/react-locale';
import Alert from '_src/component/Alert';
import './index.less';
const delay = 250;
const timeout = 20000;
function loading(props) {
let loadingPart = null;
if (props.error || props.timedOut) {
loadingPart = (
<div className="err-while-loading">
<Alert
type={Alert.TYPE.error}
message={
<div>
<span>{ toLocale(props.error ? 'spot.error' : 'spot.timeout') }! </span>
<a onClick={() => { window.location.reload(); }} >{ toLocale('spot.retry') }</a>
</div>
}
closable={false}
/>
</div>
);
} else if (props.pastDelay) {
loadingPart = <div className="loading-container"><Loading when={1} /></div>;
}
return loadingPart;
}
export default (loader, showLoading = true) => {
return Loadable({
loader,
delay,
timeout,
loading: (showLoading ? loading : () => { return null; }), // 默认不显示loading
});
};
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { calc } from '_component/omit';
import { toLocale } from '_src/locale/react-locale';
import moment from 'moment';
import { wsV3, channelsV3 } from '../utils/websocket';
import Config from '../constants/Config';
import * as SpotTradeActions from '../redux/actions/SpotTradeAction';
import util from '../utils/util';
function mapStateToProps(state) {
const { product, deals } = state.SpotTrade;
const { wsIsOnlineV3, wsErrCounterV3 } = state.Spot;
return {
product,
deals,
wsIsOnlineV3,
wsErrCounterV3
};
}
function mapDispatchToProps(dispatch) {
return {
spotTradeActions: bindActionCreators(SpotTradeActions, dispatch)
};
}
const LastestDealWrapper = (Component) => {
@connect(mapStateToProps, mapDispatchToProps)
class LastestDeals extends React.Component {
// constructor(props) {
// super(props);
// }
componentDidMount() {
const { product, wsIsOnlineV3, spotTradeActions } = this.props;
// 有币对且推送不在线
if (product.length) {
if (wsIsOnlineV3) {
this.startWs(product);
} else {
spotTradeActions.getDeals(product);
}
}
}
componentWillReceiveProps(nextProps) {
/* product变化相关 */
const oldproduct = this.props.product;
const newproduct = nextProps.product;
const { spotTradeActions } = nextProps;
/* ws状态变化相关 */
const newWsIsOnline = nextProps.wsIsOnlineV3;
const oldWsIsOnline = this.props.wsIsOnlineV3;
if (newproduct !== oldproduct) {
if (oldproduct === '') { // 首次获取product
if (newWsIsOnline) {
this.startWs(newproduct);
} else {
spotTradeActions.getDeals(newproduct);
}
} else if (newproduct !== '') { // product发生改变,比如左侧菜单切换
this.changeProduct(oldproduct, newproduct);
}
}
// ws首次连接或者重连成功
if (!oldWsIsOnline && newWsIsOnline && newproduct !== '') {
spotTradeActions.getDeals(newproduct); // 【断网补偿】获取最新成交
this.startWs(newproduct);
}
const oldWsErrCounter = this.props.wsErrCounterV3;
const newWsErrCounter = nextProps.wsErrCounterV3;
// ws断线
if (newWsErrCounter > oldWsErrCounter) {
// 获取K线数据
spotTradeActions.getDeals(newproduct);
}
}
componentWillUnmount() {
clearInterval(window.dealsHandler);
}
getDealsColumn = () => {
const { product } = this.props;
let baseCurr = '';
let tradeCurr = '';
if (product.indexOf('_') > -1) {
tradeCurr = product.split('_')[0].toUpperCase();
baseCurr = product.split('_')[1].toUpperCase();
tradeCurr = tradeCurr.split('-').length > 0 ? tradeCurr.split('-')[0] : tradeCurr;
}
// const enumColor = { 1: 'deals-green', 2: 'deals-red' };
const config = window.OM_GLOBAL.productConfig;
return [{
title: toLocale('spot.deals.price').replace('-', baseCurr),
key: 'price',
render: (text, data) => {
// const color = enumColor[data.side];
const price = calc.showFloorTruncation(text, config.max_price_digit);
return (<label className={data.color}>{price}</label>);
}
}, {
title: toLocale('spot.deals.amount').replace('-', tradeCurr),
key: 'volume',
render: (text) => {
const amount = calc.showFloorTruncation(text, config.max_size_digit);
return (<label>{amount}</label>);
}
}, {
title: toLocale('spot.deals.time'),
key: 'timestamp',
render: (text) => {
const dateTime = util.timeStampToTime(parseInt(text, 10), 'yyyy-MM-dd hh:mm:ss');
// const date = dateTime.split(' ')[0];
const time = dateTime.split(' ')[1];
return time;
}
}];
};
getDealsEmpty = () => {
return toLocale('spot.deals.no');
};
startWs = (product) => {
const { spotTradeActions } = this.props;
wsV3.stop(channelsV3.getMatches(product));
spotTradeActions.getDeals(product, () => {
wsV3.send(channelsV3.getMatches(product));
});
};
// 停止ws订阅
// stopWs = (product) => {
// // 停止订阅所有币行情,即ticker
// wsV3.stop(channelsV3.getMatches(product));
// };
// 切币对
changeProduct = (oldproduct, newproduct) => {
const { wsIsOnlineV3, spotTradeActions } = this.props;
if (window.OM_GLOBAL.ws_v3 && wsIsOnlineV3) {
// 停掉旧币种的最新成交记录
wsV3.stop(channelsV3.getMatches(oldproduct));
// 方案有2, 1是清空,可以应对99.9%的概览 ,2是ws推送的时候把deal返回的数据整体放开,可以拿返回的product与当前product比对,100%概率
spotTradeActions.clearDeals();
// 订阅新币种的最新成交记录
spotTradeActions.getDeals(newproduct, () => {
wsV3.send(channelsV3.getMatches(newproduct));
});
} else {
spotTradeActions.getDeals(newproduct);
}
};
render() {
const { deals } = this.props;
return (
<Component
dataSource={deals}
empty={this.getDealsEmpty()}
columns={this.getDealsColumn()}
/>
);
}
}
return LastestDeals;
};
export default LastestDealWrapper;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Icon from '../IconLite';
import './index.less';
const typeIcon = {
error: 'icon-close-circle',
warn: 'icon-exclamation-circle',
info: 'icon-info-circle',
success: 'icon-check-circle'
};
const AlertType = {
success: 'success',
info: 'info',
warn: 'warn',
error: 'error'
};
const prefixCls = 'om-ui-alert';
export default class Alert extends React.PureComponent {
static propTypes = {
/** 警告提示内容 */
message: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 警告提示的辅助性文字介绍 */
description: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 默认不显示关闭按钮 */
closable: PropTypes.bool,
/** 自定义关闭按钮 */
closeText: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 是否显示辅助图标 */
showIcon: PropTypes.bool,
// /** 自定义图标,showIcon 为 true 时有效 */
// icon: PropTypes.string,
/** 指定警告提示的样式,有四种选择,存在Alert.Type中的常量:success、info、warn、error */
type: PropTypes.string,
/** 关闭时触发的回调函数 */
onClose: PropTypes.func,
/** 右侧操作文案 */
operation: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
/** 右侧操作点击事件 */
operationClick: PropTypes.func,
// /** 关闭动画结束后触发的回调函数 */
// afterClose: PropTypes.func,
};
static defaultProps = {
message: '',
description: '',
closable: true,
closeText: '',
showIcon: true,
// icon: '',
type: AlertType.info,
onClose: null,
operation: '',
operationClick: null
// afterClose: null,
};
render() {
const {
message, onClose, closable, type, description, closeText, showIcon,
operation, operationClick
} = this.props;
let closeJsx = null;
if (closable) {
closeJsx = (
<span className={`${prefixCls}-close-con`} onClick={onClose}>
{closeText || <Icon className={`icon-close ${prefixCls}-close`} />}
</span>
);
}
return (
<div className={`${prefixCls} ${type}-message`}>
{
showIcon && <Icon className={`${prefixCls}-icon ${typeIcon[type]}`} />
}
<div className={`${prefixCls}-msg-box`}>
{
message && <div className={`${prefixCls}-message`}>{message}</div>
}
{
description && <div className={`${prefixCls}-description`}>{description}</div>
}
</div>
{
operation && <div className={`${prefixCls}-operation`} onClick={operationClick}>{operation}</div>
}
{closeJsx}
</div>);
}
}
Alert.TYPE = AlertType;
<file_sep>/* params:
* v:传入需要搜索的值
* return:
* 对应值的索引值
*/
import { calc } from '_component/omit';
export default class DepthMerge {
constructor() {
this.sellDepth = null;
this.buyDepth = null;
this.depthSymbol = null;
}
// 全量深度,不合并 为集合竞价使用,前端不排序,可能存在相同价格。
mergeFullSize20(data, isOverDepth001, mergeLadder) {
let bids = [];
let asks = [];
if (data.bids) {
bids = data.bids;
}
if (data.asks) {
data.asks.reverse();
asks = data.asks;
}
if (bids.length > 20) {
bids.splice(20, bids.length - 20);
}
if (asks.length > 20) {
asks.splice(0, asks.length - 20);
}
for (let k = 0; k < bids.length; k++) {
bids[k].price = calc.floorTruncate(bids[k].price, calc.digitLength(mergeLadder));
}
for (let k = 0; k < asks.length; k++) {
asks[k].price = calc.ceilTruncate(
calc.mul(Math.ceil(calc.div(asks[k].price, mergeLadder)), mergeLadder),
calc.digitLength(mergeLadder)
);// 合并值计算(卖)
}
const newData = {
bids,
asks
};
if (isOverDepth001) {
const tempData = {
bids: [],
asks: []
};
for (let i = 0; i < newData.bids.length; i++) {
if (Number(newData.bids[i].totalSize) >= 0.001) {
tempData.bids.push([newData.bids[i].price, calc.ceilTruncate(newData.bids[i].totalSize, 3)]);
}
}
for (let i = 0; i < newData.asks.length; i++) {
if (Number(newData.asks[i].totalSize) >= 0.001) {
tempData.asks.push([newData.asks[i].price, calc.ceilTruncate(newData.asks[i].totalSize, 3)]);
}
}
return tempData;
}
return newData;
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import RcMenu, { Divider } from 'rc-menu';
import SubMenu from './SubMenu';
import Item from './MenuItem';
import ItemGroup from './ItemGroup';
import './index.less';
export default class Menu extends React.Component {
static Divider = Divider;
static Item = Item;
static SubMenu = SubMenu;
static ItemGroup = ItemGroup;
static propTypes = {
/** 菜单类型,包括垂直('vertical', 'vertical-left', 'vertical-right')、水平(horizontal)、和内嵌(inline)模式三种 */
mode: PropTypes.oneOf(['horizontal', 'vertical', 'vertical-left', 'vertical-right', 'inline']),
/** 根节点样式 */
style: PropTypes.object,
/** 根节点class */
className: PropTypes.string,
/** 是否允许选中 */
selectable: PropTypes.bool,
/** 点击 menu item 调用此函数 function({ item, key, keyPath }) */
onClick: PropTypes.func,
/** 选中时调用 */
onSelect: PropTypes.func,
/** sub menu 展开/关闭的回调 */
onOpenChange: PropTypes.func,
};
static defaultProps = {
className: '',
style: {},
mode: 'vertical',
selectable: true,
onClick: () => {},
onSelect: () => {},
onOpenChange: () => {},
};
constructor(props) {
super(props);
this.state = {};
}
render() {
const fixedProps = {
prefixCls: 'om-menu',
multiple: false,
};
return <RcMenu {...this.props} {...fixedProps} />;
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import { connect } from 'react-redux';
import Tooltip from 'rc-tooltip';
import Enum from '../../utils/Enum';
function mapStateToProps(state) { // 绑定redux中相关state
const { fee } = state.SpotTrade;
return { fee };
}
function mapDispatchToProps() { // 绑定action,以便向redux发送action
return {};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
class Fee extends React.Component {
static propTypes = {
fee: PropTypes.object
};
static defaultProps = {
// maker挂单; taker吃单
fee: {
maker: '--',
taker: '--'
}
};
render() {
const { tradeType } = window.OM_GLOBAL;
const isFullTrade = tradeType === Enum.tradeType.fullTrade;
const { maker, taker } = this.props.fee;
let toolTipClass = 'tooltip-content';
let toolTipDirection = 'bottom';
if (isFullTrade) {
toolTipClass = 'full-fee-tooltip';
toolTipDirection = 'top';
}
const feeMT = (
<div className={toolTipClass}>
{toLocale('spot.fee.brokerMT', { maker, taker })}
</div>
);
return (
<Tooltip
placement={toolTipDirection}
overlay={feeMT}
>
<label className="detail float-right">
{toLocale('spot.fee')}
</label>
</Tooltip>
);
}
}
export default Fee;
<file_sep>export const OrderStatus = {
// 需要根据语义找到对应的状态码,还需要根据状态码找到对应的多语言配置
Open: '0', // 未成交
0: 'Open',
Filled: '1', // 完全成交
1: 'Filled',
Cancelled: '2', // 已取消
2: 'Cancelled',
Expired: '3', // 已过期
3: 'Expired',
PartialFilledCancelled: '4', // 部分成交撤销
4: 'PartialFilledCancelled',
PartialFilledExpired: '5', // 部分成交过期
5: 'PartialFilledExpired',
PartialFilled: '6', // 部分成交
6: 'PartialFilled',
Cancelling: '100', // 撤单中
100: 'Cancelling'
};
// 冰山和时间加权委托的状态列表
export const OrderStatusIceAndTime = {
TO_BE_FILLED: '1', // 待生效
1: 'toBeFilled',
COMPLETE_FILLED: '2', // 已生效
2: 'completeFilled',
CANCELLED: '3', // 已撤销
3: 'cancelled',
PARTIAL_FILLED: '4', // 部分生效
4: 'partialFilled',
PAUSED: '5', // 暂停生效
5: 'paused'
};
export const OrderType = {
0: 'spot.orders.orderTypeShort.always',
1: 'spot.orders.orderTypeShort.always',
2: 'spot.orders.orderTypeShort.postOnly',
3: 'spot.orders.orderTypeShort.FOK',
FOK: '3',
4: 'spot.orders.orderTypeShort.FAK',
FAK: '4',
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import './Checkbox.less';
const prefixCls = 'om-ui-checkbox';
export default class Checkbox extends React.Component {
static propTypes = {
/** 是否被选中 可选 */
checked: PropTypes.bool,
/** 是否初始被选中 可选 默认false */
defaultChecked: PropTypes.bool,
/** 是否禁止 可选 */
disabled: PropTypes.bool,
/** 变化时回调函数 必须传 */
onChange: PropTypes.func,
};
static defaultProps = {
defaultChecked: false,
disabled: false,
onChange: null,
};
constructor(props) {
super(props);
const checked = 'checked' in props ? props.checked : props.defaultChecked;
this.state = {
checked
};
}
componentWillReceiveProps(nextProps) {
if ('checked' in nextProps) {
this.setState({
checked: nextProps.checked,
});
}
}
checkboxChange = (e) => {
const checked = e.target.checked;
this.setState({
checked
});
// 兼容旧版本写法
this.props.onChange(checked, {
target: Object.assign({}, this.props, {
checked
})
});
// e.stopPropagation();
// e.preventDefault();
};
render() {
const {
disabled
} = this.props;
const { checked } = this.state;
// 控制check-box的样式
const classContent = classnames({
checkbox: true,
'checkbox-checked': checked,
'checkbox-disabled': disabled
});
// label 外层样式
const classWrapper = classnames({
'checkbox-wrapper': true,
'checkbox-wrapper-checked': checked,
'checkbox-wrapper-disabled': disabled
});
return (
<section className={`${prefixCls}`}>
<label className={classWrapper}>
<span className={classContent}>
<input
type="checkbox"
placeholder=""
checked={checked}
onChange={(e) => { this.checkboxChange(e); }}
className="check-input"
disabled={disabled}
/>
<span className="checkbox-inner" />
</span>
<span className="check-des">{this.props.children}</span>
</label>
</section>
);
}
}
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as CommonAction from '_src/redux/actions/CommonAction';
import { withRouter } from 'react-router-dom';
import Icon from '_component/IconLite';
import navBack from '_src/assets/images/nav_back@2x.png';
import PageURL from '_constants/PageURL';
import { toLocale } from '_src/locale/react-locale';
// import ont from '_src/utils/dataProxy';
// import URL from '_constants/URL';
import { setcurrentNode, getDelayType } from '_src/utils/node';
import './index.less';
function mapStateToProps(state) {
const { latestHeight } = state.Common;
const { currentNode, remoteList } = state.NodeStore;
return {
latestHeight,
currentNode,
remoteList,
};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps)
@withRouter
class DesktopNodeMenu extends Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
// this.heightTimer = setInterval(() => {
// ont.get(URL.GET_LATEST_HEIGHT).then((res) => {
// if (res.data) {
// const { commonAction } = this.props;
// commonAction.updateLatestHeight(res.data);
// }
// }).catch((err) => {
// console.log(err);
// });
// }, 3000);
}
componentWillUnmount() {
this.heightTimer && clearInterval(this.heightTimer);
}
onNodeClick = (node) => {
return () => {
setcurrentNode(node);
};
}
handleToMore = () => {
this.props.history.push(PageURL.nodeSettingPage);
}
render() {
const { latestHeight, currentNode, remoteList } = this.props;
const delayTime = 55; // 先写死
const delayType = getDelayType(delayTime);
const settingsNodeList = remoteList.filter((node) => {
return node.wsUrl !== currentNode.wsUrl;
}).slice(0, 3);
return (
<div className="desktop-node-menu-wrapper">
<img className="node-menu-back" src={navBack} alt="node-set-img" />
<div className="desktop-node-menu-container">
<div className="node-menu-item remote-node-item">
<div className="node-menu-type">
<div className="node-type">{toLocale('nodeMenu.remote')}</div>
<Icon className={`icon-node color-${delayType}`} />
<Icon className="icon-retract" />
</div>
<div className="node-assist">{toLocale('nodeMenu.block')} #{latestHeight}</div>
<div className={`node-assist color-${delayType}`}>{toLocale('nodeMenu.latency')} 55MS</div>
<div className="node-sub-menu remote-node-submenu">
{
settingsNodeList.map((node, index) => {
const { region, country, location } = node;
return (
<div
className="node-detail-container"
key={index}
onClick={this.onNodeClick(node)}
>
<div className="node-name">{`${region} - ${country} - ${location}`}</div>
<Icon className={`icon-node color-${delayType}`} />
</div>
);
})
}
<div className="node-more" onClick={this.handleToMore}>{toLocale('nodeMenu.more')}</div>
</div>
</div>
<div className="node-menu-item local-node-item">
<div className="node-menu-type">
<div className="node-type">{toLocale('nodeMenu.local')}</div>
<Icon className="icon-node" />
<Icon className="icon-retract" />
</div>
<div className="node-assist">{toLocale('node.stopped')}</div>
</div>
</div>
</div>
);
}
}
export default DesktopNodeMenu;
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import WalletContainer from './WalletContainer';
import Step1 from './Step1';
import Step2 from './Step2';
import Step3 from './Step3';
import Step4 from './Step4';
import './CreateWallet.less';
function mapStateToProps(state) {
const { step } = state.WalletStore;
return { step };
}
function mapDispatchToProps() {
return {};
}
@connect(mapStateToProps, mapDispatchToProps)
class CreateWallet extends Component {
renderByStep = (step) => {
let component = <Step1 />;
switch (step) {
case 1:
component = <Step1 />;
break;
case 2:
component = <Step2 />;
break;
case 3:
component = <Step3 />;
break;
case 4:
component = <Step4 />;
break;
default:
component = <Step1 />;
break;
}
return component;
}
render() {
const { step } = this.props;
return (
<WalletContainer>
<div className="wallet-create-container">
{this.renderByStep(step)}
</div>
</WalletContainer>
);
}
}
export default CreateWallet;
<file_sep>import React from 'react';
import Select from 'react-select';
import Icon from '_src/component/IconLite';
const arrowRenderer = ({ isOpen }) => {
return <Icon className={isOpen ? 'icon-fold' : 'icon-Unfold'} />;
};
const index = ({ ...props }) => {
return (
<Select {...props} arrowRenderer={arrowRenderer} />
);
};
export default index;
<file_sep>const Enum = {
buy: 'buy',
sell: 'sell',
ajax: 'ajax',
ws: 'websocket',
spot: 'spot',
margin: 'margin',
tradeType: {
normalTrade: 'normalTrade', // 普通交易(非全屏)
fullTrade: 'fullTrade', // 全屏交易
},
themes: {
theme1: 'theme-1', // 白天模式
theme2: 'theme-2', // 夜间模式
},
spotOrMargin: {
spot: 1, // 币币模式
margin: 2 // 杠杆模式
},
defaultMergeType: '0.001', // 默认深度合并系数
defaultMergeTypes: ['0.001', '0.01', '0.1'], // 默认深度合并系数选项
placeOrder: {
type: { // 买卖类型
buy: 1, // 买
sell: 2 // 卖
},
strategyType: { // 委托类型
limit: 1, // 限价单
market: 2, // 市价单
plan: 3, // 计划委托
track: 4, // 跟踪委托
iceberg: 5, // 冰山委托
timeWeight: 6, // 时间加权委托
advancedLimit: 7, // 高级限价单
},
advancedOrderType: { // 高级限价单类别
postOnly: 2, // 只做Maker(Post only)
FOK: 3, // 全部成交或立即取消(FillOrKill)
FAK: 4, // 立即成交并取消剩余(ImmediatelOrCancel)
},
},
order: {
type: { // 一级tab
noDeal: 0, // 未成交
history: 1, // 历史
detail: 2, // 成交明细
},
entrustType: { // 二级委托类型
normal: 0, // 普通
plan: 1, // 计划
track: 2, // 跟踪
iceberg: 3, // 冰山
timeWeight: 4, // 时间加权
},
periodInterval: {
oneDay: 'oneDay',
oneWeek: 'oneWeek',
oneMonth: 'oneMonth',
threeMonth: 'threeMonth',
}
},
noticeTypes: {
1: { icon: 'icon-weekly', locale: 'notice.category.week' },
2: { icon: 'icon-Monthly', locale: 'notice.category.month' },
0: { icon: 'icon-Activitynotificatio', locale: 'notice.category.news' },
3: { icon: 'icon-Newsflash', locale: 'notice.category.act' },
4: { icon: 'icon-FinancialReport', locale: 'notice.category.treasure' },
5: { icon: 'icon-Triggerorderfuben', locale: 'notice.category.rate' },
},
};
export default Enum;
<file_sep>import React, { Component } from 'react';
import { toLocale } from '_src/locale/react-locale';
import { calc } from '_component/omit';
import Tooltip from '_component/Tooltip';
import Icon from '_component/IconLite';
import DashboardSection from './DashboardSection';
import './DashboardIssue.less';
const tokenCols = [
{
title: toLocale('issue_column_token'),
key: 'original_symbol',
render: (text, data) => {
const { whole_name, symbol } = data;
const whole_nameString = whole_name ? ` (${whole_name})` : '';
return (
<div className="symbol-line">
<Tooltip
placement="bottomLeft"
overlayClassName="symbol-tooltip"
overlay={symbol}
maxWidth={400}
noUnderline
>
{text.toUpperCase() + whole_nameString}
</Tooltip>
</div>
);
},
},
{
title: toLocale('issue_column_mintable'),
key: 'mintable',
render(text) {
return text ? <Icon className="icon-check" style={{ color: '#00BC6C' }} /> : <Icon className="icon-close" style={{ color: '#E35E5E' }} />;
}
},
{
title: toLocale('issue_column_original'),
key: 'original_total_supply',
render: (text) => {
return calc.showFloorTruncation(text, 8, false);
}
},
{
title: toLocale('issue_column_total'),
key: 'total_supply',
render: (text) => {
return calc.showFloorTruncation(text, 8, false);
}
},
{
title: '',
key: '',
render() {
return (
<div className="issue-action-container">
<span
className="td-action"
>
{toLocale('issue_cell_mint')}
</span>
<div className="action-boundary" />
<span
className="td-action"
>
{toLocale('issue_cell_burn')}
</span>
</div>
);
}
}
];
class DashboardIssue extends Component {
constructor() {
super();
this.addr = window.OM_GLOBAL.senderAddr;
}
render() {
const { loading, tokens } = this.props;
const fTokens = tokens.slice(0, 3).filter((token) => {
return token.owner === this.addr;
});
return (
<DashboardSection
title={toLocale('dashboard_issue_title')}
columns={tokenCols}
dataSource={fTokens}
rowKey="symbol"
isLoading={loading}
empty={toLocale('issue_empty')}
/>
);
}
}
export default DashboardIssue;
<file_sep>const contentPath = '/dex-test';
export const short = {
billForce: 'LiquidationOrders',
readyRisk: 'InsuranceFunds',
};
export default {
homePage: `${contentPath}`,
indexPage: `${contentPath}/index`,
spotDefaultPage: `${contentPath}/spot`, // 全屏交易
spotFullPage: `${contentPath}/spot/trade`, // 全屏交易
spotOpenPage: `${contentPath}/spot/open`, // 当前委托
spotHistoryPage: `${contentPath}/spot/history`, // 历史委托
spotDealsPage: `${contentPath}/spot/deals`, // 成交明细
spotOrdersPage: `${contentPath}/spot/orders?isMargin={0}`, // 币币委托
// loginPage: `${contentPath}account/login?forward={0}&logout=true`, // 登录
loginPage: `${contentPath}/wallet/import?forward={0}&logout=true`, // 登录
wallet: `${contentPath}/wallet`, // 钱包
walletAssets: `${contentPath}/wallet/assets`, // 钱包资产
walletTransactions: `${contentPath}/wallet/transactions`, // 钱包交易记录
walletCreate: `${contentPath}/wallet/create`, // 创建钱包
walletImport: `${contentPath}/wallet/import`, // 导入钱包
nodeSettingPage: `${contentPath}/node`, // 节点设置
registerPage: `${contentPath}/register`, // 注册运营商
issueTokenPage: `${contentPath}/issue-token`, // 发行币种
listTokenpairPage: `${contentPath}/list-tokenpair`, // 发行币对
dashboardPage: `${contentPath}/dashboard`, // 总览
};
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { toLocale } from '_src/locale/react-locale';
import { Button } from '_component/Button';
import Icon from '_src/component/IconLite';
import { Dialog } from '_component/Dialog';
import WalletLeft from '_component/WalletLeft';
import WalletRight from '_component/WalletRight';
import PageURL from '_constants/PageURL';
import * as commonActions from '_src/redux/actions/CommonAction';
import questionGenerator from './questionGenerator';
import walletUtil from './walletUtil';
import './Step.less';
import './Step4.less';
function mapStateToProps(state) {
const { mnemonic, keyStore, privateKey } = state.WalletStore;
return { mnemonic, keyStore, privateKey };
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(commonActions, dispatch),
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class Step4 extends Component {
constructor(props) {
super(props);
this.questions = questionGenerator.getQuestions(props.mnemonic);
}
componentDidMount() {
const { keyStore, privateKey } = this.props;
walletUtil.setUserInSessionStroage(privateKey, keyStore);
this.props.commonAction.setPrivateKey(privateKey);
}
selectOption = (questionNo, selectedIndex) => {
return () => {
const { selectArr } = this.state;
const selectArrTemp = [...selectArr];
selectArrTemp[questionNo] = selectedIndex;
this.setState({
selectArr: selectArrTemp
});
};
}
showPrivate = () => {
this.privateDialog = Dialog.show({
windowStyle: { backgroundColor: '#112F62' },
children: this.renderPrivateDialog(),
});
}
hidePrivate = () => {
this.privateDialog.destroy();
}
handleCopy = () => {
this.privateDialog.update({
children: this.renderPrivateDialog(true),
});
clearTimeout(this.copyTimer);
this.copyTimer = setTimeout(() => {
this.privateDialog.update({
children: this.renderPrivateDialog(false),
});
}, 1000);
}
onRedirctToTradePage = () => {
const { privateKey } = this.props;
return () => {
// console.log('step4 click next');
this.props.commonAction.setPrivateKey(privateKey);
this.props.history.push(PageURL.spotFullPage);
};
}
renderPrivateDialog = (copySuccess = false) => {
const { privateKey } = this.props;
return (
<div className="private-container">
<div className="private-title">
{toLocale('wallet_privateKey')}
</div>
<Icon className="icon-icon_successfuzhi" isColor style={{ width: 60, height: 60, marginBottom: 30 }} />
<div className="private-content">
<span id="omdex-wallet-private-key">{privateKey}</span>
<span data-clipboard-target="#omdex-wallet-private-key">
<CopyToClipboard text={privateKey} onCopy={this.handleCopy}>
<Icon
className={copySuccess ? 'icon-icon_success' : 'icon-icon_copy'}
isColor
style={{ width: 14, height: 14, cursor: 'pointer' }}
/>
</CopyToClipboard>
</span>
</div>
{/* <div className="private-success-tip">{successTip}</div> */}
<Button type="primary" onClick={this.hidePrivate}>
{toLocale('wallet_ensure')}
</Button>
</div>
);
};
render() {
return (
<div>
<div className="create-wallet-step3 wallet-step-dialog">
<WalletLeft
stepNo={3}
stepName={toLocale('wallet_create_step4')}
imgUrl="https://static.bafang.com/cdn/assets/imgs/MjAxOTQ/355F3AD5BD296D7EEA40263B0F98E4F3.png"
/>
<WalletRight>
<div className="validate-success-container">
<Icon className="icon-icon_success" isColor style={{ width: 60, height: 60 }} />
<div className="validate-success-text">
{toLocale('wallet_mnemonicSuccess')}
</div>
<div className="next-row">
<Button type="primary" onClick={this.onRedirctToTradePage()}>{toLocale('wallet_toTrade')}</Button>
<div className="see-private" onClick={this.showPrivate}>{toLocale('wallet_seePrivate')}</div>
</div>
</div>
</WalletRight>
</div>
</div>
);
}
}
export default Step4;
<file_sep>import WalletActionType from '../actionTypes/WalletActionType';
/**
* 更新创建钱包-当前步骤
*/
export function updateCreateStep(step) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_CREATE_STEP,
data: step
});
};
}
/**
* 更新是否出现安全提示
*/
export function updateIsShowSafeTip(isShow) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_IS_SHOW_SAFE_TIP,
data: isShow
});
};
}
/**
* 更新助记词校验状态
*/
export function updateIsPass(isPass) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_IS_PASS,
data: isPass
});
};
}
/**
* 更新助记词
*/
export function updateMnemonic(mnemonic) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_MNEMONIC,
data: mnemonic
});
};
}
/**
* 更新keyStore
*/
export function updateKeyStore(keyStore) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_KEYSTORE,
data: keyStore
});
};
}
/**
* 更新私钥
*/
export function updatePrivate(privateKey) {
return (dispatch) => {
dispatch({
type: WalletActionType.UPDATE_PRIVATE,
data: privateKey
});
};
}
<file_sep>import React, { Component } from 'react';
import DexDesktopContainer from '_component/DexDesktopContainer';
import { Dialog } from '_component/Dialog';
import Message from '_src/component/Message';
import PasswordDialog from '_component/PasswordDialog';
import { toLocale } from '_src/locale/react-locale';
import RegisterInput from '_component/DexDesktopInput';
import ClientWrapper from '_src/wrapper/ClientWrapper';
import Config from '_constants/Config';
import './index.less';
const showError = () => {
Message.error({
content: '服务端异常,请稍后重试'
});
};
@ClientWrapper
class Register extends Component {
constructor() {
super();
this.state = {
websiteValue: '',
feeAddressValue: '',
isActionLoading: false,
};
}
onWebsiteChange = (e) => {
this.setState({
websiteValue: e.target.value
});
}
onFeeAddressChange = (e) => {
this.setState({
feeAddressValue: e.target.value
});
}
onRegister = () => {
this.setState({ isActionLoading: true });
const { websiteValue, feeAddressValue } = this.state;
const { omchainClient } = this.props;
omchainClient.sendRegisterDexOperatorTransaction(websiteValue, feeAddressValue).then((res) => {
this.setState({ isActionLoading: false });
const { result, status } = res;
const { txhash } = result;
const log = JSON.parse(result.raw_log);
if (status !== 200 || (log && log.code)) {
showError();
} else {
const dialog = Dialog.success({
className: 'desktop-success-dialog',
confirmText: 'Get detail',
theme: 'dark',
title: 'Register success!',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
window.open(`${Config.omchain.browserUrl}/tx/${txhash}`);
dialog.destroy();
},
});
}
}).catch((err) => {
console.log(err);
this.setState({ isActionLoading: false });
showError();
});
}
onPwdEnter = (password) => {
this.props.onPwdEnter(password, this.onRegister);
}
handleRegister = () => {
this.props.checkPK(this.onRegister);
}
render() {
const {
websiteValue, feeAddressValue, isActionLoading
} = this.state;
const { isShowPwdDialog, isLoading, warning } = this.props;
return (
<DexDesktopContainer
isShowHelp
isShowAddress
needLogin
loading={isActionLoading}
>
<div className="register-container">
<RegisterInput
label={toLocale('register.website.label')}
value={websiteValue}
onChange={this.onWebsiteChange}
hint={toLocale('register.website.hint')}
/>
<RegisterInput
label={toLocale('register.feeAddress.label')}
value={feeAddressValue}
onChange={this.onFeeAddressChange}
hint={toLocale('register.feeAddress.hint')}
/>
<div className="register-get-operato">Get operato</div>
<button
className="dex-desktop-btn register-btn"
onClick={this.handleRegister}
>
Register
</button>
<PasswordDialog
btnLoading={isLoading}
warning={warning}
isShow={isShowPwdDialog}
updateWarning={this.props.updateWarning}
onEnter={this.onPwdEnter}
onClose={this.props.onPwdClose}
/>
</div>
</DexDesktopContainer>
);
}
}
export default Register;
<file_sep>import Message from './Message';
function createFunction(type) {
return (props) => {
const config = {
type: Message.TYPE[type],
...props,
};
return Message.create(config);
};
}
// 完全一个数组遍历来写,只不过用的时候就没有提示了
Message.success = createFunction(Message.TYPE.success);
Message.info = createFunction(Message.TYPE.info);
Message.warn = createFunction(Message.TYPE.warn);
Message.error = createFunction(Message.TYPE.error);
Message.loading = createFunction(Message.TYPE.loading);
export default Message;
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as CommonAction from '_src/redux/actions/CommonAction';
import Config from '_constants/Config';
import { toLocale } from '_src/locale/react-locale';
function mapStateToProps(state) {
const { omchainClient, privateKey } = state.Common;
return {
privateKey,
omchainClient,
};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch),
};
}
const ClientWrapper = (Com) => {
@connect(mapStateToProps, mapDispatchToProps)
class Client extends Component {
constructor() {
super();
this.state = {
isShowPwdDialog: false,
isLoading: false,
warning: '',
};
}
// 开启资金密码弹窗
onPwdOpen = () => {
this.setState({
isShowPwdDialog: true
}, () => {
const o = window.document.getElementsByClassName('pwd-input');
if (o && o[0] && o[0].focus) {
o[0].focus();
}
});
};
onPwdClose = () => {
this.setState({
isLoading: false,
isShowPwdDialog: false
});
}
onPwdEnter = (password, success) => {
const { commonAction } = this.props;
if (password.trim() === '') {
return this.updateWarning(toLocale('spot.place.tips.pwd'));
}
this.updateWarning('');
this.setState({
isLoading: true
}, () => {
setTimeout(() => {
commonAction.validatePassword(password, () => {
this.setState({
isShowPwdDialog: false,
}, () => {
this.setAccountInfo(success);
});
}, () => {
this.setState({
warning: toLocale('pwd_error'),
isLoading: false,
});
});
}, Config.validatePwdDeferSecond);
});
return false;
}
setAccountInfo = (success) => {
const { omchainClient, privateKey } = this.props;
omchainClient.setAccountInfo(privateKey).then(() => {
success && success();
});
}
updateWarning = (warning) => {
this.setState({
warning
});
}
checkPK = (success) => {
// 检查私钥,如果未过期直接取私钥,如果过期显示弹窗
const expiredTime = window.localStorage.getItem('pExpiredTime') || 0;
// 小于30分钟,且privateKey,(true时),不需要输入密码,直接提交
if ((new Date().getTime() < +expiredTime) && this.props.privateKey) {
// 没过期、提交操作
this.setAccountInfo(success);
} else {
this.onPwdOpen();
}
}
render() {
const { isShowPwdDialog, isLoading, warning } = this.state;
const p = { isShowPwdDialog, isLoading, warning };
return (<Com
{...p}
{...this.props}
onPwdOpen={this.onPwdOpen}
onPwdClose={this.onPwdClose}
checkPK={this.checkPK}
onPwdEnter={this.onPwdEnter}
updateWarning={this.updateWarning}
/>);
}
}
return Client;
};
export default ClientWrapper;
<file_sep>import React from 'react';
import { withRouter, Link } from 'react-router-dom';
import LanguageSwitch from '_component/LanguageSwitch';
import Icon from '_src/component/IconLite';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Cookies from 'js-cookie';
import CurrencySelector from '../CurrencySelector';
import * as CommonAction from '../../redux/actions/CommonAction';
import { LoggedMenu, LoginMenu } from '../DexMenu';
import util from '../../utils/util';
import './index.less';
import PageURL from '../../constants/PageURL';
function mapStateToProps(state) { // 绑定redux中相关state
const {
privateKey
} = state.Common;
return {
privateKey
};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch)
};
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class DexHeader extends React.Component {
componentWillMount() {
}
componentDidMount() {
// 初始化omchain客户端
this.props.commonAction.initOMChainClient();
}
componentWillReceiveProps(nextProps) {
}
onLanguageSelect(item) {
Cookies.set('locale', item.rel);
window.location.reload();
}
render() {
const lang = util.getSupportLocale(Cookies.get('locale') || 'en_US');
return (
<header className="omdex-header">
<input style={{ display: 'none' }} type="password" />
<Link to={PageURL.homePage} className="logo-wrap">
<Icon className="icon-dex-logo-new" isColor style={{ width: '103px', height: '45px' }} />
</Link>
<div className="omdex-header-right">
{util.isLogined() ? <LoggedMenu /> : <LoginMenu />}
<LanguageSwitch
titleMode="icon"
direction="bottomRight"
isShowArrow={false}
defaultValue={lang}
overlayClassName="omdex-language-popup"
dropDownMatchSelectWidth={false}
onSelect={this.onLanguageSelect}
/>
<div className="line-divider" />
</div>
</header>
);
}
}
export default DexHeader;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import Enum from '../../utils/Enum';
import util from '../../utils/util';
// 全屏交易独立组件
import FullTradeHead from './FullTradeHead';
import FullTradeData from './FullTradeData';
import SpotAsset from '../trade/SpotAsset';
import SpotPlaceOrderNotLogin from '../placeOrders/NotLogin';
import SpotOrder from '../trade/SpotOrder';
// import FullTradeProduct from './FullTradeProduct';
// import FullTradeTicker from './FullTradeTicker';
import FullDepthDeal from './FullDepthDeal';
// import FullLeftMenu from './FullLeftMenu';
import FullTradeKLine from './FullTradeKLine';
// right
import FullDepth from './FullDepth';
import SpotPlaceOrder from '../trade/SpotPlaceOrder';
import FullTradeDeals from './FullTradeDeals';
import './FullTrade.less';
import {bindActionCreators} from "redux";
import * as CommonAction from "../../redux/actions/CommonAction";
function mapStateToProps(state) { // 绑定redux中相关state
const { product, productObj } = state.SpotTrade;
const { privateKey } = state.Common;
return { product, productObj, privateKey };
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps)
export default class FullTradeFrame extends React.Component {
constructor(props) {
super(props);
window.OM_GLOBAL.tradeType = Enum.tradeType.fullTrade;
window.OM_GLOBAL.isMarginType = false;
window.addEventListener('resize', this.onResize);
}
componentWillMount() {
if (document.querySelector("#headerContainer")) {
document.querySelector("#headerContainer").style.display = 'none';
}
if (document.querySelector("#footerContainer")) {
document.querySelector("#footerContainer").style.display = 'none';
}
}
componentWillUnmount() {
if (document.querySelector("#headerContainer")) {
document.querySelector("#headerContainer").style.display = 'block';
}
if (document.querySelector("#footerContainer")) {
document.querySelector("#footerContainer").style.display = 'block';
}
window.removeEventListener('resize', this.onResize);
}
onResize = util.debounce(() => {
if (window.innerWidth >= 1280) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflowX = 'scroll';
}
if (window.innerHeight >= 600) {
document.body.style.overflowY = 'hidden';
} else {
document.body.style.overflowY = 'scroll';
}
});
render() {
// const { isLogin } = window.OM_GLOBAL;
const isLogin = util.isLogined();
return (
<div className="full-wrap">
{/*<div className="full-head">
<FullTradeHead />
</div>*/}
<div className="trade-container">
<div className="full-left">
<div className="full-left-top">
{/*<div className="full-left-top-left">
<FullLeftMenu />
</div>*/}
<div className="full-left-top-right">
<div className="full-ticker-kline">
{/*<div className="full-ticker">
<FullTradeProduct />
<FullTradeTicker />
</div>*/}
<FullTradeKLine />
</div>
</div>
</div>
<div className="full-left-bottom">
<SpotAsset />
<SpotOrder />
{/*<div className="full-left-bottom-left"></div>
<div className="full-left-bottom-right">
<SpotPlaceOrder /> isLogin ? <SpotPlaceOrder /> : <SpotPlaceOrderNotLogin />
</div>*/}
</div>
</div>
<div className="full-right">
<div className="full-right-left">
<FullDepth />
<SpotPlaceOrder />
</div>
<div className="full-right-right">
<FullTradeDeals />
</div>
</div>
</div>
<FullTradeData />
</div>
);
}
}
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { toLocale } from '_src/locale/react-locale';
import { Button } from '_component/Button';
import WalletLeft from '_component/WalletLeft';
import WalletRight from '_component/WalletRight';
import * as walletActions from '_src/redux/actions/WalletAction';
import SafeTip from './SafeTip';
import './Step.less';
import './Step2.less';
function mapStateToProps(state) {
const { isPass, isShowSafeTip, mnemonic } = state.WalletStore;
return { isPass, isShowSafeTip, mnemonic };
}
function mapDispatchToProps(dispatch) {
return {
walletAction: bindActionCreators(walletActions, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps)
class Step2 extends Component {
onNext = () => {
this.props.walletAction.updateCreateStep(3);
}
handleSafeTipEnsure = () => {
this.props.walletAction.updateIsShowSafeTip(false);
}
render() {
const { isPass, isShowSafeTip, mnemonic } = this.props;
return (
<div>
<div className="create-wallet-step2 wallet-step-dialog">
<WalletLeft
stepNo={2}
stepName={toLocale('wallet_create_step2')}
imgUrl="https://static.bafang.com/cdn/assets/imgs/MjAxOTQ/985BA29EFF0DE4AE191822AEDC867924.png"
/>
<WalletRight>
<div className="mnemonic-container">
<div className="mnemonic-title">
{toLocale('wallet_create_backupMnemonic')}
</div>
<div className="mnemonic-content">
{
mnemonic.split(' ').map((item, index) => {
return (
<div className="mnemonic-item" key={item}>
<span className="mnemonic-item-no">{index + 1}</span>
<span className="mnemonic-item-word">{item}</span>
</div>
);
})
}
</div>
{
!isPass &&
<span className="error-tip">
{toLocale('wallet_create_backupMnemonic_error')}
</span>
}
</div>
<div className="next-row">
<Button type="primary" onClick={this.onNext}>
{toLocale('wallet_create_beginValidate')}
</Button>
</div>
</WalletRight>
</div>
<SafeTip
visible={isShowSafeTip}
onEnsure={this.handleSafeTipEnsure}
/>
</div>
);
}
}
export default Step2;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import Icon from '_src/component/IconLite';
import './Depth.less';
export default class DepthTitle extends React.Component {
// 生成深度按钮风格
renderMergeButton = () => {
const { onDepthPosition, theme } = this.props;
const btnStyle = { width: '18px', height: '18px' };
const isDark = theme === 'dark';
return (
<div className="spot-depth-button">
<div onClick={() => {
onDepthPosition('center');
}}
>
<Icon className={isDark ? 'icon-center' : 'icon-Buyandsell-L'} style={btnStyle} isColor />
</div>
<div onClick={() => {
onDepthPosition('bottom');
}}
>
<Icon className={isDark ? 'icon-sell' : 'icon-sell-L'} style={btnStyle} isColor />
</div>
<div onClick={() => {
onDepthPosition('top');
}}
>
<Icon className={isDark ? 'icon-buy' : 'icon-buy-L'} style={btnStyle} isColor />
</div>
</div>
);
};
render() {
const { needHeadBtn } = this.props;
return (
<div className="spot-depth-title">
{
needHeadBtn ?
this.renderMergeButton()
:
toLocale('spot.group')
}
</div>
);
}
}
DepthTitle.propTypes = {
needHeadBtn: PropTypes.bool,
onDepthPosition: PropTypes.func
};
DepthTitle.defaultProps = {
needHeadBtn: false,
onDepthPosition: null
};
<file_sep>const NodeActionType = {
UPDATE_CURRENT_NODE: 'UPDATE_CURRENT_NODE', // 更新当前节点
UPDATE_REMOTE_LIST: 'UPDATE_REMOTE_LIST',
};
export default NodeActionType;
<file_sep>/**
* 弹框按钮封装
* 用于支持Promise loading的显示和隐藏
* Created by yuxin.zhang on 2018/9/1.
*/
import React from 'react';
import { Button } from '../Button';
import './Dialog.less';
export default class ActionButton extends React.PureComponent {
constructor() {
super();
this.state = {
loading: false
};
}
onClick = () => {
const { onClick, closeDialog } = this.props;
if (onClick) {
const ret = onClick();
// if (!ret) {
// closeDialog && closeDialog();
// }
// if return a Promise
if (ret && ret.then) {
this.setState({ loading: true });
ret.then(() => {
closeDialog && closeDialog();
}, () => {
this.setState({ loading: false });
});
}
} else {
closeDialog && closeDialog();
}
};
render() {
const {
children, type, disabled, loading, theme
} = this.props;
const isLoading = this.state.loading || loading;
return (
<Button
className="dialog-btn"
type={type}
size={Button.size.default}
disabled={disabled}
loading={isLoading}
theme={theme}
onClick={this.onClick}
>
{children}
</Button>
);
}
}
ActionButton.size = Button.size;
ActionButton.btnType = Button.btnType;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toLocale } from '_src/locale/react-locale';
import { Dialog } from "_component/Dialog";
import Icon from '_src/component/IconLite';
import { calc } from '_component/omit';
import Loading from '_component/Loading';
import PageURL from '_constants/PageURL';
import Table from '../../component/om-table';
import commonUtil from './commonUtil';
import normalColumns from './normalColumns';
import Enum from '../../utils/Enum';
import * as OrderAction from '../../redux/actions/OrderAction';
import * as SpotAction from '../../redux/actions/SpotAction';
import * as CommonAction from "../../redux/actions/CommonAction";
import PasswordDialog from '../../component/PasswordDialog';
import Message from "_src/component/Message";
import * as FormAction from "../../redux/actions/FormAction";
import Config from "../../constants/Config";
import { Link } from 'react-router-dom';
import util from '../../utils/util';
function mapStateToProps(state) { // 绑定redux中相关state
const { theme, wsIsOnline } = state.Spot;
const { productObj, product } = state.SpotTrade;
const { type, entrustType, data, isHideOthers, periodIntervalType } = state.OrderStore;
const { privateKey } = state.Common;
const { FormStore } = state;
return {
theme, wsIsOnline, productObj, product, type, entrustType, data, privateKey, FormStore, isHideOthers, periodIntervalType
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
orderAction: bindActionCreators(OrderAction, dispatch),
formAction: bindActionCreators(FormAction, dispatch),
spotAction: bindActionCreators(SpotAction, dispatch),
commonAction: bindActionCreators(CommonAction, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
export default class NormalOrderList extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
isShowPwdDialog: false, // 资金密码弹窗
cancelLoading: false // 取消订单期间的loading状态
};
this.targetNode = null;
}
handleCommonParam(periodInterval) {
let start = new Date();
const end = Math.floor(new Date().getTime() / 1000);
if (periodInterval === Enum.order.periodInterval.oneDay) {
start = start.setDate(start.getDate() - 1);
} else if (periodInterval === Enum.order.periodInterval.oneWeek) {
start = start.setDate(start.getDate() - 7);
} else if (periodInterval === Enum.order.periodInterval.oneMonth) {
start = start.setDate(start.getDate() - 30);
} else if (periodInterval === Enum.order.periodInterval.threeMonth) {
start = start.setDate(start.getDate() - 90);
}
start = Math.floor(new Date(start).getTime() / 1000);
return {
start,
end
};
}
// 撤销订单
onCancelOrder = (order) => {
return (e) => {
e.persist(); // 移出事件池从而保留事件对象
// 2019-08-13 增加用户清空全部缓存的判断
if (!util.isLogined()) {
window.location.reload();
}
const order_id = order.order_id;
let title = toLocale('spot.myOrder.cancelPartDealTip');
if ((order.quantity - order.remain_quantity) === 0) { // 未成交
title = toLocale('spot.myOrder.cancelNoDealTip');
}
const dialog = Dialog.confirm({
title: title,
confirmText: toLocale('ensure'),
cancelText: toLocale('cancel'),
theme: 'dark',
dialogId: 'omdex-confirm',
windowStyle: {
background: '#112F62'
},
onConfirm: () => {
dialog.destroy();
if (Number(e.target.getAttribute('canceling'))) {
return;
}
e.target.setAttribute('canceling', 1);
this.targetNode = e.target;
this.formParam = { order_id };
// const startEndObj = this.handleCommonParam(this.props.periodIntervalType);
// this.formParam = { ...this.formParam, start: startEndObj.start, end: startEndObj.end };
if (this.props.isHideOthers && this.props.product) {
this.formParam = { ...this.formParam, product: this.props.product };
}
// 检查私钥,如果未过期直接取私钥,如果过期显示弹窗
const expiredTime = window.localStorage.getItem('pExpiredTime') || 0;
// 小于30分钟,且privateKey,(true时),不需要输入密码,直接提交
if ((new Date().getTime() < +expiredTime) && this.props.privateKey) {
const param = { ...this.formParam, pk: this.props.privateKey };
this.setState({
isShowPwdDialog: false,
cancelLoading: true
}, () => {
e.target.setAttribute('canceling', 0);
this.props.orderAction.cancelOrder(param, this.successToast, this.onSubmitErr);
});
// return this.props.orderAction.cancelOrder(param, this.successToast, this.onSubmitErr);
} else {
e.target.setAttribute('canceling', 0);
this.onPwdOpen();
}
// return this.onPwdOpen();
},
});
};
};
// 页码改变
onPageChange = (page) => {
this.props.orderAction.getOrderList({ page });
};
// 渲染页码
renderPagination = (theme) => {
const { entrustType, type, data } = this.props;
// if (entrustType === Enum.order.entrustType.normal) {
// return null;
// }
const { page } = data;
return commonUtil.renderPagination(page, type, this.onPageChange, theme);
};
// 下单成功提示
successToast = () => {
this.successCallback && this.successCallback();
// setTimeout(() => {
// this.setState({cancelLoading: false});
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_success" isColor />{toLocale('spot.myOrder.cancelSuccessed')}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
this.setState({cancelLoading: false});
Message.success({ content: toLocale('spot.myOrder.cancelSuccessed'), duration: 3 });
};
// 后端返回失败时
onSubmitErr = (err) => {
this.onPwdClose();
this.targetNode.removeAttribute('canceling');
this.errorCallback && this.errorCallback(err);
// setTimeout(() => {
// this.setState({cancelLoading: false});
// const dialog = Dialog.show({
// theme: 'dark operate-alert',
// hideCloseBtn: true,
// children: <div className="operate-msg"><Icon className="icon-icon_fail" isColor />{toLocale('spot.myOrder.cancelFailed')}</div>,
// });
// setTimeout(() => {
// dialog.destroy();
// }, Config.operateResultTipInterval);
// }, Config.operateResultDelaySecond);
this.setState({cancelLoading: false});
Message.error({ content: toLocale('spot.myOrder.cancelFailed'), duration: 3 });
};
// 开启资金密码弹窗
onPwdOpen = () => {
this.setState({
isShowPwdDialog: true
}, () => {
const o = window.document.getElementsByClassName('pwd-input');
if (o && o[0] && o[0].focus) {
o[0].focus();
}
});
};
// 关闭资金密码弹窗
onPwdClose = () => {
this.setState({
isLoading: false,
isShowPwdDialog: false
}, () => {
this.errorCallback && this.errorCallback();
});
};
// 资金密码弹窗点击提交
onPwdEnter = (password) => {
const { formAction, orderAction, commonAction } = this.props;
if (password.trim() === '') {
return formAction.updateWarning(toLocale('spot.place.tips.pwd'));
}
formAction.updateWarning('');
this.setState({
isLoading: true
}, () => {
setTimeout(() => {
commonAction.validatePassword(password, (pk) => {
const param = { ...this.formParam, pk };
this.setState({
isShowPwdDialog: false,
cancelLoading: true
}, () => {
orderAction.cancelOrder(param, () => {
this.successToast();
this.onPwdClose();
}, this.onSubmitErr);
});
}, () => {
this.setState({
isLoading: false
});
});
}, Config.validatePwdDeferSecond)
});
return false;
};
// 资金密码弹窗
renderPwdDialog = () => {
const { isLoading, isShowPwdDialog } = this.state;
const { warning } = this.props.FormStore;
const title = toLocale('please_input_pwd');
return (
<PasswordDialog
title={title}
btnLoading={isLoading}
warning={warning}
updateWarning={this.props.formAction.updateWarning}
isShow={isShowPwdDialog}
onEnter={this.onPwdEnter}
onClose={this.onPwdClose}
/>
);
};
render() {
const { tradeType } = window.OM_GLOBAL;
const tableTheme = tradeType === Enum.tradeType.fullTrade ? 'dark' : '';
const { data, theme, type, product, productObj, isHideOthers, spotAction } = this.props;
const { isLoading, orderList, page } = data;
const {total} = page;
const pageTheme = theme === Enum.themes.theme2 ? 'dark' : '';
let columns = [];
let dataSource = [];
let path = 'open';
if (type === Enum.order.type.noDeal || type === Enum.order.type.history) {
if (orderList.length && orderList[0].uniqueKey) {
dataSource = [];
}
}
if (type === Enum.order.type.noDeal) {
dataSource = commonUtil.formatOpenData(orderList, productObj, product);
columns = normalColumns.noDealColumns(this.onCancelOrder, spotAction.updateProduct);
} else if (type === Enum.order.type.history) {
dataSource = commonUtil.formatClosedData(orderList, productObj);
columns = normalColumns.historyColumns();
path = 'history';
} else if (type === Enum.order.type.detail) {
dataSource = commonUtil.formatDealsData(orderList, productObj);
columns = normalColumns.detailColumns();
path = 'deals';
}
let queryProduct = 'all';
if (isHideOthers && product) {
queryProduct = product;
}
// 跳转链接参数:, period: this.props.periodIntervalType 'product=' + queryProduct
return (
<div>
<Table
columns={columns}
isLoading={isLoading}
dataSource={dataSource}
empty={commonUtil.getEmpty()}
rowKey={type === Enum.order.type.detail ? "uniqueKey" : "order_id"}
theme={tableTheme}
>
{dataSource.length >= 20 ? <div style={{textAlign: 'center', 'lineHeight': '22px'}}>
<Link to={`${PageURL.homePage}/spot/${path}`}>
{toLocale('link_to_all')}
</Link>
</div> : null}
</Table>
<div className={`wait-loading ${this.state.cancelLoading ? '' : 'hide'}`} >
<div className="loading-icon"><Icon className="icon-loadingCopy" isColor /></div>
</div>
{/*{this.renderPagination(pageTheme)}*/}
{this.renderPwdDialog()}
</div>
);
}
}
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { toLocale } from '_src/locale/react-locale';
import { crypto } from '@omexchain/javascript-sdk';
import Icon from '_src/component/IconLite';
import Input from '_component/Input';
import WalletPassword from '_component/WalletPassword';
import { Button } from '_component/Button';
import { Checkbox } from '_component/Checkbox';
import * as walletActions from '_src/redux/actions/WalletAction';
import WalletLeft from '_component/WalletLeft';
import WalletRight from '_component/WalletRight';
import PageURL from '_constants/PageURL';
import './Step.less';
import './Step1.less';
function mapStateToProps() {
return {};
}
function mapDispatchToProps(dispatch) {
return {
walletAction: bindActionCreators(walletActions, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps)
class Step1 extends Component {
constructor(props) {
super(props);
this.state = {
pwdFirst: '',
pwdTwice: '',
showTwicePwd: false, // 第一次设置密码的input type在WalletPassword中控制
isSamePwd: true,
knowCheck: false,
canNext: false,
nextLoading: false
};
this.isValidatedPassword = false;
}
onNext = () => {
if (this.state.nextLoading) {
return false;
}
return this.setState({
nextLoading: true
}, () => {
setTimeout(() => {
const { walletAction } = this.props;
const mnemonic = crypto.generateMnemonic(); // => 12 words
const privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic);
const keyStore = crypto.generateKeyStore(privateKey, this.state.pwdFirst);
// const mnemonic = '1 2 3 4 5 6 7 8 9 10 11 12'; // 12 words
// const privateKey = 'XHOW23EdWEDXl123D';
// const keyStore = {
// address: '<KEY>',
// privateKey: {
// version: 1,
// id: '<KEY>'
// }
// };
walletAction.updateMnemonic(mnemonic);
walletAction.updatePrivate(privateKey);
walletAction.updateKeyStore(keyStore);
return walletAction.updateCreateStep(2);
}, 20);
});
};
validateCanNext = () => {
const {
isSamePwd,
pwdTwice,
knowCheck,
} = this.state;
this.setState({
canNext: this.isValidatedPassword && isSamePwd && (pwdTwice != '') && knowCheck // && knowCheck
});
}
tooglePwdTwiceType = () => {
this.setState({
showTwicePwd: !this.state.showTwicePwd
});
}
changePwdFirst = ({ value, lengthCheck, chartCheck }) => {
this.isValidatedPassword = lengthCheck === 'right' && chartCheck === 'right';
const pwdFirst = value;
const { pwdTwice } = this.state;
this.setState({
pwdFirst,
isSamePwd: pwdTwice === '' ? true : pwdFirst === pwdTwice
}, this.validateCanNext);
}
changePwdTwice = (e) => {
const pwdTwice = e.target.value;
const { pwdFirst } = this.state;
this.setState({
pwdTwice,
isSamePwd: (pwdTwice != '') && (pwdFirst === pwdTwice)
}, this.validateCanNext);
}
changeKnow = (checked) => {
this.setState({
knowCheck: checked
}, this.validateCanNext);
}
render() {
const {
showTwicePwd, pwdTwice,
isSamePwd, canNext, nextLoading,
knowCheck
} = this.state;
return (
<div className="create-wallet-step1 wallet-step-dialog">
<WalletLeft
stepNo={1}
stepName={toLocale('wallet_create_step1')}
imgUrl="https://static.bafang.com/cdn/assets/imgs/MjAxOTQ/2746959A3B06A9073C31362399AD0C32.png"
/>
<WalletRight>
<div className="set-password-container">
<div className="set-password-first">
<WalletPassword
onChange={this.changePwdFirst}
/>
</div>
<div className="set-password-twice">
<Input
value={pwdTwice}
placeholder={toLocale('wallet_twicePassword')}
onChange={this.changePwdTwice}
onPaste={(e) => { e.preventDefault(); }}
error={isSamePwd ? '' : toLocale('wallet_passwordNotSame')}
className={showTwicePwd ? 'show' : ''}
theme="dark"
suffix={() => {
const IconClsName = showTwicePwd ? 'icon-icon_display' : 'icon-icon_hide';
return <Icon className={IconClsName} onClick={this.tooglePwdTwiceType} />;
}}
/>
<div className="mar-top8">
<Checkbox checked={knowCheck} className="mar-top8" onChange={this.changeKnow}>
<span className="know-check">{toLocale('wallet_unsaveTip')}</span>
</Checkbox>
</div>
</div>
<div className="next-row">
<span>
{toLocale('wallet_hadWallet')}
<Link to={PageURL.walletImport}>
{toLocale('wallet_importNow')}
</Link>
</span>
<Button
type="primary"
onClick={this.onNext}
loading={nextLoading}
disabled={!canNext}
>
{toLocale('wallet_nextStep')}
</Button>
</div>
</div>
</WalletRight>
</div>
);
}
}
export default Step1;
<file_sep>import React, { Component } from 'react';
import Banner from './Banner';
import Advantage from './Advantage';
import Experience from './Experience';
import Steps from './Steps';
import './index.less';
class index extends Component {
constructor(props) {
super(props);
window.omGlobal && window.omGlobal.ui && window.omGlobal.ui.setNav({
// transparent = true 设置透明header,在非桌面端在滑动时自动根据距离判断变为透明/不透明样式,设置该参数后 header在所有尺寸都将不占高度
transparent: true,
});
}
render() {
return (
<main className="home-container">
<Banner />
<Steps />
<Advantage />
<Experience />
</main>
);
}
}
export default index;
<file_sep>import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Icon from '_src/component/IconLite';
import * as SpotActions from '../../redux/actions/SpotAction';
import theme from '../../utils/TriggerTheme';
import Enum from '../../utils/Enum';
function mapStateToProps(state) { // 绑定redux中相关state
return {
theme: state.Spot.theme
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch)
};
}
@connect(mapStateToProps, mapDispatchToProps) // 与redux相关的组件再用connect修饰,容器组件
export default class ThemeSetting extends React.Component {
triggerTheme = () => {
theme.triggerTheme();
this.props.spotActions.updateTheme(localStorage.getItem('theme'));
};
render() {
const light2Dark = (this.props.theme === Enum.themes.theme2) ? 'icon-daytime' : 'icon-night';
return (
<div className="trigger-theme" onClick={this.triggerTheme}>
<Icon
className={`primary-blue ${light2Dark}`}
style={{ fontSize: '18px', cursor: 'pointer' }}
/>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Icon from '../IconLite';
import './index.less';
const prefixCls = 'om-ui-input';
export default class Input extends React.Component {
static propTypes = {
// prefix: PropTypes.oneOfType([PropTypes.string, PropTypes.element, PropTypes.func]),
/** 带有后缀的 input */
suffix: PropTypes.oneOfType([PropTypes.string, PropTypes.element, PropTypes.func]),
/** placeholder */
placeholder: PropTypes.string,
/** disabled */
disabled: PropTypes.bool,
/** readOnly */
readOnly: PropTypes.bool,
/** 可以点击清除图标删除内容 */
allowClear: PropTypes.bool,
/** 错误描述信息 */
error: PropTypes.oneOfType([PropTypes.string, PropTypes.element, PropTypes.func]),
/** 声明 input 类型,同原生 input 标签的 type 属性 */
type: PropTypes.string,
/** 输入框内容 */
value: PropTypes.string,
/** 主题 可选“dark” */
theme: PropTypes.oneOf(['', 'dark']),
/** 输入框内容变化时的回调 */
onChange: PropTypes.func
};
static defaultProps = {
// prefix: '',
suffix: '',
placeholder: '',
disabled: false,
error: '',
value: '',
theme: '',
readOnly: false,
allowClear: false,
type: 'text',
onChange: null
};
handleClearInput = () => {
this.props.onChange({ target: { value: '' } });
}
renderInput = () => {
const extraProps = ['suffix', 'error', 'theme', 'allowClear'];
const inputProps = Object.keys(this.props).reduce((props, key) => {
const propsClone = { ...props };
if (!extraProps.includes(key)) {
propsClone[key] = this.props[key];
}
return propsClone;
}, {});
return <input {...inputProps} />;
};
// renderPrefix = (prefix) => {
// let children = prefix;
// if (typeof prefix === 'function') {
// children = prefix();
// }
// return <span className={`${prefixCls}-prefix`}>{children}</span>;
// };
renderSuffix = () => {
const { suffix, allowClear, value } = this.props;
let children = suffix;
if (typeof suffix === 'function') {
children = suffix();
}
return (
<div className={`${prefixCls}-suffix`}>
{allowClear && value && <span onClick={this.handleClearInput} ><Icon className="icon-close-circle" /></span>}
{children}
</div>
);
};
renderError = (error) => {
if (typeof error !== 'function') {
return <span className={`${prefixCls}-error`}>{error}</span>;
}
return <span className={`${prefixCls}-error`}>{error()}</span>;
};
render() {
const {
theme, style, disabled, error
} = this.props;
const clsName = classnames(prefixCls, { disabled }, theme === 'dark' && 'dark', error && 'error');
return (
<div className={clsName} style={style}>
<div style={{ position: 'relative' }}>
{/* {prefix && this.renderPrefix(prefix)} */}
{this.renderInput()}
{this.renderSuffix()}
</div>
{
error && this.renderError(error)
}
</div>
);
}
}
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import ont from '../../utils/dataProxy';
import URL from '../../constants/URL';
import './ValuationUnit.less';
class ValuationUnit extends React.Component {
constructor(props) {
super(props);
this.state = {
valuationItems: [],
isHide: true,
valuationUnit: 'TUSDK',
};
}
componentDidMount() {
!this.gotUnit && this.getValuationUnit();
}
/**
* 响应计价选择
* @param e
*/
onChangeValua = (e) => {
const index = e.target.getAttribute('data-index');
const item = this.state.valuationItems[index];
this.selectValuation(item.label, item.value, item.symbol, item.dig);
// 关闭选择项
this.setState({
isHide: true,
});
}
/**
* 鼠标覆盖处理
*/
onMouseOverHandler = () => {
this.setState({ isHide: false });
}
/**
* 鼠标移开处理
*/
onMouseOutHandler = () => {
this.setState({ isHide: true });
};
/**
* 获取计价单位
*/
getValuationUnit() {
this.fetching = true;
ont.get(URL.GET_VALUATION_LIST).then((res) => {
// 处理一下资产格式
const valuationItems = [];
res.data && res.data.forEach((item) => {
const params = {
label: item.name,
value: item.smallAmount,
symbol: item.symbol,
dig: item.dig
};
valuationItems.push(params);
});
this.setState({
valuationItems
});
this.gotUnit = true;
this.fetching = false;
}).catch(() => {
this.gotUnit = true;
this.fetching = false;
});
}
// 切换计价
selectValuation(valuationUnit, smallAmount, valuationUnitSymbol, valuationDig) {
if (valuationUnit !== this.state.valuationUnit) {
this.smallAmount = smallAmount;
this.props.getValuationUnit(valuationUnit, smallAmount, valuationUnitSymbol, valuationDig);
localStorage.setItem('valuationUnit', valuationUnit);
this.setState({
valuationUnit: localStorage.getItem('valuationUnit'),
});
}
}
renderValuationRows(valuationItems) {
const { valuationUnit } = this.state;
return valuationItems.map((item, index) => {
return (
<span className={['item', item.label === valuationUnit ? 'active' : ''].join(' ')} key={index} onClick={this.onChangeValua} data-index={index}>
{item.label}
</span>
);
});
}
render() {
const {
isHide, valuationItems, valuationUnit
} = this.state;
const newValuationUnit = [valuationUnit, ' ', toLocale('valuation')].join('');
const listValuationItems = this.renderValuationRows(valuationItems);
return (
<span className="valuation" onMouseOver={this.onMouseOverHandler} onMouseOut={this.onMouseOutHandler}>
{newValuationUnit}
<i className="icon-transfer" />
<div className={['drop-down-list', isHide ? 'hide-drop-down-list' : ''].join(' ')}>
{listValuationItems}
</div>
</span>
);
}
}
export default ValuationUnit;
<file_sep>import WatchMedia from './js/WatchMedia';
import getMedia from './js/getMedia';
export { WatchMedia, getMedia };
<file_sep>const path = require('path');
const webpack = require('webpack');
const env = require('./dev.env');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const base = require('./webpack.config.base');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const config = require('./config');
// const ip = require('ip');
// const address = ip.address();
// const address = 'local.omex.com';
// const address = 'localhost';
const address = '127.0.0.1';
const mockUrl = 'http://mock.omcoin-inc.com';
base.output.publicPath = `http://${address}:${config.dev.port}/`;
base.plugins.unshift(
// new BundleAnalyzerPlugin(),
new webpack.DefinePlugin(env),
new webpack.HotModuleReplacementPlugin({}),
new HtmlWebpackPlugin({
template: path.resolve(path.resolve(__dirname, '../src'), 'index.html'),
filename: 'index.html'
}),
);
module.exports = Object.assign(base, {
mode: 'development',
devServer: {
contentBase: path.resolve(__dirname, '../src'),
hot: true,
host: address,
port: config.dev.port,
proxy: {
'/rap/*': {
target: mockUrl,
changeOrigin: true,
secure: true,
},
'/v2/*': {
target: config.dev.apiUrl,
changeOrigin: true,
secure: true,
},
'/tradingview/*': {
target: 'http://omcombeta.bafang.com/',
// pathRewrite: { '^/omui-tv/libs': '' },
changeOrigin: true,
secure: true,
},
'/v3/*': {
target: config.dev.apiUrl,
changeOrigin: true,
secure: true,
}
},
historyApiFallback: {
rewrites: [
{ from: /^\/$/, to: '/omexapp/index.html' }
]
}
},
devtool: 'source-map'
});
<file_sep>import React from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../IconLite';
import './index.less';
const arrowRenderer = ({ isOpen }) => {
return <Icon className={classNames({ 'icon-Unfold': true, 'arrow-open': isOpen })} />;
};
export default class ReactSelect extends React.PureComponent {
static propTypes = {
/** 是否有搜索icon */
hasSearch: PropTypes.bool,
/** 是否是小尺寸 */
small: PropTypes.bool,
/** 主题(dark) */
theme: PropTypes.string
};
static defaultProps = {
hasSearch: false,
small: false,
theme: ''
};
render() {
const {
className, small, theme, hasSearch,
...props
} = this.props;
const selectEle = (
<Select
{...props}
className={classNames({
'om-select': true, [className]: className, small, [theme]: theme
})}
arrowRenderer={arrowRenderer}
/>
);
if (hasSearch) {
return (
<div
className={classNames({
'om-select-wrap': true, small, [theme]: theme
})}
>
<Icon className="icon-enlarge" />
{selectEle}
</div>
);
}
return selectEle;
}
}
<file_sep>import calc from './calc';
import { depth, Depth } from './depth';
import storage from './storage';
export { calc, depth, Depth, storage };
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toLocale } from '_src/locale/react-locale';
import * as FormAction from '../redux/actions/FormAction';
import * as OrderAction from '../redux/actions/OrderAction';
import Enum from '../utils/Enum';
import util from '../utils/util';
function mapStateToProps(state) {
const { product } = state.SpotTrade;
const { strategyType } = state.FormStore;
const { entrustType } = state.OrderStore;
return {
product, strategyType, entrustType
};
}
function mapDispatchToProps(dispatch) {
return {
formAction: bindActionCreators(FormAction, dispatch),
orderAction: bindActionCreators(OrderAction, dispatch)
};
}
const StrategyTypeWrapper = (Component) => {
@connect(mapStateToProps, mapDispatchToProps)
class StrategyType extends React.Component {
// 切换委托类型
onChangeStrategyType = (e) => {
const {
formAction, orderAction, strategyType, entrustType
} = this.props;
if (e.value !== strategyType) { // 选择不同的委托类型才刷新下单区域
if (strategyType === 1 || strategyType === 7) {
formAction.updateDepthInput({
type: Enum.placeOrder.type.buy,
price: '',
amount: '',
total: '',
couponId: '',
});
}
formAction.updateWarning('');
formAction.updateStrategyType(e.value);
const newEntrustType = (e.value < 3 || e.value === 7) ? 0 : (e.value - 2);
if (entrustType !== newEntrustType) {
orderAction.updateEntrustType(newEntrustType);
}
}
};
render() {
const { tradeType } = window.OM_GLOBAL;
const { strategyType, theme } = this.props;
let limitId = 'spot.limitOrder';
let marketId = 'spot.marketOrder';
const planId = 'spot.planOrder';
const trackId = 'spot.trackOrder';
const icebergId = 'spot.icebergOrder';
const timeWeightId = 'spot.timeWeightOrder';
const advancedLimitId = 'spot.advancedLimitOrder';
const strategyTypes = Enum.placeOrder.strategyType;
let options = [
{ value: strategyTypes.limit, label: toLocale(limitId) },
{ value: strategyTypes.market, label: toLocale(marketId) },
{ value: strategyTypes.plan, label: toLocale(planId) },
{ value: strategyTypes.track, label: toLocale(trackId) },
{ value: strategyTypes.iceberg, label: toLocale(icebergId) },
{ value: strategyTypes.timeWeight, label: toLocale(timeWeightId) },
{ value: strategyTypes.advancedLimit, label: toLocale(advancedLimitId) },
];
// TODO
if (tradeType === Enum.tradeType.fullTrade) {
// 全屏交易只有市价和限价
limitId = 'spot.FullLimitOrder';
marketId = 'spot.shortMarketOrder';
options = [
{ value: 1, label: toLocale(limitId) },
// { value: 2, label: toLocale(marketId) }
];
}
// console.log('options', options);
return (
<Component
strategyType={strategyType}
options={options}
onChangeStrategyType={this.onChangeStrategyType}
theme={util.getTheme(theme)}
/>
);
}
}
return StrategyType;
};
export default StrategyTypeWrapper;
<file_sep>import React from 'react';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import FormatWS from '../utils/FormatWS';
import { getConnectCfg, wsV3 } from '../utils/websocket';
import * as SpotActions from '../redux/actions/SpotAction';
import * as SpotTradeActions from '../redux/actions/SpotTradeAction';
import * as OrderAction from '../redux/actions/OrderAction';
import util from '../utils/util';
import history from '../utils/history';
import PageURL from '../constants/PageURL';
function mapStateToProps(state) {
const { tickers } = state.Spot;
const { currencyList, productList } = state.SpotTrade;
return {
currencyList, productList, tickers
};
}
function mapDispatchToProps(dispatch) { // 绑定action,以便向redux发送action
return {
spotActions: bindActionCreators(SpotActions, dispatch),
spotTradeActions: bindActionCreators(SpotTradeActions, dispatch),
orderAction: bindActionCreators(OrderAction, dispatch),
};
}
// 全屏交易/简约交易相关页面
const InitWrapper = (Component) => {
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class SpotInit extends React.Component {
componentDidMount() {
const { match } = this.props;
if (match.path.includes('/spot/fullMargin') || match.path.includes('/spot/marginTrade')) {
window.OM_GLOBAL.isMarginType = true;
}
this.sendBasicAjax();
this.startInitWebSocket();
const header = document.querySelector('.spot-head-box');
const left = document.querySelector('.left-menu-container');
if (header) {
header.style = 'block';
}
if (left) {
left.style = 'block';
}
}
componentWillReceiveProps() {
// 如果登录状态从未登录变成已登录时,页面刷新
// 考虑到在另一个tab页进行登录的情况
// const currentIsLogin = !!localStorage.getItem('dex_token');
// if (!window.OM_GLOBAL.isLogin && currentIsLogin) {
// window.location.reload();
// }
}
componentWillUnmount() {
}
// 基础ajax,其他业务数据对此有依赖
sendBasicAjax = () => {
const { spotActions } = this.props;
// 获取所有收藏的币对 和 所有在线币对基础配置
spotActions.fetchCollectAndProducts();
// 获取所有币对行情
spotActions.fetchTickers();
// 获取所有币种的配置
spotActions.fetchCurrency();
};
wsHandler = (table) => {
const { orderAction, spotTradeActions, spotActions } = this.props;
const fns = {
'dex_spot/account': (data) => {
spotTradeActions.wsUpdateAsset(data);
},
'dex_spot/order': (data) => {
// orderAction.wsUpdateList(FormatWS.order(data));
orderAction.wsUpdateList(data);
},
'dex_spot/ticker': (data) => {
spotTradeActions.wsUpdateTicker(FormatWS.ticker(data));
},
'dex_spot/all_ticker_3s': (data) => {
spotActions.wsUpdateTickers(FormatWS.allTickers(data));
},
'dex_spot/optimized_depth': (data, res) => {
spotTradeActions.wsUpdateDepth(FormatWS.depth(res));
},
'dex_spot/matches': (data) => {
spotTradeActions.wsUpdateDeals(data);
},
};
return fns[table.split(':')[0]];
};
// 建立ws连接
startInitWebSocket = () => {
const OM_GLOBAL = window.OM_GLOBAL;
if (!OM_GLOBAL.ws_v3) {
const { spotActions } = this.props;
OM_GLOBAL.ws_v3 = new window.WebSocketCore(getConnectCfg());
const v3 = OM_GLOBAL.ws_v3;
v3.onSocketConnected(() => {
function getJwtToken() {
if (!util.isLogined()) {
setTimeout(getJwtToken, 1000);
} else {
wsV3.login(util.getMyAddr());
}
}
// 针对未登陆,用户使用三种方式登录
if (!util.isLogined()) {
getJwtToken();
} else { // 针对已登录,用户刷新
wsV3.login(util.getMyAddr());
}
spotActions.updateWsStatus(true);
});
v3.onSocketError(() => {
spotActions.addWsErrCounter(); // 累计加1
spotActions.updateWsStatus(false);
spotActions.updateWsIsDelay(false);
});
v3.onPushDiscontinue(() => {
v3.sendChannel('ping');
});
v3.setPushDataResolver((pushData) => {
const {
table, data, event, success, errorCode
} = pushData;
if (table && data) {
const handler = this.wsHandler(table);
handler && handler(data, pushData);
}
if (event === 'dex_login' && success === true) {
spotActions.updateWsIsDelay(true);
}
// 如果tomen过期,相当于退出,强制用户重新登录
if (event === 'error' && (Number(errorCode) === 30043 || Number(errorCode) === 30008 || Number(errorCode) === 30006)) {
util.doLogout();
// history.push(PageURL.homePage);
}
});
v3.connect();
}
if (OM_GLOBAL.ws_v3 && OM_GLOBAL.ws_v3.isConnected() && util.isLogined()) {
wsV3.login(util.getMyAddr());
}
};
render() {
const { currencyList, productList, tickers } = this.props;
if (currencyList && currencyList.length // 所有单币种信息
&& productList && productList.length // 所有币对信息
) { // 行情信息 && Object.keys(tickers).length
return <Component />;
}
return null;
}
}
return SpotInit;
};
export default InitWrapper;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import util from '../../utils/util';
const AssetSpot = (props) => {
const { dataSource, onTransfer } = props;
return (
<div>
<div className="om-asset spot">
<div className="default-fz c-disabled">
{toLocale('spot.asset')}
</div>
{
dataSource.map((item) => {
const {
currencyName, available, locked
} = item;
return (
<div className="asset-unit" key={currencyName}>
<label>{util.getSymbolShortName(currencyName)}</label>
<label>{toLocale('spot.asset.ava')}</label>
<label className="weight">{available}</label>
<label>/</label>
<label>{toLocale('spot.asset.freeze')}</label>
<label className="weight">{locked}</label>
{/* <a
onClick={onTransfer(currencyName, currencyId)}
className="float-right om-asset-charge"
>
{
toLocale('spot.asset.transfer')
}
</a> */}
</div>
);
})
}
<div className="asset-right" />
</div>
</div>
);
};
AssetSpot.propTypes = {
dataSource: PropTypes.array
};
AssetSpot.defaultProps = {
dataSource: [
{
currencyName: ' --', // 币种名称
available: 0, // 可用
locked: 0 // 冻结
}, {
currencyName: '-- ', // 币种名称
available: 0, // 可用
locked: 0 // 冻结
}
]
};
export default AssetSpot;
<file_sep>import React from 'react';
import Icon from '_src/component/IconLite';
import PropTypes from 'prop-types';
import './index.less';
const typeEnum = {
none: 'icon-icon_circlex',
warning: 'icon-icon_warningx',
wrong: 'icon-icon_wrongx',
right: 'icon-icon_success'
};
const ValidateCheckbox = (props) => {
const {
type, children, className, style
} = props;
const clsName = typeEnum[type] || 'icon-icon_circle';
return (
<div className={`${className} validate-checkbox ${type}`} style={style}>
<Icon
className={clsName}
style={{ fontSize: '14px', marginRight: '5px' }}
/>
<span>{children}</span>
</div>
);
};
ValidateCheckbox.propTypes = {
type: PropTypes.oneOf(['none', 'warning', 'wrong', 'right'])
};
ValidateCheckbox.defaultProps = {
type: 'none'
};
export default ValidateCheckbox;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import { Dialog } from '_component/Dialog';
import { Button } from '_component/Button';
import Icon from '_src/component/IconLite';
import Config from '_constants/Config';
import './index.less';
/* eslint-disable react/sort-comp */
class Index extends React.Component {
static propTypes = {
isShow: PropTypes.bool,
btnLoading: PropTypes.bool,
warning: PropTypes.string,
onEnter: PropTypes.func,
onClose: PropTypes.func,
updateWarning: PropTypes.func,
};
static defaultProps = {
isShow: false,
btnLoading: false,
warning: '',
onEnter: () => {},
onClose: () => {},
updateWarning: () => {},
};
constructor(props) {
super(props);
this.state = {
password: '',
};
this.inputType = 'password';
if (window.navigator.userAgent.match(/webkit/i)) {
this.inputType = 'text';
}
}
componentWillReceiveProps(nextProps) {
if (this.props.isShow !== nextProps.isShow) {
if (nextProps.isShow) {
setTimeout(() => {
this.pwdInput.focus();
}, 100);
}
if (!nextProps.isShow) {
// 从显示到隐藏,清空密码框
this.setState({
password: '',
});
}
}
}
clearPwd = () => {
this.setState({ password: '' }, () => {
this.pwdInput.focus();
});
};
// 输入密码
onChangePwd = (e) => {
const password = e.target.value;
let localWarning = '';
this.setState({ password });
const { lengthReg, chartReg } = Config.pwdValidate;
const lengthCheck = lengthReg.test(password);
const chartCheck = chartReg.test(password);
// todo: 是否要在onfirm的时候检查呢?
if (!lengthCheck) {
localWarning = toLocale('wallet_password_lengthValidate'); // 至少10位字符
} else if (!chartCheck) {
localWarning = toLocale('wallet_password_chartValidate'); // 必须包含数字、大小写字母
}
this.props.updateWarning(localWarning);
};
isDisabled = () => {
const { lengthReg, chartReg } = Config.pwdValidate;
const { password } = this.state;
const lengthCheck = lengthReg.test(password);
const chartCheck = chartReg.test(password);
return password === '' || !lengthCheck || !chartCheck;
};
render() {
const {
btnLoading, isShow, onEnter, onClose, warning
} = this.props;
const { password } = this.state;
return (
<Dialog
theme="base-dialog pwd-dialog"
title={toLocale('please_input_pwd')}
openWhen={isShow}
onClose={onClose}
>
<div className="pwd-container">
<input
placeholder={toLocale('wallet_password_placeholder')}
type={this.inputType}
className="pwd-input"
autoComplete="new-pwd-input"
value={password}
onChange={this.onChangePwd}
onPaste={(e) => { e.preventDefault(); }}
ref={(dom) => {
this.pwdInput = dom;
}}
/>
<Icon className="clear-pwd icon-close-circle" onClick={this.clearPwd} />
<p className="pwd-error">{warning}</p>
<Button
block
type={Button.btnType.primary}
onClick={() => {
onEnter(this.state.password);
}}
loading={btnLoading}
disabled={this.isDisabled()}
>
{toLocale('OK')}
</Button>
</div>
</Dialog>
);
}
}
export default Index;
<file_sep>export default class theme {
// 查询本地是否存有theme
static getLocalTheme() {
return localStorage.getItem('theme') || 'theme-1';
}
// 动态加载主题
static triggerTheme() {
this.checkDark(this.getLocalTheme() === 'theme-2');
}
// 切换主题
static checkDark(hasDark) {
localStorage.setItem('theme', hasDark ? 'theme-1' : 'theme-2');
if (!hasDark) {
// 切到dark 添加dark_theme
this.importDarkTheme();
} else {
// 默认light
this.importLightTheme();
}
}
static importDarkTheme() {
// document.body.setAttribute('class', 'theme-2');
document.body.classList.add('theme-2');
}
static importLightTheme() {
// document.body.setAttribute('class', 'theme-1');
document.body.classList.add('theme-1');
}
}
<file_sep>import React, { Component } from 'react';
import { toLocale } from '_src/locale/react-locale';
import Loading from '_component/Loading';
import moment from 'moment';
import './ReportList.less';
class ReportList extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { dataSource, loading, projectId } = this.props;
return (
<div className="report-list-container">
<Loading when={loading} />
<ul>
{
dataSource.map(({
title, publishTime: createTime, accessory
}, index) => {
return (
<li key={index}>
<a href={accessory} target="_blank" rel="noopener noreferrer">
<span title={title}><label>{toLocale('spot.kline.tabs[2]')}</label><span className="splitter" />{title}</span>
<span>{moment(createTime).format('YYYY-MM-DD')}</span>
</a>
</li>
);
})
}
</ul>
{!loading && dataSource.length === 0 && <div className="no-data">{toLocale('spot.noData')}</div>}
{!loading && dataSource.length > 0 && <a className="more" href={`/project/${projectId}?tab=1`}>{toLocale('spot.kline.tabs[2].more')} ></a>}
</div>
);
}
}
export default ReportList;
<file_sep>/**
* 用于挂单的百分比按钮
* Created by wanghongguang on 2018-06-08
*/
import React from 'react';
import PropTypes from 'prop-types';
const PercentButton = (props) => {
const { percentValue, chosen, onClick } = props;
const activeCls = chosen ? ' active' : '';
return (
<div className={`input-container mar-left5 percent-btn ${activeCls}`} onClick={onClick}>
{ percentValue }%
</div>
);
};
PercentButton.propTypes = {
percentValue: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
chosen: PropTypes.bool,
onClick: PropTypes.func
};
PercentButton.defaultProps = {
chosen: false,
onClick: null
};
export default PercentButton;
<file_sep>import CommonActionType from '../actionTypes/CommonActionType';
const initialState = {
omchainClient: {}, // OMChain客户端对象
privateKey: '', // 私钥
legalList: [], // 法币货币列表
legalId: -1, // 法币货币当前id
legalObj: {}, // 法币货币当前obj
latestHeight: 0, // OMChain区块最新高度
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case CommonActionType.SET_OMCHAIN_CLIENT:
return {
...state,
omchainClient: action.data
};
case CommonActionType.UPDATE_CURRENCY_LIST:
return {
...state,
legalList: action.data
};
case CommonActionType.UPDATE_CURRENCY_ID:
return {
...state,
legalId: action.data
};
case CommonActionType.UPDATE_CURRENCY_OBJ:
return {
...state,
legalObj: action.data
};
case CommonActionType.SET_PRIVATE_KEY:
return {
...state,
privateKey: action.data
};
case CommonActionType.UPDATE_LATEST_HEIGHT:
return {
...state,
latestHeight: action.data
};
default:
return state;
}
}
<file_sep>/**
* 弹框
* Created by yuxin.zhang on 2018/1/1.
*/
import Dialog from './Dialog';
import DialogOneBtn from './DialogOneBtn';
import DialogTwoBtn from './DialogTwoBtn';
import PromptDialog from './PromptDialog';
function createFunction(type) {
return (props) => {
const config = {
dialogType: PromptDialog.dialogType.prompt,
infoType: PromptDialog.infoType[type],
...props,
};
return PromptDialog.create(config);
};
}
// 完全一个数组遍历来写,只不过用的时候就没有提示了
Dialog.success = createFunction(PromptDialog.infoType.success);
Dialog.info = createFunction(PromptDialog.infoType.info);
Dialog.prompt = createFunction(PromptDialog.infoType.prompt);
Dialog.warn = createFunction(PromptDialog.infoType.warn);
Dialog.error = createFunction(PromptDialog.infoType.error);
Dialog.confirm = (props) => {
const config = {
dialogType: PromptDialog.dialogType.confirm,
infoType: PromptDialog.infoType.warn,
...props,
};
return PromptDialog.create(config);
};
Dialog.show = (props) => {
return Dialog.create(props);
};
export { Dialog, DialogOneBtn, DialogTwoBtn, PromptDialog };
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { toLocale } from '_src/locale/react-locale';
import util from '_src/utils/util';
import Enum from '../../utils/Enum';
import DepthTitle from '../../component/depth/DepthTitle';
import DepthList from './DepthList';
import './Depth.less';
export default class Depth extends React.Component {
constructor(props, context) {
super(props, context);
this.init = false;
this.enum = {
buy: Enum.placeOrder.type.buy,
sell: Enum.placeOrder.type.sell
};
}
// 选择某一档深度
onChooseOneDepth = (index, type) => {
const config = window.OM_GLOBAL.productConfig;
const { onChooseOneDepth, listSource } = this.props;
const sizeTruncate = 'max_size_digit' in config ? config.max_size_digit : 2;
if (typeof onChooseOneDepth !== 'undefined') {
let amount = 0;
let price = 0;
if (type === this.enum.buy) {
price = listSource.buyList[index].price.replace(/,/g, '');
amount = listSource.buyList[index].sum.replace(/,/g, '');
} else {
price = listSource.sellList[index].price.replace(/,/g, '');
amount = listSource.sellList[index].sum.replace(/,/g, '');
}
amount = Number(amount).toFixed(sizeTruncate);
onChooseOneDepth(price, amount, type);
}
};
// 将DepthList中的方法scrollToPosition,传给平级的DepthTitle
onDepthPosition = (position) => {
this.depthList.scrollToPosition(position);
};
// 生成DepthList组件需要的数据格式
getListDataSource = () => {
const {
needSum, listSource, tickerSource, product
} = this.props;
const tradeCurr = product.indexOf('_') > -1 ? product.split('_')[0].toUpperCase() : '';
const baseCurr = product.indexOf('_') > -1 ? product.split('_')[1].toUpperCase() : '';
const listDataSource = {
...listSource,
ticker: {
price: tickerSource.price,
trend: (tickerSource.change && tickerSource.change.toString().indexOf('-') > -1) ? 'down' : 'up'
}
};
const priceTitle = (
<span>
{toLocale('spot.price')}
(<em>{baseCurr}</em>)
</span>
);
const sizeTitle = (
<span>
{toLocale('spot.depth.amount')}
(<em>{util.getSymbolShortName(tradeCurr)}</em>)
</span>
);
const columnTitle = [priceTitle, sizeTitle];
if (needSum) {
const sumTitle = (
<span>
{toLocale('spot.depth.sum')}
(<em>{util.getSymbolShortName(tradeCurr)}</em>)
</span>
);
columnTitle.push(sumTitle);
}
return {
columnTitle,
dataSource: listDataSource
};
};
render() {
const listDataSource = this.getListDataSource();
const {
needHeadBtn, needBgColor, needSum, product, isShowMerge, onChooseMergeType, theme
} = this.props;
return (
<div className="spot-depth">
<DepthTitle
theme={theme}
needHeadBtn={needHeadBtn}
onDepthPosition={this.onDepthPosition}
/>
<DepthList
ref={(ref) => {
this.depthList = ref;
}}
needSum={needSum}
needBgColor={needBgColor}
columnTitle={listDataSource.columnTitle}
dataSource={listDataSource.dataSource}
toCenterLabel={toLocale('spot.depth.backToCenter')}
selectItem={this.onChooseOneDepth}
theme={theme}
product={product}
isShowMerge={isShowMerge}
onChooseMergeType={onChooseMergeType}
/>
</div>
);
}
}
Depth.propTypes = {
listSource: PropTypes.object.isRequired,
tickerSource: PropTypes.object.isRequired,
product: PropTypes.string.isRequired,
needSum: PropTypes.bool,
needHeadBtn: PropTypes.bool,
needBgColor: PropTypes.bool,
theme: PropTypes.oneOf(['light', 'dark']),
onChooseMergeType: PropTypes.func,
onChooseOneDepth: PropTypes.func
};
Depth.defaultProps = {
// dataSource: {},
// tickerDataSource: {},
// product: '',
needSum: false,
needHeadBtn: false,
needBgColor: false,
theme: 'light',
onChooseMergeType: null,
onChooseOneDepth: null
};
<file_sep>import React from 'react';
import { toLocale } from '_src/locale/react-locale';
import './index.less';
const DexHelp = () => {
return (
<div className="dex-help-container">
<h4 className="dex-help-title">{toLocale('dex.help.title')}</h4>
<ul className="help-list">
<li className="help-list-item">
<a className="help-list-item-link" target="_blank" rel="noopener noreferrer" href="https://omchain-docs.readthedocs.io/en/latest/dex-operators/dex-operators-overview.html">{toLocale('dex.help.item1')}</a>
</li>
<li className="help-list-item">
<a className="help-list-item-link" target="_blank" rel="noopener noreferrer" href="https://omchain-docs.readthedocs.io/en/latest/dex-operators/dex-operators-guide-cli.html">{toLocale('dex.help.item2')}</a>
</li>
<li className="help-list-item">
<a className="help-list-item-link" target="_blank" rel="noopener noreferrer" href="https://omchain-docs.readthedocs.io/en/latest/dex-operators/dex-operators-faq.html">{toLocale('dex.help.item3')}</a>
</li>
</ul>
</div>
);
};
export default DexHelp;
<file_sep>import moment from 'moment';
import React from 'react';
import FormatNum from '_src/utils/FormatNum';
import Tooltip from '_src/component/Tooltip';
import { calc } from '_component/omit';
import { Button } from '_component/Button';
import IconLite from '_src/component/IconLite';
import { toLocale } from '_src/locale/react-locale';
import utils from '../../utils/util';
import Config from '../../constants/Config';
const util = {};
util.tabs = [{ id: 1, label: toLocale('assets_tab_accounts'), }, { id: 2, label: toLocale('assets_tab_transactions'), }];
util.accountsCols = ({ transfer }, { valuationUnit }) => {
// const valuationName = valuationUnit || '--';
return [
{
title: toLocale('assets_column_assets'),
key: 'assetToken',
render: (text, data) => {
const { whole_name, symbol } = data;
console.log(data);
console.log(symbol);
const whole_nameString = whole_name ? ` (${whole_name})` : '';
return (
<div className="symbol-line">
<Tooltip
placement="bottomLeft"
overlayClassName="symbol-tooltip"
overlay={symbol}
maxWidth={400}
noUnderline
>
{text + whole_nameString}
</Tooltip>
</div>
);
}
},
{
title: toLocale('assets_column_total'),
key: 'total',
alignRight: true,
render: (text) => {
return text;
}
},
{
title: toLocale('assets_column_balance'),
key: 'available',
alignRight: true,
render: (text) => {
return calc.showFloorTruncation(text, 8, false);
}
},
// {
// title: toLocale('assets_column_freeze'),
// key: 'freeze',
// alignRight: true,
// render: (text) => {
// return calc.showFloorTruncation(text, 8, false);
// }
// },
{
title: toLocale('assets_column_list'),
key: 'locked',
alignRight: true,
render: (text) => {
return calc.showFloorTruncation(text, 8, false);
}
},
// {
// title: `OMB ${toLocale('valuation')}`,
// key: 'ombValuation',
// alignRight: true,
// render: (text) => {
// return text;
// }
// },
// {
// title: `${valuationName} ${toLocale('valuation')}`,
// key: 'legalValuation',
// alignRight: true,
// render: (text) => {
// return text;
// }
// },
{
title: '',
key: 'transfer',
render: (text, { symbol }) => {
return (
<Button
size={Button.size.mini}
onClick={transfer(symbol)}
>
{toLocale('assets_trans_btn')}
</Button>
);
}
},
];
};
util.transactionsTypes = [
{ value: 1, label: toLocale('trade_type_trans') },
{ value: 2, label: toLocale('trade_type_order') },
{ value: 3, label: toLocale('trade_type_cancle') },
];
const transactionsTypesMap = {};
util.transactionsTypes.forEach(({ value, label }) => {
transactionsTypesMap[value] = label;
});
util.transactionsCols = [
{
title: toLocale('trade_column_hash'),
key: 'txhash',
render: (text) => { // trade-info/
return <a href={`${Config.omchain.browserUrl}/tx/${text}`} target="_blank" rel="noopener noreferrer">{FormatNum.hashShort(text)}</a>;
}
},
{
title: toLocale('trade_column_time'),
key: 'timestamp',
alignRight: true,
render: (text) => {
return moment(Number(`${text}000`)).format('MM-DD HH:mm:ss');
}
},
{
title: toLocale('trade_column_assets'),
alignRight: true,
key: 'symbol',
render: (text) => {
const symbol = (text.indexOf('_') > 0) ? utils.getShortName(text) : utils.getSymbolShortName(text);
return symbol.toUpperCase();
}
},
{
title: toLocale('trade_column_type'),
alignRight: true,
key: 'type',
render: (text) => {
return transactionsTypesMap[text] || '';
}
},
{
title: toLocale('trade_column_direction'),
alignRight: true,
key: 'side',
render: (text, data) => {
const { type } = data;
let sideText = '';
let color = 'primary-green';
if (type === 1) {
if (text === 3) {
color = 'primary-red';
sideText = toLocale('trade_type_pay');
}
if (text === 4) {
sideText = toLocale('trade_type_receive');
}
} else {
if (text === 1) {
sideText = toLocale('trade_type_buy');
}
if (text === 2) {
sideText = toLocale('trade_type_sell');
color = 'primary-red';
}
}
return (
<span className={color}>
{sideText}
</span>
);
}
},
{
title: toLocale('trade_column_amount'),
alignRight: true,
key: 'quantity',
},
{
title: `${toLocale('trade_column_fee')}`,
key: 'fee',
render: (text) => {
return String(text.split('-')[0]).toUpperCase();
}
},
];
export default util;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import { toLocale } from '_src/locale/react-locale';
import Checkbox from 'rc-checkbox';
import Enum from '../utils/Enum';
import * as OrderAction from '../redux/actions/OrderAction';
import Config from '../constants/Config';
function mapStateToProps(state) {
const {
type, entrustType, isHideOthers, isHideOrders
} = state.OrderStore;
return {
type, entrustType, isHideOthers, isHideOrders
};
}
function mapDispatchToProps(dispatch) {
return {
orderAction: bindActionCreators(OrderAction, dispatch),
};
}
const OrderHeaderWrapper = (Component) => {
@connect(mapStateToProps, mapDispatchToProps)
class OrderHeader extends React.Component {
// 改变一级 tab 类型(我的挂单 or 历史委托)
onTabChange = (checkTab) => {
return () => {
const { orderAction } = this.props;
orderAction.resetData();
// if (this.props.type === Enum.order.type.noDeal) {
// orderAction.getNoDealList({ page: 1 });
// }
orderAction.updateType(checkTab);
};
};
// 全部挂单链接
getOrderPageLink = () => {
const { type } = this.props;
let path = 'open';
if (type === Enum.order.type.history) {
path = 'history';
} else if (type === Enum.order.type.detail) {
path = 'deals';
}
return (
<Link
to={path}
className="order-page-link"
>
{toLocale('all')}
</Link>
);
};
// 获取一级表头 tab 数据
getHeaderList = () => {
return [
{ type: Enum.order.type.noDeal, name: toLocale('spot.orders.openOrders') },
{ type: Enum.order.type.history, name: toLocale('spot.orders.orderHistory') },
{ type: Enum.order.type.detail, name: toLocale('spot.myOrder.detail') }
];
};
// 历史委托 切换 "隐藏已撤单"
updateHideCanceledOrders = (e) => {
this.props.orderAction.updateHideOrders(e.target.checked);
};
// 切换"隐藏其他币对"
updateHideOthers = (e) => {
this.props.orderAction.updateHideOthers(e.target.checked);
};
// 渲染"隐藏其他币对"等其他操作
extraOperations = () => {
const { props } = this;
const {
type, isHideOthers, isHideOrders
} = props;
// 只有 未成交 && 普通委托 包含"隐藏其他币对"功能
const { noDeal, history } = Enum.order.type;
if (type === noDeal) {
return (
<div className="hide-others flex-row flex-center fz12">
{this.props.children}
<div className="line-item" />
<label className="cursor-pointer">
<Checkbox
onChange={this.updateHideOthers}
className="content-box"
checked={isHideOthers}
/>
<span className="mar-left8">{toLocale('spot.orders.historyRecord')} </span>
</label>
{/* <div className="line-item" />
<BatchCancelOrder
entrustType={props.entrustType}
symbol={props.symbol}
onCancel={props.orderAction.cancelAll}
disable={!props.hasOrder || !isHideOthers}
/> */}
</div>
);
}
if (type === '') { // history
return (
<div className="hide-others flex-row flex-center fz12">
{this.props.children}
<div className="line-item" />
<label className="cursor-pointer">
<Checkbox
onChange={this.updateHideCanceledOrders}
className="content-box"
checked={isHideOrders}
/>
<span className="mar-left8">{toLocale('spot.orders.historyRescinded')}</span>
</label>
</div>
);
}
return null;
};
render() {
const { type } = this.props;
return (
<Component
type={type}
dataSource={this.getHeaderList()}
onTabChange={this.onTabChange}
orderPageLink={this.getOrderPageLink()}
>
<div className="float-right">
{this.extraOperations()}
</div>
</Component>
);
}
}
return OrderHeader;
};
export default OrderHeaderWrapper;
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { toLocale } from '_src/locale/react-locale';
import { debounce } from 'throttle-debounce';
import URL from '_src/constants/URL';
import { calc } from '_component/omit';
import Checkbox from 'rc-checkbox';
import Icon from '_src/component/IconLite';
import DexTable from '_component/DexTable';
import ont from '../../utils/dataProxy';
import TransferDialog from './TransferDialog';
import assetsUtil from './assetsUtil';
import './Assets.less';
import * as CommonAction from '../../redux/actions/CommonAction';
function mapStateToProps(state) { // 绑定redux中相关state
const {
legalId, legalObj, legalList
} = state.Common;
return {
legalId,
legalObj,
legalList
};
}
function mapDispatchToProps(dispatch) {
return {
commonAction: bindActionCreators(CommonAction, dispatch),
};
}
@connect(mapStateToProps, mapDispatchToProps)
class AssetsAccounts extends Component { /* eslint-disable react/sort-comp, camelcase */
constructor(props) {
super(props);
this.allCurrencies = [];
this.state = {
currencies: [],
tokenList: [],
tokenMap: {},
showTransfer: false,
transferSymbol: '',
loading: false,
ombTotalValuation: '--',
legalTotalValuation: '--',
hideZero: true,
valuationUnit: '--',
};
this.symbolSearch = '';
this.addr = window.OM_GLOBAL.senderAddr;
}
componentDidMount() {
// 初始化omchain客户端。原因是交易页、未成交委托页撤单和资产页转账都需要
this.props.commonAction.initOMChainClient();
document.title = toLocale('assets_tab_accounts') + toLocale('spot.page.title');
if (this.addr) {
this.fetchAccounts();
document.querySelector('.search-symbol').addEventListener('keyup', debounce(250, false, this.filterList));
}
}
fetchAccounts = () => {
this.setState({ loading: true });
// 获取资产
const fetchAccounts = new Promise((resolve) => {
ont.get(`${URL.GET_ACCOUNTS}/${this.addr}`, { params: { show: this.state.hideZero ? undefined : 'all' } }).then(({ data }) => {
const { currencies } = data;
resolve(currencies || []);
}).catch(() => {
resolve([]);
});
});
// 获取所有币种列表
const fetchTokens = new Promise((resolve) => {
ont.get(URL.GET_TOKENS).then(({ data }) => {
const tokenMap = {};
const tokenList = data.map((token) => {
const { symbol, original_symbol, whole_name } = token;
const originalAndWhole = `${original_symbol.toUpperCase()}___${whole_name}`; // 用于计算数量
tokenMap[symbol] = { ...token, originalAndWhole };
return {
value: symbol,
label: <span><span className="symbol-left">{original_symbol.toUpperCase()}</span>{whole_name}</span>,
};
});
this.setState({ tokenList, tokenMap });
resolve(tokenMap);
}).catch(() => {
resolve({});
});
});
Promise.all([fetchAccounts, fetchTokens])
.then(([currencies, tokenMap]) => {
const originalAndWholeCounts = {};
currencies.forEach((curr) => {
const { symbol } = curr;
const tokenObj = tokenMap[symbol] || {};
const { originalAndWhole } = tokenObj;
if (originalAndWhole) {
let count = originalAndWholeCounts[originalAndWhole] || 0;
count++;
originalAndWholeCounts[originalAndWhole] = count;
}
});
this.allCurrencies = currencies.map((curr) => {
const {
symbol, available, freeze, locked
} = curr;
const tokenObj = tokenMap[symbol] || {
original_symbol: '',
};
const { original_symbol, originalAndWhole } = tokenObj; // 兼容旧版币种简称
const symbolUp = symbol.toUpperCase();
const assetToken = (original_symbol || '').toUpperCase() || symbolUp;
const sumOMB = calc.add(calc.add(available || 0, freeze || 0), locked || 0);
return {
...curr,
...tokenObj,
assetToken,
symbolId: originalAndWholeCounts[originalAndWhole] <= 1 ? '' : symbolUp,
total: calc.showFloorTruncation(sumOMB, 8, false), // 资产返回8位,2020-01-10
};
});
this.setState({
currencies: this.allCurrencies
});
}).catch(() => {}).then(() => {
this.setState({ loading: false });
});
};
openTransfer = (symbol) => {
return () => {
this.setState({
transferSymbol: symbol,
showTransfer: true,
});
};
};
closeTransfer = () => {
this.setState({
showTransfer: false,
});
};
transferSuccess = () => {
this.fetchAccounts();
};
filterList = (e) => {
const symbol = e.target.value.trim().toLowerCase();
this.symbolSearch = symbol;
const { legalObj } = this.props;
this.setFilteredList(legalObj);
};
toggleHideZero = (e) => {
this.setState({ hideZero: e.target.checked }, this.fetchAccounts);
};
setFilteredList = (legalObj = {}) => {
let filterList = this.allCurrencies;
const symbol = this.symbolSearch;
if (symbol) {
filterList = this.allCurrencies.filter((c) => {
return (c.assetToken && c.assetToken.toLowerCase().includes(symbol)) ||
(c.whole_name && c.whole_name.toLowerCase().includes(symbol));
});
}
this.setState({
currencies: filterList // list
});
};
render() {
const {
currencies, showTransfer, transferSymbol, loading, tokenList, ombTotalValuation, legalTotalValuation,
tokenMap, hideZero, valuationUnit
} = this.state;
return (
<div>
<div className="query-container">
<div>
<Icon className="icon-enlarge search-symbol-icon" />
<input className="search-symbol" placeholder={toLocale('assets_product_search')} />
<label className="cursor-pointer hide-zero-checkbox">
<Checkbox
onChange={this.toggleHideZero}
className="content-box"
checked={hideZero}
/>
{toLocale('assets_hide_zero')}
</label>
</div>
</div>
<DexTable
isLoading={loading}
columns={assetsUtil.accountsCols({ transfer: this.openTransfer }, { valuationUnit })}
dataSource={currencies}
rowKey="symbol"
hidePage
empty={<p>{toLocale('assets_empty')}</p>}
/>
<TransferDialog
show={showTransfer}
symbol={transferSymbol}
tokenList={tokenList}
tokenMap={tokenMap}
onClose={this.closeTransfer}
onSuccess={this.transferSuccess}
/>
</div>
);
}
}
export default AssetsAccounts;
| 83e0a6a0bfb895ac49930eadeb1b056f8097233e | [
"JavaScript",
"Markdown"
] | 157 | JavaScript | omexapp/omexdex-ui | dd05dbd3d9948325f5542ec8311607c62f8b7fd3 | 56da54a9a069e0c34cb74a81d9337b39c2ef247c |
refs/heads/master | <repo_name>gabrielgpa/import-data-express-sequelize<file_sep>/src/controllers/Customer.js
import CustomerService from '../service/CustomerService';
const Customer = {
/**
* @param {object} req
* @param {object} res
* @returns {void} return statuc code 204
*/
import(req, res) {
const Customer = CustomerService.import(req, res);
return res.status(201).send(Customer);
},
}
export default Customer;<file_sep>/sequelize.js
const Sequelize = require('sequelize');
const CustomerModel = require('./src/models/Customer');
const AddressModel = require('./src//models/Address');
const sequelize = new Sequelize('<scheme>', '<user>', '<password>', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
},
logging: false
});
const Customer = CustomerModel(sequelize, Sequelize);
const Address = AddressModel(sequelize, Sequelize);
Customer.belongsTo(Address, { foreignKey: 'ADDRESS_ID', onCreate: 'CASCADE' });
sequelize.sync({ force: false })
.then(() => {
console.log(`Database & tables created!`)
}, (err) => {
console.log(`Error => ${err}`)
});
module.exports = { Customer, Address }<file_sep>/src/models/Address.js
module.exports = (sequelize, type) => {
return sequelize.define('ADDRESS', {
ID: {
type: type.INTEGER,
primaryKey: true,
autoIncrement: true
},
ZIP_CODE: type.STRING,
STREET: type.STRING,
NUMBER: type.STRING,
SUPPLEMENT: type.STRING,
STATE: type.STRING,
CITY: type.STRING
}, {
freezeTableName: true,
timestamps: false
});
}<file_sep>/README.md
# import-data-express-sequelize
Simple api to import data from csv using express + sequelize
### Steps
```
npm install
npm run build
npm run dev
```
| 556a4855bf896a3c4c835d1df5d83e8ae6185f19 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | gabrielgpa/import-data-express-sequelize | 9e16c4b0417580c4e25a3ead9a433626b42cd740 | d305cf04c1994601c600b7e766cdd9d64ffec689 |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: thesk
* Date: 30.03.2019
* Time: 11:39
*/ | c18be4f3eea7d9fe5ba3f0fec2906401de334cb7 | [
"PHP"
] | 1 | PHP | onyxiris/film-site-hevs | 2ecf4d22d946cba2b396add7820ff7698f5a6b83 | a122d7ddbf40763ece1b32b59b2b3298f23d786b |
refs/heads/master | <repo_name>ballen101/dlhr-09-22<file_sep>/src/com/corsair/server/util/DownloadsFilesInfo.java
package com.corsair.server.util;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.corsair.server.base.ConstsSw;
public class DownloadsFilesInfo {
// private String FilePath = "";
//
// public String getDownLoadsFilesInfoXML(String XMLStr) {
// FilePath = ConstsSw._root_filepath + "downloads";
// // FilePath = "C:\\Downloads";
// return getFilesInfoXML(FilePath);
// }
//
// public String getFilesInfoXML(String strPath) {
// ArrayList<String[]> filelist = new ArrayList<String[]>();
// String FileInft[] = new String[3];
// FileInft[0] = "filename";
// FileInft[1] = "filesize";
// FileInft[2] = "lastupdate";
// filelist.add(FileInft);
// getFilesInfo(strPath, filelist);
// return generateListXML(filelist);
// }
//
// private void getFilesInfo(String strPath, ArrayList<String[]> filelist) {
// File dir = new File(strPath);
// File[] files = dir.listFiles();
//
// if (files == null)
// return;
// for (int i = 0; i < files.length; i++) {
// if (files[i].isDirectory()) {
// getFilesInfo(files[i].getAbsolutePath(), filelist);
// } else {
// String FileInft[] = new String[3];
// String strFileName = files[i].getAbsolutePath();
// String strSize = String.valueOf(files[i].length());
// Date dt = new Date(files[i].lastModified());
// SimpleDateFormat df = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss"); // 设置日期格式
// String lastUpdate = df.format(dt);
//
// strFileName = strFileName.substring(FilePath.length());
//
// FileInft[0] = strFileName;
// FileInft[1] = strSize;
// FileInft[2] = lastUpdate;
//
// filelist.add(FileInft);
// }
// }
// }
//
// public String generateListXML(final ArrayList<String[]> flist) {
// String result = null;
// if (flist.isEmpty())
// return result;
// Document document = DocumentHelper.createDocument();
// Element root = document.addElement(ConstsSw.xml_root_corsair);// 创建根节点
// Element meta_root = root.addElement(ConstsSw.xml_data_metadata);
// Element data_root = root.addElement(ConstsSw.xml_data_data);
// Element field;
// Element data;
// Element row;
//
// String fino[] = flist.get(0);
// for (int i = 0; i < fino.length; i++) {
// field = meta_root.addElement(ConstsSw.xml_field);
// data = field.addElement(ConstsSw.xml_field_name);
// data.setText(fino[i]);
//
// data = field.addElement(ConstsSw.xml_field_type);
// data.setText("1");
//
// data = field.addElement(ConstsSw.xml_field_size);
// data.setText("1024");
// }
//
// int id = 0;
// for (int i = 1; i < flist.size(); i++) {
// row = data_root.addElement(ConstsSw.xml_row);
// row.setText(String.valueOf(++id));
// fino = flist.get(i);
// for (int j = 0; j < fino.length; j++) {
// data = row.addElement(ConstsSw.xml_field_value);
// data.setText(fino[j]);
// }
// }
// result = document.asXML();
// return result;
// }
}
<file_sep>/src/com/hr/util/DateUtil.java
package com.hr.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.corsair.dbpool.util.Systemdate;
public class DateUtil {
/*
* 把MM/dd/yyyy转成yyyy/MM/dd
*/
public static String DateParseYYYYMMDD(String d1) throws ParseException{
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(d1);//有异常要捕获
format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(date);
}
/**
* 获取当前月的第一天
* @return
*/
public static String getFirstDayOfMonth(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String firstday;
// 获取当前月的第一天
Calendar cale = Calendar.getInstance();
cale.add(Calendar.MONTH, 0);
cale.set(Calendar.DAY_OF_MONTH, 1);
firstday = format.format(cale.getTime());
return firstday;
}
/**
* 获取当前月的第一天
* @return
*/
public static String getFirstDayOfMonth(String yerDateString){
Date yerDates =Systemdate.getDateByyyyy_mm_dd(yerDateString);
Calendar cal = Calendar.getInstance();
cal.setTime(yerDates);
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH) + 1;
String firstday=year+"-"+month+"-1";
return firstday;
}
/**
* 获取当前月的最后一天
* @return
*/
public static String getLastDayOfMonth(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String lastday;
Calendar cale = Calendar.getInstance();
cale.add(Calendar.MONTH, 1);
cale.set(Calendar.DAY_OF_MONTH, 0);
lastday = format.format(cale.getTime());
return lastday;
}
/**
* 获取当前日期
* @return
*/
public static String getNowDate(){
String now;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
now = format.format(d);
return now;
}
/**
* 获取昨天日期
* @return
*/
public static String getYerDate(){
String yer;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.add(Calendar.DATE,-1);
Date d=cal.getTime();
yer=format.format(d);
return yer;
}
public static long getBetweenDays(Date dateStart,Date dateEnd) throws ParseException{
// 获取日期
Date date1 =Systemdate.getDateYYYYMMDD(dateStart);
Date date2 = Systemdate.getDateYYYYMMDD(dateEnd);
// 获取相差的天数
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
long timeInMillis1 = calendar.getTimeInMillis();
calendar.setTime(date2);
long timeInMillis2 = calendar.getTimeInMillis();
long betweenDays = (timeInMillis2 - timeInMillis1) / (1000L*3600L*24L);
return betweenDays;
}
public static void main(String[] args) {
}
}
<file_sep>/src/com/hr/canteen/entity/Hr_canteen_mealcharge.java
package com.hr.canteen.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_canteen_mealcharge extends CJPA {
@CFieldinfo(fieldname="ctmc_id",iskey=true,notnull=true,caption="餐标ID",datetype=Types.INTEGER)
public CField ctmc_id; //餐标ID
@CFieldinfo(fieldname="ctmc_code",codeid=103,notnull=true,caption="餐标编码",datetype=Types.VARCHAR)
public CField ctmc_code; //餐标编码
@CFieldinfo(fieldname="ctmc_name",notnull=true,caption="餐标名称",datetype=Types.VARCHAR)
public CField ctmc_name; //餐标名称
@CFieldinfo(fieldname="price",caption="餐标",datetype=Types.DECIMAL)
public CField price; //餐标
@CFieldinfo(fieldname="subsidies",caption="补贴金额",datetype=Types.DECIMAL)
public CField subsidies; //补贴金额
@CFieldinfo(fieldname="cost",caption="自费金额",datetype=Types.DECIMAL)
public CField cost; //自费金额
@CFieldinfo(fieldname="mc_id",notnull=true,caption="餐类ID",datetype=Types.INTEGER)
public CField mc_id; //餐类ID
@CFieldinfo(fieldname="mc_name",notnull=true,caption="餐类名称",datetype=Types.VARCHAR)
public CField mc_name; //餐类名称
@CFieldinfo(fieldname="mealbegin",caption="用餐开始时间",datetype=Types.VARCHAR)
public CField mealbegin; //用餐开始时间
@CFieldinfo(fieldname="mealend",caption="用餐结束时间",datetype=Types.VARCHAR)
public CField mealend; //用餐结束时间
@CFieldinfo(fieldname="sublimit",caption="每月补贴餐数上限",datetype=Types.INTEGER)
public CField sublimit; //每月补贴餐数上限
@CFieldinfo(fieldname="orgid",notnull=true,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="lv_id",caption="职级ID",datetype=Types.INTEGER)
public CField lv_id; //职级ID
@CFieldinfo(fieldname="lv_num",caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="emplev",caption="人事层级",datetype=Types.INTEGER)
public CField emplev; //人事层级
@CFieldinfo(fieldname="costtype",caption="消费类型",datetype=Types.INTEGER)
public CField costtype; //消费类型
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname="wfid",caption="wfid",datetype=Types.INTEGER)
public CField wfid; //wfid
@CFieldinfo(fieldname="attid",caption="attid",datetype=Types.INTEGER)
public CField attid; //attid
@CFieldinfo(fieldname="stat",notnull=true,caption="流程状态",datetype=Types.INTEGER)
public CField stat; //流程状态
@CFieldinfo(fieldname="idpath",notnull=true,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="entid",notnull=true,caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname="creator",notnull=true,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname="createtime",notnull=true,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="updator",caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname="updatetime",caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
@CFieldinfo(fieldname="attribute1",caption="备用字段1",datetype=Types.VARCHAR)
public CField attribute1; //备用字段1
@CFieldinfo(fieldname="attribute2",caption="备用字段2",datetype=Types.VARCHAR)
public CField attribute2; //备用字段2
@CFieldinfo(fieldname="attribute3",caption="备用字段3",datetype=Types.VARCHAR)
public CField attribute3; //备用字段3
@CFieldinfo(fieldname="attribute4",caption="备用字段4",datetype=Types.VARCHAR)
public CField attribute4; //备用字段4
@CFieldinfo(fieldname="attribute5",caption="备用字段5",datetype=Types.VARCHAR)
public CField attribute5; //备用字段5
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_canteen_mealcharge() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/dc/dc108a5277811fea801ce7d047567ad873e0c2d2.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.hr.perm.ctr.CtrHr_employee_linked;
@CEntity(tablename = "hr_employee", controller = CtrHr_employee_linked.class)
public class Hr_employee_linked extends Hr_employee {
@CLinkFieldInfo(jpaclass = Hr_employee_work.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_work> hr_employee_works;
@CLinkFieldInfo(jpaclass = Hr_employee_reward.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_reward> hr_employee_rewards;
//@CLinkFieldInfo(jpaclass = Hr_employee_relation.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
//public CJPALineData<Hr_employee_relation> hr_employee_relations;
@CLinkFieldInfo(jpaclass = Hr_employee_phexa.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_phexa> hr_employee_phexas;
@CLinkFieldInfo(jpaclass = Hr_employee_leanexp.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_leanexp> hr_employee_leanexps;
@CLinkFieldInfo(jpaclass = Hr_employee_family.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_family> hr_employee_familys;
@CLinkFieldInfo(jpaclass = Hr_employee_cretl.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_cretl> hr_employee_cretls;
@CLinkFieldInfo(jpaclass = Hr_employee_trainexp.class, linkFields = { @LinkFieldItem(lfield = "er_id", mfield = "er_id") })
public CJPALineData<Hr_employee_trainexp> hr_employee_trainexps;
public Hr_employee_linked() throws Exception {
super();
// TODO Auto-generated constructor stub
}
}
<file_sep>/src/com/hr/perm/entity/Hr_entry.java
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import com.hr.perm.ctr.CtrHr_entry;
import java.sql.Types;
@CEntity(controller = CtrHr_entry.class)
public class Hr_entry extends CJPA {
@CFieldinfo(fieldname = "entry_id", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField entry_id; // ID
@CFieldinfo(fieldname = "entry_code", codeid = 58, notnull = true, caption = "入职表单编码", datetype = Types.VARCHAR)
public CField entry_code; // 入职表单编码
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "人事档案ID", datetype = Types.INTEGER)
public CField er_id; // 人事档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "entrytype", notnull = true, caption = "入职类型 新招 重聘", datetype = Types.INTEGER)
public CField entrytype; // 入职类型 新招 重聘
@CFieldinfo(fieldname = "entrysourcr", notnull = true, caption = "人员来源 社会招聘/校园招聘/其它", datetype = Types.INTEGER)
public CField entrysourcr; // 人员来源 社会招聘/校园招聘/其它
@CFieldinfo(fieldname = "entrydate", caption = "入职日期", datetype = Types.TIMESTAMP)
public CField entrydate; // 入职日期
@CFieldinfo(fieldname = "probation", caption = "试用期", datetype = Types.INTEGER)
public CField probation; // 试用期
@CFieldinfo(fieldname = "promotionday", caption = "转正日期", datetype = Types.TIMESTAMP)
public CField promotionday; // 转正日期
@CFieldinfo(fieldname = "ispromotioned", caption = "已转正", datetype = Types.INTEGER)
public CField ispromotioned; // 已转正
@CFieldinfo(fieldname = "quota_over", caption = "是否超编", datetype = Types.INTEGER)
public CField quota_over; // 是否超编
@CFieldinfo(fieldname = "quota_over_rst", caption = "超编审批结果 1 允许增加编制入职 ps是否自动生成编制调整单 2 超编入职 3 不允许入职", datetype = Types.INTEGER)
public CField quota_over_rst; // 超编审批结果 1 允许增加编制入职 ps是否自动生成编制调整单 2 超编入职 3
// 不允许入职
@CFieldinfo(fieldname = "orgid", caption = "入职机构ID", datetype = Types.INTEGER)
public CField orgid; // 入职机构ID
@CFieldinfo(fieldname = "orghrlev", notnull = true, caption = "机构人事层级", datetype = Types.INTEGER)
public CField orghrlev; // 机构人事层级
@CFieldinfo(fieldname = "ospid", precision = 10, scale = 0, caption = "入职职位", datetype = Types.INTEGER)
public CField ospid; // 入职职位
@CFieldinfo(fieldname = "lv_num", caption = "入职职级", datetype = Types.DECIMAL)
public CField lv_num; // 入职职级
@CFieldinfo(fieldname = "rectname", caption = "招聘人", datetype = Types.VARCHAR)
public CField rectname; // 招聘人
@CFieldinfo(fieldname = "rectcode", caption = "招聘人工号", datetype = Types.VARCHAR)
public CField rectcode; // 招聘人工号
@CFieldinfo(fieldname = "quachk", caption = "资格比对 合格不合格", datetype = Types.INTEGER)
public CField quachk; // 资格比对 合格不合格
@CFieldinfo(fieldname = "quachknote", caption = "资格比对备注", datetype = Types.VARCHAR)
public CField quachknote; // 资格比对备注
@CFieldinfo(fieldname = "iview", caption = "面试 合格不合格", datetype = Types.INTEGER)
public CField iview; // 面试 合格不合格
@CFieldinfo(fieldname = "iviewnote", caption = "面试 备注", datetype = Types.VARCHAR)
public CField iviewnote; // 面试 备注
@CFieldinfo(fieldname = "forunit", caption = "应聘单位", datetype = Types.VARCHAR)
public CField forunit; // 应聘单位
@CFieldinfo(fieldname = "forunitnote", caption = "应聘单位备注", datetype = Types.VARCHAR)
public CField forunitnote; // 应聘单位备注
@CFieldinfo(fieldname = "cercheck", caption = "证件检查 合格 不合格", datetype = Types.INTEGER)
public CField cercheck; // 证件检查 合格 不合格
@CFieldinfo(fieldname = "cerchecknote", caption = "证件检查备注", datetype = Types.VARCHAR)
public CField cerchecknote; // 证件检查备注
@CFieldinfo(fieldname = "wtexam", caption = "笔试 合格不合格", datetype = Types.INTEGER)
public CField wtexam; // 笔试 合格不合格
@CFieldinfo(fieldname = "wtexamnote", caption = "笔试备注", datetype = Types.VARCHAR)
public CField wtexamnote; // 笔试备注
@CFieldinfo(fieldname = "transorg", caption = "输送机构", datetype = Types.VARCHAR)
public CField transorg; // 输送机构
@CFieldinfo(fieldname = "transorgnote", caption = "输送机构备注", datetype = Types.VARCHAR)
public CField transorgnote; // 输送机构备注
@CFieldinfo(fieldname = "formchk", caption = "形体检查 合格不合格", datetype = Types.INTEGER)
public CField formchk; // 形体检查 合格不合格
@CFieldinfo(fieldname = "formchknote", caption = "形体检查备注", datetype = Types.VARCHAR)
public CField formchknote; // 形体检查备注
@CFieldinfo(fieldname = "train", caption = "培训合格不合格", datetype = Types.INTEGER)
public CField train; // 培训合格不合格
@CFieldinfo(fieldname = "trainnote", caption = "培训备注", datetype = Types.VARCHAR)
public CField trainnote; // 培训备注
@CFieldinfo(fieldname = "transextime", caption = "输送期限", datetype = Types.VARCHAR)
public CField transextime; // 输送期限
@CFieldinfo(fieldname = "transextimenote", caption = "输送期限备注", datetype = Types.VARCHAR)
public CField transextimenote; // 输送期限备注
@CFieldinfo(fieldname = "tetype", caption = "人员类型 劳务工、临时工、正式工", datetype = Types.INTEGER)
public CField tetype; // 人员类型 劳务工、临时工、正式工
@CFieldinfo(fieldname = "tetypenote", caption = "人员类型备注", datetype = Types.VARCHAR)
public CField tetypenote; // 人员类型备注
@CFieldinfo(fieldname = "meexam", caption = "体检 合格不合格", datetype = Types.INTEGER)
public CField meexam; // 体检 合格不合格
@CFieldinfo(fieldname = "meexamnote", caption = "体检备注", datetype = Types.VARCHAR)
public CField meexamnote; // 体检备注
@CFieldinfo(fieldname = "dispunit", caption = "派遣机构", datetype = Types.VARCHAR)
public CField dispunit; // 派遣机构
@CFieldinfo(fieldname = "dispunitnote", caption = "派遣机构说明", datetype = Types.VARCHAR)
public CField dispunitnote; // 派遣机构说明
@CFieldinfo(fieldname = "ovtype", caption = "加班类型 有 无", datetype = Types.INTEGER)
public CField ovtype; // 加班类型 有 无
@CFieldinfo(fieldname = "ovtypenote", caption = "加班类型说明", datetype = Types.VARCHAR)
public CField ovtypenote; // 加班类型说明
@CFieldinfo(fieldname = "rcenl", caption = "招聘渠道", datetype = Types.VARCHAR)
public CField rcenl; // 招聘渠道
@CFieldinfo(fieldname = "rcenlnote", caption = "招聘渠道说明", datetype = Types.VARCHAR)
public CField rcenlnote; // 招聘渠道说明
@CFieldinfo(fieldname = "dispeextime", caption = "派遣期限", datetype = Types.VARCHAR)
public CField dispeextime; // 派遣期限
@CFieldinfo(fieldname = "dispeextimenote", caption = "派遣期限说明", datetype = Types.VARCHAR)
public CField dispeextimenote; // 派遣期限说明
@CFieldinfo(fieldname = "chkok", caption = "验证合格", datetype = Types.INTEGER)
public CField chkok; // 验证合格
@CFieldinfo(fieldname = "chkigmsg", caption = "验证不合格原因", datetype = Types.VARCHAR)
public CField chkigmsg; // 验证不合格原因
@CFieldinfo(fieldname = "salarydate", caption = "核薪生效日期", datetype = Types.DATE)
public CField salarydate; // 核薪生效日期
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "stru_id", precision = 10, scale = 0, caption = "工资结构ID", datetype = Types.INTEGER)
public CField stru_id; // 工资结构ID
@CFieldinfo(fieldname = "stru_name", precision = 32, scale = 0, caption = "工资结构名", datetype = Types.VARCHAR)
public CField stru_name; // 工资结构名
@CFieldinfo(fieldname = "position_salary", precision = 10, scale = 2, caption = "职位工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField position_salary; // 职位工资
@CFieldinfo(fieldname = "base_salary", precision = 10, scale = 2, caption = "基本工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField base_salary; // 基本工资
@CFieldinfo(fieldname = "tech_salary", precision = 10, scale = 2, caption = "技能工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField tech_salary; // 技能工资
@CFieldinfo(fieldname = "achi_salary", precision = 10, scale = 2, caption = "绩效工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField achi_salary; // 绩效工资
@CFieldinfo(fieldname = "otwage", precision = 10, scale = 2, caption = "固定加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField otwage; // 固定加班工资
@CFieldinfo(fieldname = "tech_allowance", precision = 10, scale = 2, caption = "技术津贴", defvalue = "0.00", datetype = Types.DECIMAL)
public CField tech_allowance; // 技术津贴
@CFieldinfo(fieldname = "postsubs", precision = 10, scale = 2, caption = "岗位津贴", defvalue = "0.00", datetype = Types.DECIMAL)
public CField postsubs; // 岗位津贴
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", notnull = true, caption = "流程状态", datetype = Types.INTEGER)
public CField stat; // 流程状态
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1 记录自动转正信息
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
@CFieldinfo(fieldname = "pay_way", caption = "计薪方式", datetype = Types.VARCHAR)
public CField pay_way; // 计薪方式
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;
public Hr_entry() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/perm/entity/Hr_traintran_batchline.java
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_traintran_batchline extends CJPA {
@CFieldinfo(fieldname = "ttranbl_id", iskey = true, notnull = true, caption = "批入行ID", datetype = Types.INTEGER)
public CField ttranbl_id; // 批入行ID
@CFieldinfo(fieldname = "ttranb_id", notnull = true, caption = "批入ID", datetype = Types.INTEGER)
public CField ttranb_id; // 批入ID
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "人事档案ID", datetype = Types.INTEGER)
public CField er_id; // 人事档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "sex", notnull = true, caption = "性别", datetype = Types.INTEGER)
public CField sex; // 性别
@CFieldinfo(fieldname = "id_number", notnull = true, caption = "身份证号", datetype = Types.VARCHAR)
public CField id_number; // 身份证号
@CFieldinfo(fieldname = "employee_name", notnull = true, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "degree", caption = "学历", datetype = Types.INTEGER)
public CField degree; // 学历
@CFieldinfo(fieldname = "hiredday", notnull = true, caption = "入职日期", datetype = Types.TIMESTAMP)
public CField hiredday; // 入职日期
@CFieldinfo(fieldname = "enddatetry", notnull = true, caption = "试用到期日期", datetype = Types.TIMESTAMP)
public CField enddatetry; // 试用到期日期
@CFieldinfo(fieldname = "jxdatetry", notnull = true, caption = "见习到期日期", datetype = Types.TIMESTAMP)
public CField jxdatetry; // 见习到期日期
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "部门名称", datetype = Types.VARCHAR)
public CField orgname; // 部门名称
@CFieldinfo(fieldname = "ospid", notnull = true, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称
@CFieldinfo(fieldname = "hg_name", caption = "职等", datetype = Types.VARCHAR)
public CField hg_name; // 职等
@CFieldinfo(fieldname = "lv_num", caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "norgid", caption = "拟用人部门ID", datetype = Types.INTEGER)
public CField norgid; // 拟用人部门ID
@CFieldinfo(fieldname = "norgname", caption = "拟用人部门名称", datetype = Types.VARCHAR)
public CField norgname; // 拟用人部门名称
@CFieldinfo(fieldname = "nospid", caption = "拟职位ID", datetype = Types.INTEGER)
public CField nospid; // 拟职位ID
@CFieldinfo(fieldname = "nsp_name", caption = "拟职位名称", datetype = Types.VARCHAR)
public CField nsp_name; // 拟职位名称
@CFieldinfo(fieldname = "exam_title", caption = "考试课题", datetype = Types.VARCHAR)
public CField exam_title; // 考试课题
@CFieldinfo(fieldname = "exam_time", caption = "考试时间", datetype = Types.TIMESTAMP)
public CField exam_time; // 考试时间
@CFieldinfo(fieldname = "exam_score", caption = "考试分数", datetype = Types.DECIMAL)
public CField exam_score; // 考试分数
@CFieldinfo(fieldname = "psalary", caption = "转正前薪资", datetype = Types.DECIMAL)
public CField psalary; // 转正前薪资
@CFieldinfo(fieldname = "nsalary", caption = "转正后薪资", datetype = Types.DECIMAL)
public CField nsalary; // 转正后薪资
@CFieldinfo(fieldname = "sypj", caption = "试用期评价", datetype = Types.VARCHAR)
public CField sypj; // 试用期评价
@CFieldinfo(fieldname = "wfresult", caption = "评审结果1 通过 2 没通过", datetype = Types.INTEGER)
public CField wfresult; // 评审结果1 通过 2 没通过
@CFieldinfo(fieldname ="oldstru_id",precision=10,scale=0,caption="转正前工资结构ID",datetype=Types.INTEGER)
public CField oldstru_id; //转正前工资结构ID
@CFieldinfo(fieldname ="oldstru_name",precision=32,scale=0,caption="转正前工资结构名",datetype=Types.VARCHAR)
public CField oldstru_name; //转正前工资结构名
@CFieldinfo(fieldname ="oldposition_salary",precision=10,scale=2,caption="转正前职位工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldposition_salary; //转正前职位工资
@CFieldinfo(fieldname ="oldbase_salary",precision=10,scale=2,caption="转正前基本工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldbase_salary; //转正前基本工资
@CFieldinfo(fieldname ="oldtech_salary",precision=10,scale=2,caption="转正前技能工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldtech_salary; //转正前技能工资
@CFieldinfo(fieldname ="oldachi_salary",precision=10,scale=2,caption="转正前绩效工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldachi_salary; //转正前绩效工资
@CFieldinfo(fieldname ="oldotwage",precision=10,scale=2,caption="转正前固定加班工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldotwage; //转正前固定加班工资
@CFieldinfo(fieldname ="oldtech_allowance",precision=10,scale=2,caption="转正前技术津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldtech_allowance; //转正前技术津贴
@CFieldinfo(fieldname ="oldpostsubs",precision=10,scale=2,caption="转正前岗位津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldpostsubs; //转正前岗位津贴
@CFieldinfo(fieldname ="newstru_id",precision=10,scale=0,caption="转正后工资结构ID",datetype=Types.INTEGER)
public CField newstru_id; //转正后工资结构ID
@CFieldinfo(fieldname ="newstru_name",precision=32,scale=0,caption="转正后工资结构名",datetype=Types.VARCHAR)
public CField newstru_name; //转正后工资结构名
@CFieldinfo(fieldname ="newposition_salary",precision=10,scale=2,caption="转正后职位工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newposition_salary; //转正后职位工资
@CFieldinfo(fieldname ="newbase_salary",precision=10,scale=2,caption="转正后基本工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newbase_salary; //转正后基本工资
@CFieldinfo(fieldname ="newtech_salary",precision=10,scale=2,caption="转正后技能工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newtech_salary; //转正后技能工资
@CFieldinfo(fieldname ="newachi_salary",precision=10,scale=2,caption="转正后绩效工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newachi_salary; //转正后绩效工资
@CFieldinfo(fieldname ="newotwage",precision=10,scale=2,caption="转正后固定加班工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newotwage; //转正后固定加班工资
@CFieldinfo(fieldname ="newtech_allowance",precision=10,scale=2,caption="转正后技术津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField newtech_allowance; //转正后技术津贴
@CFieldinfo(fieldname ="newpostsubs",precision=10,scale=2,caption="转正后岗位津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField newpostsubs; //转正后岗位津贴
@CFieldinfo(fieldname ="oldchecklev",precision=2,scale=0,caption="调薪前绩效考核层级",datetype=Types.INTEGER)
public CField oldchecklev; //调薪前绩效考核层级
@CFieldinfo(fieldname ="oldattendtype",precision=32,scale=0,caption="调薪前出勤类别",datetype=Types.VARCHAR)
public CField oldattendtype; //调薪前出勤类别
@CFieldinfo(fieldname ="newchecklev",precision=2,scale=0,caption="调薪后绩效考核层级",datetype=Types.INTEGER)
public CField newchecklev; //调薪后绩效考核层级
@CFieldinfo(fieldname ="newattendtype",precision=32,scale=0,caption="调薪后出勤类别",defvalue="0",datetype=Types.VARCHAR)
public CField newattendtype; //调薪后出勤类别
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_traintran_batchline() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/generic/Shwposition.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwposition extends CJPA {
@CFieldinfo(fieldname = "positionid", iskey = true, notnull = true, datetype = Types.FLOAT)
public CField positionid; // ID
@CFieldinfo(fieldname = "qty", datetype = Types.FLOAT)
public CField qty; // 数量
@CFieldinfo(fieldname = "superposition", datetype = Types.VARCHAR)
public CField superposition; // 上级岗位
@CFieldinfo(fieldname = "lowerposition", datetype = Types.VARCHAR)
public CField lowerposition; // 下级岗位
@CFieldinfo(fieldname = "innercontact", datetype = Types.VARCHAR)
public CField innercontact; // 内部联系人
@CFieldinfo(fieldname = "outercontact", datetype = Types.VARCHAR)
public CField outercontact; // 外部联系人
@CFieldinfo(fieldname = "positiondesc", datetype = Types.VARCHAR)
public CField positiondesc; // 岗位说明
@CFieldinfo(fieldname = "sex", datetype = Types.FLOAT)
public CField sex; // 性别
@CFieldinfo(fieldname = "age", datetype = Types.FLOAT)
public CField age; // 年龄
@CFieldinfo(fieldname = "experience", datetype = Types.VARCHAR)
public CField experience; //
@CFieldinfo(fieldname = "degree", datetype = Types.VARCHAR)
public CField degree; // 学历
@CFieldinfo(fieldname = "specialty", datetype = Types.VARCHAR)
public CField specialty; //
@CFieldinfo(fieldname = "lang", datetype = Types.VARCHAR)
public CField lang; // 语言
@CFieldinfo(fieldname = "mustreq", datetype = Types.VARCHAR)
public CField mustreq; //
@CFieldinfo(fieldname = "specialreq", datetype = Types.VARCHAR)
public CField specialreq; //
@CFieldinfo(fieldname = "duty", datetype = Types.VARCHAR)
public CField duty; // 职责
@CFieldinfo(fieldname = "isvisible", datetype = Types.FLOAT)
public CField isvisible; //
@CFieldinfo(fieldname = "rposition", datetype = Types.VARCHAR)
public CField rposition; //
@CFieldinfo(fieldname = "code", datetype = Types.VARCHAR)
public CField code; //
@CFieldinfo(fieldname = "creator", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "orgid", datetype = Types.FLOAT)
public CField orgid; //
@CFieldinfo(fieldname = "dutyclas", datetype = Types.VARCHAR)
public CField dutyclas; //
@CFieldinfo(fieldname = "dutykindid", datetype = Types.FLOAT)
public CField dutykindid; //
@CFieldinfo(fieldname = "dutygrade", datetype = Types.VARCHAR)
public CField dutygrade; //
@CFieldinfo(fieldname = "dutyaim", datetype = Types.VARCHAR)
public CField dutyaim; //
@CFieldinfo(fieldname = "certificate", datetype = Types.VARCHAR)
public CField certificate; //
@CFieldinfo(fieldname = "entid", notnull = true, datetype = Types.INTEGER)
public CField entid; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwposition() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/WebContent/webapp/js/common/docorg.js
/**
* Created by shangwen on 2016/3/1.
*/
var MENU_POP_TYPE = {
Folder: 1,
FileDiv: 2,
FileItem: 3
};
var ACTION_COPY_CUT_TYPE = {
Copy: 1,
Cut: 2
};
var cur_files = [];
var selected_files = [];
var cur_menu_pop_type = 0;
var files_cur_folder = undefined;//当前文件列 所属文件夹
//cporct:复制还是剪切 dfdrid 目标文件夹id
var cpOrctInfo = {
inpaste: false,
rfdrid: undefined,//如果是剪切 剪切后需要刷新的文件夹
cporct: undefined,//复制还是剪切
sinfo: undefined,//复制的文件和文件夹
dfdrid: undefined//目标文件夹id
};
function clearPaste() {
cpOrctInfo.inpaste = false;
cpOrctInfo.rfdrid = undefined;
cpOrctInfo.cporct = undefined;
cpOrctInfo.sinfo = undefined;
cpOrctInfo.dfdrid = undefined;
}
F_M_T = {
REFRESH: "刷新",
DOWONLOAD: "下载",
UPLOAD: "上传",
COPY: "复制",
CUT: "剪切",
PASTE: "粘贴",
RENAME: "重命名",
DEL: "删除",
NEW: "新建",
SAHRE: "共享",
ACL: "权限",
TEST: "测试",
PROPERTY: "属性"
};
var FOLDER_MENU_DATA = [
//{iconCls: "", text: F_M_T.TEST, onclick: dotest},
{iconCls: "icon-reload", text: F_M_T.REFRESH, onclick: doRefreshMenuClick},
{separator: true},
{iconCls: "", text: F_M_T.NEW, onclick: newFolder},
{iconCls: "icon-ml_upload", text: F_M_T.UPLOAD, onclick: uploadfiles},
{iconCls: "", text: F_M_T.RENAME, onclick: doRenameClick},
{separator: true},
{iconCls: "icon-ml_download", text: F_M_T.DOWONLOAD, onclick: doDownLoadClick},
{separator: true},
{iconCls: "icon-copy", text: F_M_T.COPY, onclick: doCopyClick},
{iconCls: "icon-cut", text: F_M_T.CUT, onclick: doCutClick},
{iconCls: "icon-paste", text: F_M_T.PASTE, onclick: doPasteClick},
{iconCls: "icon-ml_del", text: F_M_T.DEL, onclick: doRemoveClick},
//{separator: true},
//{iconCls: "", text: F_M_T.SAHRE},
{separator: true},
{iconCls: "", text: F_M_T.ACL, onclick: getFolderAcl},
{iconCls: "icon-ml_detail", text: F_M_T.PROPERTY, onclick: getFolderAttr}
];
function setFolderMenuAllDisable() {
$.each(F_M_T, function () {
var item = $("#foldermenu").menu("findItem", this);
if (item)
$('#foldermenu').menu('disableItem', item.target);
});
}
function setFolderMenuEanble(t) {
var item = $("#foldermenu").menu("findItem", t);
if (item)
$('#foldermenu').menu('enableItem', item.target);
}
var SACL = {ADMIN: 0, WD: 1, W: 2, D: 3, R: 4, ROUTE: 5, REJECT: 6, EMPTY: 7};
function closes() {
closed = true;
$("#loading").fadeOut("normal", function () {
$(this).remove();
});
}
var pc;
var closed = false;
$.parser.auto = false;
$.parser.onComplete = function () {
if (pc) clearTimeout(pc);
pc = setTimeout(closes, 1000);
};
$().ready(function () {
$.parser.parse();
setTimeout(function () {
if (!closed)
closes();
}, 3000);
initGrids();
initfldtree();
initFolderMenu();
initOrgUsers();
initFileDivMenu();
});
var startX = 0;
var startY = 0;
var moveflag = false;
var mouseDownAndUpTimer = null;
var onMouseDownFlag = false;
function initFileDivMenu() {
$("#filediv").bind('contextmenu', function (e) {
e.preventDefault();
onFileDivMenu(e);
}).mousedown(function (e) {
e.preventDefault();
e.stopPropagation();
onMouseDownFlag = false;
mouseDownAndUpTimer = setTimeout(function () {
//down
$(".mouseSelect").css("width", "0px");
$(".mouseSelect").css("height", "0px");
$(".mouseSelect").css("display", "block");
var offtp = $('#filediv').offset().top;
var offleft = $('#filediv').offset().left;
startX = e.pageX - offleft;// (e.originalEvent.x || e.originalEvent.layerX || 0);
startY = e.pageY;// (e.originalEvent.y || e.originalEvent.layerY || 0) + offtp;
$(".mouseSelect").css("left", startX + "px");
$(".mouseSelect").css("top", startY + "px");
moveflag = true;
onMouseDownFlag = true;
}, 200);
}).mouseup(function (e) {
e.preventDefault();
e.stopPropagation();
moveflag = false;
$(".mouseSelect").css("display", "none");
if (onMouseDownFlag) {
//up
// $(".mouseSelect").css("display", "none");
} else {
//click
selected_files = [];
resetActiveFiles();
clearTimeout(mouseDownAndUpTimer); // 清除延迟时间
}
}).mousemove(function (e) {
e.preventDefault();
e.stopPropagation();
if (moveflag) {
var offtp = $('#filediv').offset().top;
var offleft = $('#filediv').offset().left;
var endX = e.pageX - offleft;// (e.originalEvent.x || e.originalEvent.layerX || 0);
var endY = e.pageY;// (e.originalEvent.y || e.originalEvent.layerY || 0) + offtp;
var left = (startX > endX) ? endX : startX;
var top = (startY > endY) ? endY : startY;
$(".mouseSelect").css("width", Math.abs(endX - startX) + "px");
$(".mouseSelect").css("height", Math.abs(endY - startY) + "px");
$(".mouseSelect").css("left", left + "px");
$(".mouseSelect").css("top", top + "px");
resetSelectFiles();
}
});
}
function resetSelectFiles() {
selected_files = [];
var rleft = $(".mouseSelect").position().left;
var rtop = $(".mouseSelect").position().top;
var rright = rleft + $(".mouseSelect").width();
var rbuttom = rtop + $(".mouseSelect").height();
var offtp = $('#filediv').offset().top;
var offleft = $('#filediv').offset().left;
for (var i = 0; i < cur_files.length; i++) {
var item = cur_files[i].target;
var ileft = item.position().left;
var itop = item.position().top;
var iright = ileft + item.width();
var ibuttom = itop + item.height();
if ((iright > rleft) && (ileft < rright) && (ibuttom > rtop) && (itop < rbuttom)) {
selected_files.push(cur_files[i])
}
}
resetActiveFiles();
}
function getFileByDomObj(domobj) {
for (var i = 0; i < cur_files.length; i++) {
if (cur_files[i].target[0] == domobj) {
return cur_files[i];
}
}
return null;
}
function isFileSelected(file) {
for (var i = 0; i < selected_files.length; i++) {
if (selected_files[i] == file) {
return true;
}
}
return false;
}
function setActiveFile(file) {
selected_files = [file];
resetActiveFiles();
}
function removeActiveFile(file) {
for (var i = 0; i < selected_files.length; i++) {
if (selected_files[i] == file) {
selected_files.splice(i, 1);
return;
}
}
}
function addActiveFile(file) {
if (isFileSelected(file))
return;
selected_files.push(file);
}
function resetActiveFiles() {
for (var i = 0; i < cur_files.length; i++) {
var file = cur_files[i];
var finded = false;
for (var j = 0; j < selected_files.length; j++) {
var stfile = selected_files[j];
if (file == stfile) {
finded = true;
break;
}
}
if (finded) {
file.target.addClass("file_item_div_active");
} else {
file.target.removeClass("file_item_div_active");
}
}
}
function initFileItemMenu() {
$(".file_item_div").unbind("contextmenu");
$(".file_item_div").bind("contextmenu", function (e) {
e.preventDefault();
var file = getFileByDomObj(this);
if (file == null) {
alert("文件为空");
}
onFileDivMenu(e, file);
});
$(".file_item_div").mousedown(function (e) {
e.preventDefault();
e.stopPropagation();
moveflag = false;
});
$(".file_item_div").mouseup(function (e) {
e.preventDefault();
e.stopPropagation();
});
$(".file_item_div").click(function (e) {
e.preventDefault();
e.stopPropagation();
var file = getFileByDomObj(this);
if (e.ctrlKey) {
if (isFileSelected(file)) {
removeActiveFile(file);
} else {
addActiveFile(file);
}
resetActiveFiles();
} else if (!isFileSelected(file)) {
selected_files = [file];
resetActiveFiles();
}
});
$(".file_item_div").dblclick(function (e) {
e.preventDefault();
e.stopPropagation();
var file = getFileByDomObj(this);
if (file.type == 1) {
$("#foldergrid").treegrid("select", file.fdrid);
showfolderfiles(file);
}
if (file.type == 2) {
setActiveFile(file);
var furl = $C.cos.downattfile() + "?pfid=" + file.pfid;
window.open(furl);
}
});
}
function getfilebyid(pfid) {
if ((cur_files == undefined) || (cur_files == null) || (cur_files.length == 0)) {
return null;
}
for (var i = 0; i < cur_files.length; i++) {
var file = cur_files[i];
if (file.pfid == pfid) {
return file;
}
}
return null;
}
function initGrids() {
$C.grid.initComFormaters({
comUrls: [
{
index: "dic637",
type: "combobox",
url: _serUrl + "/web/dict/getdictvalues.co?dicid=637",
valueField: 'dictvalue',
textField: 'language1'
},
{
index: "dic643",
type: "combobox",
url: _serUrl + "/web/dict/getdictvalues.co?dicid=643",
valueField: 'dictvalue',
textField: 'language1'
}
],
onOK: function () {
$("#grid_shwfdracl").datagrid({
columns: [[{field: 'ownername', title: '对象', width: 70},
{field: 'access', title: '权限', width: 60, formatter: $C.grid.comFormaters['dic637']},
{field: 'acltype', title: '类型', width: 70, formatter: $C.grid.comFormaters['dic643']},
{field: 'statime', title: '生效', width: 80},
{field: 'endtime', title: '失效', width: 80}]]
});
$("#cbx_access").combobox({
valueField: 'dictvalue',
textField: 'language1',
data: $C.grid.comDatas['dic637'].data
});
}
});
}
function initFolderMenu() {
for (var i = 0; i < FOLDER_MENU_DATA.length; i++) {
$('#foldermenu').menu('appendItem', FOLDER_MENU_DATA[i]
);
}
$('#foldermenu').menu({onShow: onMenuShow, onHide: onMenuHide});
}
function onMenuShow() {
}
function onMenuHide() {
}
function initfldtree() {
$("#foldergrid").treegrid({
url: _serUrl + "/web/doc/getDocFolders.co",
loadFilter: folderFilter,
onClickRow: showfolderfiles,
onContextMenu: onFolderMenu
});
}
function aclInArr(acl, acls) {
for (var i = 0; i < acls.length; i++) {
if (acl == acls[i])
return true;
}
return false;
}
function setFolderMenuIsEnableByAcl(acl) {
setFolderMenuAllDisable();
setFolderMenuEanble(F_M_T.TEST);
setFolderMenuEanble(F_M_T.REFRESH);
setFolderMenuEanble(F_M_T.DOWONLOAD);
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileItem))
setFolderMenuEanble(F_M_T.COPY);
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W, SACL.D])) {
setFolderMenuEanble(F_M_T.UPLOAD);
setFolderMenuEanble(F_M_T.RENAME);
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileItem))
setFolderMenuEanble(F_M_T.CUT);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W])) {
if (cpOrctInfo.inpaste)
setFolderMenuEanble(F_M_T.PASTE);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.D])) {
setFolderMenuEanble(F_M_T.DEL);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W])) { //if ((aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W])) && (cur_menu_pop_type == MENU_POP_TYPE.Folder)) {
setFolderMenuEanble(F_M_T.NEW);
}
if (aclInArr(acl, [SACL.ADMIN])) {
setFolderMenuEanble(F_M_T.ACL);
setFolderMenuEanble(F_M_T.SAHRE);
}
setFolderMenuEanble(F_M_T.PROPERTY);
}
function setFileMenuIsEnableByAcl(acl) {
setFolderMenuAllDisable();
setFolderMenuEanble(F_M_T.TEST);
setFolderMenuEanble(F_M_T.REFRESH);
setFolderMenuEanble(F_M_T.DOWONLOAD);
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileItem))
setFolderMenuEanble(F_M_T.COPY);
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W, SACL.D])) {
setFolderMenuEanble(F_M_T.UPLOAD);
if (selected_files.length == 1)
setFolderMenuEanble(F_M_T.RENAME);
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileItem))
setFolderMenuEanble(F_M_T.CUT);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W])) {
if (cpOrctInfo.inpaste)
setFolderMenuEanble(F_M_T.PASTE);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.D])) {
setFolderMenuEanble(F_M_T.DEL);
}
if (aclInArr(acl, [SACL.ADMIN, SACL.WD, SACL.W])) {
setFolderMenuEanble(F_M_T.NEW);
}
if (aclInArr(acl, [SACL.ADMIN])) {
//setFolderMenuEanble(F_M_T.ACL);
setFolderMenuEanble(F_M_T.SAHRE);
}
setFolderMenuEanble(F_M_T.PROPERTY);
}
function onFolderMenu(e, node) {
cur_menu_pop_type = MENU_POP_TYPE.Folder;
//$('#foldergrid').treegrid("select", node.fdrid);
//showfolderfiles(node);
showFolderMenu(e, node);
}
function onFileDivMenu(e, file) {
e.stopPropagation();
if (files_cur_folder == null) return;
if (!file) {
cur_menu_pop_type = MENU_POP_TYPE.FileDiv;
showFolderMenu(e, files_cur_folder);
} else {
cur_menu_pop_type = MENU_POP_TYPE.FileItem;
showFileMenu(e, file);
}
}
function showFolderMenu(e, node) {
var acl = parseInt(node.acl);
setFolderMenuIsEnableByAcl(acl);
e.preventDefault();
$("#foldergrid").treegrid('select', node.fdrid);
$('#foldermenu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
function showFileMenu(e, file) {
var node = $('#foldergrid').treegrid('getSelected');
if (!file.acl)
file.acl = node.acl;
if (!isFileSelected(file))
setActiveFile(file);
var acl = parseInt(file.acl);
setFileMenuIsEnableByAcl(acl);
e.preventDefault();
$('#foldermenu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
function showfolderfiles(row) {
files_cur_folder = row;
$('#foldergrid').treegrid("expand", row.fdrid);
$("#filediv").panel("setTitle", getrootnode("#foldergrid", row));
var url = _serUrl + "/web/doc/getFolderDocs.co?fdrid=" + row.fdrid;
$ajaxjsonget(url, function (jsdata) {
cur_files = jsdata;
showfiles();
}, function (err) {
alert(JSON.stringify(err));
});
}
function showfiles() {
$("#filediv").html("<div class='mouseSelect'></div>");
if ((cur_files == undefined) || (cur_files == null) || (cur_files.length == 0)) {
return;
}
var h = $("#html_temp_file_item").html();
for (var i = 0; i < cur_files.length; i++) {
var file = cur_files[i];
if (file.type == 1) {
var ht = $putStrParmValue(h, "pfid", file.fdrid);
ht = $putStrParmValue(ht, "file_ico", "icon-file-folder32");
ht = $putStrParmValue(ht, "displayfname", file.fdrname);
}
if (file.type == 2) {
var ht = $putStrParmValue(h, "pfid", file.pfid);
ht = $putStrParmValue(ht, "file_ico", $getfileicobyfileext(file.extname));
ht = $putStrParmValue(ht, "displayfname", file.displayfname);
}
ht = $putStrParmValue(ht, "type", file.type);
var tgt = $(ht);
tgt.appendTo("#filediv");
file.target = tgt;
}
initFileItemMenu();
}
function $putStrParmValue(src, parmname, value) {
return src.replace(new RegExp("{{" + parmname + "}}", "g"), value);
}
function folderFilter(jsondata, parentId) {
if (!parentId)
parentId = 0;
else
parentId = parseInt(parentId);
jsondata = setICONode(parentId, jsondata);
return jsondata;
}
function setICONode(pid, jsondata) {
if (pid == 0) {
for (var i = 0; i < jsondata.length; i++) {
var node = jsondata[i];
//node.state = "closed";
var fdtype = parseInt(node.fdtype);
if (fdtype == 1) {
node.iconCls = "icon-xietongmg";
}
if (fdtype == 2) {
node.iconCls = "icon-folderuser";
}
if (fdtype == 4) {
node.iconCls = "icon-reload";
}
if (fdtype == 3) {
node.iconCls = "icon-folderlink";
}
}
} else {
for (var i = 0; i < jsondata.length; i++) {
var node = jsondata[i];
//node.state = "closed";
var fdtype = parseInt(node.fdtype);
if (fdtype == 1) {
node.iconCls = "icon-folder";
}
if (fdtype == 2) {
node.iconCls = "icon-folderuser";
}
if (fdtype == 4) {
node.iconCls = "icon-folder";
}
if (fdtype == 3) {
node.iconCls = "icon-folderlink";
}
}
}
return jsondata;
}
//新建文件夹
function newFolder() {
var fd = $('#foldergrid').treegrid('getSelected');
if (fd == null) {
alert("选择文件夹");
return;
}
$.messager.prompt('提示', '输入文件夹名称:', function (r) {
if (r) {
var id = fd.fdrid;
var url = _serUrl + "/web/doc/createFloder.co";
var data = {id: id, name: r};
$ajaxjsonpost(url, JSON.stringify(data), function (rst) {
$('#foldergrid').treegrid('append', {
parent: id,
data: [rst]
});
}, function (err) {
alert(JSON.stringify(err));
});
}
});
}
//删除文件夹 或文件
function doRemoveClick() {
var node = $('#foldergrid').treegrid('getSelected');
if (node == null) return;
var dinfo = {};
var cinfo = [];
if (cur_menu_pop_type == MENU_POP_TYPE.Folder) {
cinfo = [{type: 1, fdrid: node.fdrid}];
var pnode = $("#foldergrid").treegrid("getParent", node.fdrid);
dinfo.rfdrid = node.fdrid;
} else if (cur_menu_pop_type == MENU_POP_TYPE.FileItem) {
dinfo.rfdrid = node.fdrid;
for (var i = 0; i < selected_files.length; i++) {
var file = selected_files[i];
if (file.type == 1) {//folder
cinfo.push({
type: 1,
fdrid: file.fdrid
});
}
if (file.type == 2) {//file
cinfo.push({
type: 2,
pfid: file.pfid
});
}
}
} else return;
if (cinfo.length == 0) return;
dinfo.data = cinfo;
$.messager.confirm('提示', '确定删除选中的【' + cinfo.length + '】项?', function (r) {
if (r) {
var id = node.fdrid;
var url = _serUrl + "/web/doc/removeFolderOrFiles.co";
$ajaxjsonpost(url, JSON.stringify(dinfo), function (rst) {
if (cur_menu_pop_type == MENU_POP_TYPE.Folder) {
$('#foldergrid').treegrid('remove', node.fdrid);
} else {
//刷新目录
$("#foldergrid").treegrid("reload", dinfo.rfdrid);
doRefreshMenuClick();
}
}, function (err) {
alert(JSON.stringify(err));
});
}
});
}
function getrootnode(filter, node) {
var rst = "/";
getsupernode(filter, node);
return "." + rst;
function getsupernode(filter, nd) {
rst = "/" + nd.fdrname + rst;
if (nd.superid == 0) {
return nd;
} else {
var pnd = $(filter).treegrid("getParent", nd.fdrid);
var root = getsupernode(filter, pnd);
if (root) return root;
}
}
}
function dofindFolderACL() {
var node = $('#foldergrid').treegrid('getSelected');
$("#folder_alc_path").html(getrootnode("#foldergrid", node));
var url = _serUrl + "/web/doc/getFolderAcled.co?atp=2&id=" + node.fdrid;
$ajaxjsonget(url, function (jsdata) {
$("#grid_shwfdracl").datagrid("loadData", jsdata);
}, function (err) {
alert("错误:" + JSON.stringify(err));
});
return node;
}
function getFolderAcl() {
var node = dofindFolderACL();
$("#wfolderalc").window({iconCls: node.iconCls});
$("#wfolderalc").window("open");
}
function initOrgUsers() {
$ajaxjsonget($C.cos.getorgs + "?type=orgusrtree", function (data) {
$C.tree.setTree1OpendOtherClosed(data);
setNodesIco(data);
$("#tree_orguser").combotree("loadData", data);
function setNodesIco(nodes) {
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.tp == "usr")
node.iconCls = "icon-user";
if (node.children) {
setNodesIco(node.children);
}
}
}
}, function (err) {
alert(err);
});
}
function addacl() {
//var ownerid = $('#tree_orguser').combotree("getValue");
var data = {};
var t = $('#tree_orguser').combotree('tree'); // get the tree object
var n = t.tree('getSelected'); // get selected node
if ((n == undefined) || (n == null)) {
alert("选择机构或用户");
return;
}
data.ownerid = n.id;
if (n.tp == "usr")data.acltype = 3; else data.acltype = 1;
data.access = $('#cbx_access').combobox("getValue");
if ((data.access == undefined) || (data.access == null)) {
alert("选择权限");
return;
}
data.statime = $('#dt_statime').datebox("getValue");
if ((data.statime == undefined) || (data.statime == null)) {
alert("选择开始日期");
return;
}
data.endtime = $('#dt_endtime').datebox("getValue");
if ((data.endtime == undefined) || (data.endtime == null)) {
alert("选择截止日期");
return;
}
var node = $('#foldergrid').treegrid('getSelected');
data.id = node.fdrid;
var url = _serUrl + "/web/doc/setFolderAcl.co";
var data = [data];
$ajaxjsonpost(url, JSON.stringify(data), function (jsdata) {
dofindFolderACL();
$('#waddalc').window('close');
}, function (err) {
alert(JSON.stringify(err));
});
}
function delacl() {
var rows = $("#grid_shwfdracl").datagrid("getSelections");
if (rows.length == null) {
alert("没有选择的权限");
}
var pdata = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
pdata.push({aclid: row.aclid});
}
var url = _serUrl + "/web/doc/removeFolderAcl.co";
$ajaxjsonpost(url, JSON.stringify(pdata), function (json) {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var idx = $("#grid_shwfdracl").datagrid("getRowIndex", row);
$("#grid_shwfdracl").datagrid("deleteRow", idx);
}
}, function (err) {
alert(JSON.stringify(err));
});
}
function getFolderAttr() {
var node = $('#foldergrid').treegrid('getSelected');
$("#folder_attr_path").html(getrootnode("#foldergrid", node));
var url = _serUrl + "/web/doc/getFolderAttr.co?type=2&id=" + node.fdrid;
$ajaxjsonget(url, function (jsdata) {
if ((jsdata.size < 1024)) {
var size = jsdata.size + "(K)";
} else {
var size = (jsdata.size / 1024).toFixed(2) + "(M)";
}
$("#attr_size").html(size);
$("#attr_createtime").html(jsdata.createtime);
$("#attr_creator").html(jsdata.creator);
$("#attr_updatetime").html(jsdata.updatetime);
$("#attr_updator").html(jsdata.updator);
$("#attr_childfoldercount").html(jsdata.childfoldercount);
$("#attr_childfilecount").html(jsdata.fcount);
}, function (err) {
alert("错误:" + JSON.stringify(err));
});
$("#wfolderattr").window({iconCls: node.iconCls});
$("#wfolderattr").window("open");
}
function doRenameClick() {
var node = $('#foldergrid').treegrid('getSelected');
if (cur_menu_pop_type == MENU_POP_TYPE.Folder) {
$.messager.prompt('提示', '输入新文件夹名称:', function (r) {
if (r) {
if (node.fdrname == r) {
alert("新旧文件同名");
return;
}
var id = node.fdrid;
var url = _serUrl + "/web/doc/UpdateFloderName.co";
var data = {id: id, name: r};
$ajaxjsonpost(url, JSON.stringify(data), function (rst) {
$('#foldergrid').treegrid('update', {
id: id,
row: rst
});
}, function (err) {
alert(JSON.stringify(err));
});
}
});
$('.messager-input').val(node.fdrname).focus();
}
if (cur_menu_pop_type == MENU_POP_TYPE.FileItem) {
if (selected_files.length != 1) return;
var file = selected_files[0];
if (file.type == 2) {//文件重命名
$.messager.prompt('提示', '输入新文件名称:', function (r) {
if (r) {
if (file.displayfname == r) {
alert("新旧文件同名");
return;
}
var url = _serUrl + "/web/doc/UpdateFileName.co";
var data = {fdrid: node.fdrid, pfid: file.pfid, name: r};
$ajaxjsonpost(url, JSON.stringify(data), function (rst) {
file.displayfname = rst.displayfname;
showfiles();
setActiveFile(file);
}, function (err) {
alert(JSON.stringify(err));
});
}
});
$('.messager-input').val(file.displayfname).focus();
}
if (file.type == 1) {//文件夹重命名
$.messager.prompt('提示', '输入新文件夹名称:', function (r) {
if (r) {
if (file.fdrname == r) {
alert("新旧文件同名");
return;
}
var id = file.fdrid;
var url = _serUrl + "/web/doc/UpdateFloderName.co";
var data = {id: id, name: r};
$ajaxjsonpost(url, JSON.stringify(data), function (rst) {
$('#foldergrid').treegrid('update', {
id: id,
row: rst
});
file.fdrname = rst.fdrname;
showfiles();
setActiveFile(file);
}, function (err) {
alert(JSON.stringify(err));
});
}
});
$('.messager-input').val(file.fdrname).focus();
}
}
}
function uploadfiles() {
var node = files_cur_folder;
if (node == null) {
alert("没有选择文件夹");
return;
}
var url = _serUrl + "/web/doc/uploadfile.co?attImgThb=true&fdrid=" + node.fdrid;
$uploadfile(url, null, function (err) {
$.messager.alert('上传文件错误', err, 'error');
}, function (jsdata) {
try {
var pfs = jsdata;
if (pfs.errmsg) {
alert(pfs.errmsg);
} else {
for (var i = 0; i < pfs.length; i++) {
pfs[i].type = 2;
}
cur_files = cur_files.concat(pfs);
showfiles();
$("#pw_uploadfile").window("close");
}
} catch (e) {
if (JSON.stringify(jsdata).indexOf("Request Entity Too Large") > -1) {
$.messager.alert('上传文件错误', "文件超大", 'error');
} else {
$.messager.alert('上传文件错误', JSON.stringify(jsdata), 'error');
}
}
});
}
function doDownLoadClick() {
var dinfo = [];
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileDiv)) {
var node = $('#foldergrid').treegrid('getSelected');
if (node == null) return;
dinfo = [{type: 1, fdrid: node.fdrid}];
} else if (cur_menu_pop_type == MENU_POP_TYPE.FileItem) {
for (var i = 0; i < selected_files.length; i++) {
var file = selected_files[i];
if (file.type == 1) {//folder
dinfo.push({
type: 1,
fdrid: file.fdrid
});
}
if (file.type == 2) {//file
dinfo.push({
type: 2,
pfid: file.pfid
});
}
}
} else return;
var furl = _serUrl + "/web/doc/downloadFiles.co?dinfo=" + JSON.stringify(dinfo);
window.open(furl);
}
//刷新
function doRefreshMenuClick() {
var node = $('#foldergrid').treegrid('getSelected');
if (node == null) {
alert("没有选择文件夹");
return;
}
if (cur_menu_pop_type == MENU_POP_TYPE.Folder) {
$("#foldergrid").treegrid("reload", node.fdrid);
}
if ((cur_menu_pop_type == MENU_POP_TYPE.FileDiv) || (cur_menu_pop_type == MENU_POP_TYPE.FileItem)) {
showfolderfiles(node);
}
}
function dotest() {
alert($getfileicobyfileext(".docx"));
}
function doCopyClick() {
doCutOrCopy(ACTION_COPY_CUT_TYPE.Copy);
}
function doCutClick() {
doCutOrCopy(ACTION_COPY_CUT_TYPE.Cut);
}
function getStdFids() {
var rst = [];
for (var i = 0; i < selected_files.length; i++) {
rst.push({pfid: selected_files[i].pfid, fdrid: selected_files[i].fdrid});
}
return rst;
}
function doCutOrCopy(acttp) {
clearPaste();
var node = $('#foldergrid').treegrid('getSelected');
if (node == null) return;
var cinfo = [];
if ((cur_menu_pop_type == MENU_POP_TYPE.Folder) || (cur_menu_pop_type == MENU_POP_TYPE.FileDiv)) {
cinfo = [{type: 1, fdrid: node.fdrid}];
var pnode = $("#foldergrid").treegrid("getParent", node.fdrid);
cpOrctInfo.rfdrid = node.fdrid;
} else if (cur_menu_pop_type == MENU_POP_TYPE.FileItem) {
cpOrctInfo.rfdrid = node.fdrid;
for (var i = 0; i < selected_files.length; i++) {
var file = selected_files[i];
if (file.type == 1) {//folder
cinfo.push({
type: 1,
fdrid: file.fdrid
});
}
if (file.type == 2) {//file
cinfo.push({
type: 2,
pfid: file.pfid
});
}
}
} else return;
cpOrctInfo.inpaste = true;
cpOrctInfo.sinfo = cinfo;
cpOrctInfo.cporct = acttp;
}
function doPasteClick() {
if (!cpOrctInfo.inpaste)
return;
var node = $('#foldergrid').treegrid('getSelected');
if (node == null) return;
cpOrctInfo.dfdrid = node.fdrid;
var url = _serUrl + "/web/doc/Paste.co";
$ajaxjsonpost(url, JSON.stringify(cpOrctInfo), function (jsdata) {
if ((cpOrctInfo.cporct == ACTION_COPY_CUT_TYPE.Cut) && (cpOrctInfo.rfdrid)) {
$("#foldergrid").treegrid("reload", cpOrctInfo.rfdrid);
}
$("#foldergrid").treegrid("reload", cpOrctInfo.dfdrid);
doRefreshMenuClick();
clearPaste();
},
function () {
alert(JSON.stringify(err));
}
);
}<file_sep>/src/com/corsair/server/html/CcomUrl.java
package com.corsair.server.html;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.util.HttpTookit;
public class CcomUrl {
private String index;
private String type;
private boolean multiple;
private String url;
private String valueField;
private String textField;
private String jsondata;
private HttpTookit ht;
public CcomUrl(HttpTookit ht, String index, String type, boolean multiple, String url, String valueField, String textField) throws Exception {
this.ht = ht;
this.index = index;
this.type = type;
this.multiple = multiple;
this.url = url;
this.valueField = valueField;
this.textField = textField;
}
public String fetchJSFunction() throws Exception {
Logsw.debug("url:" + url);
jsondata = ht.doGet(url, null);
String jsstr = null;
if (type.equalsIgnoreCase("combobox")) {
List<HashMap<String, String>> rows = CJSON.parArrJson(jsondata);
List<HashMap<String, String>> nrows = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> row : rows) {
HashMap<String, String> nrow = new HashMap<String, String>();
nrow.put(valueField, row.get(valueField));
nrow.put(textField, row.get(textField));
nrows.add(nrow);
}
jsstr = "jsondata:" + CJSON.List2JSON(nrows) + ",";
}
if (type.equalsIgnoreCase("combotree")) {
jsstr = "jsondata:" + jsondata + ",";
// System.out.println("jsondata:" + jsondata);
}
String vname = "comUrl_" + index;
String cd = "var " + vname + " = {"
+ "index: '" + index + "',"
+ "type: '" + type + "',"
+ "multiple: " + multiple + ","
+ "valueField: '" + valueField + "',"
+ "textField: '" + textField + "',"
+ jsstr
+ " formator: function (value, row) {"
+ " var jsondata = " + vname + ".jsondata;"
+ " if (value == 'get_com_data') {"
+ " return jsondata;"
+ " }"
+ " if (value == 'get_com_url') {"
+ " return " + vname + ";"
+ " }"
+ " if (" + vname + ".type == 'combobox') {"
+ " if (" + vname + ".multiple) {"
+ " if((!value)||(value.length==0)) return value;"
+ " var vs = value.split(',');"
+ " var rst = '';"
+ " for (var j = 0; j < vs.length; j++) {"
+ " var v = vs[j];"
+ " if ((v) && (v.length > 0)) {"
+ " for (var i = 0; i < jsondata.length; i++) {"
+ " if (v == jsondata[i][" + vname + ".valueField]) {"
+ " rst = rst + jsondata[i][" + vname + ".textField] + ',';"
+ " break;"
+ " }"
+ " }"
+ " }"
+ " }"
+ " if (rst.length > 0)"
+ " rst= rst.substring(0, rst.length - 1);"
+ " return rst;"
+ " } else {"
+ " for (var i = 0; i < jsondata.length; i++) {"
+ " if (value == jsondata[i][" + vname + ".valueField])"
+ " return jsondata[i][" + vname + ".textField];"
+ " }"
+ " }"
+ " }"
+ " if (" + vname + ".type == 'combotree') {"
+ " var txt = $getTreeTextById(jsondata, value);"
+ " if (txt == undefined) txt = value;"
+ " return txt;"
+ " }"
+ " return value;"
+ " }";
cd = cd + " };\n";
if (type.equalsIgnoreCase("combobox"))
cd = cd + vname + ".editor= {type: 'combobox', options: {valueField:" + vname + ".valueField, textField:" + vname + ".textField, data: " + vname
+ ".jsondata}};";
if (type.equalsIgnoreCase("combotree"))
cd = cd + vname + ".editor= {type: 'combotree', options: {data: $C.tree.setTree1OpendOtherClosed(" + vname + ".jsondata)}};";
return cd;
}
public String getIndex() {
return index;
}
public String getType() {
return type;
}
public String getUrl() {
return url;
}
public String getValueField() {
return valueField;
}
public String getTextField() {
return textField;
}
public String getJsondata() {
return jsondata;
}
public void setIndex(String index) {
this.index = index;
}
public void setType(String type) {
this.type = type;
}
public void setUrl(String url) {
this.url = url;
}
public void setValueField(String valueField) {
this.valueField = valueField;
}
public void setTextField(String textField) {
this.textField = textField;
}
public void setJsondata(String jsondata) {
this.jsondata = jsondata;
}
}
<file_sep>/src/com/corsair/server/weixin/entity/Shwwxmsgcfg.java
package com.corsair.server.weixin.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.ctrl.CtrShwwxmsgcfg;
import java.sql.Types;
@CEntity(controller = CtrShwwxmsgcfg.class, caption = "微信自动回复消息配置")
public class Shwwxmsgcfg extends CJPA {
@CFieldinfo(fieldname = "mcid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "id", datetype = Types.INTEGER)
public CField mcid; // id
@CFieldinfo(fieldname = "appid", notnull = true, precision = 10, scale = 0, caption = "微信ID", datetype = Types.INTEGER)
public CField appid; // 微信ID
@CFieldinfo(fieldname = "wxappid", notnull = true, precision = 50, scale = 0, caption = "微信appid", datetype = Types.VARCHAR)
public CField wxappid; // 微信appid
@CFieldinfo(fieldname = "acaption", precision = 100, scale = 0, caption = "标题", datetype = Types.VARCHAR)
public CField acaption; // 标题
@CFieldinfo(fieldname = "usable", precision = 1, scale = 0, caption = "可用", defvalue = "1", datetype = Types.INTEGER)
public CField usable; // 可用
@CFieldinfo(fieldname = "text_atrep", precision = 1, scale = 0, caption = "收到消息自动回复启用", defvalue = "1", datetype = Types.INTEGER)
public CField text_atrep; // 收到消息自动回复启用
@CFieldinfo(fieldname = "text_atrep_tp", precision = 32, scale = 0, caption = "自动回复内容方式 1 文本 2 连接 可多选", datetype = Types.VARCHAR)
public CField text_atrep_tp; // 自动回复内容方式 1 文本 2 连接 可多选
@CFieldinfo(fieldname = "text_atrep_msg", precision = 1024, scale = 0, caption = "自动回复内容", datetype = Types.VARCHAR)
public CField text_atrep_msg; // 自动回复内容
@CFieldinfo(fieldname = "text_newsid", precision = 10, scale = 0, caption = "图文消息ID", datetype = Types.INTEGER)
public CField text_newsid; // 图文消息ID
@CFieldinfo(fieldname = "text_newstitle", precision = 64, scale = 0, caption = "图文消息标题", datetype = Types.VARCHAR)
public CField text_newstitle; // 图文消息标题
@CFieldinfo(fieldname = "text_resend_openids", precision = 512, scale = 0, caption = "文本消息转发微信用户/24小时内联系过才可以?", datetype = Types.VARCHAR)
public CField text_resend_openids; // 文本消息转发微信用户/24小时内联系过才可以?
@CFieldinfo(fieldname = "text_atrep_key", precision = 1, scale = 0, caption = "启用关键字回复", defvalue = "1", datetype = Types.INTEGER)
public CField text_atrep_key; // 启用关键字回复
@CFieldinfo(fieldname = "text_atrep_key_type", precision = 2, scale = 0, caption = "多关键字检索方式:1 所有关键字匹配 2 按顺序匹配第一个关键字 ", defvalue = "1", datetype = Types.INTEGER)
public CField text_atrep_key_type; // 多关键字检索方式:1 所有关键字匹配 2 按顺序匹配第一个关键字
@CFieldinfo(fieldname = "subscribe_atrep", precision = 1, scale = 0, caption = "关注自动回复启用", defvalue = "1", datetype = Types.INTEGER)
public CField subscribe_atrep; // 关注自动回复启用
@CFieldinfo(fieldname = "subscribe_atrep_tp", precision = 32, scale = 0, caption = "关注自动回复内容方式 1 文本 2 连接 可多选", datetype = Types.VARCHAR)
public CField subscribe_atrep_tp; // 关注自动回复内容方式 1 文本 2 连接 可多选
@CFieldinfo(fieldname = "subscribe_atrep_msg", precision = 1024, scale = 0, caption = "关注自动回复内容", datetype = Types.VARCHAR)
public CField subscribe_atrep_msg; // 关注自动回复内容
@CFieldinfo(fieldname = "subscribe_newsid", precision = 64, scale = 0, caption = "关注回复图文消息ID", datetype = Types.INTEGER)
public CField subscribe_newsid; // 关注回复图文消息ID
@CFieldinfo(fieldname = "subscribe_newstitle", precision = 32, scale = 0, caption = "关注回复图文消息编码", datetype = Types.VARCHAR)
public CField subscribe_newstitle; // 关注回复图文消息编码
@CFieldinfo(fieldname = "attr1", precision = 1024, scale = 0, caption = "attr1", datetype = Types.VARCHAR)
public CField attr1; // attr1
@CFieldinfo(fieldname = "attr2", precision = 32, scale = 0, caption = "attr2", datetype = Types.VARCHAR)
public CField attr2; // attr2
@CFieldinfo(fieldname = "attr3", precision = 32, scale = 0, caption = "attr3", datetype = Types.VARCHAR)
public CField attr3; // attr3
@CFieldinfo(fieldname = "attr4", precision = 32, scale = 0, caption = "attr4", datetype = Types.VARCHAR)
public CField attr4; // attr4
@CFieldinfo(fieldname = "attr5", precision = 32, scale = 0, caption = "attr5", datetype = Types.VARCHAR)
public CField attr5; // attr5
@CFieldinfo(fieldname = "creator", precision = 32, scale = 0, caption = "制单人", datetype = Types.VARCHAR)
public CField creator; // 制单人
@CFieldinfo(fieldname = "create_time", precision = 19, scale = 0, caption = "制单时间", datetype = Types.TIMESTAMP)
public CField create_time; // 制单时间
@CFieldinfo(fieldname = "updator", precision = 32, scale = 0, caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "idpath", notnull = true, precision = 512, scale = 0, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "update_time", precision = 19, scale = 0, caption = "更新时间", datetype = Types.TIMESTAMP)
public CField update_time; // 更新时间
@CFieldinfo(fieldname = "entid", precision = 1, scale = 0, caption = "entid", defvalue = "0", datetype = Types.INTEGER)
public CField entid; // entid
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Shwwxmsgcfg_key.class, linkFields = { @LinkFieldItem(lfield = "mcid", mfield = "mcid") })
public CJPALineData<Shwwxmsgcfg_key> shwwxmsgcfg_keys;
public Shwwxmsgcfg() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/dbpool/util/ICBDLog.java
package com.corsair.dbpool.util;
import com.corsair.dbpool.CDBConnection;
/**
* 连接池日志接口
*
* @author Administrator
*
*/
public interface ICBDLog {
public void writelog(CDBConnection con, String msg);
}
<file_sep>/src/com/corsair/server/generic/Shw_physic_file.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shw_physic_file extends CJPA {
@CFieldinfo(fieldname = "pfid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField pfid; // ID
@CFieldinfo(fieldname = "fsid", caption = "文件服务器ID", datetype = Types.INTEGER)
public CField fsid; // 文件服务器ID
@CFieldinfo(fieldname = "ppath", caption = "物理路径", datetype = Types.VARCHAR)
public CField ppath; // 物理路径
@CFieldinfo(fieldname = "pfname", caption = "物理文件名", datetype = Types.VARCHAR)
public CField pfname; // 物理文件名
@CFieldinfo(fieldname = "note", caption = "", datetype = Types.VARCHAR)
public CField note; //
@CFieldinfo(fieldname = "create_time", caption = "", datetype = Types.TIMESTAMP)
public CField create_time; //
@CFieldinfo(fieldname = "creator", caption = "", datetype = Types.VARCHAR)
public CField creator; //
@CFieldinfo(fieldname = "property1", caption = "", datetype = Types.VARCHAR)
public CField property1; //
@CFieldinfo(fieldname = "property2", caption = "", datetype = Types.VARCHAR)
public CField property2; //
@CFieldinfo(fieldname = "property3", caption = "", datetype = Types.VARCHAR)
public CField property3; //
@CFieldinfo(fieldname = "property4", caption = "", datetype = Types.VARCHAR)
public CField property4; //
@CFieldinfo(fieldname = "property5", caption = "", datetype = Types.VARCHAR)
public CField property5; //
@CFieldinfo(fieldname = "displayfname", caption = "", datetype = Types.VARCHAR)
public CField displayfname; //
@CFieldinfo(fieldname = "extname", caption = "", datetype = Types.VARCHAR)
public CField extname; //
@CFieldinfo(fieldname = "filesize", caption = "", datetype = Types.FLOAT)
public CField filesize; //
@CFieldinfo(fieldname = "filevision", caption = "", datetype = Types.VARCHAR)
public CField filevision; //
@CFieldinfo(fieldname = "ppfid", caption = "父文件ID", datetype = Types.INTEGER)
public CField ppfid; // 父文件ID
@CFieldinfo(fieldname = "ptype", caption = "扩展文件类型 1: 缩略图", datetype = Types.INTEGER)
public CField ptype; // 扩展文件类型 1: 缩略图
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shw_attach_line getNewShw_attach_line() throws Exception {
Shw_attach_line rst = new Shw_attach_line();
rst.pfid.setValue(this.pfid.getValue());
rst.fdrid.setAsInt(0);
rst.displayfname.setValue(this.displayfname.getValue());
rst.extname.setValue(this.extname.getValue());
rst.filesize.setValue(this.filesize.getValue());
return rst;
}
public Shw_physic_file() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/7b/7bd70ca6c47144c68be902051ee3d402b644e553.svn-base
package com.hr.salary.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption="团队奖拉线人员明细",tablename="Hr_salary_teamaward_line_emps")
public class Hr_salary_teamaward_line_emps extends CJPA {
@CFieldinfo(fieldname ="twle_id",iskey=true,notnull=true,precision=20,scale=0,caption="团队奖拉线人员明细ID",datetype=Types.INTEGER)
public CField twle_id; //团队奖拉线人员明细ID
@CFieldinfo(fieldname ="twl_id",notnull=true,precision=20,scale=0,caption="团队奖明细ID",datetype=Types.INTEGER)
public CField twl_id; //团队奖明细ID
@CFieldinfo(fieldname ="er_id",notnull=true,precision=10,scale=0,caption="员工档案ID",datetype=Types.INTEGER)
public CField er_id; //员工档案ID
@CFieldinfo(fieldname ="employee_code",notnull=true,precision=16,scale=0,caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname ="employee_name",notnull=true,precision=64,scale=0,caption="姓名",datetype=Types.VARCHAR)
public CField employee_name; //姓名
@CFieldinfo(fieldname ="orgid",notnull=true,precision=10,scale=0,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname ="orgcode",notnull=true,precision=16,scale=0,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname ="orgname",notnull=true,precision=128,scale=0,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname ="idpath",notnull=true,precision=256,scale=0,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname ="ospid",precision=20,scale=0,caption="职位ID",datetype=Types.INTEGER)
public CField ospid; //职位ID
@CFieldinfo(fieldname ="ospcode",precision=16,scale=0,caption="职位编码",datetype=Types.VARCHAR)
public CField ospcode; //职位编码
@CFieldinfo(fieldname ="sp_name",precision=128,scale=0,caption="标准职位名称",datetype=Types.VARCHAR)
public CField sp_name; //标准职位名称
@CFieldinfo(fieldname ="descriprev",precision=6,scale=2,caption="分配比例",datetype=Types.DECIMAL)
public CField descriprev; //分配比例
@CFieldinfo(fieldname ="realpay",precision=10,scale=2,caption="实际分配金额",datetype=Types.DECIMAL)
public CField realpay; //实际分配金额
@CFieldinfo(fieldname ="shouldpay",precision=10,scale=2,caption="可分配金额",datetype=Types.DECIMAL)
public CField shouldpay; //可分配金额
@CFieldinfo(fieldname ="remark",precision=512,scale=0,caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname ="isparttime",precision=1,scale=0,caption="是否兼职",defvalue="2",datetype=Types.INTEGER)
public CField isparttime; //是否兼职
@CFieldinfo(fieldname ="ptnums",precision=2,scale=0,caption="兼职数量",defvalue="0",datetype=Types.INTEGER)
public CField ptnums; //兼职数量
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_salary_teamaward_line_emps() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/util/CBDLog.java
package com.corsair.server.util;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.ICBDLog;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
public class CBDLog implements ICBDLog {
@Override
public void writelog(CDBConnection con, String msg) {
String ms = "【user:" + CSContext.getUserNameNoErr() + "】【id:"+CSContext.getClientIP()+"】【dbsession:" + con.getKey() + "】" + msg;
Logsw.dblog(ms);
}
}
<file_sep>/src/com/hr/.svn/pristine/13/1313034086aaf3267756928d7cfa3fd4ca8ce134.svn-base
package com.hr.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.base.entity.Hr_orgposition;
import com.hr.base.entity.Hr_standposition;
import com.hr.inface.entity.View_TxZlEmployee;
import com.hr.inface.entity.View_TxZlEmployee_zp;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_entry;
/**
*
* 招募对接
*
* @author shangwen
*
*/
public class TimerTaskHRZM extends TimerTask {
private static String[] fdnames = { "sp_id", "sp_code", "sp_name",
"sp_exp", "lv_id", "lv_num", "hg_id", "hg_code", "hg_name", "hwc_idzl", "hw_codezl",
"hwc_namezl", "hwc_idzq", "hw_codezq", "hwc_namezq", "hwc_idzz", "hw_codezz", "hwc_namezz", "gtitle",
"usable", "isadvtech", "isoffjob", "issensitive", "iskey", "ishighrisk", "isneedadtoutwork",
"isdreamposition", "maxage", "minage", "mindegree" };
@Override
public void run() {
// TODO Auto-generated method stub
try {
// importDayData(new Date());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
*
* @throws Exception
*/
/***
* 一次性同步指定时间段内入职的人事资料 或者工号,
*
* @param bgdate
* @param eddate
* @param empcode
* @return
* @throws Exception
*/
public static String importDayData(Date bgdate, Date eddate, String empcode) throws Exception {
String sqlstr = "select * from HRMS.dbo.view_TxZlEmployee_zp where 1=1 ";
if ((empcode == null) || empcode.isEmpty()) {
if ((bgdate == null) || (eddate == null))
throw new Exception("日期和工号不能同时为空");
sqlstr = sqlstr + "and pydate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "'"
+ " and pydate<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'";
} else
sqlstr = sqlstr + " and code=" + empcode;
CJPALineData<View_TxZlEmployee_zp> txes = new CJPALineData<View_TxZlEmployee_zp>(View_TxZlEmployee_zp.class);
Shworg org = new Shworg();
Hr_standposition sp = new Hr_standposition();
Hr_entry enty = new Hr_entry();
Hr_employee emp = new Hr_employee();
Hr_orgposition osp = new Hr_orgposition();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
txes.findDataBySQL(sqlstr);
CDBConnection con = emp.pool.getCon("importDayData");
con.startTrans();
int drct = 0, lgct = 0;
try {
for (CJPABase jpa : txes) {
View_TxZlEmployee_zp txe = (View_TxZlEmployee_zp) jpa;
String employee_code = txe.code.getValue().trim();
sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);
boolean isupdate_emp = false;
if (!emp.isEmpty()) {// 已经存在人事资料,略过
lgct++;
// continue; //18-05-01
isupdate_emp = true;
} else
drct++;
// emp.clear();
// 根据机构编码扩展属性获取机构
sqlstr = "SELECT * FROM shworg WHERE attribute1='" + txe.dept.getValue().trim() + "'";
org.findBySQL(sqlstr, false);
if (org.isEmpty())
throwerr("招募系统工号【" + employee_code + "】同步错误,招募系统机构编码【" + txe.dept.getValue().trim() + "】在HRMS系统无对应机构");
String zhiwu = (txe.zhiwu.isEmpty()) ? "" : txe.zhiwu.getValue().trim();
String yuzhiwu = (txe.yuZhiWu.isEmpty()) ? "" : txe.yuZhiWu.getValue().trim();
if ((zhiwu.isEmpty() || (yuzhiwu.isEmpty()))) {
throwerr("招募系统工号【" + employee_code + "】同步错误,招募系统职位编码或职位名称为空");
}
sqlstr = "SELECT count(*) ct FROM hr_standposition WHERE attribute1 LIKE '%" + zhiwu + "#" + yuzhiwu + "%'";
if (Integer.valueOf(sp.pool.openSql2List(sqlstr).get(0).get("ct").toString()) > 1) {
throwerr("招募系统工号【" + employee_code + "】同步错误,招募系统职位编码【" + zhiwu + "】在HRMS系统发现多个标准职位,不满足同步要求");
}
sqlstr = "SELECT * FROM hr_standposition WHERE attribute1 LIKE '%" + zhiwu + "#" + yuzhiwu + "%'";
sp.clear();
sp.findBySQL(sqlstr, false);
if (sp.isEmpty())
throwerr("招募系统工号【" + employee_code + "】同步错误,招募系统职位编码【" + zhiwu + "】在HRMS系统无对应的标准职位,不满足同步要求");
sqlstr = "SELECT * FROM hr_orgposition WHERE orgid=" + org.orgid.getValue() + " AND sp_id=" + sp.sp_id.getValue();
osp.findBySQL(sqlstr);
if (osp.isEmpty()) {// 创建机构职位
createosp(osp, sp, org, con);
}
if (osp.isEmpty()) {// 创建机构职位
throw new Exception("创建了还是为空?为啥");
}
saveentry(txe, enty, emp, osp, dictemp, con, isupdate_emp);
}
// if (true)
// throw new Exception("测试");
con.submit();
return "共计【" + txes.size() + "】人,更新【" + lgct + "】人,新同步【" + drct + "】人";
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
/**
* 同步某工号的相片
*
* @param employee_code
* @return
* @throws Exception
*/
public static boolean syncempphoto(String employee_code) throws Exception {
String sqlstr = "select * from [HRMSTest].[dbo].[view_TxZlEmployee] where code='" + employee_code + "'";
View_TxZlEmployee txe = new View_TxZlEmployee();
txe.findBySQL(sqlstr);
if (txe.isEmpty())
throw new Exception(" 工号【" + employee_code + "】在接口【view_TxZlEmployee】中不存在");
return savepic(txe);
}
/**
* 保存所有图片
*
* @param txes
* @throws Exception
*/
private static void savepics(CJPALineData<View_TxZlEmployee> txes) throws Exception {
for (CJPABase jpa : txes) {
try {
View_TxZlEmployee txe = (View_TxZlEmployee) jpa;
savepic(txe);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 导入一个人的相片
*
* @param txemp
* @return
* @throws Exception
*/
private static boolean savepic(View_TxZlEmployee txemp) throws Exception {
Hr_employee emp = new Hr_employee();
String employee_code = txemp.code.getValue().trim();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
if (emp.avatar_id1.isEmpty()) {
String photo = txemp.photo.getValue();
if (photo != null) {
String fname = employee_code + ".jpg";
Shw_physic_file pf = UpLoadFileEx.witrefileFromFieldValue(photo, fname);
if (pf != null) {
emp.avatar_id1.setValue(pf.pfid.getValue());
emp.save(false);
return true;
} else {
Logsw.debug("保存图片后物理文件为空" + employee_code);
return false;
}
} else {
Logsw.debug("接口图片为空" + employee_code);
return false;
}
} else {
Logsw.debug("已经有图片了" + employee_code);
return false;
}
}
private static String gettrimv(String v) {
return (v == null) ? null : v.trim();
}
private static String gettrimvdef(String v, String df) {
return ((v == null) || (v.trim().isEmpty())) ? df : v.trim();
}
private static int getinterfaceSex(String sex) {
try {
String s = (sex == null) ? "2" : sex.trim();
if (s == null)
return 0;
else if (Integer.valueOf(s) == 0)
return 2;
else if (Integer.valueOf(s) == 1)
return 1;
else
return 0;
} catch (NumberFormatException e) {
e.printStackTrace();
return 0;
}
}
// 学历对照map 前面是源 后面是 HRMS系统的
private static int[][] Xueli_Degree_Map = {
{ 1, 9 }, // 小学
{ 2, 8 }, // 初中
{ 3, 5 }, // 高中
{ 4, 6 }, // 中专
{ 5, 4 }, // 大专
{ 6, 3 }, // 本科
{ 7, 2 }, // 硕士
{ 8, 1 }, // 博士
{ 9, 7 }, // 职高
{ 10, 2 } // 研究生
};
private static int getinterfaceDegree(String xl) {
try {
String s = gettrimv(xl);
if (s == null)
return 10;
int x = Integer.valueOf(s);
for (int i = 0; i < Xueli_Degree_Map.length; i++) {
if (Xueli_Degree_Map[i][0] == x)
return Xueli_Degree_Map[i][1];
}
return 10;
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 10;
}
}
private static void saveentry(View_TxZlEmployee_zp txe, Hr_entry enty, Hr_employee emp,
Hr_orgposition osp, DictionaryTemp dictemp, CDBConnection con, boolean isupdate_emp) throws Exception {
emp.orgid.setValue(osp.orgid.getValue());
emp.orgcode.setValue(osp.orgcode.getValue());
emp.orgname.setValue(osp.orgname.getValue());
emp.idpath.setValue(osp.idpath.getValue());
// emp.property2.setValue(txe.card_sn.getValue());
emp.employee_code.setValue(gettrimv(txe.code.getValue()));
emp.employee_name.setValue(gettrimv(txe.name.getValue()));
emp.sex.setValue(gettrimv(txe.sex.getValue()));// getinterfaceSex(txe.sex.getValue())
// System.out.println("sex:" + txe.sex.getValue() + "-" + (getinterfaceSex(txe.sex.getValue())));
emp.birthday.setAsDatetime(txe.borndate.getAsDatetime());
emp.height.setValue(gettrimv(txe.g_sg.getValue()));
emp.nation.setValue(gettrimv(txe.hrcode.getValue()));
emp.married.setValue(gettrimv(txe.hunyin.getValue()));
emp.pay_way.setValue(gettrimv(txe.jxfs.getValue()));
emp.noclock.setValue(gettrimv(txe.ifdaka.getValue()));
emp.nativeplace.setValue(gettrimv(txe.jiguan.getValue()));
emp.sign_org.setValue(gettrimvdef(txe.g_sfzf.getValue(), "招募没填"));
emp.registeraddress.setValue(gettrimv(txe.g_jtzz.getValue()));// 户籍地址
emp.address.setValue(gettrimv(txe.G_Dqzz.getValue()));// 家庭地址 都是家庭地址
emp.telphone.setValue(gettrimvdef(txe.g_lxdh.getValue(), "招募没填"));
emp.id_number.setValue(gettrimv(txe.sfz.getValue()));
emp.sign_date.setValue(gettrimvdef(txe.g_qfrq.getValue(), "1899-12-31"));
emp.expired_date.setValue(gettrimvdef(txe.g_sxq.getValue(), "1899-12-31"));
emp.degree.setValue(gettrimv(txe.xueli.getValue()));// getinterfaceDegree(txe.xueli.getValue())
emp.major.setValue(gettrimv(txe.g_zy.getValue()));
emp.atdtype.setValue(dictemp.getValueByCation("1399", txe.G_cqlb.getValue(), "0"));// G_cqlb 出勤类别 无法对应 先置为0
emp.urgencycontact.setValue(gettrimv(txe.g_jjllr.getValue()));
emp.cellphone.setValue(gettrimv(txe.g_jjlldh.getValue()));
emp.hiredday.setValue(gettrimv(txe.pydate.getValue()));
emp.kqdate_start.setAsDatetime(emp.hiredday.getAsDatetime());
emp.dorm_bed.setValue(gettrimv(txe.roomBed.getValue()));
emp.dispunit.setValue(gettrimv(txe.g_pqjg.getValue()));
emp.orgid.setValue(osp.orgid.getValue()); // 部门ID
emp.orgcode.setValue(osp.orgcode.getValue()); // 部门编码
emp.orgname.setValue(osp.orgname.getValue()); // 部门名称
emp.hwc_namezl.setValue(osp.hwc_namezl.getValue()); // 职类
emp.lv_id.setValue(osp.lv_id.getValue()); // 职级ID
emp.lv_num.setValue(osp.lv_num.getValue()); // 职级
emp.hg_id.setValue(osp.hg_id.getValue()); // 职等ID
emp.hg_code.setValue(osp.hg_code.getValue()); // 职等编码
emp.hg_name.setValue(osp.hg_name.getValue()); // 职等名称
emp.ospid.setValue(osp.ospid.getValue()); // 职位ID
emp.ospcode.setValue(osp.ospcode.getValue()); // 职位编码
emp.sp_name.setValue(osp.sp_name.getValue()); // 职位名称
emp.iskey.setValue(osp.iskey.getValue()); // 关键岗位
emp.hwc_namezq.setValue(osp.hwc_namezq.getValue()); // 职群
emp.hwc_namezz.setValue(osp.hwc_namezz.getValue()); // 职种
emp.registertype.setValue(gettrimvdef(txe.g_ygjg.getValue(), "0"));// 户籍类型
emp.rectcode.setValue(gettrimv(txe.G_ZPRY.getValue()));
emp.rectname.setValue(gettrimv(txe.G_ZPRYXM.getValue()));
emp.entrysourcr.setValue(dictemp.getValueByCation("741", txe.G_rzfs.getValue(), "0"));// 人员来源 社会招聘/校园招聘/其它
emp.eovertype.setValue(dictemp.getValueByCation("1394", txe.G_jblb.getValue(), "0"));// 加班类别
emp.transorg.setValue(gettrimv(txe.G_lsgjg.getValue()));
emp.transextime.setValue(gettrimv(txe.G_lwhz.getValue()));
if (osp.isoffjob.getAsIntDefault(0) == 1) {
emp.emnature.setValue("脱产");
} else {
emp.emnature.setValue("非脱产");
}
// System.out.println("户籍类型:" + gettrimv(txe.code.getValue()) + "-" + gettrimv(txe.g_ygjg.getValue()));
emp.usable.setAsInt(1); // 有效
if (!isupdate_emp) {// 更新人事资料,这个不能更新啦
emp.empstatid.setAsInt(6);
}
emp.save(con);
// System.out.println("emp:" + emp.tojson());
if (!isupdate_emp) {// 更新人事资料,入职表单不能修改
enty.clear();
enty.er_id.setValue(emp.er_id.getValue());
enty.employee_code.setValue(emp.employee_code.getValue());
enty.entrytype.setAsInt(1);
enty.entrysourcr.setValue(emp.entrysourcr.getValue());// 人员来源 社会招聘/校园招聘/其它
enty.entrydate.setAsDatetime(emp.hiredday.getAsDatetime());
enty.probation.setAsInt(1);// 会议决定按一个月算
Date pd = Systemdate.dateMonthAdd(emp.hiredday.getAsDatetime(), 1);
enty.promotionday.setAsDatetime(pd);
enty.ispromotioned.setAsInt(2);
enty.quota_over.setAsInt(2);
enty.orgid.setValue(emp.orgid.getValue());
enty.transorg.setValue(gettrimv(txe.G_lsgjg.getValue()));
enty.transextime.setValue(gettrimv(txe.G_lwhz.getValue()));
enty.orghrlev.setAsInt(0);
enty.quota_over_rst.setAsInt(2);// 默认允许超编入职
enty.lv_num.setAsFloat(emp.lv_num.getAsFloat());
enty.save(con);
enty.wfcreate(null, con);
}
}
private static void createosp(Hr_orgposition osp, Hr_standposition sp, Shworg org, CDBConnection con) throws Exception {
osp.assignfieldOnlyValue(sp, fdnames);
osp.orgid.setValue(org.orgid.getValue());
osp.orgcode.setValue(org.code.getValue());
osp.orgname.setValue(org.extorgname.getValue());
osp.idpath.setValue(org.idpath.getValue());
osp.pid.setAsInt(0);
osp.save(con);
}
private static void throwerr(String err) throws Exception {
throw new Exception(err);
}
}
<file_sep>/src/com/hr/canteen/entity/Hr_canteen_costrecords.java
package com.hr.canteen.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import java.sql.Types;
@CEntity()
public class Hr_canteen_costrecords extends CJPA {
@CFieldinfo(fieldname="core_id",iskey=true,notnull=true,caption="消费打卡记录ID",datetype=Types.INTEGER)
public CField core_id; //消费打卡记录ID
@CFieldinfo(fieldname="cardnumber",notnull=true,caption="卡号",datetype=Types.VARCHAR)
public CField cardnumber; //卡号
@CFieldinfo(fieldname="er_id",caption="档案ID",datetype=Types.INTEGER)
public CField er_id; //档案ID
@CFieldinfo(fieldname="employee_code",caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname="employee_name",caption="姓名",datetype=Types.VARCHAR)
public CField employee_name; //姓名
@CFieldinfo(fieldname="orgid",notnull=true,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="ospid",caption="职位ID",datetype=Types.INTEGER)
public CField ospid; //职位ID
@CFieldinfo(fieldname="ospcode",caption="职位编码",datetype=Types.VARCHAR)
public CField ospcode; //职位编码
@CFieldinfo(fieldname="sp_name",caption="职位名称",datetype=Types.VARCHAR)
public CField sp_name; //职位名称
@CFieldinfo(fieldname="lv_id",caption="职级ID",datetype=Types.INTEGER)
public CField lv_id; //职级ID
@CFieldinfo(fieldname="lv_num",caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="ctr_id",notnull=true,caption="用餐餐厅ID",datetype=Types.INTEGER)
public CField ctr_id; //用餐餐厅ID
@CFieldinfo(fieldname="ctr_code",notnull=true,caption="用餐餐厅编码",datetype=Types.VARCHAR)
public CField ctr_code; //用餐餐厅编码
@CFieldinfo(fieldname="ctr_name",notnull=true,caption="用餐餐厅名称",datetype=Types.VARCHAR)
public CField ctr_name; //用餐餐厅名称
@CFieldinfo(fieldname="ctcr_id",notnull=true,caption="卡机ID",datetype=Types.INTEGER)
public CField ctcr_id; //卡机ID
@CFieldinfo(fieldname="ctcr_code",notnull=true,caption="卡机编号",datetype=Types.VARCHAR)
public CField ctcr_code; //卡机编号
@CFieldinfo(fieldname="ctcr_name",notnull=true,caption="名称",datetype=Types.VARCHAR)
public CField ctcr_name; //名称
@CFieldinfo(fieldname="costtime",caption="刷卡时间",datetype=Types.TIMESTAMP)
public CField costtime; //刷卡时间
@CFieldinfo(fieldname="mc_id",caption="餐类ID",datetype=Types.INTEGER)
public CField mc_id; //餐类ID
@CFieldinfo(fieldname="mc_name",caption="餐类名称",datetype=Types.VARCHAR)
public CField mc_name; //餐类名称
@CFieldinfo(fieldname="cost",caption="消费金额",datetype=Types.DECIMAL)
public CField cost; //消费金额
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname="entid",notnull=true,caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname="creator",notnull=true,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname="createtime",notnull=true,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="updator",caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname="updatetime",caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
@CFieldinfo(fieldname="attribute1",caption="备用字段1",datetype=Types.VARCHAR)
public CField attribute1; //备用字段1
@CFieldinfo(fieldname="attribute2",caption="备用字段2",datetype=Types.VARCHAR)
public CField attribute2; //备用字段2
@CFieldinfo(fieldname="attribute3",caption="备用字段3",datetype=Types.VARCHAR)
public CField attribute3; //备用字段3
@CFieldinfo(fieldname="attribute4",caption="备用字段4",datetype=Types.VARCHAR)
public CField attribute4; //备用字段4
@CFieldinfo(fieldname="attribute5",caption="备用字段5",datetype=Types.VARCHAR)
public CField attribute5; //备用字段5
@CFieldinfo(fieldname="idpath",notnull=true,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="inporttime",caption="导入时间",datetype=Types.TIMESTAMP)
public CField inporttime; //刷卡时间
@CFieldinfo(fieldname="synid",caption="关联ID",datetype=Types.INTEGER)
public CField synid; //关联ID
@CFieldinfo(fieldname ="classtype",precision=1,scale=0,caption="餐类类型",datetype=Types.INTEGER)
public CField classtype; //餐类类型
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
/*@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;*/
public Hr_canteen_costrecords() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/common/shwpostion.js
/**
* Created by Administrator on 2014-10-13.
*/
$(document).ready(function () {
$ajaxjsonget($C.cos.findPositions, function (jsondata) {
$("#tb_positions").datagrid({
data: jsondata,
onDblClickRow: function (rowIndex, rowData) {
toolbarAction($C.action.Edit);
}
});
}, function () {
});
$("#shwpositionform").c_initDictionary();
});
function toolbarAction(action) {
var otb = $('#tb_positions');
var row = otb.datagrid('getSelected');
switch (action) {
case $C.action.Edit:
if (!row) {
$.messager.alert('错误', '没选定的岗位!', 'error');
return;
}
var jsondata = row;
isnew = false;
break;
case $C.action.Append:
isnew = true;
var jsondata = {};
break;
case $C.action.Del:
if (!row) {
$.messager.alert('错误', '没选定的岗位!', 'error');
return;
}
$.messager.confirm('提醒', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delPosition + "?positionid=" + row.positionid, function (jsondata) {
if (jsondata.result == "OK")
otb.datagrid("deleteRow", otb.datagrid("getRowIndex", row));
}, function () {
$.messager.alert('错误', '删除岗位错误!', 'error');
});
}
});
return;
}
$("#positionInfoWindow").c_popInfo({
isNew: isnew,
jsonData: jsondata,
onOK: function (jsondata) {
$ajaxjsonpost($C.cos.savePosition, JSON.stringify(jsondata), function (jsondata) {
if (isnew) {
otb.datagrid("appendRow", jsondata)
} else {
var idx = otb.datagrid("getRowIndex", row);
otb.datagrid("updateRow", {index: idx, row: jsondata});
otb.datagrid("refreshRow", idx);
}
}, function () {
alert("保存岗位错误")
});
return true;
},
onShow: function () {
$ajaxjsonget($C.cos.findUsersByPosition + "?positionid=" + row.positionid, function (jsondata) {
$("#position_users").datagrid({data: jsondata});
}, function () {
})
}
});
}
<file_sep>/WebContent/webapp/js/common/cwbsktclient.js
/**
* Created by Administrator on 2020/01/13.
*/
if (!"WebSocket" in window) {
alert("您的浏览器不支持 WebSocket");
}
//
/**
*
* options{
* url:"ws://localhost:8081/calldll.co",//server socket url 服务器地址
* CallBack_StatChanged:function(stat){//skt状态变化 1 连上 2 断开 3 重连中
* },
* ReconnectTime:1000,//重连时间间隔 1S
* }
*
* action.dlltype = actPropertys.dlltype;
action.dllfname = actPropertys.dllfname;
action.MethodName = actPropertys.MethodName;
* function regAction(actname, actPropertys) {//注册Action
* }
*
*
*/
function CWBSKTClient(options) {
var url = options.url;
var CallBack_StatChanged = options.CallBack_StatChanged;
var ReconnectTime = options.ReconnectTime;
if (!ReconnectTime) ReconnectTime = 1000;
var _ws = undefined;
var _sktstat = 2;//1 连上 2 断开 3 重连中
var _actions = {};
if (!url) {
$.messager.alert('错误', "需要设置URL参数", 'error');
return;
}
this.getStat = getStat;
function getStat() {
return _sktstat;
}
this.isConnected = isConnected;
function isConnected() {
return _sktstat == 1;
}
function connect() {
_ws = new WebSocket(url);
_ws.onopen = function () {
_sktstat = 1;
if (CallBack_StatChanged)
CallBack_StatChanged(_sktstat);
};
_ws.onclose = function () {
_sktstat = 2;
if (CallBack_StatChanged)
CallBack_StatChanged(_sktstat);
setTimeout(function () {
_sktstat = 3;
CallBack_StatChanged(_sktstat);
connect();
}, ReconnectTime);
};
}
connect();
this.regAction = regAction;
function regAction(ActionName, actPropertys) {
var action = _actions[ActionName];
if (!action) {
action = {};
}
action.DillType = actPropertys.DillType;
action.DllFileName = actPropertys.DllFileName;
action.MethodName = actPropertys.MethodName;
_actions[ActionName] = action;
}
this.callAction = callAction;
function callAction(ActionName, printdata, OnMessageCallBack) {
var action = _actions[ActionName];
if (!action) {
$.messager.alert('错误', "【" + ActionName + "】未注册", 'error');
return;
}
if ((_sktstat != 1) || !_ws) {
$.messager.alert('错误', "【" + url + "】服务未连接", 'error');
return;
}
_ws.onmessage = OnMessageCallBack;
var data = {};
data.DillType = action.DillType;//表示c#的dll
data.DllFileName = action.DllFileName;//dll名称
data.MethodName = action.MethodName;//方法名
if (printdata)
data.parms = [printdata];
_ws.send(JSON.stringify(data));
}
}
<file_sep>/src/com/hr/attd/ctr/CtrHrkq_leave_blance.java
package com.hr.attd.ctr;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Systemdate;
import com.hr.attd.entity.Hrkq_leave_blance;
import com.hr.base.entity.Hr_grade;
import com.hr.perm.entity.Hr_employee;
public class CtrHrkq_leave_blance {
/**
* @param con
* @param sid
* @param sccode
* @param lbname
* @param stype
* @param alllbtime
* @param valdate
* @param er_id
* @param remark
* @param wkym
* 工龄
* @return
* @throws Exception
*/
public static Hrkq_leave_blance putLeave_blance(CDBConnection con, String sid, String sccode, String lbname, int stype, float alllbtime,
Date valdate, String er_id, String remark, Float wkym) throws Exception {
Hr_employee emp = new Hr_employee();
emp.findByID(er_id);
if (emp.isEmpty())
throw new Exception("没有找到ID为【" + er_id + "】的人事档案");
String sqlstr = "SELECT * FROM hrkq_leave_blance WHERE stype=" + stype + " and er_id=" + er_id + " AND sid =" + sid + " and sccode='" + sccode + "'";
Hrkq_leave_blance lb = new Hrkq_leave_blance();
lb.findBySQL(con, sqlstr, false);
float usedlbtime = (lb.isEmpty()) ? 0 : lb.usedlbtime.getAsFloat();
// String r = (lb.remark.isEmpty()) ? remark : lb.remark.getValue() + remark;
lb.lbname.setValue(lbname); // 标题
lb.stype.setAsInt(stype); // 源类型 1 年假 2 加班 3 值班 4出差
lb.sid.setValue(sid); // 源ID
lb.sccode.setValue(sccode); // 源编码/年假的年份
lb.er_id.setValue(er_id); // 人事ID
lb.employee_code.setValue(emp.employee_code.getValue()); // 工号
lb.employee_name.setValue(emp.employee_name.getValue());
lb.hiredday.setValue(emp.hiredday.getValue());
lb.wkym.setAsInt(new BigDecimal(wkym).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
//lb.wkym.setValue(1.1f);
lb.hg_name.setValue(emp.hg_name.getValue()); // 职等名称
lb.njsp_name.setValue(emp.sp_name.getValue());
lb.lv_num.setValue(emp.lv_num.getValue()); // 职级
lb.orgid.setValue(emp.orgid.getValue()); // 部门ID
lb.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
lb.orgname.setValue(emp.orgname.getValue()); // 部门名称
lb.alllbtime.setAsFloat(alllbtime); // 可调休时间小时
lb.usedlbtime.setAsFloat(usedlbtime); // 已调休时间小时
lb.valdate.setAsDatetime(valdate); // 有效期
lb.remark.setValue(remark);
lb.idpath.setValue(emp.idpath.getValue()); // idpath
lb.save(con);
return lb;
}
/**
* @param con
* @param emp
* @param year2016
* @param existsdoupdate
* 存在则更新
* @throws Exception
*/
public static void getYearLeave_blance(CDBConnection con, Hr_employee emp, String year, boolean existsdoupdate) throws Exception {// 获取年假
String yeartitle = String.valueOf(Integer.valueOf(year) - 1);
if (!existsdoupdate) {
Hrkq_leave_blance lb = new Hrkq_leave_blance();
String sqlstr = "SELECT * FROM hrkq_leave_blance WHERE er_id=" + emp.er_id.getValue() + " AND sccode='" + yeartitle + "'";
lb.findBySQL(sqlstr);
if (!lb.isEmpty())
return;
}
Date hiredday = emp.hiredday.getAsDatetime();
//System.out.println("year:" + year);
Date todate = Systemdate.getDateByStr(year + "-01-01");
Date valdate = Systemdate.getDateByStr((Integer.valueOf(year) + 1) + "-01-01 00:00:00");// 到期日期
float ym = getworkym(hiredday, todate);
int alllbtime = getylh(ym);
String r = Systemdate.getStrDateByFmt(hiredday, "yyMMdd") + "至" + Systemdate.getStrDateByFmt(todate, "yyMMdd");
putLeave_blance(con, "0", yeartitle, "年假", 1, alllbtime, valdate, emp.er_id.getValue(), r, ym);
}
// 满1年不满10年的,年休假5天;已满10年不满20年的,年休假10天;已满20年的,年休假15天
public static int getylh(Float ym) {
if (ym<1 )
return 0;
else if ((ym>= 1) && (ym < 10))
return 5 * 8;
else if ((ym>= 10) && (ym < 20))
return 10 * 8;
else if (ym >= 20)
return 15 * 8;
else
return 0;
}
// 计算工作年限 年月 1年11个月 返回 1.11
public static float getworkym(Date hiredday, Date todate) throws Exception {
if (todate.getTime() <= hiredday.getTime())
// throw new Exception("日期错误!");
return 0;
Calendar cf = Calendar.getInstance();
cf.setTime(hiredday);
Calendar ct = Calendar.getInstance();
ct.setTime(todate);
int ms = (ct.get(Calendar.YEAR) * 12 + ct.get(Calendar.MONTH) + 1) - (cf.get(Calendar.YEAR) * 12 + cf.get(Calendar.MONTH) + 1);
int y = (int) Math.floor(ms / 12);
int m = ms % 12;
int cd = ct.get(Calendar.DATE) - cf.get(Calendar.DATE);
if (cd > 0) {
if (cd >= 15) {
m = m + 1;
}
if (m > 12) {
y = y + 1;
m = m - 12;
}
} else if (cd < 0) {
if (cd < -15) {
m = m - 1;
}
if (m < 0) {
y = y - 1;
m = 0;
}
if (y < 0)
y = 0;
}
return Float.valueOf(y + "." + m);
}
public static String getworkymString(Date hiredday, Date todate) throws Exception {
if (todate.getTime() <= hiredday.getTime())
// throw new Exception("日期错误!");
return "0";
Calendar cf = Calendar.getInstance();
cf.setTime(hiredday);
Calendar ct = Calendar.getInstance();
ct.setTime(todate);
int ms = (ct.get(Calendar.YEAR) * 12 + ct.get(Calendar.MONTH) + 1) - (cf.get(Calendar.YEAR) * 12 + cf.get(Calendar.MONTH) + 1);
int y = (int) Math.floor(ms / 12);
int m = ms % 12;
int cd = ct.get(Calendar.DATE) - cf.get(Calendar.DATE);
if (cd > 0) {
if (cd >= 15) {
m = m + 1;
}
if (m > 12) {
y = y + 1;
m = m - 12;
}
} else if (cd < 0) {
if (cd < -15) {
m = m - 1;
}
if (m < 0) {
y = y - 1;
m = 0;
}
if (y < 0)
y = 0;
}
return y + "." + m;
}
}
<file_sep>/src/com/corsair/server/generic/Shw_attach.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shw_attach extends CJPA {
@CFieldinfo(fieldname = "attid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField attid; // ID
@CFieldinfo(fieldname = "create_time", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField create_time; // 创建时间
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "note", caption = "备注", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "property1", caption = "", datetype = Types.VARCHAR)
public CField property1; //
@CFieldinfo(fieldname = "property2", caption = "", datetype = Types.VARCHAR)
public CField property2; //
@CFieldinfo(fieldname = "property3", caption = "", datetype = Types.VARCHAR)
public CField property3; //
@CFieldinfo(fieldname = "property4", caption = "", datetype = Types.VARCHAR)
public CField property4; //
@CFieldinfo(fieldname = "property5", caption = "", datetype = Types.VARCHAR)
public CField property5; //
@CFieldinfo(fieldname = "stat", caption = "", datetype = Types.INTEGER)
public CField stat; //
@CFieldinfo(fieldname = "wfid", caption = "", datetype = Types.INTEGER)
public CField wfid; //
@CFieldinfo(fieldname = "idpath", caption = "", datetype = Types.VARCHAR)
public CField idpath; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach_line.class, linkFields = {
@LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach_line> shw_attach_lines;
public Shw_attach() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
shw_attach_lines.addLinkField("attid", "attid");
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/asset/co/COHr_asset_register.java
package com.hr.asset.co;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.base.entity.Hr_grade;
import com.hr.base.entity.Hr_orgposition;
import com.hr.base.entity.Hr_orgpositionkpi;
import com.hr.base.entity.Hr_standposition;
import com.hr.base.entity.Hr_wclass;
import com.hr.asset.entity.Hr_asset_item;
import com.hr.asset.entity.Hr_asset_register;
import com.hr.asset.entity.Hr_asset_statement;
import com.hr.asset.entity.Hr_asset_sum;
import com.hr.asset.entity.Hr_asset_type;
import com.hr.canteen.entity.Hr_canteen_room;
@ACO(coname = "web.hr.Asset")
public class COHr_asset_register extends JPAController {
// 流程完成时数据插入流水表
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doUpdateAssetList(jpa, con);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc,
Shwwfproc nxtproc, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doUpdateAssetList(jpa, con);
}
}
private void doUpdateAssetList(CJPA jpa, CDBConnection con) throws Exception {
Hr_asset_register ar = (Hr_asset_register) jpa;
Hr_asset_statement as = new Hr_asset_statement();
Date df = new Date();
SimpleDateFormat nowdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
as.clear();
as.source.setValue("asset_register");
as.source_id.setValue(ar.asset_register_id.getValue());
as.source_num.setValue(ar.asset_register_num.getValue());
as.asset_item_id.setValue(ar.asset_item_id.getValue());
as.asset_item_code.setValue(ar.asset_item_code.getValue());
as.asset_item_name.setValue(ar.asset_item_name.getValue());
as.asset_type_id.setValue(ar.asset_type_id.getValue());
as.asset_type_code.setValue(ar.asset_type_code.getValue());
as.asset_type_name.setValue(ar.asset_type_name.getValue());
as.brand.setValue(ar.brand.getValue());
as.model.setValue(ar.model.getValue());
as.original_value.setValue(ar.original_value.getValue());
as.net_value.setValue(ar.net_value.getValue());
as.uom.setValue(ar.uom.getValue());
as.service_life.setValue(ar.service_life.getValue());
as.acquired_date.setValue(ar.acquired_date.getValue());
as.deploy_area.setValue(ar.deploy_area.getValue());
as.deploy_restaurant_id.setValue(ar.deploy_restaurant_id.getValue());
as.deploy_restaurant.setValue(ar.deploy_restaurant.getValue());
as.keep_own.setValue(ar.keep_own.getValue());
as.adjust_qty.setValue(ar.deploy_qty.getValue());
as.adjust_date.setAsDatetime(new Date());
as.save(con);
}
// Excel导入
@ACOAction(eventname = "ImpRegExcel", Authentication = true, ispublic = false, notes = "导入Excel")
public String ImpRegExcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_asset_register ar = new Hr_asset_register();
Hr_asset_item at = new Hr_asset_item();
Hr_canteen_room cr = new Hr_canteen_room();
CDBConnection con = ar.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String asset_item_code = v.get("asset_item_code");
String deploy_restaurant = v.get("deploy_restaurant");
if ((asset_item_code == null) || (asset_item_code.isEmpty()))
continue;
rst++;
at.clear();
at.findBySQL("SELECT * FROM hr_asset_item t WHERE t.asset_item_code ='" + asset_item_code + "'");
if (at.isEmpty())
throw new Exception("类型【" + asset_item_code + "】不存在");
cr.clear();
cr.findBySQL("SELECT * FROM hr_canteen_room t WHERE t.ctr_name= '" + deploy_restaurant + "'");
if (cr.isEmpty())
throw new Exception("餐厅【" + deploy_restaurant + "】不存在");
ar.clear();
ar.asset_type_id.setValue(at.asset_type_id.getValue());
ar.asset_type_code.setValue(at.asset_type_code.getValue());
ar.asset_type_name.setValue(at.asset_type_name.getValue());
ar.asset_item_id.setValue(at.asset_item_id.getValue());
ar.asset_item_code.setValue(v.get("asset_item_code"));
ar.asset_item_name.setValue(at.asset_item_name.getValue());
ar.brand.setValue(v.get("brand"));
ar.model.setValue(v.get("model"));
ar.original_value.setValue(v.get("original_value"));
ar.net_value.setValue(v.get("net_value"));
ar.service_life.setValue(v.get("service_life"));
ar.acquired_date.setValue(v.get("acquired_date"));
ar.deploy_qty.setValue(v.get("deploy_qty"));
ar.deploy_area.setValue(v.get("deploy_area"));
ar.deploy_restaurant_id.setValue(cr.ctr_id.getValue());
ar.deploy_restaurant.setValue(v.get("deploy_restaurant"));
ar.keep_own.setValue(v.get("keep_own"));
ar.uom.setValue(dictemp.getVbCE("9", v.get("uom"), true, "是否词汇【" + v.get("isemcat") + "】不存在"));
ar.remark.setValue(v.get("remark"));
ar.save(con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("类型编码", "asset_type_code", false));
efields.add(new CExcelField("类型名称", "asset_type_name", false));
efields.add(new CExcelField("资产物料编码", "asset_item_code", true));
efields.add(new CExcelField("资产物料名称", "asset_item_name", false));
efields.add(new CExcelField("品牌", "brand", false));
efields.add(new CExcelField("型号", "model", false));
efields.add(new CExcelField("原值", "original_value", false));
efields.add(new CExcelField("净值", "net_value", false));
efields.add(new CExcelField("报废年限", "service_life", false));
efields.add(new CExcelField("购置日期", "acquired_date", false));
efields.add(new CExcelField("配置数量", "deploy_qty", true));
efields.add(new CExcelField("配置区域", "deploy_area", true));
efields.add(new CExcelField("配置餐厅", "deploy_restaurant", true));
efields.add(new CExcelField("保管人", "keep_own", false));
efields.add(new CExcelField("单位", "uom", false));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
}
<file_sep>/WebContent/webapp/js/common/Shwdict.js
/**
* Created by Administrator on 2014-10-14.
*/
function $OnCorsairReady() {
initGrids();
$("#dictform").c_initDictionary();
$ajaxjsonget($C.cos.getDicTree, function (jsondata) {
//$("#btnewch").linkbutton("disable");
//$('#menuDict').menu('disableItem', $('#menuDict').menu('findItem', '新建词汇值').target);
setNodesIco(jsondata);
$C.tree.setTree1OpendOtherClosed(jsondata);
$("#shwdict_grid").treegrid({
data: jsondata,
onDblClickRow: function (rowIndex, rowData) {
toolbarAction(5);
},
onSelect: function (rowData) {
reSetAction(rowData);
}
});
}, function () {
$.messager.alert('错误', '查询数据字典错误!', 'error');
});
}
$(document).ready(function () {
//
});
function setNodeIco(node) {
if (node.dtype == 1) {
node.iconCls = "icon-folder";
}
if (node.dtype == 2) {
node.iconCls = "icon-folder_page";
}
if (node.dtype == 3) {
node.iconCls = "icon-text_ab";
}
}
function setNodesIco(nodes) {
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
setNodeIco(node);
if (node.children) {
setNodesIco(node.children);
}
}
}
function reSetAction(rowData) {
if (rowData.dtype == 1) {//分类
$("#btnewch").linkbutton("disable");
$('#menuDict').menu('disableItem', $('#menuDict').menu('findItem', '新建词汇值').target);
} else {
$("#btnewch").linkbutton("enable");
$('#menuDict').menu('enableItem', $('#menuDict').menu('findItem', '新建词汇值').target);
}
}
function getPid(act, snode) {
if (act == 1) {
var root = $('#shwdict_grid').treegrid('getRoot');
return root.pid;
}
if (act == 2) {//新建组
if (snode.dtype == 1) {
return snode.dictid;
} else if (snode.dtype == 2) {
return snode.pid;
} else if (snode.dtype == 3) {
return $('#shwdict_grid').treegrid("getParent", snode.dictid).pid;
}
}
if (act == 3) {//新建值
if (snode.dtype == 1) {
return null;
} else if (snode.dtype == 2) {
return snode.dictid;
} else if (snode.dtype == 3) {
return snode.pid;
}
}
}
function toolbarAction(act) {
var otb = $('#shwdict_grid');
var node = otb.treegrid('getSelected');
if (!node) {
$.messager.alert('错误', '没选定词汇!', 'error');
return;
}
var jsondata = {};
if (act == 1) {//新建分类
var isnew = true;
jsondata.dtype = 1;
jsondata.pid = getPid(act, node);
}
if (act == 2) {//新建组
var isnew = true;
jsondata.dtype = 2;
jsondata.pid = getPid(act, node);
}
if (act == 3) {//新建值
var isnew = true;
jsondata.dtype = 3;
jsondata.pid = getPid(act, node);
}
if (act == 4) {//删除
$.messager.confirm('提醒', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delDict + "?dictid=" + node.dictid, function (jsondata) {
if (jsondata.result == "OK")
otb.treegrid("remove", node.dictid);
}, function () {
$.messager.alert('错误', '删除词汇错误!', 'error');
});
}
});
return;
}
if (act == 5) {//编辑
jsondata = node;
var isnew = false;
}
$("#dictInfoWindow").c_popInfo({
isNew: isnew,
jsonData: jsondata,
onOK: function (jsondata) {
$ajaxjsonpost($C.cos.saveDict, JSON.stringify(jsondata), function (jsondata) {
jsondata.id = jsondata.dictid;
if (isnew) {
setNodeIco(jsondata);
if (jsondata.dtype == 1) {
otb.treegrid("append", {data: [jsondata]});
} else {
otb.treegrid("append", {parent: jsondata.pid, data: [jsondata]});
}
} else {
otb.treegrid("update", {id: jsondata.id, row: jsondata});
}
}, function () {
alert("保存错误!");
});
return true;
}
});
}
<file_sep>/src/com/corsair/server/wordflow/Shwwftemparms.java
package com.corsair.server.wordflow;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwwftemparms extends CJPA {
@CFieldinfo(fieldname = "wfpid", iskey = true, notnull = true, caption = "流程模板参数ID", datetype = Types.INTEGER)
public CField wfpid; // 流程模板参数ID
@CFieldinfo(fieldname = "wftempid", caption = "流程模板ID", datetype = Types.INTEGER)
public CField wftempid; // 流程模板ID
@CFieldinfo(fieldname = "frmclassname", caption = "窗体类名", datetype = Types.VARCHAR)
public CField frmclassname; // 窗体类名
@CFieldinfo(fieldname = "frmcaption", caption = "窗体标题", datetype = Types.VARCHAR)
public CField frmcaption; // 窗体标题
@CFieldinfo(fieldname = "parmname", caption = "参数名", datetype = Types.VARCHAR)
public CField parmname; // 参数名
@CFieldinfo(fieldname = "reloper", caption = "运算方式", datetype = Types.VARCHAR)
public CField reloper; // 运算方式
@CFieldinfo(fieldname = "rowreloper", caption = "行运算关系", datetype = Types.VARCHAR)
public CField rowreloper; // 行运算关系
@CFieldinfo(fieldname = "parmvalue", caption = "参数值", datetype = Types.VARCHAR)
public CField parmvalue; // 参数值
@CFieldinfo(fieldname = "note", caption = "备注", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "parm1", caption = "", datetype = Types.VARCHAR)
public CField parm1; //
@CFieldinfo(fieldname = "parm2", caption = "", datetype = Types.VARCHAR)
public CField parm2; //
@CFieldinfo(fieldname = "parm3", caption = "", datetype = Types.VARCHAR)
public CField parm3; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwwftemparms() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/hr/portals/co/COHr_portals.java
package com.hr.portals.co;
import java.util.Date;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.perm.entity.Hr_employee;
@ACO(coname = "web.hr.Portals")
public class COHr_portals extends JPAController {
@ACOAction(eventname = "getportalrole", Authentication = false, notes = "获取角色")
public String getportalrole() throws Exception {
String useid = CSContext.getUserID();
String sqlstr = "SELECT ifnull(count(*),0) ct FROM shwroleuser t WHERE t.roleid = 40 AND t.userid = " + useid;
String sqlstr1 = "SELECT ifnull(count(*),0) ct FROM shwroleuser t WHERE t.roleid = 41 AND t.userid = " + useid;
JSONObject rst = new JSONObject();
if (Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr).get(0).get("ct")) > 0)
rst.put("role40", 1);
else
rst.put("role40", 2);
if (Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr1).get(0).get("ct")) > 0)
rst.put("role41", 1);
else
rst.put("role41", 2);
return rst.toString();
}
@ACOAction(eventname = "getimageid", Authentication = true, notes = "获取人员照片ID")
public String getimageid() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_employee t WHERE t.usable=1 AND t.employee_code = '" + username + "'";
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty()) {
throw new Exception("当前登录用户无对应人事资料");
}
return emp.tojson();
}
@ACOAction(eventname = "getweekbirthday", Authentication = true, notes = "获取本周生日名单")
public String getweekbirthday() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr = "SELECT * FROM hr_employee "
+ " WHERE DATE_FORMAT(birthday, '%m-%d') >= DATE_FORMAT(CURDATE(), '%m-%d') "
+ " AND DATE_FORMAT(birthday, '%m-%d') <= DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL 7 DAY), '%m-%d')"
+ " AND empstatid NOT IN (12, 13) " + CSContext.getIdpathwhere();
sqlstr = sqlstr + " ORDER BY DATE_FORMAT(birthday, '%m-%d') ";
if (!tp.equals("Y")) {
sqlstr = sqlstr + " limit 3 ";
}
// if (tp.equals("Y")) {//moyh 180130
// sqlstr =
// "SELECT * FROM hr_employee t WHERE DATE_FORMAT(t.birthday,'%m-%d') >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY),'%m-%d') " +
// " AND t.birthday <= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) - 6 DAY) " +
// " AND t.empstatid NOT IN(12,13) ORDER BY t.birthday ";
// } else {
// sqlstr =
// "SELECT * FROM hr_employee t WHERE DATE_FORMAT(t.birthday,'%m-%d') >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY),'%m-%d') " +
// " AND t.birthday <= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) - 6 DAY) " +
// " AND t.empstatid NOT IN(12,13) ORDER BY t.birthday limit 3";
// }
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getmonthbirthday", Authentication = true, notes = "获取本月生日名单")
public String getmonthbirthday() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT * FROM hr_employee t WHERE MONTH(t.birthday) = MONTH(NOW()) AND t.empstatid NOT IN(12,13) " + CSContext.getIdpathwhere() + " ORDER BY t.birthday ";
} else {
sqlstr = "SELECT * FROM hr_employee t WHERE MONTH(t.birthday) = MONTH(NOW()) AND t.empstatid NOT IN(12,13) " + CSContext.getIdpathwhere() + " ORDER BY t.birthday limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getfullmember", Authentication = true, notes = "获取待转正清单")
public String getfullmember() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT a.* FROM hr_entry_try a,hr_employee t WHERE a.er_id = t.er_id AND t.empstatid NOT IN(12,13) AND a.trystat NOT IN(4,5) AND DATE_FORMAT(a.promotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') "
+ CSContext.getIdpathwhere().replace("idpath", "t.idpath") + " ORDER BY promotionday";
} else {
sqlstr = "SELECT a.* FROM hr_entry_try a,hr_employee t WHERE a.er_id = t.er_id AND t.empstatid NOT IN(12,13) AND a.trystat NOT IN(4,5) AND DATE_FORMAT(a.promotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') "
+ CSContext.getIdpathwhere().replace("idpath", "t.idpath") + " ORDER BY promotionday limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getdelaymember", Authentication = true, notes = "获取延期转正清单")
public String getdelaymember() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT a.* FROM hr_entry_try a,hr_employee t WHERE a.er_id = t.er_id AND t.empstatid NOT IN(12,13) AND a.trystat =3 AND DATE_FORMAT(a.delaypromotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') "
+ CSContext.getIdpathwhere().replace("idpath", "t.idpath") + " ORDER BY delaypromotionday";
} else {
sqlstr = "SELECT a.* FROM hr_entry_try a,hr_employee t WHERE a.er_id = t.er_id AND t.empstatid NOT IN(12,13) AND a.trystat =3 AND DATE_FORMAT(a.delaypromotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') "
+ CSContext.getIdpathwhere().replace("idpath", "t.idpath") + " ORDER BY delaypromotionday limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getmonthcontract", Authentication = true, notes = "")
public String getmonthcontract() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT employee_code,employee_name,orgname,sp_name,hiredday,sign_date,end_date FROM hr_employee_contract " +
" WHERE stat = 9 " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')" + CSContext.getIdpathwhere() +
" ORDER BY end_date";
} else {
sqlstr = "SELECT employee_code,employee_name,orgname,sp_name,hiredday,sign_date,end_date FROM hr_employee_contract " +
" WHERE stat = 9 " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere() +
" ORDER BY end_date" +
" limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getlastmonthcontract", Authentication = true, notes = "")
public String getlastmonthcontract() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT employee_code,employee_name,orgname,sp_name,hiredday,sign_date,end_date FROM hr_employee_contract " +
" WHERE stat = 9 " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(DATE_ADD(CURDATE()-DAY(CURDATE())+1,INTERVAL 1 MONTH),'%Y-%m')" + CSContext.getIdpathwhere() +
" ORDER BY end_date";
} else {
sqlstr = "SELECT employee_code,employee_name,orgname,sp_name,hiredday,sign_date,end_date FROM hr_employee_contract " +
" WHERE stat = 9 " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(DATE_ADD(CURDATE()-DAY(CURDATE())+1,INTERVAL 1 MONTH),'%Y-%m')" + CSContext.getIdpathwhere() +
" ORDER BY end_date" +
" limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getcontract", Authentication = true, notes = "")
public String getcontract() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT t.con_id,t.er_id,t.employee_code,t.employee_name,t.orgname,t.sp_name,t.hiredday,t.sign_date,t.end_date,e.idpath "
+ "FROM hr_employee_contract t,hr_employee e " +
" WHERE stat = 9 and t.er_id=e.er_id " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 " +
" AND end_date<CURDATE() " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " +CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" ORDER BY end_date";
} else {
sqlstr = "SELECT t.con_id,t.er_id,t.employee_code,t.employee_name,t.orgname,t.sp_name,t.hiredday,t.sign_date,t.end_date,e.idpath FROM hr_employee_contract t,hr_employee e " +
" WHERE stat = 9 and t.er_id=e.er_id " +
" AND deadline_type = 1 " +
" AND contractstat = 1 " +
" AND contract_type = 1 "+
" AND end_date<CURDATE() " +
" AND DATE_FORMAT(end_date,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" ORDER BY end_date" +
" limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getkcmember", Authentication = true, notes = "获取清单")
public String getkcmember() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT * FROM hr_transfer_try t WHERE t.trystat NOT IN (4,5) AND DATE_FORMAT(t.probationdate,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere() + " ORDER BY t.probationdate ";
} else {
sqlstr = "SELECT * FROM hr_transfer_try t WHERE t.trystat NOT IN (4,5) AND DATE_FORMAT(t.probationdate,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere() + " ORDER BY t.probationdate limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getdelaykcmember", Authentication = true, notes = "获取延期考察清单")
public String getdelaykcmember() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT * FROM hr_transfer_try t WHERE t.trystat = 3 AND DATE_FORMAT(t.delaypromotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere() + " ORDER BY t.delaypromotionday ";
} else {
sqlstr = "SELECT * FROM hr_transfer_try t WHERE t.trystat = 3 AND DATE_FORMAT(t.delaypromotionday,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') " + CSContext.getIdpathwhere() + " ORDER BY t.delaypromotionday limit 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getsfz", Authentication = true, notes = "获取身份证清单")
public String getsfz() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr = null;
if (tp.equals("Y")) {
sqlstr = " SELECT *" +
" FROM (SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" '身份证' ertname," +
" IF((expired_date IS NULL OR expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" e.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e" +
" WHERE e.er_id <> 0 and expired_date <= date_add(NOW(), interval 1 MONTH) and e.empstatid<10 " + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" UNION" +
" SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" c.cert_name," +
" IF((c.expired_date IS NULL OR c.expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" c.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e, hr_employee_cretl c" +
" WHERE e.er_id = c.er_id" +
" AND c.cert_name LIKE '%身份证%'" +
" AND c.expired_date <= date_add(NOW(), interval 1 MONTH) and e.empstatid<10 " + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" AND e.er_id <> 0) sfz" +
" ORDER BY expired_date";
} else {
sqlstr = " SELECT *" +
" FROM (SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" '身份证' ertname," +
" IF((expired_date IS NULL OR expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" e.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e" +
" WHERE e.er_id <> 0 and expired_date <= date_add(NOW(), interval 1 MONTH) and empstatid<10 " + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" UNION" +
" SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" c.cert_name," +
" IF((c.expired_date IS NULL OR c.expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" c.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e, hr_employee_cretl c" +
" WHERE e.er_id = c.er_id" +
" AND c.cert_name LIKE '%身份证%'" +
" AND c.expired_date <= date_add(NOW(), interval 1 MONTH) and empstatid<10 " + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" AND e.er_id <> 0) sfz" +
" ORDER BY expired_date LIMIT 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getotherlieson", Authentication = true, notes = "获取其他证件清单")
public String getotherlieson() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms, "num", "需要参数num");
String sqlstr;
if (tp.equals("Y")) {
sqlstr = " SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" c.cert_name ertname," +
" IF((c.expired_date IS NULL OR c.expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" c.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e, hr_employee_cretl c" +
" WHERE e.er_id = c.er_id" +
" AND c.cert_name NOT LIKE '%身份证%'" +
" AND e.er_id <> 0" + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" ORDER BY c.expired_date";
} else {
sqlstr = " SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgname," +
" c.cert_name ertname," +
" IF((c.expired_date IS NULL OR c.expired_date >= NOW())," +
" '即将过期'," +
" '已过期') cerstat," +
" c.expired_date," +
" e.orgid," +
" e.orgcode," +
" e.idpath" +
" FROM hr_employee e, hr_employee_cretl c" +
" WHERE e.er_id = c.er_id" +
" AND c.cert_name NOT LIKE '%身份证%'" +
" AND e.er_id <> 0" + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" ORDER BY c.expired_date LIMIT 3";
}
String[] ignParms = null;
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
@ACOAction(eventname = "getschedule", Authentication = true, notes = "获取排班信息")
public String getschedule() throws Exception {
HashMap<String, String> parms1 = CSContext.getParms();
String tp = CorUtil.hashMap2Str(parms1, "num", "需要参数num");
// 获取弹出窗参数
HashMap<String, String> parms = CSContext.get_pjdataparms();
String ps = parms.get("parms");
List<JSONParm> jps = CJSON.getParms(ps);
JSONParm jyearmonth = CjpaUtil.getParm(jps, "yearmonth");
String ym = (jyearmonth == null) ? Systemdate.getStrDateByFmt(new Date(), "YYYY-MM") : jyearmonth.getParmvalue();
String sqlstr;
if (tp.equals("Y")) {
sqlstr = "SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgid," +
" e.orgcode," +
" e.orgname," +
" e.sp_name," +
" e.hiredday," +
" '" + ym + "' yearmonth" +
" FROM hr_employee e" +
" WHERE empstatid <= 10" +
" AND e.er_id <> 0" + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" AND NOT EXISTS (SELECT 1" +
" FROM hrkq_workschmonthlist l" +
" WHERE l.yearmonth = '" + ym + "'" +
" AND l.er_id = e.er_id)";
} else {
sqlstr = "SELECT e.er_id," +
" e.employee_code," +
" e.employee_name," +
" e.orgid," +
" e.orgcode," +
" e.orgname," +
" e.sp_name," +
" e.hiredday," +
" DATE_FORMAT(CURDATE(), '%Y-%m') yearmonth" +
" FROM hr_employee e" +
" WHERE empstatid <= 10" +
" AND e.er_id <> 0" + CSContext.getIdpathwhere().replace("idpath", "e.idpath") +
" AND NOT EXISTS (SELECT 1" +
" FROM hrkq_workschmonthlist l" +
" WHERE l.yearmonth = DATE_FORMAT(CURDATE(), '%Y-%m')" +
" AND l.er_id = e.er_id) LIMIT 3";
}
String[] ignParms = { "yearmonth" };// 忽略的查询条件
String idpathw = null;
return new CReport(sqlstr, null).findReport(ignParms, idpathw);
}
}
<file_sep>/src/com/hr/perm/co/COHr_quota_adjust.java
package com.hr.perm.co;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_quota_adjustline;
@ACO(coname = "web.hr.quotaadjust")
public class COHr_quota_adjust {
@ACOAction(eventname = "impexcel", Authentication = true, notes = "从excel导入编制发布信息")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
String rst = parserExcelFile(p);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
return rst;
} else
return "[]";
}
private String parserExcelFile(Shw_physic_file pf) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fullname));
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
HSSFSheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet);
}
// 序号 机构编码 机构名称 职位编码 职位名称 调整类型 调整数量
private String parserExcelSheet(HSSFSheet aSheet) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "[]";
}
int ospcodecol = -1;
int adjtpcol = -1;
int adjqtcol = -1;
HSSFRow aRow = aSheet.getRow(0);
for (int col = 0; col <= aRow.getLastCellNum(); col++) {
HSSFCell aCell = aRow.getCell(col);
String celltext = getCellValue(aCell);
if ((celltext == null) || (celltext.isEmpty()))
continue;
if ("职位编码".equals(celltext.trim())) {
ospcodecol = col;
}
if ("调整类型".equals(celltext.trim())) {
adjtpcol = col;
}
if ("调整数量".equals(celltext.trim())) {
adjqtcol = col;
}
}
if ((ospcodecol == -1) || (adjtpcol == -1) || (adjqtcol == -1)) {
throw new Exception("没找到【职位编码】或【调整类型】或【调整数量】列");
}
CJPALineData<Hr_quota_adjustline> rls = new CJPALineData<Hr_quota_adjustline>(Hr_quota_adjustline.class);
Hr_orgposition hop = new Hr_orgposition();
for (int row = 1; row <= aSheet.getLastRowNum(); row++) {
aRow = aSheet.getRow(row);
if (null != aRow) {
HSSFCell aCell = aRow.getCell(ospcodecol);
String ospcode = getCellValue(aCell);
if ((ospcode == null) || (ospcode.isEmpty()))
continue;
if (ospcode.indexOf("e") >= 0) {
BigDecimal db = new BigDecimal(ospcode);
ospcode = db.toPlainString();
}
aCell = aRow.getCell(adjtpcol);
String adjtp = getCellValue(aCell);
if ((adjtp == null) || (adjtp.isEmpty()))
new Exception("调整类型错误");
aCell = aRow.getCell(adjqtcol);
String adjqt = getCellValue(aCell);
if ((adjqt == null) || (adjqt.isEmpty()))
adjqt = "0";
hop.findBySQL("select * from hr_orgposition where ospcode = '" + ospcode + "'");
if (!hop.isEmpty()) {
if (hop.usable.getAsInt() == 1) {
Hr_quota_adjustline qadjl = new Hr_quota_adjustline();
qadjl.orgid.setValue(hop.orgid.getValue());
qadjl.orgname.setValue(hop.orgname.getValue());
qadjl.orgcode.setValue(hop.orgcode.getValue());
qadjl.ospid.setValue(hop.ospid.getValue());
qadjl.ospcode.setValue(hop.ospcode.getValue());
qadjl.sp_name.setValue(hop.sp_name.getValue());
qadjl.oldquota.setValue(hop.quota.getValue());
if (adjtp.equals("增加"))
qadjl.adjtype.setAsInt(1);
else if (adjtp.equals("减少"))
qadjl.adjtype.setAsInt(2);
else
throw new Exception("调整类型【" + adjtp + "】错误");
qadjl.adjquota.setValue(adjqt);
rls.add(qadjl);
} else {
throw new Exception("职位编码【" + ospcode + "】设置为不可用!");
}
} else {
throw new Exception("职位编码【" + ospcode + "】不存在!");
}
}
}
return rls.tojson();
}
private String getCellValue(HSSFCell aCell) {
if (aCell != null) {
int cellType = aCell.getCellType();
switch (cellType) {
case 0:// Numeric
return String.valueOf(aCell.getNumericCellValue()).toLowerCase();
case 1:// String
return aCell.getStringCellValue().toLowerCase();
default:
return null;
}
} else
return null;
}
}
<file_sep>/src/com/corsair/server/util/CDBContext.java
package com.corsair.server.util;
import com.corsair.dbpool.IDBContext;
import com.corsair.server.base.CSContext;
public class CDBContext implements IDBContext {
@Override
public String getCurUserName() {
return CSContext.getUserNameEx();
}
@Override
public String getClentIP() {
return CSContext.getClientIP();
}
}
<file_sep>/src/com/corsair/server/listener/CorsairSessionListener.java
package com.corsair.server.listener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.Login;
import com.corsair.server.csession.CSession;
import com.corsair.server.generic.Shwsessionct;
import com.corsair.server.util.TerminalType;
import com.corsair.server.websocket.CWebSocketPool;
public class CorsairSessionListener implements HttpSessionListener, ServletRequestListener {
public static int sessioncount = 0;
private HttpServletRequest request;
private static int sessioncount_h = 0;// 一小时内访问量
private static String per_ymh = null;// 前一个小时字符串
private SimpleDateFormat date_formater = new SimpleDateFormat("yyyy-MM-dd HH"); //
private Shwsessionct sct = null;
private ThreadSaveCT tsct = null;
private int sleeptime = 1000 * 60;// 10分钟
public CorsairSessionListener() {
// TODO Auto-generated constructor stub】
// Logsw.debug("CorsairSessionListener create..................................");
per_ymh = date_formater.format(new Date());
// tsct = new ThreadSaveCT();
// tsct.start();
}
public void sessionCreated(HttpSessionEvent hse) {
sessioncount++;
sessioncount_h++;
Logsw.debug("add session1111111111111:" + hse.getSession().getId());
}
public class ThreadSaveCT extends Thread {
public void run() {
while (!isInterrupted()) {
String ymh = date_formater.format(new Date());
// Logsw.debug("ymh:" + ymh + ";per_ymh:" + per_ymh + ";在线数量:" + sessioncount + ";上一小时访问量:" + sessioncount_h);
if (!ymh.equals(per_ymh)) {// 新的一个小时
try {
savect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// sessioncount_h = 0;// 重置计数
sessioncount_h = sessioncount;// 重置计数 为在线数量
per_ymh = ymh;// 更新前一小时标志
}
try {
sleep(sleeptime);// 延迟
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
}
}
/**
* 保存小时访问量
*
* 如果有多个应用,都是锁定最后一条数据,所以行锁 和 表锁 完全一样
*
* @throws Exception
*/
private void savect() throws Exception {
// System.out.println("savect1111111111111111111111");
if (sct == null)
sct = new Shwsessionct();
CDBConnection con = sct.pool.getCon(this);
con.startTrans();
try {
String sqlstr = "SELECT * FROM shwsessionct WHERE ymhh='" + per_ymh + "' for update ";
sct.findBySQL4Update(con, sqlstr, false);
sct.ymhh.setValue(per_ymh);
sct.scnum.setAsInt(sct.scnum.getAsIntDefault(0) + sessioncount_h);
sct.acactive.setAsInt(sct.acactive.getAsIntDefault(0) + sessioncount);
sct.save(con);
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
public void sessionDestroyed(HttpSessionEvent hse) {
// TODO Auto-generated method stub
try {
Login.dologinout();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sessioncount--;
Logsw.debug("remove session:" + hse.getSession().getId());
}
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
try {
// System.out.println("requestDestroyed:"+((HttpServletRequest)
// arg0.getServletRequest()).getSession().getId());
CSContext.removeSession();
CSContext.removeRequest();
CSContext.removeParms();
CSContext.removePostdata();
CSContext.removeisMultipartContent();
CSContext.removeservlet();
CSContext.removeactiontype();
CSContext.removeTermType();
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
@Override
public void requestInitialized(ServletRequestEvent arg0) {
try {
// System.out.println("requestInitialized:" + ((HttpServletRequest)
// arg0.getServletRequest()).getSession().getId());
request = (HttpServletRequest) arg0.getServletRequest();
String userAgent = request.getHeader("user-agent");
CSContext.setTermType(TerminalType.getTerminalType(userAgent));
CSContext.setSession(request.getSession(true));
CSContext.setRequest(request);
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
<file_sep>/src/com/corsair/server/generic/Shworgfile.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "机构文件,文件管理扩展")
public class Shworgfile extends CJPA {
@CFieldinfo(fieldname = "ofid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "ID", datetype = Types.INTEGER)
public CField ofid; // ID
@CFieldinfo(fieldname = "pfid", notnull = true, precision = 10, scale = 0, caption = "物理文件ID", datetype = Types.INTEGER)
public CField pfid; // 物理文件ID
@CFieldinfo(fieldname = "orgid", notnull = true, precision = 10, scale = 0, caption = "机构ID", datetype = Types.INTEGER)
public CField orgid; // 机构ID
@CFieldinfo(fieldname = "orgname", notnull = true, precision = 64, scale = 0, caption = "机构名称", datetype = Types.VARCHAR)
public CField orgname; // 机构名称
@CFieldinfo(fieldname = "suri", precision = 128, scale = 0, caption = "抓取源", datetype = Types.VARCHAR)
public CField suri; // 抓取源
@CFieldinfo(fieldname = "stime", precision = 19, scale = 0, caption = "抓取时间", datetype = Types.TIMESTAMP)
public CField stime; // 抓取时间
@CFieldinfo(fieldname = "mask", precision = 32, scale = 0, caption = "备注", datetype = Types.VARCHAR)
public CField mask; // 备注
@CFieldinfo(fieldname = "idpath", notnull = true, precision = 256, scale = 0, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "ptype", precision = 2, scale = 0, caption = "类型 扩展", datetype = Types.INTEGER)
public CField ptype; // 类型 扩展
@CFieldinfo(fieldname = "entid", notnull = true, precision = 5, scale = 0, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, precision = 32, scale = 0, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, precision = 19, scale = 0, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "attr1", precision = 32, scale = 0, caption = "备用字段1", datetype = Types.VARCHAR)
public CField attr1; // 备用字段1
@CFieldinfo(fieldname = "attr2", precision = 32, scale = 0, caption = "备用字段2", datetype = Types.VARCHAR)
public CField attr2; // 备用字段2
@CFieldinfo(fieldname = "attr3", precision = 32, scale = 0, caption = "备用字段3", datetype = Types.VARCHAR)
public CField attr3; // 备用字段3
@CFieldinfo(fieldname = "attr4", precision = 32, scale = 0, caption = "备用字段4", datetype = Types.VARCHAR)
public CField attr4; // 备用字段4
@CFieldinfo(fieldname = "attr5", precision = 32, scale = 0, caption = "备用字段5", datetype = Types.VARCHAR)
public CField attr5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shworgfile() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/wordflow/WorkFlowController.java
package com.corsair.server.wordflow;
import com.corsair.server.cjpa.CJPA;
public class WorkFlowController {
public String wfMainFunction(String xmlstr) {
return xmlstr;
}
public String findWFTemp(String xmlstr) {
return xmlstr;
}
public String findWFTem(String frmClass, CJPA jpa) {
return null;
}
}
<file_sep>/src/com/corsair/dbpool/util/JSONParm.java
package com.corsair.dbpool.util;
import java.util.List;
import net.sf.json.JSONObject;
/** JSON参数对象
* @author Administrator
*
*/
public class JSONParm {
private String parmname;
private String reloper;
private String parmvalue;
public static JSONParm getParmByName(List<JSONParm> parms, String parmname) {
for (JSONParm parm : parms) {
if (parmname.equals(parm.parmname)) {
return parm;
}
}
return null;
}
public static boolean hasParmName(List<JSONParm> parms, String parmname) {
JSONParm parm = getParmByName(parms, parmname);
return (parm != null);
}
public JSONParm(String parmname, String reloper, String parmvalue) {
this.parmname = parmname;
this.reloper = reloper;
this.parmvalue = parmvalue;
}
public String getParmname() {
return parmname;
}
public String getReloper() {
return reloper;
}
public String getParmvalue() {
return parmvalue;
}
public void setParmname(String parmname) {
this.parmname = parmname;
}
public void setReloper(String reloper) {
this.reloper = reloper;
}
public void setParmvalue(String parmvalue) {
this.parmvalue = parmvalue;
}
public String toJSON() {
JSONObject jo = new JSONObject();
jo.put("parmname", parmname);
jo.put("reloper", reloper);
jo.put("parmvalue", parmvalue);
return jo.toString();
}
}<file_sep>/src/com/hr/.svn/pristine/ae/aee6978dd52b54d5ebef8c67ca9d8e5f6078c19c.svn-base
package com.hr.attd.co;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.attd.ctr.CtrHrkq_leave_blance;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.attd.entity.Hrkq_leave_blance;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_leavejob;
@ACO(coname = "web.hrkq.leaveblc")
public class COhrkq_leave_blance {
@ACOAction(eventname = "createYearLeaveInfo", Authentication = true, notes = "生成年假")
public String createYearLeaveInfo() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String year = CorUtil.hashMap2Str(parms, "year", "参数year不能为空");
String orgid = CorUtil.hashMap2Str(parms, "orgid", "参数orgid不能为空");
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String sqlstr = "select distinct * from(SELECT e.* FROM hr_employee e,hr_orgposition op,hr_standposition sp "
+ " WHERE e.ospid=op.ospid AND op.sp_id=sp.sp_id AND e.empstatid IN(3,4,5) and sp.yhtype=1 "
+ " AND e.idpath LIKE '" + org.idpath.getValue() + "%') tb where 1=1 ";
CJPALineData<Hr_employee> emps = new CJPALineData<Hr_employee>(Hr_employee.class);
CDBConnection con = (new Hr_employee()).pool.getCon(this);
con.startTrans();
try {
emps.findDataBySQL(con, sqlstr, false, false);
int i = 0;
for (CJPABase jpa : emps) {
Hr_employee emp = (Hr_employee) jpa;
CtrHrkq_leave_blance.getYearLeave_blance(con, emp, year, true);
System.out.println("进度:" + (++i) + "/" + emps.size());
}
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
JSONObject rst = new JSONObject();
rst.put("result", "OK");
return rst.toString();
}
@ACOAction(eventname = "geterleavelblc", Authentication = true, notes = "获取某人可休假列表")
public String geterleavelblc() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "参数er_id不能为空");
boolean isv = Boolean.valueOf(CorUtil.hashMap2Str(parms, "isv"));// 是否可用 没超时 且 没用完
String sqlstr = "SELECT * FROM hrkq_leave_blance WHERE 1=1 and er_id=" + er_id;
if (isv)
sqlstr = sqlstr + " and valdate>'" + Systemdate.getStrDateyyyy_mm_dd() + "' and alllbtime>usedlbtime";
sqlstr = sqlstr + " order by valdate desc, lbid desc";
Hrkq_leave_blance lb = new Hrkq_leave_blance();
return lb.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "可调休余额导入Excel")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
String idpathwhere = CSContext.getIdpathwhere();
String entid = CSContext.getCurEntID();
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 1);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 1);
Hr_employee emp = new Hr_employee();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
int ct = values.size();
int curidx = 0;
for (Map<String, String> v : values) {
Logsw.debug("可调休余额导入【" + (curidx++) + "/" + ct + "】");
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'" + idpathwhere);
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在或权限范围内不存在");
String sstype = dictemp.getVbCE("1019", v.get("stype"), false, "工号【" + employee_code + "】调休来源【" + v.get("stype") + "】不存在");
int stype = Integer.valueOf(sstype);
String sccode = (stype == 1) ? v.get("sccode") : "0";
String sqlstr = "SELECT * FROM hrkq_leave_blance WHERE stype=" + stype + " and er_id=" + emp.er_id.getValue()
+ " AND sid =0 and sccode='" + sccode + "'";
Hrkq_leave_blance lb = new Hrkq_leave_blance();
// lb.findBySQL(con, sqlstr, false);
// if (!lb.isEmpty())
// throw new Exception("工号【" + employee_code + "】【" + v.get("stype") + "】调休信息已经存在");
float alllbtime = Float.valueOf(v.get("alllbtime"));
float usedlbtime = Float.valueOf(v.get("usedlbtime"));
Date valdate = Systemdate.getDateByStr(v.get("valdate"));
lb.clear();
lb.lbname.setValue(v.get("stype")); // 标题
lb.stype.setAsInt(stype); // 源类型 1 年假 2 加班 3 值班 4出差
lb.sid.setAsInt(0); // 源ID
lb.sccode.setValue(sccode); // 源编码/年假的年份
lb.er_id.setValue(emp.er_id.getValue()); // 人事ID
lb.employee_code.setValue(emp.employee_code.getValue()); // 工号
lb.employee_name.setValue(emp.employee_name.getValue());
lb.hg_name.setValue(emp.hg_name.getValue()); // 职等名称
lb.lv_num.setValue(emp.lv_num.getValue()); // 职级
lb.orgid.setValue(emp.orgid.getValue()); // 部门ID
lb.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
lb.orgname.setValue(emp.orgname.getValue()); // 部门名称
lb.alllbtime.setAsFloat(alllbtime); // 可调休时间小时
lb.usedlbtime.setAsFloat(usedlbtime); // 已调休时间小时
lb.valdate.setAsDatetime(valdate); // 有效期
lb.note.setValue(v.get("note"));
lb.idpath.setValue(emp.idpath.getValue()); // idpath
lb.save(con);
}
// throw new Exception("不给通过");
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("来源类型", "stype", true));
efields.add(new CExcelField("年度", "sccode", true));
efields.add(new CExcelField("总调休时间(H)", "alllbtime", true));
efields.add(new CExcelField("已经调休时间(H)", "usedlbtime", true));
efields.add(new CExcelField("到期时间", "valdate", true));
efields.add(new CExcelField("备注", "note", false));
return efields;
}
}
<file_sep>/src/com/hr/publishedco/COPublicTransfer.java
package com.hr.publishedco;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.base.CSContext;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.DictionaryTemp;
import com.hr.attd.entity.Hrkq_holidayapp_cancel;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_transfer;
@ACO(coname = "hr.transfer")
public class COPublicTransfer {
// {
// "employee_code": "540039",
// "tranflev": "4",
// "tranftype1": "3",
// "tranftype2": "1",
// "tranftype3": "4",
// "tranfreason": "测试",
// "probation": "0",
// "oldcalsalarytype": "计件",
// "oldchecklev": "5",
// "neworgcode": "00012400",
// "newospcode": "OP2001000300",
// "neworgcode": "00012400",
// "newospcode": "OP2001000300",
// "newsp_name": "装配工",
// "newattendtype": "3",
// "newcalsalarytype": "计件",
// "newstru_id": "2",
// "newstru_name": "5天无考核",
// "newchecklev": "5",
// "salary_qcnotnull": "2",
// "istp": "2",
// "tranamt": "0.00",
// "exam_score": "0.00",
// "mupexam_score": "0.00",
// "quota_over": "2",
// "quota_over_rst": "0",
// "isdreamposition": "2",
// "isdreamemploye": "2",
// "tranftype4": "4",
// "isexistsrl": "2",
// "stat": "1",
// "idpath": "1,179,181,144,",
// "entid": "1",
// "creator": "DEV",
// "createtime": "2020-09-15 10:17:58",
// "updator": "DEV",
// "updatetime": "2020-09-15 10:17:58",
// "shw_attachs": [],
// "hr_employee_transfer_rls": []
// }
@ACOAction(eventname = "getTransferJson", Authentication = false, notes = "创建调动单")
public String getTransferJson() throws Exception {
Hr_employee_transfer hr_employee_transfer = new Hr_employee_transfer();// 创建销假表单实体
hr_employee_transfer.findByID("180303");
return hr_employee_transfer.tojson();
}
@ACOAction(eventname = "hr_add_transfer", Authentication = false, notes = "创建调单并自动提交生效")
public String hr_add_transfer() throws Exception{
Hr_employee emp = new Hr_employee();
Hr_orgposition oldosp = new Hr_orgposition();
Hr_orgposition newosp = new Hr_orgposition();
Hr_employee_transfer tr = new Hr_employee_transfer();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
tr.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
String employee_code =tr.employee_code.getValue();
if ((employee_code == null) || (employee_code.isEmpty())){
return "N";
}
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
oldosp.clear();
oldosp.findBySQL("SELECT * FROM hr_orgposition WHERE ospcode='" + tr.odospcode.getValue() + "'", false);
if (oldosp.isEmpty())
throw new Exception("工号【" + employee_code + "】的调动前机构职位编码【" + tr.odospcode.getValue()+ "】不存在");
newosp.clear();
newosp.findBySQL("SELECT * FROM hr_orgposition WHERE ospcode='" + tr.newospcode.getValue() + "'", false);
if (newosp.isEmpty())
throw new Exception("工号【" + employee_code + "】的调动后机构职位编码【" + tr.newospcode.getValue() + "】不存在");
tr.clear();
tr.er_id.setValue(emp.er_id.getValue()); // 人事ID
tr.employee_code.setValue(emp.employee_code.getValue()); // 工号
tr.id_number.setValue(emp.id_number.getValue()); // 身份证号
tr.employee_name.setValue(emp.employee_name.getValue()); // 姓名
tr.mnemonic_code.setValue(emp.mnemonic_code.getValue()); // 助记码
tr.email.setValue(emp.email.getValue()); // 邮箱/微信
tr.empstatid.setValue(emp.empstatid.getValue()); // 人员状态
tr.telphone.setValue(emp.telphone.getValue()); // 电话
//tr.tranfcmpdate.setValue(v.get("tranfcmpdate")); // 调动时间
// tr.hiredday.setValue(emp.hiredday.getValue()); // 聘用日期
tr.degree.setValue(emp.degree.getValue()); // 学历
tr.tranflev.setValue(dictemp.getVbCE("1215",tr.tranflev.getValue(), false, "工号【" + employee_code + "】调动层级【" +tr.tranflev.getValue() + "】不存在")); // 调动层级
tr.tranftype1.setValue(dictemp.getVbCE("719",tr.tranftype1.getValue(), false, "工号【" + employee_code + "】调动类别【" + tr.tranftype1.getValue() + "】不存在")); // 调动类别
tr.tranftype2.setValue(dictemp.getVbCE("724",tr.tranftype2.getValue(), false, "工号【" + employee_code + "】调动性质【" +tr.tranftype2.getValue() + "】不存在")); // 调动性质
tr.tranftype3.setValue(dictemp.getVbCE("729",tr.tranftype3.getValue(), true, "工号【" + employee_code + "】调动范围【" + tr.tranftype3.getValue() + "】不存在")); // 调动范围
tr.ispromotioned.setValue("1"); // 已转正
tr.odorgid.setValue(oldosp.orgid.getValue()); // 调动前部门ID
tr.odorgcode.setValue(oldosp.orgcode.getValue()); // 调动前部门编码
tr.odorgname.setValue(oldosp.orgname.getValue()); // 调动前部门名称
tr.odorghrlev.setValue("0"); // 调调动前部门人事层级
tr.odlv_id.setValue(oldosp.lv_id.getValue()); // 调动前职级ID
tr.odlv_num.setValue(oldosp.lv_num.getValue()); // 调动前职级
tr.odhg_id.setValue(oldosp.hg_id.getValue()); // 调动前职等ID
tr.odhg_code.setValue(oldosp.hg_code.getValue()); // 调动前职等编码
tr.odhg_name.setValue(oldosp.hg_name.getValue()); // 调动前职等名称
tr.odospid.setValue(oldosp.ospid.getValue()); // 调动前职位ID
tr.odospcode.setValue(oldosp.ospcode.getValue()); // 调动前职位编码
tr.odsp_name.setValue(oldosp.sp_name.getValue()); // 调动前职位名称
String oldemnature = (oldosp.isoffjob.getAsIntDefault(0) == 1) ? "脱产" : "非脱产";
tr.oldemnature.setValue(oldemnature);// 调动后职位性质
tr.oldemnature.setValue(emp.emnature.getValue());// 调动前职位性质
tr.odattendtype.setValue(emp.atdtype.getValue()); // 调动前出勤类别
tr.oldcalsalarytype.setValue("0"); // 调动前计薪方式
tr.oldhwc_namezl.setValue(oldosp.hwc_namezl.getValue()); // 调动前职类
tr.oldhwc_namezq.setValue(oldosp.hwc_namezq.getValue());// 调动前职群
tr.oldhwc_namezz.setValue(oldosp.hwc_namezz.getValue());// 调动前职种
tr.oldposition_salary.setValue("0"); // 调动前职位工资
tr.oldbase_salary.setValue("0"); // 调动前基本工资
tr.oldtech_salary.setValue("0"); // 调动前技能工资
tr.oldachi_salary.setValue("0"); // 调动前技能工资
tr.oldtech_allowance.setValue("0"); // 调动前技术津贴
tr.oldavg_salary.setValue("0"); // 调动前平均工资
tr.neworgid.setValue(newosp.orgid.getValue()); // 调动后部门ID
tr.neworgcode.setValue(newosp.orgcode.getValue()); // 调动后部门编码
tr.neworgname.setValue(newosp.orgname.getValue()); // 调动后部门名称
tr.neworghrlev.setValue("0"); // 调动后部门人事层级*
tr.newlv_id.setValue(newosp.lv_id.getValue()); // 调动后职级ID
tr.newlv_num.setValue(newosp.lv_num.getValue()); // 调动后职级
tr.newhg_id.setValue(newosp.hg_id.getValue()); // 调动后职等ID
tr.newhg_code.setValue(newosp.hg_code.getValue()); // 调动后职等编码
tr.newhg_name.setValue(newosp.hg_name.getValue()); // 调动后职等名称
tr.newospid.setValue(newosp.ospid.getValue()); // 调动后职位ID
tr.newospcode.setValue(newosp.ospcode.getValue()); // 调动后职位编码
tr.newsp_name.setValue(newosp.sp_name.getValue()); // 调动后职位名称
String newemnature = (newosp.isoffjob.getAsIntDefault(0) == 1) ? "脱产" : "非脱产";
tr.newemnature.setValue(newemnature);// 调动后职位性质
tr.newattendtype.setValue("0"); // 19.3.21 取消 调动后出勤类别 dictemp.getVbCE("1399", v.get("newattendtype"), true, "工号【" + employee_code + "】调动后出勤类别【" + v.get("newattendtype") + "】不存在")
tr.newcalsalarytype.setValue("0"); // 调动后计薪方式
tr.newhwc_namezl.setValue(newosp.hwc_namezl.getValue()); // 调动后职类
tr.newhwc_namezq.setValue(newosp.hwc_namezq.getValue());// 调动后职群
tr.newhwc_namezz.setValue(newosp.hwc_namezz.getValue());// 调动后职种
tr.newposition_salary.setValue("0"); // 调动前职位工资
tr.newbase_salary.setValue("0"); // 调动后基本工资
tr.newtech_salary.setValue("0"); // 调动后技能工资
tr.newachi_salary.setValue("0"); // 调动后技能工资
tr.newtech_allowance.setValue("0"); // 调动后技术津贴
tr.newavg_salary.setValue("0"); // 调动后平均工资
tr.salary_quotacode.setValue("0"); // 可用工资额度证明编号
tr.salary_quota_stand.setValue("0"); // 标准工资额度
tr.salary_quota_canuse.setValue("0"); // 可用工资额度
tr.salary_quota_used.setValue("0"); // 己用工资额度
tr.salary_quota_blance.setValue("0"); // 可用工资余额
tr.salary_quota_appy.setValue("0"); // 申请工资额度
tr.salary_quota_ovsp.setValue("0"); // 超额度审批
tr.salarydate.setValue(null); // 核薪生效日期
tr.istp.setValue(dictemp.getVbCE("5", tr.istp.getValue(), true, "工号【" + employee_code + "】是否词汇【" + tr.istp.getValue() + "】不存在")); // 是否特批
tr.quota_over.setValue("2"); // 是否超编
tr.quota_over_rst.setValue("2"); // 超编审批结果 1 允许增加编制调动 ps是否自动生成编制调整单 2 超编调动 3 不允许调动
tr.isdreamposition.setValue("2"); // 是否梦职场调入
tr.isdreamemploye.setValue("2"); // 是否梦职场储备员工
tr.tranftype4.setValue(dictemp.getVbCE("1189",tr.tranftype4.getValue(), true, "工号【" + employee_code + "】调动类型【" +tr.tranftype4.getValue() + "】不存在")); // 调动类型
// 4其他调动
tr.isexistsrl.setValue("2"); // 关联关系 有关联关系 无关联关系
tr.rlmgms.setValue("1"); // 管控措施 不需管控 终止调动 申请豁免
tr.ismangerl.setValue("2"); // 是否构成需要管控的管理关系类别
tr.isapprlhm.setValue(null); // 是否申请关联关系豁免
tr.isapprlhmsp.setValue(null); // 关联关系豁免申请是否得到审批
tr.quotastand.setValue("0"); // 标准配置人数
tr.quotasj.setValue("0"); // 实际配置人数
tr.quotacq.setValue("0"); // 超缺编人数(正数表示超编、负数表示缺编)
tr.isallowdrmin.setValue(null); // 是否同意特批调动至梦职场职位
tr.idpath.setValue(emp.idpath.getValue()); // idpath
tr.stat.setAsInt(9);
tr.attribute3.setValue("BMS接口写入");
tr.save(con);
tr.wfcreate(null, con);
return "Y";
}
}
<file_sep>/src/com/corsair/server/weixin/entity/Shwwxappqrcode.java
package com.corsair.server.weixin.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "微信参数二维码")
public class Shwwxappqrcode extends CJPA {
@CFieldinfo(fieldname = "qcid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "平台ID", datetype = Types.INTEGER)
public CField qcid; // 平台ID
@CFieldinfo(fieldname = "appid", notnull = true, precision = 10, scale = 0, caption = "平台appid", datetype = Types.INTEGER)
public CField appid; // 平台appid
@CFieldinfo(fieldname="expiretime",notnull=true,precision=11,scale=0,caption="到期时间 linux时间戳 /1000",datetype=Types.INTEGER)
public CField expiretime; //到期时间 linux时间戳 /1000 0表示永久
@CFieldinfo(fieldname = "ticket", notnull = true, precision = 128, scale = 0, caption = "获取的二维码ticket https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET", datetype = Types.VARCHAR)
public CField ticket; // 获取的二维码ticket https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
@CFieldinfo(fieldname = "url", precision = 256, scale = 0, caption = "二维码字符串", datetype = Types.VARCHAR)
public CField url; // 二维码字符串
@CFieldinfo(fieldname = "scene_id", precision = 10, scale = 0, caption = "场景值ID", datetype = Types.INTEGER)
public CField scene_id; // 场景值ID
@CFieldinfo(fieldname = "scene_str", precision = 64, scale = 0, caption = "字符串形式的ID", datetype = Types.VARCHAR)
public CField scene_str; // 字符串形式的ID
@CFieldinfo(fieldname = "remark", precision = 32, scale = 0, caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwwxappqrcode() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/3a/3a77633ea39b0373b56deb2e7dc351cea3d4c3c7.svn-base
package com.hr.inface.ctr;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.hr.access.entity.Hr_access_emauthority_sum;
import com.hr.access.entity.Hr_access_list;
import com.hr.card.entity.Hr_ykt_card;
import com.hr.inface.entity.View_ICCO_AssignEmp;
public class TimerTaskHRAccessSum extends TimerTask {
private static int syncrowno = 5000;
@Override
public void run() {
try {
String sqlstr = "SELECT t.parmvalue FROM hrkq_parms t where t.parmcode = 'ACCESS_SUM_SYNTIME'";
Hr_access_emauthority_sum aes1 = new Hr_access_emauthority_sum();
List<HashMap<String, String>> sws = aes1.pool.openSql2List(sqlstr);
String mx = ((sws.size() == 0) || (sws.get(0).get("parmvalue") == null)) ? "" : String.valueOf(sws.get(0).get("parmvalue"));
CJPALineData<Hr_access_emauthority_sum> aes = new CJPALineData<Hr_access_emauthority_sum>(Hr_access_emauthority_sum.class);
sqlstr = "SELECT * FROM hr_access_emauthority_sum t WHERE t.updatetime>'" + mx + "' order by t.updatetime LIMIT 0," + syncrowno;
aes.findDataBySQL(sqlstr, true, false);
CJPALineData<View_ICCO_AssignEmp> iae = new CJPALineData<View_ICCO_AssignEmp>(View_ICCO_AssignEmp.class);
String lastDate = "";
for (CJPABase jpa : aes) {
Hr_access_emauthority_sum ae = (Hr_access_emauthority_sum) jpa;
View_ICCO_AssignEmp iae1 = new View_ICCO_AssignEmp();
Hr_ykt_card yc = new Hr_ykt_card();
String sqlstr2 = "SELECT * FROM hr_ykt_card t WHERE t.employee_code = '" + ae.employee_code.getValue() + "'";
yc.findBySQL(sqlstr2);
if (yc.isEmpty())
throw new Exception("工号【" + ae.employee_code.getValue() + "】不存在");
Hr_access_list al = new Hr_access_list();
String sqlstr4 = "SELECT * FROM hr_access_list t WHERE t.access_list_id = " + ae.access_list_id.getValue();
al.findBySQL(sqlstr4);
/*
* iae1.card_id.setValue(yc.card_id.getValue());
* iae1.clock_id.setValue(ae.access_list_code.getValue());//门禁编码
* iae1.opDate.setValue(ae.accredit_date.getValue());//授权日期
* iae1.join_id.setValue(ae.employee_name.getValue());//员工姓名
* iae1.card_sn.setValue(yc.card_sn.getValue());//卡号
* iae1.depart_id.setValue(ae.orgcode.getValue());//部门编码
* iae.add(iae1);
*/
lastDate = ae.updatetime.getValue();
if (!al.isEmpty()) {
String sqlstr3 = "INSERT INTO dbo.ICCO_TaskCard (card_id,clock_id,ope_date,join_id,card_sn,depart_id,user_name,code,state,door_val,down_flag) VALUES ('" +
yc.card_number.getValue() + "','" + al.access_list_code.getValue() + "','" + ae.accredit_date.getValue() + "','" + yc.er_id.getValue() +
"','" + yc.card_sn.getValue() + "','" + ae.orgcode.getValue() + "','" + ae.creator.getValue() + "','" + yc.employee_code.getValue() +
"','0','01020304','0')";
DBPools.poolByName("oldtxmssql").execsql(sqlstr3);
}
}
if (aes.size() > 0) {
// iae.saveBatchSimple();// 高速存储
String sqlstr1 = "UPDATE hrkq_parms t SET t.parmvalue = '" + lastDate + "' WHERE t.parmcode='ACCESS_SUM_SYNTIME'";
aes1.pool.execsql(sqlstr1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/server/weixin/TonkenReflash.java
package com.corsair.server.weixin;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.weixin.entity.Shwwxapp;
public class TonkenReflash {
private static int expires_in = 7200;
private List<Thread> tonkensers = new ArrayList<Thread>();
public TonkenReflash() throws Exception {
// WxTonkenServiceActive appid1;appid2;appid3;
// if (ConstsSw.getAppParm("WxTonkenSerAppid") != null) {
// String ids = ConstsSw.geAppParmStr("WxTonkenSerAppid");
// String[] appids = ids.split(";");
// for (String appid : appids) {
// Shwwxapp app = WXAppParms.getShwwxappByAppID(appid);
// if (app != null) {
// if ("1".equals(WXAppParms.getAppParm(app, "UsesAble"))) {
// createAPPReflasher(app);
// }
// }
// }
// }
if (ConstsSw.getAppParmBoolean("WxTonkenServiceActive")) {
CJPALineData<Shwwxapp> shwwxapps = WXAppParms.getShwwxapps();
for (CJPABase jpa : shwwxapps) {
Shwwxapp wxapp = (Shwwxapp) jpa;
if ("1".equals(WXAppParms.getAppParm(wxapp, "UsesAble"))) {
createAPPReflasher(wxapp);
}
}
}
}
private void createAPPReflasher(Shwwxapp app) throws Exception {
System.out.println("TonkenReflash created,APPID:" + app.wxappid.getValue());
String pn = WXAppParms.getAppParm(app, "WxDbpool");
CDBPool pool = DBPools.poolByName(pn);
String appsecret = WXAppParms.getAppParm(app, "Wxappsecret");
createTable(pool);
Thread tonkenService = new Thread(new TonkenService(pool, app.wxappid.getValue(), appsecret));
tonkensers.add(tonkenService);
}
public void StartService() {
for (Thread t : tonkensers) {
t.start();
}
}
public void StopService() {
for (Thread t : tonkensers) {
if (t != null)
t.interrupt();
}
}
private void createTable(CDBPool pool) throws Exception {
String csql = " CREATE TABLE IF NOT EXISTS `wx_access_tonken` ("
+ " `appid` varchar(128) NOT NULL,"
+ " `tonken` varchar(1024) NOT NULL,"
+ " `ticket` varchar(1024) NOT NULL,"
+ " `updatetime` datetime NOT NULL,"
+ " PRIMARY KEY (`appid`)"
+ ") ENGINE=MyISAM DEFAULT CHARSET=utf8";
pool.execsql(csql);
}
private class TonkenService implements Runnable {
private CDBPool pool;
public String appid;
public String appsecret;
private TonkenService(CDBPool pool, String appid, String appsecret) {
this.pool = pool;
this.appid = appid;
this.appsecret = appsecret;
}
@Override
public void run() {
while (true) {
// {"access_token":"<KEY>","expires_in":7200}
try {
getaccess_token();
} catch (Exception e1) {
try {
Thread.sleep(5000);
getaccess_token();
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
try {
Logsw.error(e1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep((expires_in - 5) * 1000);// 提前5m刷新
} catch (InterruptedException e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
private void getaccess_token() throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/token";
HashMap<String, String> parms = new HashMap<String, String>();
parms.put("grant_type", "client_credential");
parms.put("appid", appid);
parms.put("secret", appsecret);
String rst = WXHttps.getHttps(url, parms);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
if (rootNode.has("access_token")) {
String access_token = rootNode.path("access_token").getTextValue();
url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
rst = WXHttps.getHttps(url, null);
rootNode = mapper.readTree(rst);
if (rootNode.has("ticket")) {
String ticket = rootNode.path("ticket").getTextValue();
updateToken(access_token, ticket);
} else
System.out.println("获取jsapi错误!");
System.out.println("reflash access tonken【" + access_token + "】at 【" + Systemdate.getStrDate() + "】");
}
if (rootNode.has("expires_in")) {
expires_in = rootNode.path("expires_in").asInt();
}
}
private void updateToken(String token, String ticket) throws Exception {
CDBConnection con = pool.getCon(this);
try {
con.startTrans();
con.execsql("delete from wx_access_tonken where appid='" + appid + "'");
String sqlstr = "insert into wx_access_tonken(appid,tonken,ticket,updatetime) values('"
+ appid + "','" + token + "','" + ticket + "',sysdate())";
con.execsql(sqlstr);
con.submit();
} catch (Exception e) {
con.rollback();
Logsw.error(e);
} finally {
con.close();
}
}
}
private boolean isIPInSelf(String ip) {
if (ip == null)
return false;
try {
for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface item = e.nextElement();
for (InterfaceAddress address : item.getInterfaceAddresses()) {
if (address.getAddress() instanceof Inet4Address) {
Inet4Address inet4Address = (Inet4Address) address.getAddress();
if (ip.equalsIgnoreCase(inet4Address.getHostAddress()))
return true;
}
}
}
} catch (IOException ex) {
}
return false;
}
}
<file_sep>/src/com/corsair/dbpool/util/Systemdate.java
package com.corsair.dbpool.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* 日期处理类
*
* @author Administrator
*
*/
public final class Systemdate {
// ///标准
/**
* @return 返回yyyy-MM-dd HH:mm:ss 格式日期
*/
public static String getStrDate() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //
return df.format(new Date()); //
}
/**
* @param dt
* @return 返回yyyy-MM-dd HH:mm:ss 格式日期
*/
public static String getStrDate(Date dt) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //
return df.format(dt); //
}
/**
* 支持将以下格式字符串转为日期
* 2016-02-03 14:30:12:667;
* 2016-02-03 14:30:12;
* 2016-02-03 14:30;
* 2016-02-03 14;
* 2016-02-03;
* 2016-02;
* 2016;
* 2016-2-3 14:30:12;
* 2016/2/3 14:30:12;
* 16/2/3 14:30:12;
* 2001-11-06 11:10:58.098
*
* @param strdt
* @return
*/
public static Date getDateByStr(String strdt) {
try {
String ymd = null;
String hms = null;
int dhidx = strdt.indexOf(" ");
if (dhidx == -1) {
ymd = strdt;
hms = "00:00:00";
} else {
ymd = strdt.substring(0, dhidx);
hms = strdt.substring(dhidx + 1, strdt.length());
}
String dsp = getSepDate(ymd);// 获取年月日分隔符
String[] dts = (dsp == null) ? new String[] { ymd } : ymd.split(getSepDate(ymd));
int y = (dts.length > 0) ? Integer.valueOf(dts[0]) : 1970;
y = (y < 100) ? 2000 + y : y;
int m = (dts.length > 1) ? Integer.valueOf(dts[1]) : 1;
int d = (dts.length > 2) ? Integer.valueOf(dts[2]) : 1;
hms = hms.replace(".", ":");
dts = hms.split(":");
int hh = (dts.length > 0) ? Integer.valueOf(dts[0]) : 0;
int mm = (dts.length > 1) ? Integer.valueOf(dts[1]) : 0;
int ss = (dts.length > 2) ? Integer.valueOf(dts[2]) : 0;
int mmm = (dts.length > 3) ? Integer.valueOf(dts[3]) : 0;
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, y);
c.set(Calendar.MONTH, m - 1);
c.set(Calendar.DAY_OF_MONTH, d);
c.set(Calendar.HOUR_OF_DAY, hh);
c.set(Calendar.MINUTE, mm);
c.set(Calendar.SECOND, ss);
c.set(Calendar.MILLISECOND, mmm);
return c.getTime();
} catch (NumberFormatException e) {
Logsw.debug("解析日期字符串错误【" + strdt + "】");
throw e;
}
}
/**
* @param strdt
* @param format
* @return 返回指定格式日期
* @throws Exception
*/
public static Date getDateByStr(String strdt, String format) throws Exception {
return new SimpleDateFormat(format).parse(strdt);
}
private static String getSepDate(String ymd) {
for (int i = 0; i < ymd.length(); i++) {
if (!Character.isDigit(ymd.charAt(i))) {
return ymd.substring(i, i + 1);
}
}
return null;
}
// public static Date getDateByStr(String dts) {
// SimpleDateFormat sdf = null;
// if (dts.indexOf(":") > 0)
// sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// else
// sdf = new SimpleDateFormat("yyyy-MM-dd");
// try {
// return sdf.parse(dts);
// } catch (ParseException e) {
// // TODO Auto-generated catch block
// try {
// Logsw.error(e);
// } catch (Exception e1) {
// return null;
// }
// return null;
// }
// }
public static String getStrDateByFmt(Date dt, String fmt) {
SimpleDateFormat df = new SimpleDateFormat(fmt); //
return df.format(dt); //
}
/**
* @return yyyy-MM-dd HH:mm:ss:SSS毫秒
*/
public static String getStrDateMs() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //
return df.format(new Date()); //
}
/**
* @param dt
* @return yyyy-MM-dd HH:mm:ss.SSS
*/
public static String getStrDateMs(Date dt) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //
return df.format(dt); //
}
/**
* @return yyyy-MM-dd
*/
public static String getStrDateyyyy_mm_dd() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //
return df.format(new Date()); //
}
/*
* 获取当月1号
*/
public static String getStrDateyyyy_mm_01() throws Exception {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-01"); //
return df.format(new Date()); //
}
/**
* @param dt
* @return yyyy-MM-dd
*/
public static String getStrDateyyyy_mm_dd(Date dt) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //
return df.format(dt); //
}
/**
* @param value
* @return yyyy-MM-dd
*/
public static Date getDateByyyyy_mm_dd(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(value);
} catch (ParseException e) {
// TODO Auto-generated catch block
try {
Logsw.error(e);
} catch (Exception e1) {
return null;
}
return null;
}
}
// ////非标准
/**
* @return yyMM
*/
public static String getStrDateNowYYMM() {
SimpleDateFormat df = new SimpleDateFormat("yyMM");
return df.format(new Date()); //
}
/**
* @return yyMMdd
*/
public static String getStrDateYYMMDD() {
SimpleDateFormat df = new SimpleDateFormat("yyMMdd");
return df.format(new Date()); //
}
/**
* 去掉时分秒
*
* @param date
* @return yyyy-MM-dd
* @throws ParseException
*/
public static Date getDateYYYYMMDD(Date date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String s = sdf.format(date);
return sdf.parse(s);
}
/**
* 去掉时分秒
*
* @param date
* @throws ParseException
*/
public static Date getDateYYYYMMDD(String datestr) throws ParseException {
return getDateYYYYMMDD(getDateByStr(datestr));
}
//
/**
* 日期加秒 原日期不变
*
* @param date
* @param second
* @return
*/
public static Date dateSecondAdd(Date date, int second) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
//
/**
* 日期加分钟 原日期不变
*
* @param date
* @param minute
* @return
*/
public static Date dateMinuteAdd(Date date, int minute) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
/**
* 日期加小时 原日期不变
*
* @param date
* @param hour
* @return
*/
public static Date dateHourAdd(Date date, int hour) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hour);
return calendar.getTime();
}
/**
* 日期加天 原日期不变
*
* @param date
* @param days
* @return
*/
public static Date dateDayAdd(Date date, int days) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
/**
* 日期加月 原日期不变
*
* @param date
* @param months
* @return
*/
public static Date dateMonthAdd(Date date, int months) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
/**
* 获取季度
*
* @param month
* @return
* @throws Exception
*/
public static int getQuarterByMoth(int month) throws Exception {
if ((month < 1) || (month > 12))
throw new Exception("计算季度错误,月份必须在1到12之间");
if ((month >= 1) && (month <= 3)) {
return 1;
} else if ((month >= 4) && (month <= 6)) {
return 2;
} else if ((month >= 7) && (month <= 9)) {
return 3;
} else
return 4;
}
/**
* 获取月最大一天
*
* @param year
* @param month
* @return
* @throws Exception
*/
public static int getMothMaxDay(int year, int month) throws Exception {
if ((month < 1) || (month > 12))
throw new Exception("计算日期错误,月份必须在1到12之间");
Calendar cd = Calendar.getInstance();
cd.set(year, month - 1, 1);
return cd.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* @param dt
* @return 返回指定日期中文星期
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 获取两个给定时间之间相差月份
*
* @param dtbegin
* @param dtEnd
* @return
*/
public static int getBetweenMonth(Date dtbegin, Date dtEnd) {
Calendar bef = new GregorianCalendar();
Calendar aft = new GregorianCalendar();
bef.setTime(dtbegin);
aft.setTime(dtEnd);
int ms = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
int yms = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
return Math.abs(yms + ms);
}
/**
* 时间段 f1-->t1 ,f2-->t2是否交叉
*
* @param f1
* @param t1
* @param f2
* @param t2
* @return
*/
public static boolean isOverlapDate(Date f1, Date t1, Date f2, Date t2) {
return ((f2.getTime() >= f1.getTime()) && (f2.getTime() <= t1.getTime())
|| (t2.getTime() >= f1.getTime()) && (t2.getTime() <= t1.getTime())
|| ((f2.getTime() <= f1.getTime()) && (t2.getTime() >= t1.getTime())));
}
/**
* 时间段 f1-->t1 ,f2-->t2 交叉长度 (单位 分钟)
*
* @param f1
* @param t1
* @param f2
* @param t2
* @return
*/
public static float getMinuteOverlapDate(Date f1, Date t1, Date f2, Date t2) {
long lf1 = f1.getTime(), lt1 = t1.getTime(), lf2 = f2.getTime(), lt2 = t2.getTime();
long lmm = 0;
System.out.println("lf1:" + lf1);
System.out.println("lt1:" + lt1);
System.out.println("lf2:" + lf2);
System.out.println("lt2:" + lt2);
if ((lf2 <= lf1) && (lt2 >= lf1) && (lt2 <= lt1)) {
// ********f1**********t1*****
// ****f2******t2*************
// System.out.println("tp1");
lmm = lt2 - lf1;
} else if ((lf2 <= lf1) && (lt2 >= lt1)) {
// ********f1**********t1*****
// ****f2******************t2*
// System.out.println("tp2");
lmm = lt1 - lf1;
} else if ((lf2 >= lf1) && (lt2 <= lt1)) {
// ********f1**********t1*****
// ***********f2****t2********
// System.out.println("tp3");
lmm = lt2 - lf2;
} else if ((lf2 >= lf1) && (lf2 <= lt1) && (lt2 > lt1)) {
// ********f1**********t1*****
// ***********f2**********t2**
// System.out.println("tp4");
lmm = lt1 - lf2;
} else {
System.out.println("GRD~~~~~~~~~~~");
}
float rst = lmm / (1000 * 60);
return rst;
}
/**
* @param date
* @return 获取指定日期所在周,周一的 日期
*/
public static Date getFirstOfWeek(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int d = 0;
if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
d = -6;
} else {
d = 2 - cal.get(Calendar.DAY_OF_WEEK);
}
cal.add(Calendar.DAY_OF_WEEK, d);
// 所在周开始日期
return cal.getTime();
}
/**
* @param date
* @return 返回指定日期所在周,周一,周天 的日期
*/
public static TwoDate getFirstAndLastOfWeek(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int d = 0;
if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
d = -6;
} else {
d = 2 - cal.get(Calendar.DAY_OF_WEEK);
}
cal.add(Calendar.DAY_OF_WEEK, d);
// 所在周开始日期
Date date1 = cal.getTime();
cal.add(Calendar.DAY_OF_WEEK, 6);
// 所在周结束日期
Date date2 = cal.getTime();
return new TwoDate(date1, date2);
}
/**
* @param date
* @return 获取指定日期所在月, 第一天和最后一天所在日期
* @throws Exception
*/
public static TwoDate getFirstAndLastOfMonth(Date date) throws Exception {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String ym = getStrDateByFmt(date, "yyyy-MM");
Date date1 = getDateByStr(ym + "-01");
int md = getMothMaxDay(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);
Date date2 = getDateByStr(ym + "-" + md);
return new TwoDate(date1, date2);
}
/**
* @param yearmonth
* yyyy-MM
* @param weekday
* 1:周天 2:周一 ......
* 与Calendar定义的常量一致 Calendar.MONDAY
* @return 获取某月第一周,周几所在日期
*/
public static Date getMonthFirstWeekDay(String yearmonth, int weekday) {
Date date = getDateByStr(yearmonth + "-01");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int i = 0;
while (cal.get(Calendar.DAY_OF_WEEK) != weekday) {
cal.add(Calendar.DATE, i++);
}
return cal.getTime();
}
public static void main(String[] args) throws Exception {
Date f1 = getMonthFirstWeekDay("2018-04", Calendar.MONDAY);
System.out.println("第一个周一:" + getStrDateyyyy_mm_dd(f1));
Calendar time = Calendar.getInstance();
time.setTime(f1);
int days = time.getActualMaximum(Calendar.DAY_OF_MONTH);// 本月份的天数
System.out.println(days);
}
}
<file_sep>/src/com/hr/publishedco/COPublished1.java
package com.hr.publishedco;
import java.util.List;
import java.util.Date;
//以上二项新增
import java.util.HashMap;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.Login;
import com.corsair.server.csession.CSession;
import com.corsair.server.genco.COCSCommon;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shworguser;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.hr.attd.entity.Hrkq_business_trip;
import com.hr.attd.entity.Hrkq_holidayapp;
import com.hr.attd.entity.Hrkq_holidayapp_cancel;
import com.hr.attd.entity.Hrkq_holidaytype;
import com.hr.attd.entity.Hrkq_overtime;
import com.hr.attd.entity.Hrkq_overtime_hour;
import com.hr.attd.entity.Hrkq_overtime_line;
import com.hr.attd.entity.Hrkq_resign;
import com.hr.attd.entity.Hrkq_wkoff;
import com.hr.attd.entity.Hrkq_wkoffsourse;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_linked;
import com.hr.perm.entity.Hr_entry;
import com.hr.salary.co.Cosacommon;
import com.hr.util.HRUtil;
import com.sun.corba.se.impl.encoding.OSFCodeSetRegistry.Entry;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.attd.entity.Hrkq_bckqrst;//以下二项新增
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@ACO(coname = "hr.published1")
public class COPublished1 {
@ACOAction(eventname = "hrkq_holidayapp_new", Authentication = false, notes = "创建请假表单并自动提交生效")
public String hrkq_holidayapp_new() throws Exception {
Hrkq_holidayapp happ = new Hrkq_holidayapp();// 创建请假表单实体
happ.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
if (happ.employee_code.isEmpty()) {
new Exception("请假表单字段【employee_code】不能为空");
}
if (happ.hdays.isEmpty()) {
new Exception("请假表单字段【hdays】不能为空");
}
if (happ.timebg.isEmpty()) {
new Exception("请假表单字段【timebg】不能为空");
}
if (happ.timeed.isEmpty()) {
new Exception("请假表单字段【timeed】不能为空");
}
if (happ.htid.isEmpty()) {
new Exception("请假表单字段【htid】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + happ.employee_code.getValue() + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + happ.er_id.getValue() + "】的人事资料不存在");
Hrkq_holidaytype ht = new Hrkq_holidaytype();// 创建假期类型实体
ht.findByID(happ.htid.getValue());
if (ht.isEmpty())
new Exception("ID为【" + happ.htid.getValue() + "】的假期类型不存在");
happ.er_id.setValue(emp.er_id.getValue()); // 人事ID
happ.employee_code.setValue(emp.employee_code.getValue()); // 工号
happ.employee_name.setValue(emp.employee_name.getValue()); // 姓名
happ.orgid.setValue(emp.orgid.getValue()); // 部门ID
happ.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
happ.orgname.setValue(emp.orgname.getValue()); // 部门
happ.ospid.setValue(emp.ospid.getValue()); // 职位ID
happ.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
happ.sp_name.setValue(emp.sp_name.getValue()); // 职位
happ.lv_num.setValue(emp.lv_num.getValue()); // 职级
// happ.hdays.setValue(value); // 请假天数
happ.hdaystrue.setValue(happ.hdays.getValue()); // 实际天数 如果没销假 则==销假天数
// happ.timebg.setValue(value); // 请假时间开始 yyyy-MM-dd hh:mm
// happ.timeed.setValue(value); // 请假时间截止 yyyy-MM-dd hh:mm
happ.timeedtrue.setValue(happ.timeed.getValue()); // 实际截止时间 如果有销假 按销假时间 否则按申请截止时间 yyyy-MM-dd hh:mm
happ.htid.setValue(ht.htid.getValue()); // 类型ID
happ.htname.setValue(ht.htname.getValue()); // 假期类型
// happ.htreason.setValue(value); // 事由
happ.htconfirm.setValue("1"); // 假期确认 //符合规则 违反规则 空
happ.viodeal.setValue(null); // 违规处理 //事假 旷工 空
happ.timebk.setValue(null); // 销假时间 yyyy-MM-dd hh:mm
happ.btconfirm.setValue(null); // 销假确认
happ.iswfagent.setValue("1"); // 启用流程代理
happ.stat.setValue("1"); // 表单状态
happ.idpath.setValue(emp.idpath.getValue()); // idpath
happ.entid.setValue("1"); // entid
happ.creator.setValue("inteface"); // 创建人
happ.createtime.setAsDatetime(new Date()); // 创建时间
happ.orghrlev.setValue("0");
happ.emplev.setValue("0");
happ.creator.setValue("inteface");
happ.entid.setValue("1");
CDBConnection con = happ.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
// System.out.println("happ json:" + happ.tojson());
happ.save(con);// 保存请假表单
// happ.wfcreate(null, con);// 提交表单(无流程)
Shwuser admin = Login.getAdminUser();
happ.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
// String rxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><haid>" + happ.haid.getValue() + "</haid><hacode>" + happ.hacode.getValue() +
// "</hacode></xml>";
// /return rxml;
// return happ.toxml();
return happ.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "testfindhapp_cancel", Authentication = false, notes = "创建销假表单并自动提交生效")
public String testfindhapp_cancel() throws Exception {
Hrkq_holidayapp_cancel happ_cancel = new Hrkq_holidayapp_cancel();// 创建销假表单实体
happ_cancel.findByID("2733");
return happ_cancel.tojson();
}
@ACOAction(eventname = "hrkq_holidayapp_cancel_new", Authentication = false, notes = "创建销假表单并自动提交生效")
public String hrkq_holidayapp_cancel_new() throws Exception {
Hrkq_holidayapp_cancel happ_cancel = new Hrkq_holidayapp_cancel();// 创建销假表单实体
happ_cancel.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
if (happ_cancel.hacode.isEmpty())
new Exception("销假表单字段【hacode】不能为空");
if (happ_cancel.canceltime.isEmpty()) {
new Exception("销假表单字段【canceltime】不能为空");
}
if (happ_cancel.cancelreason.isEmpty()) {
new Exception("销假表单字段【cancelreason】不能为空");
}
if (happ_cancel.hdaystrue.isEmpty()) {
new Exception("销假表单字段【hdaystrue】不能为空");
}
Hrkq_holidayapp happ = new Hrkq_holidayapp();// 创建请假表单实体
String sqlstr = "select * from hrkq_holidayapp where hacode='" + happ_cancel.hacode.getValue() + "'";
happ.findBySQL(sqlstr);// 查询请假表单实体
if (happ.isEmpty())
new Exception("CODE为【" + happ_cancel.hacode.getValue() + "】的请假表单不存在");
happ_cancel.haid.setValue(happ.haid.getValue()); // 请假表单ID
// happ_cancel.hacode.setValue(value); // 请假表单CODE
// happ_cancel.canceltime.setValue(value); // 销假时间
// happ_cancel.cancelreason.setValue(value); // 销假事由
happ_cancel.er_id.setValue(happ.er_id.getValue()); // 人事ID
happ_cancel.employee_code.setValue(happ.employee_code.getValue()); // 工号
happ_cancel.employee_name.setValue(happ.employee_name.getValue()); // 姓名
happ_cancel.orgid.setValue(happ.orgid.getValue()); // 部门ID
happ_cancel.orgcode.setValue(happ.orgcode.getValue()); // 部门编码
happ_cancel.orgname.setValue(happ.orgname.getValue()); // 部门
happ_cancel.ospid.setValue(happ.ospid.getValue()); // 职位ID
happ_cancel.ospcode.setValue(happ.ospcode.getValue()); // 职位编码
happ_cancel.sp_name.setValue(happ.sp_name.getValue()); // 职位
happ_cancel.lv_num.setValue(happ.lv_num.getValue()); // 职级
happ_cancel.hdays.setValue(happ.hdays.getValue()); // 请假天数
// happ_cancel.hdaystrue.setValue(value); // 实际天数 如果没销假 则==销假天数hdaystrue
happ_cancel.timebg.setValue(happ.timebg.getValue()); // 请假时间开始 yyyy-MM-dd hh:mm
happ_cancel.timeed.setValue(happ.timeed.getValue()); // 请假时间截止 yyyy-MM-dd hh:mm
happ_cancel.orghrlev.setValue(happ.orghrlev.getValue()); // 机构人事层级
happ_cancel.emplev.setValue(happ.emplev.getValue()); // 人事层级
// happ_cancel.remark.setValue(value); // 备注
happ_cancel.stat.setValue("1"); // 表单状态
happ_cancel.idpath.setValue(happ.idpath.getValue()); // idpath
happ_cancel.entid.setValue("1"); // entid
happ_cancel.creator.setValue("inteface"); // 创建人
happ_cancel.createtime.setAsDatetime(new Date()); // 创建时间
CDBConnection con = happ_cancel.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
// System.out.println("happ_cancel json:" + happ_cancel.tojson());
happ_cancel.save(con);// 保存销假表单
// happ_cancel.wfcreate(null, con);// 提交表单(无流程)
Shwuser admin = Login.getAdminUser();
happ_cancel.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
// String rxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><hacid>" + happ_cancel.hacid.getValue() + "</hacid><haccode>" +
// //happ_cancel.haccode.getValue() +
// "</haccode></xml>";
// /return rxml;
// return happ_cancel.toxml();
return happ_cancel.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "findempsuper_test", Authentication = false, notes = "查找人员上级名单")
public String findempsuper_test() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String stremployee_code = "270884";
String strtype = "中心负责人";
String sqlstr = "SELECT * FROM hrms_emp_super ";
sqlstr = sqlstr + " where employee_code='" + stremployee_code + "' and type='" + strtype + "'";
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "findempsuper", Authentication = false, notes = "查找人员上级名单")
public String findempsuper() throws Exception {
// HashMap<String, String> parms = CSContext.getParms();
// String eparms = parms.get("parms");
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String stremployee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
String strtype = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String sqlstr = "SELECT * FROM hrms_emp_super ";
sqlstr = sqlstr + " where employee_code='" + stremployee_code + "' and type='" + strtype + "'";
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "testbusinesstrip", Authentication = false, notes = "创建出差单并自动提交生效")
public String testbusinesstrip() throws Exception {
Hrkq_business_trip happ_btrip = new Hrkq_business_trip();// 创建出差单实体
happ_btrip.findByID("32");
return happ_btrip.tojson();
}
@ACOAction(eventname = "Hrkq_business_trip_new", Authentication = false, notes = "创建出差单并自动提交生效")
public String Hrkq_business_trip_new() throws Exception {
Hrkq_business_trip happ_btrip = new Hrkq_business_trip();// 创建出差单实体
happ_btrip.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
if (happ_btrip.employee_code.isEmpty()) {
new Exception("出差单字段【employee_code】不能为空");
}
if (happ_btrip.tripdays.isEmpty()) {
new Exception("出差单字段【tripdays】不能为空");
}
if (happ_btrip.begin_date.isEmpty()) {
new Exception("出差单字段【begin_date】不能为空");
}
if (happ_btrip.end_date.isEmpty()) {
new Exception("出差单字段【end_date】不能为空");
}
if (happ_btrip.trip_type.isEmpty()) {
new Exception("出差单字段【trip_type】不能为空");
}
if (happ_btrip.destination.isEmpty()) {
new Exception("出差单字段【destination】不能为空");
}
if (happ_btrip.tripreason.isEmpty()) {
new Exception("出差单字段【tripreason】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + happ_btrip.employee_code.getValue() + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + happ_btrip.er_id.getValue() + "】的人事资料不存在");
if ((happ_btrip.trip_type.getAsIntDefault(0) != 1) && (happ_btrip.trip_type.getAsIntDefault(0) != 2))
new Exception("ID为【" + happ_btrip.trip_type + "】的出差类型不存在");
happ_btrip.er_id.setValue(emp.er_id.getValue()); // 人事ID
happ_btrip.employee_code.setValue(emp.employee_code.getValue()); // 工号
happ_btrip.employee_name.setValue(emp.employee_name.getValue()); // 姓名
happ_btrip.orgid.setValue(emp.orgid.getValue()); // 部门ID
happ_btrip.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
happ_btrip.orgname.setValue(emp.orgname.getValue()); // 部门
happ_btrip.ospid.setValue(emp.ospid.getValue()); // 职位ID
happ_btrip.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
happ_btrip.sp_name.setValue(emp.sp_name.getValue()); // 职位
happ_btrip.lv_num.setValue(emp.lv_num.getValue()); // 职级
happ_btrip.trip_type.setValue(happ_btrip.trip_type.getValue()); // 出差类型
happ_btrip.tripreason.setValue(happ_btrip.tripreason.getValue()); // 事由
happ_btrip.destination.setValue(happ_btrip.destination.getValue()); // 目的地
happ_btrip.tripdays.setValue(happ_btrip.tripdays.getValue()); // 实际天数
happ_btrip.begin_date.setValue(happ_btrip.begin_date.getValue()); // 实际开始时间
happ_btrip.end_date.setValue(happ_btrip.end_date.getValue()); // 实际截止时间
happ_btrip.iswfagent.setValue("1"); // 启用流程代理
happ_btrip.stat.setValue("1"); // 表单状态
happ_btrip.idpath.setValue(emp.idpath.getValue()); // idpath
happ_btrip.creator.setValue("inteface"); // 创建人
happ_btrip.createtime.setAsDatetime(new Date()); // 创建时间
happ_btrip.orghrlev.setValue("0");
happ_btrip.emplev.setValue("0");
happ_btrip.entid.setValue("1");
CDBConnection con = happ_btrip.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
// System.out.println("happ json:" + happ.tojson());
happ_btrip.save(con);// 保存出差表单
// happ.wfcreate(null, con);// 提交表单(无流程)
Shwuser admin = Login.getAdminUser();
happ_btrip.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
// String rxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><haid>" + happ_btrip.haid.getValue() + "</haid><hacode>" + happ.hacode.getValue() +
// "</hacode></xml>";
// /return rxml;
// return happ.toxml();
return happ_btrip.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "testovertime", Authentication = false, notes = "创建加班单并自动提交生效")
public String testovertime() throws Exception {
Hrkq_overtime happ_overtime = new Hrkq_overtime();// 创建加班单实体
happ_overtime.findByID("23");
return happ_overtime.tojson();
}
@ACOAction(eventname = "hrkq_overtime_new", Authentication = false, notes = "创建加班单并自动提交生效")
public String hrkq_overtime_new() throws Exception {
Hrkq_overtime happ_overtime = new Hrkq_overtime();// 创建加班单实体
happ_overtime.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
// System.out.println("hrkq_overtime_new json:" + happ_overtime.tojson());
if (happ_overtime.orgcode.isEmpty()) {
new Exception("加班单字段【orgcode】不能为空");
}
if (happ_overtime.over_type.isEmpty()) {
new Exception("加班单字段【overtype】不能为空");
}
if (happ_overtime.dealtype.isEmpty()) {
new Exception("加班单字段【dealtype】不能为空");
}
if (happ_overtime.otrate.isEmpty()) {
new Exception("加班单字段【otrate】不能为空");
}
if (happ_overtime.otreason.isEmpty()) {
new Exception("加班单字段【otreason】不能为空");
}
if (happ_overtime.isoffjob.isEmpty()) {
new Exception("加班单字段【isoffjob】不能为空");
}
if ((happ_overtime.over_type.getAsIntDefault(0) != 1) && (happ_overtime.over_type.getAsIntDefault(0) != 2))
new Exception("ID为【" + happ_overtime.over_type + "】的加班类型不存在");
Shworg borg = new Shworg();// 创建组织实体
String sqlstr = "select * from shworg where code='" + happ_overtime.orgcode.getValue() + "'";
borg.findBySQL(sqlstr);// 查询组织档案
if (borg.isEmpty())
new Exception("ID为【" + happ_overtime.orgcode.getValue() + "】的组织资料不存在");
happ_overtime.orgid.setValue(borg.orgid.getValue()); // 组织ID
happ_overtime.orgcode.setValue(happ_overtime.orgcode.getValue()); // 组织编号
happ_overtime.orgname.setValue(borg.extorgname.getValue()); // 组织名称
happ_overtime.idpath.setValue(borg.idpath.getValue()); // 组织ID结构
// happ_overtime.over_type.setValue(happ_overtime.over_type.getValue());
// happ_overtime.dealtype.setValue(happ_overtime.dealtype.getValue());
// happ_overtime.otrate.setValue(happ_overtime.otrate.getValue());
// happ_overtime.otreason.setValue(happ_overtime.otreason.getValue());
// happ_overtime.isoffjob.setValue(happ_overtime.isoffjob.getValue());
Hr_employee emp = new Hr_employee();// 创建人事档案实体
CJPALineData<Hrkq_overtime_line> otlist = happ_overtime.hrkq_overtime_lines;
for (CJPABase sl1 : otlist) {
Hrkq_overtime_line otl = (Hrkq_overtime_line) sl1;
if (otl.employee_code.isEmpty()) {
new Exception("加班单字段【employee_code】不能为空");
}
if (otl.allothours.isEmpty()) {
new Exception("加班单字段【allothours】不能为空");
}
sqlstr = "select * from hr_employee where employee_code='" + otl.employee_code.getValue() + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + happ_overtime.er_id.getValue() + "】的人事资料不存在");
otl.er_id.setValue(emp.er_id.getValue()); // 人事ID
otl.employee_code.setValue(emp.employee_code.getValue()); // 工号
otl.employee_name.setValue(emp.employee_name.getValue()); // 姓名
otl.orgid.setValue(emp.orgid.getValue()); // 部门ID
otl.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
otl.orgname.setValue(emp.orgname.getValue()); // 部门
otl.ospid.setValue(emp.ospid.getValue()); // 职位ID
otl.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
otl.sp_name.setValue(emp.sp_name.getValue()); // 职位
otl.lv_num.setValue(emp.lv_num.getValue()); // 职级
// otl.allothours.setValue(otl.allothours.getValue()); // 实际天数
CJPALineData<Hrkq_overtime_hour> othlist = otl.hrkq_overtime_hours;
for (CJPABase sl2 : othlist) {
Hrkq_overtime_hour oth = (Hrkq_overtime_hour) sl2;
if (oth.begin_date.isEmpty()) {
new Exception("加班单字段【begin_date】不能为空");
}
if (oth.end_date.isEmpty()) {
new Exception("加班单字段【end_dae】不能为空");
}
if (oth.needchedksb.isEmpty()) {
new Exception("加班单字段【needchedksb】不能为空");
}
if (oth.needchedkxb.isEmpty()) {
new Exception("加班单字段【needchedkxb】不能为空");
}
oth.er_id.setValue(emp.er_id.getValue());
oth.employee_code.setValue(emp.employee_code.getValue());
oth.employee_name.setValue(emp.employee_name.getValue());
// oth.begin_date.setValue(happ_overtime.begin_date.getValue()); // 申请加班开始时间
// oth.end_date.setValue(happ_overtime.end_date.getValue()); // 申请加班结束时间
// oth.needchedksb.setValue(happ_overtime.needchedksb.getValue()); // 上班需要打卡
// oth.needchedkxb.setValue(happ_overtime.needchedkxb.getValue()); // 下班需要打卡
// otl.hrkq_overtime_hours.add(oth);
}
// happ_overtime.hrkq_overtime_lines.add(otl);
}
// otls=otlist.toarray();
// happ_overtime.iswfagent.setValue("1"); // 启用流程代理
happ_overtime.stat.setValue("1"); // 表单状态
happ_overtime.entid.setValue("1"); // entid
happ_overtime.creator.setValue("inteface"); // 创建人
happ_overtime.createtime.setAsDatetime(new Date()); // 创建时间
happ_overtime.orghrlev.setValue("0");
happ_overtime.emplev.setValue("0");
CDBConnection con = happ_overtime.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
// System.out.println("happ json:" + happ.tojson());
happ_overtime.save(con);// 保存加班表单
// happ.wfcreate(null, con);// 提交表单(无流程)
Shwuser admin = Login.getAdminUser();
happ_overtime.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
// String rxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><haid>" + happ_overtime.haid.getValue() + "</haid><hacode>" +
// happ.hacode.getValue() +
// "</hacode></xml>";
// /return rxml;
// return happ.toxml();
return happ_overtime.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "testfindwkoff", Authentication = false, notes = "创建调休表单并自动提交生效")
public String testfindwkoff() throws Exception {
Hrkq_wkoff happwkoff = new Hrkq_wkoff();// 创建调休表单实体
happwkoff.findByID("2733");
return happwkoff.tojson();
}
@ACOAction(eventname = "Hrkq_wkoff_new", Authentication = false, notes = "创建调休表单并自动提交生效")
public String Hrkq_wkoff_new() throws Exception {
Hrkq_wkoff happwkoff = new Hrkq_wkoff();// 创建调休表单实体
// Hrkq_wkoffsourse happwkoffss = new Hrkq_wkoffsourse();// 创建调休表单体
happwkoff.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
if (happwkoff.employee_code.isEmpty()) {
new Exception("调休表单字段【employee_code】不能为空");
}
if (happwkoff.begin_date.isEmpty()) {
new Exception("调休表单字段【begin_date】不能为空");
}
if (happwkoff.end_date.isEmpty()) {
new Exception("调休表单字段【end_date】不能为空");
}
if (happwkoff.wodays.isEmpty()) {
new Exception("调休表单字段【wodays】不能为空");
}
if (happwkoff.reason.isEmpty()) {
new Exception("调休表单字段【reason】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + happwkoff.employee_code.getValue() + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + happwkoff.employee_code.getValue() + "】的人事资料不存在");
happwkoff.er_id.setValue(emp.er_id.getValue()); // 人事ID
happwkoff.employee_code.setValue(emp.employee_code.getValue()); // 工号
happwkoff.employee_name.setValue(emp.employee_name.getValue()); // 姓名
happwkoff.orgid.setValue(emp.orgid.getValue()); // 部门ID
happwkoff.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
happwkoff.orgname.setValue(emp.orgname.getValue()); // 部门
// happwkoff.ospid.setValue(emp.ospid.getValue()); // 职位ID
// happwkoff.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
happwkoff.sp_name.setValue(emp.sp_name.getValue()); // 职位
happwkoff.lv_num.setValue(emp.lv_num.getValue()); // 职级
happwkoff.wodays.setValue(happwkoff.wodays.getValue()); // 实际天数
happwkoff.begin_date.setValue(happwkoff.begin_date.getValue()); // 调休时间开始
happwkoff.end_date.setValue(happwkoff.end_date.getValue()); // 调休时间截止
happwkoff.reason.setValue(happwkoff.reason.getValue()); // 事由
CJPALineData<Hrkq_wkoffsourse> wss = happwkoff.hrkq_wkoffsourses;
for (CJPABase jpa1 : wss) {
Hrkq_wkoffsourse ws = (Hrkq_wkoffsourse) jpa1;
ws.lbid.setValue(ws.lbid.getValue());
ws.lbname.setValue(ws.lbname.getValue());
ws.stype.setValue(ws.stype.getValue());
ws.sccode.setValue(ws.sccode.getValue());
ws.alllbtime.setValue(ws.alllbtime.getValue());
ws.usedlbtime.setValue(ws.usedlbtime.getValue());
ws.valdate.setValue(ws.valdate.getValue());
ws.note.setValue(ws.note.getValue());
ws.wotime.setValue(ws.wotime.getValue());
// happwkoff.Hrkq_wkoffsourse.add(ws);
}
// happwkoff.iswfagent.setValue("1"); // 启用流程代理
happwkoff.stat.setValue("1"); // 表单状态
happwkoff.idpath.setValue(emp.idpath.getValue()); // idpath
happwkoff.entid.setValue("1"); // entid
happwkoff.creator.setValue("inteface");// 创建人
happwkoff.createtime.setAsDatetime(new Date()); // 创建时间
happwkoff.orghrlev.setValue("0");
happwkoff.emplev.setValue("0");
CDBConnection con = happwkoff.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
// System.out.println("happwkoff json:" + happwkoff.tojson());
happwkoff.save(con);// 保存调休表单
// happwkoff.wfcreate(null, con);// 提交表单(无流程)
Shwuser admin = Login.getAdminUser();
happwkoff.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
// String rxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><xml><haid>" + happ.haid.getValue() + "</haid><hacode>" + happ.hacode.getValue() +
// "</hacode></xml>";
// /return rxml;
// return happ.toxml();
return happwkoff.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "testfindresign", Authentication = false, notes = "创建补签表单并自动提交生效")
public String testfindresign() throws Exception {
Hrkq_resign happresign = new Hrkq_resign();// 创建补签表单实体
happresign.findByID("2733");
return happresign.tojson();
}
@ACOAction(eventname = "hrkq_resign_new", Authentication = false, notes = "创建补签表单并自动提交生效")
public String hrkq_resign_new() throws Exception {
Hrkq_resign happresign = new Hrkq_resign();// 创建补签表单实体
happresign.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
if (happresign.employee_code.isEmpty()) {
new Exception("补签表单字段【employee_code】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + happresign.employee_code.getValue() + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("工号为【" + happresign.employee_code.getValue() + "】的人事资料不存在");
happresign.er_id.setValue(emp.er_id.getValue()); // 人事ID
happresign.employee_code.setValue(emp.employee_code.getValue()); // 工号
happresign.employee_name.setValue(emp.employee_name.getValue()); // 姓名
happresign.orgid.setValue(emp.orgid.getValue()); // 部门ID
happresign.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
happresign.orgname.setValue(emp.orgname.getValue()); // 部门
happresign.ospid.setValue(emp.ospid.getValue()); // 职位ID
happresign.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
happresign.sp_name.setValue(emp.sp_name.getValue()); // 职位
happresign.lv_num.setValue(emp.lv_num.getValue()); // 职级
happresign.stat.setValue("1"); // 表单状态
happresign.idpath.setValue(emp.idpath.getValue()); // idpath
happresign.entid.setValue("1"); // entid
happresign.creator.setValue("inteface");// 创建人
happresign.createtime.setAsDatetime(new Date()); // 创建时间
happresign.orghrlev.setValue("0");
happresign.emplev.setValue("0");
CDBConnection con = happresign.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
happresign.save(con);// 保存补签表单
Shwuser admin = Login.getAdminUser();
happresign.wfcreate(null, con, "1", "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
con.submit();// 提交数据库事务
return happresign.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "testchgemail", Authentication = false, notes = "修改邮件")
public String testchgemail() throws Exception {
Hr_employee emp = new Hr_employee();// 人事实体
emp.findByID("2733");
return emp.tojson();
}
@ACOAction(eventname = "hr_chgemail_new", Authentication = false, notes = "修改邮件")
public String hr_chgemail_new() throws Exception {
JSONObject jsonObject = JSONObject.fromObject(CSContext.getPostdata());// 从前端JSON获取数据
String employee_code = jsonObject.getString("employee_code");
String email = jsonObject.getString("email");
if (employee_code.isEmpty()) {
new Exception("人事档案字段【employee_code】不能为空");
}
if (email.isEmpty()) {
new Exception("人事档案字段【email】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
emp.email.setValue(email);
emp.save();
return emp.toString();
}
@ACOAction(eventname = "testqrykqresult", Authentication = false, notes = "查询考勤结果")
public String testqrykqresult() throws Exception {
Hr_employee emp = new Hr_employee();// 人事实体
emp.findByID("2733");
return emp.tojson();
}
// @ACOAction(eventname = "hr_qrykqresult_new", Authentication = false, notes = "查询考勤结果")
// public String qrykqresult_new() throws Exception {
// JSONObject jsonObject = JSONObject.fromObject(CSContext.getPostdata());// 从前端JSON获取数据
// String employee_code = jsonObject.getString("employee_code");
// String bgdate = jsonObject.getString("bgdate");
// String eddate = jsonObject.getString("eddate");
// if (employee_code.isEmpty()) {
// new Exception("字段【employee_code】不能为空");
// }
// if (bgdate.isEmpty()) {
// new Exception("字段【bgdate】不能为空");
// }
// if (eddate.isEmpty()) {
// new Exception("字段【eddate】不能为空");
// }
// Hr_employee emp = new Hr_employee();// 创建人事档案实体
// String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
// emp.findBySQL(sqlstr);// 查询人事档案
// if (emp.isEmpty())
// new Exception("ID为【" + employee_code + "】的人事资料不存在");
// String sql = "SELECT a.bckqid,a.er_id,a.kqdate,a.scdname,a.sclid,a.bcno,a.frtime,a.totime,a.frsktime,a.tosktime,";
// sql = sql + "frst,trst,a.mtslate,a.mtslearly,lrst,a.extcode,a.exttype,b.employee_code,dpt.orgname,b.lv_num ZhiJi,dpt.attribute1";
// sql = sql + " FROM hrkq_bckqrst a";
// sql = sql + " INNER JOIN hr_employee b ON a.er_id=b.er_id";
// sql = sql + " LEFT JOIN shworg dpt ON dpt.code=b.orgcode";
// sql = sql + " WHERE a.lrst IN(12) and employee_code='" + employee_code + "' and kqdate>='" + bgdate + "' and kqdate<='" + eddate + "'";
// return emp.pool.opensql2json(sqlstr);
// }
@ACOAction(eventname = "testqryresign", Authentication = false, notes = "查询考勤补签")
public String testqryresign() throws Exception {
Hr_employee emp = new Hr_employee();// 人事实体
emp.findByID("2733");
return emp.tojson();
}
@ACOAction(eventname = "hr_qrykqresign_new", Authentication = false, notes = "查询考勤补签")
public String hr_qrykqresign_new() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
String bgdate = CorUtil.hashMap2Str(urlparms, "bgdate", "需要参数bgdate");
String eddate = CorUtil.hashMap2Str(urlparms, "eddate", "需要参数eddate");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
String sql = "SELECT * from v_csr_hrkq_resign WHERE employee_code='" + employee_code + "' and kqdate>='" + bgdate + "' and kqdate<='" + eddate + "'";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "hr_qrykqresult_new", Authentication = false, notes = "查询考勤结果")
public String hr_qrykqresult_new() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
String bgdate = CorUtil.hashMap2Str(urlparms, "bgdate", "需要参数bgdate");
String eddate = CorUtil.hashMap2Str(urlparms, "eddate", "需要参数eddate");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
String sql = "SELECT * from view_hrkq_bckqrst WHERE employee_code='" + employee_code + "' and kqdate>='" + bgdate + "' and kqdate<='" + eddate + "'";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "testQrymonthdetail", Authentication = false, notes = "考勤月度明细测试")
public String testQrymonthdetail() throws Exception {
Hr_employee emp = new Hr_employee();// 人事实体
emp.findByID("2733");
return emp.tojson();
}
@ACOAction(eventname = "hr_monthdetail_new", Authentication = false, notes = "考勤月度明细")
public String hr_monthdetail_new() throws Exception {
// 定义变量
String er_id, zjbss;
float sjcq, gj, hj, snj, gsj, fdjq;
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
String bgdate = CorUtil.hashMap2Str(urlparms, "bgdate", "需要参数bgdate");
String eddate = CorUtil.hashMap2Str(urlparms, "eddate", "需要参数eddate");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
// JSONObject jo=new JSONObject();
// jo.put("employee_code",employee_code);
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
er_id = emp.er_id.getValue();
// System.out.print(employee_code);
// 计算实际出勤
sqlstr = "SELECT ";
sqlstr = sqlstr + " IFNULL(SUM(CASE WHEN r.lrst NOT IN(9,10,12,0,6) THEN sl.dayratio ELSE 0 END )/100,0) sjcq ,";
sqlstr = sqlstr + " IFNULL(SUM(CASE WHEN r.lrst IN (9, 10, 12) THEN sl.dayratio ELSE 0 END )/100,0) kg ,";
sqlstr = sqlstr + " IFNULL(SUM(CASE WHEN r.lrst =2 THEN 1 ELSE 0 END ),0) cd ,";
sqlstr = sqlstr + " IFNULL(SUM(CASE WHEN r.lrst =3 THEN 1 ELSE 0 END ),0) zt ";
sqlstr = sqlstr + " FROM hrkq_bckqrst r,hrkq_sched_line sl ";
sqlstr = sqlstr + " WHERE r.sclid=sl.sclid ";
sqlstr = sqlstr + " and r.kqdate>='" + bgdate + "' and r.kqdate<='" + eddate;
sqlstr = sqlstr + "' and r.er_id ='" + er_id + "'";
List<HashMap<String, String>> lm = (new Hrkq_bckqrst()).pool.openSql2List(sqlstr);
HashMap<String, String> m = lm.get(0);
sjcq = Float.valueOf(m.get("sjcq"));
sjcq = sjcq + sjcq % (0.5f);
String ym = Systemdate.getStrDateByFmt(Systemdate.getDateByStr(bgdate), "yyyy-MM");
sqlstr = "SELECT "
+ " IFNULL(SUM(CASE WHEN t.bhtype =2 or h.viodeal=1 THEN l.lhdaystrue ELSE 0 END ),0) sj," // 事假或违规为事假
+ " IFNULL(SUM(CASE WHEN t.bhtype =3 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) gj,"// 且没违规
+ " IFNULL(SUM(CASE WHEN t.bhtype =4 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) hj, "
+ " IFNULL(SUM(CASE WHEN t.bhtype =5 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) cj,"
+ " IFNULL(SUM(CASE WHEN t.bhtype =7 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) snj,"
+ " IFNULL(SUM(CASE WHEN t.bhtype =8 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) bj,"
+ " IFNULL(SUM(CASE WHEN t.bhtype =9 AND (htconfirm<>2 OR htconfirm IS NULL) THEN l.lhdaystrue ELSE 0 END ),0) gsj"
+ " FROM hrkq_holidayapp h,hrkq_holidayapp_month l,hrkq_holidaytype t "
+ " WHERE h.stat = 9 AND h.htid=t.htid "
+ " AND h.haid=l.haid AND l.yearmonth='" + ym + "' AND er_id='" + er_id + "'";
List<HashMap<String, String>> lm0 = (new Hrkq_bckqrst()).pool.openSql2List(sqlstr);
System.out.println(lm0.size());
gj = Float.valueOf(lm0.get(0).get("gj"));
hj = Float.valueOf(lm0.get(0).get("hj"));
snj = Float.valueOf(lm0.get(0).get("snj"));
gsj = Float.valueOf(lm0.get(0).get("gsj"));
// fdjq=Float.valueOf(lm0.get(0).get("gsj"));
System.out.println(gj);
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hrkq_ohyear WHERE ohdate>='" + bgdate + "' AND ohdate<='"
+ eddate + "' AND iswork=2";
fdjq = Float.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));
fdjq = fdjq + fdjq % (0.5f);
sjcq = (float) (sjcq + gj + hj + snj + gsj + fdjq);
// 计算加班时数
sqlstr = "SELECT IFNULL(SUM(CASE WHEN (over_type = 1 AND otltype IN(1,2)) THEN othours ELSE 0 END ),0) prjbss,"
+ " IFNULL(SUM(CASE WHEN (over_type = 2 AND otltype IN(1,2)) THEN othours ELSE 0 END ),0) zmjbss,"
+ " IFNULL(SUM(CASE WHEN (over_type = 3 AND otltype IN(1,2)) THEN othours ELSE 0 END ),0) fdjbss,"
+ " IFNULL(SUM(CASE WHEN otltype IN(3,4,5) THEN othours ELSE 0 END ),0) zlbjbss,"
+ " IFNULL(SUM(othours),0) zjbss "
+ " FROM hrkq_overtime_list WHERE ((bgtime >='"
+ bgdate + "' AND bgtime<='" + eddate + "') OR(edtime >='" + bgdate
+ "' AND edtime<='" + eddate + "')) and dealtype=2 AND er_id ='" + er_id + "'";// 只显示计算加班费的
List<HashMap<String, String>> lm1 = (new Hrkq_overtime()).pool.openSql2List(sqlstr);
HashMap<String, String> m1 = lm1.get(0);
System.out.println(lm1.size());
zjbss = m1.get("zjbss");
// 返回工号、姓名、实际出勤、加班时数
sqlstr = "select employee_code,employee_name,'" + sjcq + "','" + zjbss + "' from hr_employee where employee_code='" + employee_code + "'";
JSONObject jo = new JSONObject();
jo.put("employee_code", employee_code);
jo.put("sjcq", sjcq);
jo.put("zjbss", zjbss);
return jo.toString();
// return emp.pool.opensql2json(sqlstr);
// return new CReport(sqlstr, null).findReport();
// return DBPools.defaultPool().openrowsql2json(sqlstr);
}
// 正式地址http://192.168.117.132:8001/dlhr/hr/published1/hr_chgagent_new.co
@ACOAction(eventname = "hr_chgagent_new", Authentication = false, notes = "修改流程代理人")
public String hr_chgagent_new() throws Exception {
// 定义变量
String employee_code = null, employee_id = null;
String agent_code = null, agent_name, agent_id, starttime, endtime, OperateType, Strerror;
JSONObject rtnjsobject = new JSONObject();
// Date starttime,endtime;
// int OperateType;
// 从前端JSON获取数据
JSONObject jsonObject = JSONObject.fromObject(CSContext.getPostdata());// 从前端JSON获取数据
// 变量赋值
employee_code = jsonObject.getString("SourceCode");// 被代理人工号
agent_code = jsonObject.getString("AgentCode");// 代理人工号
starttime = jsonObject.getString("StartTime");// 代理开始时间
endtime = jsonObject.getString("EndTime");// 代理结束时间
OperateType = jsonObject.getString("OperateType");// 操作类型:1新增 3作废
// 控制传入的工号不能为空==null不可少加上以下三者之一isempty();equals("");length()
if (employee_code == null || employee_code.equals("")) {
new Exception("被代理人字段【employee_code】不能为空");
Strerror = "被代理人字段【employee_code】不能为空";
rtnjsobject.put("err", Strerror);
return rtnjsobject.toString();
// return "{\"err\":\"被代理人字段【employee_code】不能为空\"}";
}
if (agent_code == null || agent_code.length() == 0) {
new Exception("代理人字段【agent_code】不能为空");
Strerror = "代理人字段【agent_code】不能为空";
rtnjsobject.put("err", Strerror);
return rtnjsobject.toString();
}
// 通过传入的工号进一步查询用户表中的用户ID和名称,并给变量赋值
Shwuser user = new Shwuser();// 创建用户实体,作为获取数据库连接的对象
String sqlstr = "select * from shwuser where username='" + agent_code + "'";
user.findBySQL(sqlstr);// 查询代理人
if (user.isEmpty()) {
new Exception("ID为【" + user.username.getValue() + "】的代理人用户不存在");
Strerror = "ID为【" + user.username.getValue() + "】的代理人用户不存在";
rtnjsobject.put("err", Strerror);
return rtnjsobject.toString();
}
agent_id = user.userid.getValue();
agent_name = user.displayname.getValue();
sqlstr = "select * from shwuser where username='" + employee_code + "'";
user.findBySQL(sqlstr);// 查询被代理人
if (user.isEmpty()) {
new Exception("ID为【" + user.username.getValue() + "】的被代理人用户不存在");
Strerror = "ID为【" + user.username.getValue() + "】的被代理人用户不存在";
rtnjsobject.put("err", Strerror);
return rtnjsobject.toString();
}
employee_id = user.userid.getValue();
String sqlqry = " SELECT DISTINCT shu.userid,sht.wftempid,sht.wftempname";
sqlqry = sqlqry + " FROM shwuser shu";// 用户表
sqlqry = sqlqry + " INNER JOIN shwpositionuser shpu ON shpu.userid=shu.userid";// 岗位中包含的用户
sqlqry = sqlqry + " INNER JOIN shwposition shp ON shpu.positionid=shp.positionid";// 流程岗位中定义的岗位
sqlqry = sqlqry + " INNER JOIN shwwftempprocuser shwu ON shwu.displayname=shp.positiondesc";// 审批流程节点中定义的岗位
sqlqry = sqlqry + " INNER JOIN shwwftemp sht ON sht.wftempid=shwu.wftempid";// 审批流程模板(stat=1为生效的)
sqlqry = sqlqry + " where sht.stat=1 AND shu.username='" + employee_code + "'";
// Shwuser_wf_agent useragent = new shwuser_wf_agent();// 创建流程模板实体
// String sqlstr = "select * from shwuser_wf_agent where userid='" + employee_id + "'";
// useragent.findBySQL(sqlstr);// 查询流程模板代理人
String sqlins = "", sqldel = "", sqlupdate = "", sqlupdatea = "";
// 新增流程代理
if (OperateType.equals("1")) {
// 删除旧流程代理
sqldel = "delete from shwuser_wf_agent where userid='" + employee_id + "'";
// 根据审批流程模板及节点、流程岗位、用户增加新流程代理
sqlins = "INSERT INTO shwuser_wf_agent(wfagentid,userid,wftempid,wftempname,auserid,ausername,adisplayname)";
sqlins = sqlins + " SELECT DISTINCT (SELECT MAX(wfagentid)+1 FROM shwuser_wf_agent) wfagentid,shu.userid,sht.wftempid,sht.wftempname,'" + agent_id + "','" + agent_code + "','" + agent_name + "'";
sqlins = sqlins + " FROM shwuser shu";// 用户表
sqlins = sqlins + " INNER JOIN shwpositionuser shpu ON shpu.userid=shu.userid";// 岗位中包含的用户
sqlins = sqlins + " INNER JOIN shwposition shp ON shpu.positionid=shp.positionid";// 流程岗位中定义的岗位
sqlins = sqlins + " INNER JOIN shwwftempprocuser shwu ON shwu.displayname=shp.positiondesc";// 审批流程节点中定义的岗位
sqlins = sqlins + " INNER JOIN shwwftemp sht ON sht.wftempid=shwu.wftempid";// 审批流程模板(stat=1为生效的)
sqlins = sqlins + " where sht.stat=1 AND shu.username='" + employee_code + "' ORDER BY sht.wftempid";
// 更新代理模板中的代理人
sqlupdatea = "UPDATE shwuser_wf_agent SET auserid='" + agent_id + "',ausername='" + agent_code + "',adisplayname='" + agent_name + "' WHERE userid='" + employee_id + "'";
// 修改是否代理,代理时间
sqlupdate = "update shwuser set goout=2,gooutstarttime='" + starttime + "',gooutendtime='" + endtime + "' WHERE username='" + employee_code + "'";
}
;
// 删除流程代理
if (OperateType.equals("3")) {
sqldel = "delete from shwuser_wf_agent where userid='" + employee_id + "'";
sqlins = "";
sqlupdate = "update shwuser set goout=1,gooutstarttime='" + starttime + "',gooutendtime='" + endtime + "' WHERE username='" + employee_code +
"'";
}
CDBConnection con = user.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
con.execsql(sqlupdatea);
con.execsql(sqlupdate);
con.submit();// 提交数据库事务
con.close();// 关闭通道
return user.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
//新增4个查询服务2019.4.25
@ACOAction(eventname = "hr_qryempdd", Authentication = false, notes = "人员异动:入职,调动")
public String hr_qryempdd() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
String sql = "SELECT "
+ " v.employee_code,v.employee_name,v.Ym,v.cdate,v.TYPE,v.orgname,v.sp_name,v.lv_num,v.ifpt,v.note"
+ " FROM"
+ " (SELECT IFNULL(ht.employee_code,hr.employee_code) employee_code,IFNULL(ht.employee_name,hr.employee_name)" + " employee_name,"
+ " DATE_FORMAT(IFNULL(ht.hiredday,hr.hiredday),'%Y-%m') Ym,"
+ " IFNULL(ht.hiredday,hr.hiredday) cdate,'入职' TYPE,"
+ " IFNULL(ht.odorgname,hr.orgname) orgname,IFNULL(ht.odsp_name,hr.sp_name) sp_name,IFNULL(ht.odlv_num,hr.lv_num) lv_num,"
+ " CASE WHEN IFNULL(pt.ptjacode,'')='' THEN '无' ELSE '有' END ifpt,"
+ " IFNULL(ht.tranfreason,'') note"
+ " FROM hr_employee hr"
+ " LEFT JOIN hr_employee_transfer ht ON hr.employee_code=ht.employee_code"
+ " LEFT JOIN hr_empptjob_app pt ON hr.employee_code=pt.employee_code"
+ " WHERE ht.employee_code='" + employee_code + "'" + " ORDER BY ht.tranfcmpdate"
+ " LIMIT 0,1) v"
+ " UNION"
+ " SELECT ht.employee_code,ht.employee_name,DATE_FORMAT(ht.tranfcmpdate,'%Y-%m') Ym,ht.tranfcmpdate cdate,"
+ " CASE WHEN ht.tranftype1=1 THEN '晋升' WHEN ht.tranftype1=2 THEN '降职' ELSE '平级' END AS TYPE,"
+ " ht.neworgname orgname,ht.newsp_name sp_name,ht.newlv_num lv_num,CASE WHEN IFNULL(pt.ptjacode,'')='' THEN '无' " + " ELSE '有' END ifpt,"
+ " ht.tranfreason note"
+ " FROM hr_employee_transfer ht "
+ " LEFT JOIN hr_empptjob_app pt ON ht.employee_code=pt.employee_code"
+ " WHERE ht.employee_code='" + employee_code + "'"
+ " ORDER BY cdate";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "hr_qryempjl", Authentication = false, notes = "正激历")
public String hr_qryempjl() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
String sql = "SELECT "
+ " hr.`rewardtime`,hr.`rwnote`,hr.`rwamount`,hr.`rwfile`,hr.rwnature,hr.* FROM hr_employee_reward hr"
+ " INNER JOIN hr_employee he ON hr.`er_id`=he.`er_id`"
+ " WHERE hr.rwnature=1 AND"
+ " he.employee_code='" + employee_code + "'"
+ " ORDER BY hr.rewardtime";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "hr_qryempcf", Authentication = false, notes = "负激历")
public String hr_qryempcf() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr = "select * from hr_employee where employee_code='" + employee_code + "'";
emp.findBySQL(sqlstr);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + employee_code + "】的人事资料不存在");
String sql = "SELECT "
+ " hr.`rewardtime`,hr.`rwnote`,hr.`rwamount`,hr.`rwfile`,hr.rwnature,hr.* FROM hr_employee_reward hr"
+ " INNER JOIN hr_employee he ON hr.`er_id`=he.`er_id`"
+ " WHERE hr.rwnature=2 AND"
+ " he.employee_code='" + employee_code + "'"
+ " ORDER BY hr.rewardtime";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "hr_qryemptrans", Authentication = false, notes = "教育经历,厂外培训,厂内培训")
public String hr_qryemptrans() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "employee_code", "需要参数employee_code");
String sql = "SELECT "
+ " hl.begintime,hl.schoolname,hl.major,hl.degree certname,hl.remark,hl.endtime,hl.certnum,hl.gcernum ,1 type FROM hr_employee_leanexp hl "
+ " INNER JOIN hr_employee he ON hl.er_id=he.er_id WHERE he.`employee_code`='" + employee_code + "'"
+ " UNION "
+ " SELECT ht.begintime,ht.schoolname,ht.major,ht.certname,ht.remark,ht.endtime,ht.certnum,ht.certname gcernum,2 type FROM hr_employee_trainexp ht "
+ " INNER JOIN hr_employee he ON ht.er_id=he.er_id WHERE he.`employee_code`='" + employee_code + "'"
+ " UNION "
+ " SELECT htw.begintime,htw.schoolname,htw.twktitle major,htw.certname,htw.remark,htw.endtime,htw.certnum,htw.certname gcernum,3 type FROM hr_employee_trainwk htw "
+ " INNER JOIN hr_employee he ON htw.er_id=he.er_id WHERE he.`employee_code`='" + employee_code + "'"
+ " ORDER BY begintime ";
//CDBPool pool = DBPools.poolByName("dlhrmycatread");
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sql);
}
@ACOAction(eventname = "findleavlblctowx", Authentication = false, notes = "浏览可休假列表供考勤通查询用")
public String findleavlblctowx() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "code", "需要参数code");
//String[] notnull = {};
//JSONArray dws=new JSONArray();
String sqlstr = "select * from (SELECT employee_code,alllbtime,usedlbtime,valdate"+
" FROM( SELECT b.*, IF(b.valdate>curdate(),2,1) isexpire,IF(b.usedlbtime<b.alllbtime,2,1) usup,IF((b.valdate>curdate()) AND (b.usedlbtime<b.alllbtime),1,2) canuses "+
" FROM hrkq_leave_blance b,hr_employee e where e.er_id=b.er_id ) tb where canuses=1 )"+
" tb where 1=1 and `employee_code` = '"+employee_code+"' order by valdate desc;";
CDBPool pool = HRUtil.getReadPool();
return pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "hr_get_dict", Authentication = false, notes = "字典项")
public String hr_get_dict() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String searchTime=urlparms.get("searchtime");
String sqlstr="";
if(searchTime==null ||searchTime.isEmpty()){
sqlstr="select dictcode,dictname,pid,dictvalue,createtime,updatetime from shwdict where usable=1";
}else{
sqlstr="select dictcode,dictname,pid,dictvalue,createtime,updatetime from shwdict where usable=1 and (createtime>='"+searchTime+"' or updatetime>='"+searchTime+"')";
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "hr_get_orgposition", Authentication = false, notes = "机构职位表")
public String hr_get_orgposition() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String searchTime=urlparms.get("searchtime");
String sqlstr="";
if(searchTime==null){
sqlstr="SELECT orgid,orgcode,orgname,hwc_namezl,lv_id,lv_num,hg_id,hg_code,hg_name,ospid,ospcode,sp_name,iskey,hwc_namezq,hwc_namezz,createtime,updatetime FROM hr_orgposition where usable=1";
}else{
sqlstr="SELECT orgid,orgcode,orgname,hwc_namezl,lv_id,lv_num,hg_id,hg_code,hg_name,ospid,ospcode,sp_name,iskey,hwc_namezq,hwc_namezz,createtime,updatetime FROM hr_orgposition where usable=1 and (createtime>='"+searchTime+"' or updatetime>='"+searchTime+"')";
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "findEmployeeByCode", Authentication = false, notes = "根据工号获取员工档案")
public String findEmployeeByCode() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String employee_code = CorUtil.hashMap2Str(urlparms, "code", "需要参数code");
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr="select * from hr_employee where employee_code='"+employee_code+"'";
emp.findBySQL(sqlstr,false);// 查询人事档案
if (emp.isEmpty())
new Exception("工号为【" + emp.employee_code.getValue() + "】的人事资料不存在");
return emp.tojson();
}
@ACOAction(eventname = "hr_add_employee", Authentication = false, notes = "增加人员档案")
public String hr_add_employee() throws Exception {
Hr_employee emp = new Hr_employee();// 创建人事档案实体
emp.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
Hr_orgposition osp = new Hr_orgposition();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
if (emp.employee_code.isEmpty()) {
new Exception("入职档案字段【employee_code】不能为空");
}
if (emp.employee_name.isEmpty()) {
new Exception("入职档案字段【employee_name】不能为空");
}
if (emp.degree.isEmpty()) {
new Exception("入职档案字段【degree】不能为空");
}
if (emp.degreetype.isEmpty()) {
new Exception("入职档案字段【degreetype】不能为空");
}
if (emp.degreecheck.isEmpty()) {
new Exception("入职档案字段【degreecheck】不能为空");
}
if (emp.empstatid.isEmpty()) {
new Exception("入职档案字段【empstatid】不能为空");
}
if (emp.sex.isEmpty()) {
new Exception("入职档案字段【sex】不能为空");
}
if (emp.birthday.isEmpty()) {
new Exception("入职档案字段【birthday】不能为空");
}
if (emp.id_number.isEmpty()) {
new Exception("入职档案字段【id_number】不能为空");
}
if (emp.registeraddress.isEmpty()) {
new Exception("入职档案字段【registeraddress】不能为空");
}
if (emp.sign_org.isEmpty()) {
new Exception("入职档案字段【sign_org】不能为空");
}
if (emp.sign_date.isEmpty()) {
new Exception("入职档案字段【sign_date】不能为空");
}
if (emp.expired_date.isEmpty()) {
new Exception("入职档案字段【expired_date】不能为空");
}
if (emp.ospcode.isEmpty()) {
new Exception("入职档案字段【ospcode】不能为空");
}
if (emp.entrysourcr.isEmpty()) {
new Exception("入职档案字段【entrysourcr】不能为空");
}
if (emp.dispunit.isEmpty()) {
new Exception("入职档案字段【dispunit】不能为空");
}
if (emp.dispeextime.isEmpty()) {
new Exception("入职档案字段【dispeextime】不能为空");
}
if (emp.transorg.isEmpty()) {
new Exception("入职档案字段【transorg】不能为空");
}
if (emp.transextime.isEmpty()) {
new Exception("入职档案字段【transextime】不能为空");
}
if (emp.advisercode.isEmpty()) {
new Exception("入职档案字段【advisercode】不能为空");
}
if (emp.advisername.isEmpty()) {
new Exception("入职档案字段【advisername】不能为空");
}
if (emp.adviserphone.isEmpty()) {
new Exception("入职档案字段【adviserphone】不能为空");
}
if (emp.juridical.isEmpty()) {
new Exception("入职档案字段【juridical】不能为空");
}
if (emp.atdtype.isEmpty()) {
new Exception("入职档案字段【atdtype】不能为空");
}
if (emp.noclock.isEmpty()) {
new Exception("入职档案字段【noclock】不能为空");
}
if (emp.married.isEmpty()) {
new Exception("入职档案字段【married】不能为空");
}
if (emp.registertype.isEmpty()) {
new Exception("入职档案字段【registertype】不能为空");
}
if(emp.ospcode.isEmpty()){
new Exception("入职档案字段【ospcode】不能为空");
}
String sqlstr = "select * from hr_employee where employee_code='" + emp.employee_code + "'";
Hr_employee findEmp=new Hr_employee();
findEmp.findBySQL(sqlstr);// 查询人事档案
if (!findEmp.isEmpty())
new Exception("工号为【" + emp.employee_code.getValue() + "】的人事资料已存在");
sqlstr = "SELECT * FROM hr_orgposition WHERE ospcode='" + emp.ospcode.getValue() + "' ";
osp.clear();
osp.findBySQL(sqlstr, false);
if (osp.isEmpty())
throw new Exception("工号【" + emp.employee_code.getValue() + "】的机构职位编码【" + emp.ospcode.getValue() + "】不存在");
if ("正式".equals(emp.empstatid.getValue()))
emp.empstatid.setValue("4");
else
throw new Exception("【" + emp.employee_code.getValue() + "】只能导入人事状态为【正式、离职】的人事资料");
emp.pldcp.setValue(dictemp.getVbCE("495", emp.pldcp.getValue(), true,"工号【" + emp.employee_code.getValue() + "】政治面貌【" + emp.pldcp.getValue() + "】不存在"));
emp.bloodtype.setValue(dictemp.getVbCE("697", emp.bloodtype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】血型【" + emp.bloodtype.getValue() + "】不存在"));
emp.nation.setValue(dictemp.getVbCE("797", emp.nation.getValue(), false,"工号【" + emp.employee_code.getValue() + "】民族【" + emp.nation.getValue() + "】不存在"));
emp.married.setValue(dictemp.getVbCE("714", emp.married.getValue(), false,"工号【" + emp.employee_code.getValue() + "】婚姻状况【" + emp.married.getValue() + "】不存在"));
emp.registertype.setValue(dictemp.getVbCE("702", emp.registertype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】户籍类型【" + emp.registertype.getValue() + "】不存在"));
emp.entrysourcr.setValue(dictemp.getVbCE("741", emp.entrysourcr.getValue(), true,"工号【" + emp.employee_code.getValue() + "】人员来源【" + emp.entrysourcr.getValue() + "】不存在"));
emp.idtype.setValue(dictemp.getVbCE("1469", emp.idtype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】证件类型【" + emp.idtype.getValue() + "】不存在"));
//emp.entrysourcr.setValue(dictemp.getValueByCation("741", v.get("entrysourcr")));//
emp.dispunit.setValue(dictemp.getVbCE("1322", emp.dispunit.getValue(), false,"工号【" + emp.employee_code.getValue() + "】的派遣机构【" + emp.dispunit.getValue() + "】不存在"));
emp.sex.setValue(dictemp.getVbCE("81", emp.sex.getValue(), false,"工号【" + emp.employee_code.getValue() + "】性别【" + emp.sex.getValue() + "】不存在"));
emp.degree.setValue(dictemp.getVbCE("84", emp.degree.getValue(), false,"工号【" + emp.employee_code.getValue() + "】学历【" + emp.degree.getValue() + "】不存在"));
emp.degreetype.setValue(dictemp.getVbCE("1495", emp.degreetype.getValue(), false,"工号【" + emp.employee_code.getValue() + "】学历类型【" + emp.degreetype.getValue() + "】不存在"));
emp.degreecheck.setValue(dictemp.getVbCE("1507", emp.degreecheck.getValue(), false,"工号【" + emp.employee_code.getValue() + "】学历验证【" + emp.degreecheck.getValue() + "】不存在"));
emp.eovertype.setValue(dictemp.getVbCE("1394", emp.eovertype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】加班类别【" + emp.eovertype.getValue() + "】不存在"));
emp.atdtype.setValue(dictemp.getVbCE("1399", emp.atdtype.getValue(), false,"工号【" + emp.employee_code.getValue() + "】出勤类别【" + emp.atdtype.getValue() + "】不存在"));
emp.noclock.setValue(dictemp.getVbCE("5", emp.noclock.getValue(), false,"工号【" + emp.employee_code.getValue() + "】免打考勤卡【" + emp.noclock.getValue() + "】不存在"));
emp.needdrom.setValue(dictemp.getVbCE("5", emp.needdrom.getValue(), false,"工号【" + emp.employee_code.getValue() + "】入住宿舍【" + emp.needdrom.getValue() + "】不存在"));
emp.pay_way.setValue(dictemp.getVbCE("901", emp.pay_way.getValue(), true,"工号【" + emp.employee_code.getValue() + "】计薪方式【" + emp.pay_way.getValue() + "】不存在"));
emp.orgid.setValue(osp.orgid.getValue()); // 部门ID
emp.orgcode.setValue(osp.orgcode.getValue()); // 部门编码
emp.orgname.setValue(osp.orgname.getValue()); // 部门名称
emp.hwc_namezl.setValue(osp.hwc_namezl.getValue()); // 职类
emp.lv_id.setValue(osp.lv_id.getValue()); // 职级ID
emp.lv_num.setValue(osp.lv_num.getValue()); // 职级
emp.hg_id.setValue(osp.hg_id.getValue()); // 职等ID
emp.hg_code.setValue(osp.hg_code.getValue()); // 职等编码
emp.hg_name.setValue(osp.hg_name.getValue()); // 职等名称
emp.ospid.setValue(osp.ospid.getValue()); // 职位ID
emp.ospcode.setValue(osp.ospcode.getValue()); // 职位编码
emp.sp_name.setValue(osp.sp_name.getValue()); // 职位名称
emp.iskey.setValue(osp.iskey.getValue()); // 关键岗位
emp.hwc_namezq.setValue(osp.hwc_namezq.getValue()); // 职群
emp.hwc_namezz.setValue(osp.hwc_namezz.getValue()); // 职种
emp.idpath.setValue(osp.idpath.getValue());
if(osp.isoffjob.getValue().equals("1")){
emp.emnature.setValue("脱产");
}else {
emp.emnature.setValue("非脱产");
}
if (emp.kqdate_start.isEmpty() && (!emp.hiredday.isEmpty())) {
emp.kqdate_start.setAsDatetime(emp.hiredday.getAsDatetime());
}
if (emp.kqdate_end.isEmpty() && (!emp.ljdate.isEmpty())) {
emp.kqdate_end.setAsDatetime(emp.ljdate.getAsDatetime());
}
int age = Integer.valueOf(HrkqUtil.getParmValue("EMPLOYEE_AGE_LMITE"));// 年龄小于*岁不允许入职
// 0
// 不控制
System.out.println("age:" + age);
if (emp.idtype.getAsIntDefault(1) == 1) {
int l = emp.id_number.getValue().length();
if ((l != 18) && (l != 20))
throw new Exception("身份证必须为18或20位");
}
if (age > 0) {
float ag = HRUtil.getAgeByBirth(emp.birthday.getAsDatetime());
System.out.println("ag:" + ag);
if (ag < age) {
throw new Exception("年龄小于【" + age + "】周岁");
}
}
if (!"M类".equalsIgnoreCase(emp.hwc_namezl.getValue())) {
emp.mlev.setValue(null);
}
if (!emp.employee_code.isEmpty() && (emp.employee_code.getValue().length() != 6)) {
throw new Exception("工号必须为6位");
}
CDBConnection con = emp.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
emp.save(con);
con.submit();// 提交数据库事务
if(!emp.er_id.isEmpty()){
return "Y";
}else{
return "N";
}
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "hr_add_entry", Authentication = false, notes = "增加职工")
public String hr_add_entry() throws Exception {
Hr_employee_linked emp = new Hr_employee_linked();
Hr_orgposition osp = new Hr_orgposition();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
Hr_entry enty = new Hr_entry();
String psd = CSContext.getPostdata();
JSONObject oj = JSONObject.fromObject(psd);
Object oerid = oj.get("er_id");
String[] disFlds = null;
if ((oerid != null) && (!oerid.toString().isEmpty())) {
emp.findByID(oerid.toString());
if (emp.isEmpty()) {
throw new Exception("没有找到ID为【" + oerid.toString() + "】的员工档案 ");
}
disFlds = new String[] { "idpath", "creator", "createtime", "updator", "updatetime" };
} else {
disFlds = new String[] {};
}
String[] flds = emp.getFieldNames(disFlds);
emp.fromjson(psd, flds);
enty.fromjson(psd);
Logsw.dblog("政治面貌【" + emp.pldcp.getValue() + "】");
emp.pldcp.setValue(dictemp.getVbCE("495", emp.pldcp.getValue(), true,"工号【" + emp.employee_code.getValue() + "】政治面貌【" + emp.pldcp.getValue() + "】不存在"));
enty.entrytype.setValue(dictemp.getVbCE("693", enty.entrytype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】入职类型【" + enty.entrytype.getValue() + "】不存在"));
emp.bloodtype.setValue(dictemp.getVbCE("697", emp.bloodtype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】血型【" + emp.bloodtype.getValue() + "】不存在"));
emp.nation.setValue(dictemp.getVbCE("797", emp.nation.getValue(), true,"工号【" + emp.employee_code.getValue() + "】民族【" + emp.nation.getValue() + "】不存在"));
emp.married.setValue(dictemp.getVbCE("714", emp.married.getValue(), true,"工号【" + emp.employee_code.getValue() + "】婚姻状况【" + emp.married.getValue() + "】不存在"));
emp.registertype.setValue(dictemp.getVbCE("702", emp.registertype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】户籍类型【" + emp.registertype.getValue() + "】不存在"));
emp.entrysourcr.setValue(dictemp.getVbCE("741", emp.entrysourcr.getValue(), true,"工号【" + emp.employee_code.getValue() + "】人员来源【" + emp.entrysourcr.getValue() + "】不存在"));
emp.idtype.setValue(dictemp.getVbCE("1469", emp.idtype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】证件类型【" + emp.idtype.getValue() + "】不存在"));
emp.dispunit.setValue(dictemp.getVbCE("1322", emp.dispunit.getValue(), true,"工号【" + emp.employee_code.getValue() + "】的派遣机构【" + emp.dispunit.getValue() + "】不存在"));
emp.sex.setValue(dictemp.getVbCE("81", emp.sex.getValue(), true,"工号【" + emp.employee_code.getValue() + "】性别【" + emp.sex.getValue() + "】不存在"));
emp.degree.setValue(dictemp.getVbCE("84", emp.degree.getValue(), true,"工号【" + emp.employee_code.getValue() + "】学历【" + emp.degree.getValue() + "】不存在"));
emp.degreetype.setValue(dictemp.getVbCE("1495", emp.degreetype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】学历类型【" + emp.degreetype.getValue() + "】不存在"));
emp.degreecheck.setValue(dictemp.getVbCE("1507", emp.degreecheck.getValue(), true,"工号【" + emp.employee_code.getValue() + "】学历验证【" + emp.degreecheck.getValue() + "】不存在"));
emp.eovertype.setValue(dictemp.getVbCE("1394", emp.eovertype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】加班类别【" + emp.eovertype.getValue() + "】不存在"));
emp.atdtype.setValue(dictemp.getVbCE("1399", emp.atdtype.getValue(), true,"工号【" + emp.employee_code.getValue() + "】出勤类别【" + emp.atdtype.getValue() + "】不存在"));
emp.noclock.setValue(dictemp.getVbCE("5", emp.noclock.getValue(), true,"工号【" + emp.employee_code.getValue() + "】免打考勤卡【" + emp.noclock.getValue() + "】不存在"));
emp.needdrom.setValue(dictemp.getVbCE("5", emp.needdrom.getValue(), true,"工号【" + emp.employee_code.getValue() + "】入住宿舍【" + emp.needdrom.getValue() + "】不存在"));
emp.pay_way.setValue(dictemp.getVbCE("901", emp.pay_way.getValue(), true,"工号【" + emp.employee_code.getValue() + "】计薪方式【" + emp.pay_way.getValue() + "】不存在"));
emp.empstatid.setAsInt(6);// 待入职
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM `hr_balcklist` where id_number='" + emp.id_number.getValue()
+ "'";
if (Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct")) != 0)
throw new Exception("身份证号码【" + emp.id_number.getValue() + "】在黑名单");
String sqlstr2 = "select * from hr_employee where employee_code='" + emp.employee_code + "'";
Hr_employee findEmp=new Hr_employee();
findEmp.findBySQL(sqlstr2);// 查询人事档案
if (!findEmp.isEmpty())
new Exception("工号为【" + emp.employee_code.getValue() + "】的人事资料已存在");
sqlstr2 = "SELECT * FROM hr_orgposition WHERE ospcode='" + emp.ospcode.getValue() + "' ";
osp.clear();
osp.findBySQL(sqlstr2, false);
if (osp.isEmpty())
throw new Exception("工号【" + emp.employee_code.getValue() + "】的机构职位编码【" + emp.ospcode.getValue() + "】不存在");
emp.orgid.setValue(osp.orgid.getValue()); // 部门ID
emp.orgcode.setValue(osp.orgcode.getValue()); // 部门编码
emp.orgname.setValue(osp.orgname.getValue()); // 部门名称
emp.hwc_namezl.setValue(osp.hwc_namezl.getValue()); // 职类
emp.lv_id.setValue(osp.lv_id.getValue()); // 职级ID
emp.lv_num.setValue(osp.lv_num.getValue()); // 职级
emp.hg_id.setValue(osp.hg_id.getValue()); // 职等ID
emp.hg_code.setValue(osp.hg_code.getValue()); // 职等编码
emp.hg_name.setValue(osp.hg_name.getValue()); // 职等名称
emp.ospid.setValue(osp.ospid.getValue()); // 职位ID
emp.ospcode.setValue(osp.ospcode.getValue()); // 职位编码
emp.sp_name.setValue(osp.sp_name.getValue()); // 职位名称
emp.iskey.setValue(osp.iskey.getValue()); // 关键岗位
emp.hwc_namezq.setValue(osp.hwc_namezq.getValue()); // 职群
emp.hwc_namezz.setValue(osp.hwc_namezz.getValue()); // 职种
emp.idpath.setValue(osp.idpath.getValue());
enty.idpath.setValue(osp.idpath.getValue());
if(osp.isoffjob.getValue().equals("1")){
emp.emnature.setValue("脱产");
}else {
emp.emnature.setValue("非脱产");
}
if (emp.kqdate_start.isEmpty() && (!emp.hiredday.isEmpty())) {
emp.kqdate_start.setAsDatetime(emp.hiredday.getAsDatetime());
}
if (emp.kqdate_end.isEmpty() && (!emp.ljdate.isEmpty())) {
emp.kqdate_end.setAsDatetime(emp.ljdate.getAsDatetime());
}
int age = Integer.valueOf(HrkqUtil.getParmValue("EMPLOYEE_AGE_LMITE"));// 年龄小于*岁不允许入职
// 0
// 不控制
System.out.println("age:" + age);
if (emp.idtype.getAsIntDefault(1) == 1) {
int l = emp.id_number.getValue().length();
if ((l != 18) && (l != 20))
throw new Exception("身份证必须为18或20位");
}
if (age > 0) {
float ag = HRUtil.getAgeByBirth(emp.birthday.getAsDatetime());
System.out.println("ag:" + ag);
if (ag < age) {
throw new Exception("年龄小于【" + age + "】周岁");
}
}
if (!"M类".equalsIgnoreCase(emp.hwc_namezl.getValue())) {
emp.mlev.setValue(null);
}
if (!emp.employee_code.isEmpty() && (emp.employee_code.getValue().length() != 6)) {
throw new Exception("工号必须为6位");
}
int hrlev = HRUtil.getOrgHrLev(osp.orgid.getValue());
enty.orghrlev.setValue(hrlev);
emp.note.setValue(enty.remark.getValue());
CDBConnection con = emp.pool.getCon(this);
con.startTrans();
try {
emp.save(con);
enty.er_id.setValue(emp.er_id.getValue());
enty.entrysourcr.setValue(emp.entrysourcr.getValue());
enty.employee_code.setValue(emp.employee_code.getValue());
enty.er_id.setValue(emp.er_id.getValue());
enty.orgid.setValue(emp.orgid.getValue());
enty.lv_num.setAsFloat(emp.lv_num.getAsFloat());
enty.ospid.setValue(osp.ospid.getValue());
enty.save(con, false);
con.submit();
if(!emp.er_id.isEmpty()){
return "Y";
}else{
return "N";
}
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "hr_get_blacklist", Authentication = false, notes = "获取黑名单")
public String hr_get_blacklist() throws Exception {
String sqlstr="";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String searchTime=urlparms.get("searchtime");
String start=urlparms.get("start");
String take=urlparms.get("take");
if(searchTime==null){
sqlstr="SELECT e.employee_code,e.employee_name,e.id_number,e.sex,e.hiredday,e.ljdate,e.orgname,e.telphone,e.sp_name,e.lv_num,e.nation,e.registeraddress,l.ljtype2,l.ljtype1,l.ljreason"+
" FROM hr_employee e LEFT JOIN hr_leavejob l ON e.er_id=l.er_id WHERE l.`stat`=9 AND l.iscanced<>1 and e.empstatid='13' limit "+start+","+take+"";
}else{
sqlstr="SELECT e.employee_code,e.employee_name,e.id_number,e.sex,e.hiredday,e.ljdate,e.orgname,e.telphone,e.sp_name,e.lv_num,e.nation,e.registeraddress,l.ljtype2,l.ljtype1,l.ljreason"+
" FROM hr_employee e LEFT JOIN hr_leavejob l ON e.er_id=l.er_id WHERE l.`stat`=9 AND l.iscanced<>1 and e.empstatid='13' and (l.createtime>='"+searchTime+"' or l.updatetime>='"+searchTime+"') limit "+start+","+take+"";
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "hr_get_standposition", Authentication = false, notes = "标准职位库")
public String hr_get_standposition() throws Exception {
String sqlstr="";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String searchTime=urlparms.get("searchtime");
if(searchTime==null){
sqlstr="select hg_name,lv_num,sp_name,hwc_namezl,hwc_namezq,hwc_namezz,gtitle,isoffjob,updatetime from Hr_standposition where usable=1";
}else{
sqlstr="select hg_name,lv_num,sp_name,hwc_namezl,hwc_namezq,hwc_namezz,gtitle,isoffjob,updatetime from Hr_standposition where usable=1 and (createtime>='"+searchTime+"' or updatetime>='"+searchTime+"')";
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "hr_get_emptransfer", Authentication = false, notes = "调动记录")
public String hr_get_emptransfer() throws Exception {
String sqlstr="";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
//String searchTime=urlparms.get("searchtime");
String employee_code=urlparms.get("employee_code");
//String start=urlparms.get("start");
//String take=urlparms.get("take");
sqlstr="select emptranfcode,employee_code,employee_name,odorgname,odsp_name,odlv_num,neworgname,newlv_num,newsp_name,tranftype1,tranfcmpdate,updatetime from `hr_employee_transfer` where stat='9' and employee_code='"+employee_code+"'"+
" UNION ALL SELECT b.emptranfbcode,bl.employee_code,bl.employee_name,bl.odorgname,bl.odsp_name,bl.odlv_num,bl.neworgname,bl.newlv_num,bl.newsp_name,'批量调动',b.tranfcmpdate,b.updatetime"+
" FROM hr_emptransferbatch b,hr_emptransferbatch_line bl WHERE b.emptranfb_id=bl.emptranfb_id AND b.stat=9 and employee_code='"+employee_code+"'";
// if(searchTime!=null){
// sqlstr="select emptranfcode,employee_code,employee_name,odorgname,odsp_name,odlv_num,neworgname,newlv_num,newsp_name,tranftype1,tranfcmpdate,updatetime from `hr_employee_transfer` where stat='9'"+
// " and updatetime>='"+searchTime+"'"+
// " UNION ALL SELECT b.emptranfbcode,bl.employee_code,bl.employee_name,bl.odorgname,bl.odsp_name,bl.odlv_num,bl.neworgname,bl.newlv_num,bl.newsp_name,'批量调动',b.tranfcmpdate,b.updatetime"+
// " FROM hr_emptransferbatch b,hr_emptransferbatch_line bl WHERE b.emptranfb_id=bl.emptranfb_id AND b.stat=9 and updatetime>='"+searchTime+"' limit "+start+","+take+"";
// }
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
/**
* 获取人员信息
* @return
* @throws Exception
*/
@ACOAction(eventname = "hr_get_employee", Authentication = false, notes = "人员信息")
public String hr_get_employee()throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String begintime=urlparms.get("begintime");
String endtime=urlparms.get("endtime");
String sqlstr="SELECT employee_code,employee_name,RIGHT(id_number,6) id_number,lv_num,telphone,orgcode,b.orgname,b.extorgname,b.attribute1 as orgcode2,a.createtime"+
" from hr_employee a INNER JOIN shworg b on a.orgid =b.orgid"+
" where a.createtime BETWEEN '"+begintime+"' and '"+endtime+"'";
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "hr_get_finish_quotacode", Authentication = false, notes = "获取已经使用的工资额度编码")
public String hr_get_finish_quotacode()throws Exception {
String sqlstr="";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String searchTime=urlparms.get("searchtime");
if(searchTime==null){
sqlstr="SELECT * from (SELECT employee_code,salary_quotacode,createtime FROM hr_employee_transfer WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM hr_entry_prob WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM hr_transfer_prob WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM Hr_salary_specchgsa WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0')tb"+
" where createtime>'2020-07-01' order by createtime";
}else{
sqlstr="SELECT * from (SELECT employee_code,salary_quotacode,createtime FROM hr_employee_transfer WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM hr_entry_prob WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM hr_transfer_prob WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0'"+
" UNION SELECT employee_code,salary_quotacode,createtime FROM Hr_salary_specchgsa WHERE stat=9 and salary_quotacode is not NULL and salary_quotacode<>'0')tb"+
" where createtime>'"+searchTime+"' order by createtime";
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
@ACOAction(eventname = "hr_createTrip", Authentication = false, notes = "移动端创建出差单")
public String hr_createTrip() throws Exception{
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
//HashMap<String, String> pparms = CSContext.parPostDataParms();
Hrkq_business_trip happ_btrip = new Hrkq_business_trip();// 创建出差单实体
//初始化参数
String entid=null;
String userid=null;
String userids = CorUtil.hashMap2Str(urlparms, "userids");
String[] ckuserids = ((userids != null) && (userids.length() > 0)) ? userids.split(",") : null;
Shwuser user = new Shwuser();
happ_btrip.fromjson(CSContext.getPostdata());// 从前端JSON获取数据
String sqlstr = "SELECT * FROM shwuser WHERE username=?";
PraperedSql psql = new PraperedSql();
psql.setSqlstr(sqlstr);
psql.getParms().add(new PraperedValue(java.sql.Types.VARCHAR, happ_btrip.employee_code.getValue().trim()));// UserName.trim().toUpperCase()
user.findByPSQL(psql);
if (user.isEmpty())
throw new Exception("用户名不存在!");
if (user.actived.getAsIntDefault(0) != 1)
throw new Exception("用户已禁用!");
userid=user.getid();
CJPALineData<Shworguser> ous = new CJPALineData<Shworguser>(Shworguser.class);
ous.setPool(user.pool);
String sqlstrfinduser = "select * from shworguser where userid=" + user.userid.getValue();
ous.findDataBySQL(sqlstrfinduser, true, true);
for (CJPABase oub : ous) {
Shworguser ou = (Shworguser) oub;
if (ou.isdefault.getAsIntDefault(0) == 1) {
Shworg org = new Shworg();
org.findByID(ou.orgid.getValue());
entid= org.entid.getValue();
break;
}
}
int hrlev = HRUtil.getOrgHrLev(happ_btrip.orgid.getValue());
//初始化参数结束
if(happ_btrip.bta_id.getValue()==null || happ_btrip.bta_id.getValue().isEmpty())
{
if (happ_btrip.employee_code.isEmpty()) {
new Exception("出差单字段【employee_code】不能为空");
}
if (happ_btrip.tripdays.isEmpty()) {
new Exception("出差单字段【tripdays】不能为空");
}
if (happ_btrip.begin_date.isEmpty()) {
new Exception("出差单字段【begin_date】不能为空");
}
if (happ_btrip.end_date.isEmpty()) {
new Exception("出差单字段【end_date】不能为空");
}
if (happ_btrip.trip_type.isEmpty()) {
new Exception("出差单字段【trip_type】不能为空");
}
if (happ_btrip.destination.isEmpty()) {
new Exception("出差单字段【destination】不能为空");
}
if (happ_btrip.tripreason.isEmpty()) {
new Exception("出差单字段【tripreason】不能为空");
}
Hr_employee emp = new Hr_employee();// 创建人事档案实体
String sqlstr2 = "select * from hr_employee where employee_code='" + happ_btrip.employee_code.getValue() + "'";
emp.findBySQL(sqlstr2);// 查询人事档案
if (emp.isEmpty())
new Exception("ID为【" + happ_btrip.er_id.getValue() + "】的人事资料不存在");
if ((happ_btrip.trip_type.getAsIntDefault(0) != 1) && (happ_btrip.trip_type.getAsIntDefault(0) != 2))
new Exception("ID为【" + happ_btrip.trip_type + "】的出差类型不存在");
happ_btrip.er_id.setValue(emp.er_id.getValue()); // 人事ID
happ_btrip.employee_code.setValue(emp.employee_code.getValue()); // 工号
happ_btrip.employee_name.setValue(emp.employee_name.getValue()); // 姓名
happ_btrip.orgid.setValue(emp.orgid.getValue()); // 部门ID
happ_btrip.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
happ_btrip.orgname.setValue(emp.orgname.getValue()); // 部门
happ_btrip.ospid.setValue(emp.ospid.getValue()); // 职位ID
happ_btrip.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
happ_btrip.sp_name.setValue(emp.sp_name.getValue()); // 职位
happ_btrip.lv_num.setValue(emp.lv_num.getValue()); // 职级
happ_btrip.trip_type.setValue(happ_btrip.trip_type.getValue()); // 出差类型
happ_btrip.tripreason.setValue(happ_btrip.tripreason.getValue()); // 事由
happ_btrip.destination.setValue(happ_btrip.destination.getValue()); // 目的地
happ_btrip.tripdays.setValue(happ_btrip.tripdays.getValue()); // 实际天数
happ_btrip.begin_date.setValue(happ_btrip.begin_date.getValue()); // 实际开始时间
happ_btrip.end_date.setValue(happ_btrip.end_date.getValue()); // 实际截止时间
happ_btrip.iswfagent.setValue("1"); // 启用流程代理
happ_btrip.stat.setValue("1"); // 表单状态
happ_btrip.idpath.setValue(emp.idpath.getValue()); // idpath
happ_btrip.creator.setValue(emp.employee_code.getValue()); // 创建人
happ_btrip.createtime.setAsDatetime(new Date()); // 创建时间
happ_btrip.orghrlev.setValue(HRUtil.getOrgHrLev(happ_btrip.orgid.getValue()));
//happ_btrip.emplev.setValue("0");
happ_btrip.entid.setValue("1");//制单状态
CDBConnection con = happ_btrip.pool.getCon(this); // 获取数据库连接
con.startTrans(); // 开始事务
try {
happ_btrip.save(con);// 保存出差表单
con.submit();// 提交数据库事务
//return happ_btrip.tojson();
} catch (Exception e) {
con.rollback();// 回滚事务
throw e;
} finally {
con.close();
}
}
try{
return COCSCommon.createWFForMobile("com.hr.attd.entity.Hrkq_business_trip", happ_btrip.bta_id.getValue(), userid, entid,ckuserids);
}catch (Exception e){
return "{\"jpaid\":"+happ_btrip.getid()+"}";
}
}
@ACOAction(eventname = "hr_get_iccard", Authentication = false, notes = "获取IC卡数据")
public String hr_get_iccard()throws Exception {
String sqlstr="";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String start=urlparms.get("start");
String end=urlparms.get("end");
if(start!=null && end!=null){
sqlstr="select employee_code, card_stat,card_sn,card_number,updatetime from hr_ykt_card order where updatetime>='"+start+"' and updatetime<='"+end+"' by updatetime";
}else{
new Exception("开始和结束日期不能为空!");
}
return new CReport(HRUtil.getReadPool(), sqlstr, null, null).findReport();
}
}
<file_sep>/src/com/hr/.svn/pristine/98/98ebd28a0b64238e5f8aff519a33c22a9b83451c.svn-base
package com.hr.util;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.hr.attd.entity.Hrkqtransfer2insurancetimer;
import com.hr.insurance.entity.Hr_ins_buyinsurance;
import com.hr.insurance.entity.Hr_ins_insurancetype;
import com.hr.perm.entity.Hr_employee;
public class TimerTaskHRTrans2Insurance extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
Logsw.debug("调动后自动生成购保单");
try {
int synct = dosettrans2insurance();
if (synct == 0) {
System.out.println("自动生成调动后购保单【" + Systemdate.getStrDate() + "】" + "本次没有生成数据!");
} else
System.out.println("自动生成调动后购保单【" + Systemdate.getStrDate() + "】:" + synct);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int dosettrans2insurance() throws Exception {
String sqlstr = "SELECT * FROM hrkqtransfer2insurancetimer WHERE isbuyins=2 AND CURDATE()>=dobuyinsdate AND CURDATE()<=LAST_DAY(dobuyinsdate)";
CJPALineData<Hrkqtransfer2insurancetimer> timers = new CJPALineData<Hrkqtransfer2insurancetimer>(Hrkqtransfer2insurancetimer.class);
timers.findDataBySQL(sqlstr, true, false);
int rst = timers.size();
Hr_employee emp = new Hr_employee();
Hr_ins_buyinsurance bi = new Hr_ins_buyinsurance();
Hr_ins_insurancetype it = new Hr_ins_insurancetype();
// CJPALineData<Hr_ins_buyinsurance> bis=new CJPALineData<Hr_ins_buyinsurance>(Hr_ins_buyinsurance.class);
CDBConnection con = bi.pool.getCon(bi);
con.startTrans();
try {
for (CJPABase jpa : timers) {
Hrkqtransfer2insurancetimer transins = (Hrkqtransfer2insurancetimer) jpa;
emp.clear();
emp.findBySQL("select * from hr_employee where employee_code='" + transins.employee_code.getValue() + "'");
if (emp.isEmpty())
continue;
it.clear();
it.findBySQL("SELECT * FROM hr_ins_insurancetype WHERE ins_type=1 AND '" + transins.dobuyinsdate.getValue() + "'>=buydate ORDER BY buydate DESC ");
if (it.isEmpty()) {
throw new Exception("购保时间为【" + transins.dobuyinsdate.getValue() + "】时无可用的险种");
}
bi.clear();
bi.insurance_number.setValue(emp.employee_code.getValue());
bi.orgid.setValue(emp.orgid.getValue()); // 部门ID
bi.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
bi.orgname.setValue(emp.orgname.getValue()); // 部门名称
bi.buydday.setValue(transins.dobuyinsdate.getValue());
bi.insit_id.setValue(it.insit_id.getValue());
bi.insit_code.setValue(it.insit_code.getValue());
bi.insname.setValue(it.insname.getValue());
bi.ins_type.setAsInt(1);
bi.payment.setValue(it.payment.getValue());
bi.tselfpay.setValue(it.selfpay.getValue());
bi.tcompay.setValue(it.compay.getValue());
bi.er_id.setValue(emp.er_id.getValue());
bi.employee_code.setValue(emp.employee_code.getValue());
bi.employee_name.setValue(emp.employee_name.getValue());
bi.ospid.setValue(emp.ospid.getValue());
bi.ospcode.setValue(emp.ospcode.getValue());
bi.sp_name.setValue(emp.sp_name.getValue());
bi.lv_id.setValue(emp.lv_id.getValue());
bi.lv_num.setValue(emp.lv_num.getValue());
bi.hiredday.setValue(emp.hiredday.getValue());
bi.orgid.setValue(emp.orgid.getValue());
bi.orgcode.setValue(emp.orgcode.getValue());
bi.orgname.setValue(emp.orgname.getValue());
bi.degree.setValue(emp.degree.getValue());
bi.sex.setValue(emp.sex.getValue());
bi.telphone.setValue(emp.telphone.getValue());
bi.nativeplace.setValue(emp.nativeplace.getValue());
bi.registertype.setValue(emp.registertype.getValue());
bi.pay_type.setValue(emp.pay_way.getValue());
bi.id_number.setValue(emp.id_number.getValue());
bi.sign_org.setValue(emp.sign_org.getValue());
bi.sign_date.setValue(emp.sign_date.getValue());
bi.expired_date.setValue(emp.expired_date.getValue());
bi.birthday.setValue(emp.birthday.getValue());
bi.idpath.setValue(emp.idpath.getValue());
bi.entid.setValue("1");
bi.creator.setValue("DEV");
bi.createtime.setValue(Systemdate.getStrDate());
int age = getAgeByBirth(emp.birthday.getValue());
bi.age.setAsInt(age);
bi.sptype.setValue(emp.emnature.getValue());
bi.isnew.setAsInt(1);
bi.reg_type.setAsInt(1);
bi.buydday.setValue(transins.dobuyinsdate.getValue());
bi.ins_type.setValue(it.ins_type.getValue());
bi.selfratio.setValue(it.selfratio.getValue());
bi.selfpay.setValue(it.selfpay.getValue());
bi.comratio.setValue(it.comratio.getValue());
bi.compay.setValue(it.compay.getValue());
bi.insurancebase.setValue(it.insurancebase.getValue());
bi.remark.setValue("调动单【" + transins.sourcecode.getValue() + "】自动生成购保");
// bis.add(bi);
bi.save(con);
Hrkqtransfer2insurancetimer changetimer = new Hrkqtransfer2insurancetimer();
changetimer.findByID(transins.timer_id.getValue());
if (!changetimer.isEmpty()) {
changetimer.isbuyins.setAsInt(1);
changetimer.buyins_id.setValue(bi.buyins_id.getValue());
changetimer.buyins_code.setValue(bi.buyins_code.getValue());
changetimer.save(con);
}
}
/*
* if (bis.size() > 0)
* bis.saveBatchSimple();// 高速存储
* bis.clear();
*/
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private static int getAgeByBirth(String birthday) {
int age = 0;
try {
Calendar now = Calendar.getInstance();
now.setTime(new Date());// 当前时间
Calendar birth = Calendar.getInstance();
Date bd = Systemdate.getDateByStr(birthday);
birth.setTime(bd);
if (birth.after(now)) {// 如果传入的时间,在当前时间的后面,返回0岁
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {// 兼容性更强,异常后返回数据
return 0;
}
}
}
<file_sep>/src/com/hr/base/ctr/CtrBaseOrg.java
package com.hr.base.ctr;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.server.generic.Shworg;
import com.corsair.server.util.GetNewSystemCode;
import com.hr.perm.entity.Hr_employee;
public class CtrBaseOrg {
public static void BeforeSave(CDBConnection con, Shworg org) throws Exception {
if (org.attribute1.isEmpty()) {
String oldcode;
try {
oldcode = (new GetNewSystemCode()).dogetnewsyscode(org, "55");
org.attribute1.setValue(oldcode);
} catch (Exception e) {
org.attribute1.setValue("生成旧编码错误");
e.printStackTrace();
}
}
if ((!org.orgid.isEmpty()) && (org.usable.getAsIntDefault(0) == 2)) {
String sqlstr = "SELECT IFNULL(COUNT(*), 0) ct FROM `hr_employee` WHERE `empstatid` < 10 and empstatid>0 AND `idpath` LIKE '"
+ org.idpath.getValue() + "%' ";
int ct = Integer.valueOf(con.openSql2List(sqlstr).get(0).get("ct").toString());
if (ct > 0)
throw new Exception("该机构下有【" + ct + "】个在职人员,不允许禁用");
}
}
public static void BeforeDelete(CDBConnection con, Shworg org) throws Exception {
CDBPool pool = (new Hr_employee()).pool;
if (Integer.valueOf(pool.openSql2List("select count(*) ct from hr_employee where orgid=" + org.orgid.getValue()).get(0).get("ct")) > 0) {
throw new Exception("【" + org.orgname.getValue() + "】包含员工资料,不允许删除!");
}
if (Integer.valueOf(pool.openSql2List("select count(*) ct from hr_orgposition where orgid=" + org.orgid.getValue()).get(0).get("ct")) > 0) {
throw new Exception("【" + org.orgname.getValue() + "】包含职位,不允许删除!");
}
if (Integer.valueOf(pool.openSql2List("select count(*) ct from hr_quotaoc where orgid=" + org.orgid.getValue()).get(0).get("ct")) > 0) {
throw new Exception("【" + org.orgname.getValue() + "】包含编制,不允许删除!");
}
}
}
<file_sep>/src/com/corsair/server/generic/Shwsystemparms.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwsystemparms extends CJPA {
@CFieldinfo(fieldname = "sspid", iskey = true, notnull = true, caption = "", datetype = Types.INTEGER)
public CField sspid; //
@CFieldinfo(fieldname = "parmname", caption = "", datetype = Types.VARCHAR)
public CField parmname; //
@CFieldinfo(fieldname = "parmvalue", caption = "", datetype = Types.VARCHAR)
public CField parmvalue; //
@CFieldinfo(fieldname = "acaption", caption = "", datetype = Types.VARCHAR)
public CField acaption; //
@CFieldinfo(fieldname = "edtable", caption = "", datetype = Types.INTEGER)
public CField edtable; //
@CFieldinfo(fieldname = "useable", caption = "", datetype = Types.INTEGER)
public CField useable; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwsystemparms() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/util/HttpTookit.java
package com.corsair.server.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shw_physic_file;
/**
* 基于 httpclient 4.3.1版本的 http工具类
*
*/
public class HttpTookit {
private CloseableHttpClient httpClient;
public final String CHARSET = "UTF-8";
public HttpTookit() {
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(30000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public String doGet(String url, Map<String, String> params) {
return doGet(url, params, CHARSET);
}
public String doPost(String url, Map<String, String> params) {
return doPost(url, params, CHARSET);
}
/**
* HTTP Get 获取内容
*
* @param url
* 请求的url地址 ?之前的地址
* @param params
* 请求的参数
* @param charset
* 编码格式
* @return 页面内容
*/
public String doGet(String url, Map<String, String> params, String charset) {
if ((url == null) || url.isEmpty()) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
String ps = EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
if (url.indexOf("?") < 0)
url += "?" + ps;
else
url += "&" + ps;
}
HttpGet httpGet = new HttpGet(url);
Logsw.dblog("urlnew:" + url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param url
* @param json
* @param headparams
* httpres头参数
* @param charset
* @return
* @throws Exception
*/
public String doPostJSON(String url, Object json, Map<String, String> headparams, String charset) throws Exception {
String vcharset = ((charset == null) || (charset.isEmpty())) ? "utf-8" : charset;
String data = null;
if (json instanceof JSONObject)
data = ((JSONObject) json).toString();
else if (json instanceof JSONArray) {
data = ((JSONArray) json).toString();
} else
return null;
return doPostJSON(url, data, headparams, vcharset);
}
public String doPostJSON(String url, String data, Map<String, String> headparams, String charset) throws Exception {
String vcharset = ((charset == null) || (charset.isEmpty())) ? "utf-8" : charset;
try {
HttpPost httpPost = new HttpPost(url);
if (headparams != null) {
Iterator<?> iter = headparams.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<String, String> entry = (Entry<String, String>) iter.next();
String key = entry.getKey().toString();
String val = entry.getValue().toString();
httpPost.setHeader(key, val);
}
}
StringEntity reqentity = new StringEntity(data, vcharset);// 解决中文乱码问题
reqentity.setContentEncoding(vcharset);
reqentity.setContentType("application/json");
httpPost.setEntity(reqentity);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
statusCode = (int) (Math.floor(statusCode / 100) * 100);// 2**都算成功
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, vcharset);
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
throw e;
}
}
/**
* http post json
*
* @param url
* @param json
* @param charset
* @return
* @throws Exception
*/
public String doPostJSON(String url, Object json, String charset) throws Exception {
return doPostJSON(url, json, null, charset);
}
/**
* HTTP Post 获取内容
*
* @param url
* 请求的url地址 ?之前的地址
* @param params
* 请求的参数
* @param charset
* 编码格式
* @return 页面内容
*/
public String doPost(String url, Map<String, String> params, String charset) {
String vcharset = ((charset == null) || (charset.isEmpty())) ? "utf-8" : charset;
if ((url == null) || url.isEmpty()) {
return null;
}
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPost httpPost = new HttpPost(url);
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, vcharset));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, vcharset);
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从网络缓存文件
*
* @param strurl
* @param suffix
* 文件后缀 .jpg 等
* null 自动根据content-type计算
* @return
* @throws Exception
*/
public Shw_physic_file getUrlFile(String strurl, String suffix) throws Exception {
//System.out.println(strurl);
HttpGet get = new HttpGet(strurl);
HttpResponse resp = httpClient.execute(get);
int code = resp.getStatusLine().getStatusCode();
code = code / 100 * 100;// 按百位取整 有些网站 2** 都算成功
if (code == 200) {
if (suffix == null)
suffix = CMIMEType.getSuffix(resp.getLastHeader("content-type").getValue());
HttpEntity entity = resp.getEntity();
if (null != entity) {
FilePath fp = UpLoadFileEx.getFilePath();
String fname = UpLoadFileEx.getNoReptFileName(suffix);// 数据库里面存的文件名
File f = new File(fp.FilePath + fname);
FileOutputStream output = null;
InputStream input = null;
try {
output = new FileOutputStream(f);
input = entity.getContent();
byte b[] = new byte[1024];
int j = 0;
while ((j = input.read(b)) != -1) {
output.write(b, 0, j);
}
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
DecimalFormat df = new DecimalFormat("0.##");
Shw_physic_file pf = new Shw_physic_file();
pf.ppath.setValue(fp.aPath);
pf.pfname.setValue(fname);
pf.create_time.setAsDatetime(new Date());
pf.creator.setValue(un);
pf.displayfname.setValue(fname);
pf.filesize.setValue(df.format(f.length() / (1024f)));// K
pf.extname.setValue(suffix);
pf.fsid.setAsInt(0);
pf.setJpaStat(CJPAStat.RSINSERT);
pf.save();
return pf;
} finally {
if (input != null)
input.close();
if (output != null) {
output.flush();
output.close();
}
}
} else
throw new Exception("httpget 错误,NUll【" + code + "】");
} else {
throw new Exception("httpget 错误【" + code + "】");
}
}
public static void main(String[] args) throws Exception {
String url = "http://img.taopic.com/uploads/allimg/121014/234931-1210140JK414.jpg";
// String url =
// "http://thirdwx.qlogo.cn/mmopen/vi_32/MVKN0Nv3KnTIO0AFBtLIicjBiaibpImMAXRFSlMvOYCibdTxGibVn1IqrghHeHnDg8RmicSX3zzur3O5h9ibSUNlNnqHA/132";
new HttpTookit().getUrlFile(url, ".jpg");
}
}
<file_sep>/src/com/hr/.svn/pristine/f1/f19772ab8c3034019178ba3ad9f978106ff3b24a.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import com.hr.perm.ctr.CtrHr_employee_transfer;
import java.sql.Types;
@CEntity(caption = "人事调动", controller = CtrHr_employee_transfer.class)
public class Hr_employee_transfer extends CJPA {
@CFieldinfo(fieldname = "emptranf_id", iskey = true, notnull = true, precision = 20, scale = 0, caption = "调动单ID", datetype = Types.INTEGER)
public CField emptranf_id; // 调动单ID
@CFieldinfo(fieldname = "emptranfcode", codeid = 56, notnull = true, precision = 15, scale = 0, caption = "调用编码", datetype = Types.VARCHAR)
public CField emptranfcode; // 调用编码
@CFieldinfo(fieldname = "er_id", notnull = true, precision = 20, scale = 0, caption = "人事ID", datetype = Types.INTEGER)
public CField er_id; // 人事ID
@CFieldinfo(fieldname = "employee_code", notnull = true, precision = 16, scale = 0, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "id_number", notnull = true, precision = 20, scale = 0, caption = "身份证号", datetype = Types.VARCHAR)
public CField id_number; // 身份证号
@CFieldinfo(fieldname = "employee_name", notnull = true, precision = 64, scale = 0, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "mnemonic_code", precision = 8, scale = 0, caption = "助记码", datetype = Types.VARCHAR)
public CField mnemonic_code; // 助记码
@CFieldinfo(fieldname = "email", precision = 128, scale = 0, caption = "邮箱/微信", datetype = Types.VARCHAR)
public CField email; // 邮箱/微信
@CFieldinfo(fieldname = "empstatid", precision = 1, scale = 0, caption = "人员状态", datetype = Types.INTEGER)
public CField empstatid; // 人员状态
@CFieldinfo(fieldname = "telphone", precision = 32, scale = 0, caption = "电话", datetype = Types.VARCHAR)
public CField telphone; // 电话
@CFieldinfo(fieldname = "tranfcmpdate", precision = 19, scale = 0, caption = "调动生效日期", datetype = Types.TIMESTAMP)
public CField tranfcmpdate; // 调动生效日期
@CFieldinfo(fieldname = "appdate", precision = 19, scale = 0, caption = "调动申请日期", datetype = Types.TIMESTAMP)
public CField appdate; // 调动申请日期
@CFieldinfo(fieldname = "hiredday", precision = 19, scale = 0, caption = "聘用日期", datetype = Types.TIMESTAMP)
public CField hiredday; // 聘用日期
@CFieldinfo(fieldname = "degree", precision = 11, scale = 0, caption = "学历", datetype = Types.INTEGER)
public CField degree; // 学历
@CFieldinfo(fieldname = "tranflev", precision = 2, scale = 0, caption = "调动层级", datetype = Types.INTEGER)
public CField tranflev; // 调动层级
@CFieldinfo(fieldname = "tranftype1", precision = 2, scale = 0, caption = "调动类型 1晋升调动 2降职调动 3同职种平级调动 4跨职种平级调动 ", datetype = Types.INTEGER)
public CField tranftype1; // 调动类型 1晋升调动 2降职调动 3同职种平级调动 4跨职种平级调动
@CFieldinfo(fieldname = "tranftype2", precision = 2, scale = 0, caption = "调动性质 1公司安排 2个人申请 3梦职场调动 4内部招聘 ", datetype = Types.INTEGER)
public CField tranftype2; // 调动性质 1公司安排 2个人申请 3梦职场调动 4内部招聘
@CFieldinfo(fieldname = "tranftype3", precision = 3, scale = 0, caption = "调动范围 1内部调用 2 跨单位 3 跨模块/制造群", datetype = Types.INTEGER)
public CField tranftype3; // 调动范围 1内部调用 2 跨单位 3 跨模块/制造群
@CFieldinfo(fieldname = "tranfreason", precision = 128, scale = 0, caption = "调动原因", datetype = Types.VARCHAR)
public CField tranfreason; // 调动原因
@CFieldinfo(fieldname = "probation", precision = 2, scale = 0, caption = "考察期", datetype = Types.INTEGER)
public CField probation; // 考察期
@CFieldinfo(fieldname = "probationdate", precision = 10, scale = 0, caption = "考察到期日期", datetype = Types.DATE)
public CField probationdate; // 考察到期日期
@CFieldinfo(fieldname = "ispromotioned", notnull = true, precision = 1, scale = 0, caption = "已转正", defvalue = "2", datetype = Types.INTEGER)
public CField ispromotioned; // 已转正
@CFieldinfo(fieldname = "odorgid", notnull = true, precision = 10, scale = 0, caption = "调动前部门ID", datetype = Types.INTEGER)
public CField odorgid; // 调动前部门ID
@CFieldinfo(fieldname = "odorgcode", notnull = true, precision = 16, scale = 0, caption = "调动前部门编码", datetype = Types.VARCHAR)
public CField odorgcode; // 调动前部门编码
@CFieldinfo(fieldname = "odorgname", notnull = true, precision = 128, scale = 0, caption = "调动前部门名称", datetype = Types.VARCHAR)
public CField odorgname; // 调动前部门名称
@CFieldinfo(fieldname = "odorghrlev", notnull = true, precision = 1, scale = 0, caption = "调调动前部门人事层级", defvalue = "0", datetype = Types.INTEGER)
public CField odorghrlev; // 调调动前部门人事层级
@CFieldinfo(fieldname = "odlv_id", precision = 10, scale = 0, caption = "调动前职级ID", datetype = Types.INTEGER)
public CField odlv_id; // 调动前职级ID
@CFieldinfo(fieldname = "odlv_num", precision = 4, scale = 1, caption = "调动前职级", datetype = Types.DECIMAL)
public CField odlv_num; // 调动前职级
@CFieldinfo(fieldname = "odhg_id", precision = 10, scale = 0, caption = "调动前职等ID", datetype = Types.INTEGER)
public CField odhg_id; // 调动前职等ID
@CFieldinfo(fieldname = "odhg_code", precision = 16, scale = 0, caption = "调动前职等编码", datetype = Types.VARCHAR)
public CField odhg_code; // 调动前职等编码
@CFieldinfo(fieldname = "odhg_name", precision = 128, scale = 0, caption = "调动前职等名称", datetype = Types.VARCHAR)
public CField odhg_name; // 调动前职等名称
@CFieldinfo(fieldname = "odospid", precision = 20, scale = 0, caption = "调动前职位ID", datetype = Types.INTEGER)
public CField odospid; // 调动前职位ID
@CFieldinfo(fieldname = "odospcode", precision = 16, scale = 0, caption = "调动前职位编码", datetype = Types.VARCHAR)
public CField odospcode; // 调动前职位编码
@CFieldinfo(fieldname = "odsp_name", precision = 128, scale = 0, caption = "调动前职位名称", datetype = Types.VARCHAR)
public CField odsp_name; // 调动前职位名称
@CFieldinfo(fieldname = "odattendtype", precision = 32, scale = 0, caption = "调动前出勤类别", datetype = Types.VARCHAR)
public CField odattendtype; // 调动前出勤类别
@CFieldinfo(fieldname = "oldcalsalarytype", precision = 32, scale = 0, caption = "调动前计薪方式", datetype = Types.VARCHAR)
public CField oldcalsalarytype; // 调动前计薪方式
@CFieldinfo(fieldname = "oldhwc_namezl", precision = 32, scale = 0, caption = "调动前职类", datetype = Types.VARCHAR)
public CField oldhwc_namezl; // 调动前职类
@CFieldinfo(fieldname = "oldhwc_namezq", precision = 32, scale = 0, caption = "调动前职群", datetype = Types.VARCHAR)
public CField oldhwc_namezq; // 调动前职群
@CFieldinfo(fieldname = "oldhwc_namezz", precision = 32, scale = 0, caption = "调动前职种", datetype = Types.VARCHAR)
public CField oldhwc_namezz; // 调动前职种
@CFieldinfo(fieldname = "oldstru_id", precision = 10, scale = 0, caption = "调薪前工资结构ID", datetype = Types.INTEGER)
public CField oldstru_id; // 调薪前工资结构ID
@CFieldinfo(fieldname = "oldstru_name", precision = 32, scale = 0, caption = "调薪前工资结构名", datetype = Types.VARCHAR)
public CField oldstru_name; // 调薪前工资结构名
@CFieldinfo(fieldname = "oldchecklev", precision = 1, scale = 0, caption = "调薪前绩效考核层级", datetype = Types.INTEGER)
public CField oldchecklev; // 调薪前绩效考核层级
@CFieldinfo(fieldname = "oldposition_salary", precision = 10, scale = 2, caption = "调动前职位工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldposition_salary; // 调动前职位工资
@CFieldinfo(fieldname = "oldbase_salary", precision = 10, scale = 2, caption = "调动前基本工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldbase_salary; // 调动前基本工资
@CFieldinfo(fieldname = "oldotwage", precision = 10, scale = 2, caption = "调薪前固定加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldotwage; // 调薪前固定加班工资
@CFieldinfo(fieldname = "oldtech_salary", precision = 10, scale = 2, caption = "调动前技能工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldtech_salary; // 调动前技能工资
@CFieldinfo(fieldname = "oldachi_salary", precision = 10, scale = 2, caption = "调动前绩效工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldachi_salary; // 调动前绩效工资
@CFieldinfo(fieldname = "oldtech_allowance", precision = 10, scale = 2, caption = "调动前技术津贴", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldtech_allowance; // 调动前技术津贴
@CFieldinfo(fieldname = "oldavg_salary", precision = 10, scale = 2, caption = "调动前平均工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldavg_salary; // 调动前平均工资
@CFieldinfo(fieldname = "oldovt_salary", precision = 10, scale = 2, caption = "调动前加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField oldovt_salary; // 调动前加班工资
@CFieldinfo(fieldname = "oldemnature", precision = 32, scale = 0, caption = "调动前人员性质", datetype = Types.VARCHAR)
public CField oldemnature; // 调动前人员性质
@CFieldinfo(fieldname = "neworgid", notnull = true, precision = 10, scale = 0, caption = "调动后部门ID", datetype = Types.INTEGER)
public CField neworgid; // 调动后部门ID
@CFieldinfo(fieldname = "neworgcode", notnull = true, precision = 16, scale = 0, caption = "调动后部门编码", datetype = Types.VARCHAR)
public CField neworgcode; // 调动后部门编码
@CFieldinfo(fieldname = "neworgname", notnull = true, precision = 128, scale = 0, caption = "调动后部门名称", datetype = Types.VARCHAR)
public CField neworgname; // 调动后部门名称
@CFieldinfo(fieldname = "neworghrlev", notnull = true, precision = 1, scale = 0, caption = "调动后部门人事层级", defvalue = "0", datetype = Types.INTEGER)
public CField neworghrlev; // 调动后部门人事层级
@CFieldinfo(fieldname = "newlv_id", precision = 10, scale = 0, caption = "调动后职级ID", datetype = Types.INTEGER)
public CField newlv_id; // 调动后职级ID
@CFieldinfo(fieldname = "newlv_num", precision = 4, scale = 1, caption = "调动后职级", datetype = Types.DECIMAL)
public CField newlv_num; // 调动后职级
@CFieldinfo(fieldname = "newhg_id", precision = 10, scale = 0, caption = "调动后职等ID", datetype = Types.INTEGER)
public CField newhg_id; // 调动后职等ID
@CFieldinfo(fieldname = "newhg_code", precision = 16, scale = 0, caption = "调动后职等编码", datetype = Types.VARCHAR)
public CField newhg_code; // 调动后职等编码
@CFieldinfo(fieldname = "newhg_name", precision = 128, scale = 0, caption = "调动后职等名称", datetype = Types.VARCHAR)
public CField newhg_name; // 调动后职等名称
@CFieldinfo(fieldname = "newospid", precision = 20, scale = 0, caption = "调动后职位ID", datetype = Types.INTEGER)
public CField newospid; // 调动后职位ID
@CFieldinfo(fieldname = "newospcode", precision = 16, scale = 0, caption = "调动后职位编码", datetype = Types.VARCHAR)
public CField newospcode; // 调动后职位编码
@CFieldinfo(fieldname = "newsp_name", precision = 128, scale = 0, caption = "调动后职位名称", datetype = Types.VARCHAR)
public CField newsp_name; // 调动后职位名称
@CFieldinfo(fieldname = "newattendtype", precision = 32, scale = 0, caption = "调动后出勤类别", datetype = Types.VARCHAR)
public CField newattendtype; // 调动后出勤类别
@CFieldinfo(fieldname = "newcalsalarytype", precision = 32, scale = 0, caption = "调动后计薪方式", datetype = Types.VARCHAR)
public CField newcalsalarytype; // 调动后计薪方式
@CFieldinfo(fieldname = "newhwc_namezl", precision = 32, scale = 0, caption = "调动后职类", datetype = Types.VARCHAR)
public CField newhwc_namezl; // 调动后职类
@CFieldinfo(fieldname = "newhwc_namezq", precision = 32, scale = 0, caption = "调动后职群", datetype = Types.VARCHAR)
public CField newhwc_namezq; // 调动后职群
@CFieldinfo(fieldname = "newhwc_namezz", precision = 32, scale = 0, caption = "调动后职种", datetype = Types.VARCHAR)
public CField newhwc_namezz; // 调动后职种
@CFieldinfo(fieldname = "newemnature", precision = 32, scale = 0, caption = "调动后人员性质", datetype = Types.VARCHAR)
public CField newemnature; // 调动后人员性质
@CFieldinfo(fieldname = "newstru_id", precision = 10, scale = 0, caption = "调薪后工资结构ID", datetype = Types.INTEGER)
public CField newstru_id; // 调薪后工资结构ID
@CFieldinfo(fieldname = "newstru_name", precision = 32, scale = 0, caption = "调薪后工资结构名", datetype = Types.VARCHAR)
public CField newstru_name; // 调薪后工资结构名
@CFieldinfo(fieldname = "newchecklev", precision = 1, scale = 0, caption = "调薪后绩效考核层级", datetype = Types.INTEGER)
public CField newchecklev; // 调薪后绩效考核层级
@CFieldinfo(fieldname = "newposition_salary", precision = 10, scale = 2, caption = "调动后职位工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newposition_salary; // 调动后职位工资
@CFieldinfo(fieldname = "newbase_salary", precision = 10, scale = 2, caption = "调动后基本工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newbase_salary; // 调动后基本工资
@CFieldinfo(fieldname = "newotwage", precision = 10, scale = 2, caption = "调薪后固定加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newotwage; // 调薪后固定加班工资
@CFieldinfo(fieldname = "newtech_salary", precision = 10, scale = 2, caption = "调动后技能工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newtech_salary; // 调动后技能工资
@CFieldinfo(fieldname = "newachi_salary", precision = 10, scale = 2, caption = "调动后绩效工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newachi_salary; // 调动后绩效工资
@CFieldinfo(fieldname = "newtech_allowance", precision = 10, scale = 2, caption = "调动后技术津贴", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newtech_allowance; // 调动后技术津贴
@CFieldinfo(fieldname = "newavg_salary", precision = 10, scale = 2, caption = "调动后平均工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newavg_salary; // 调动后平均工资
@CFieldinfo(fieldname = "newovt_salary", precision = 10, scale = 2, caption = "调动后加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField newovt_salary; // 调动后加班工资
@CFieldinfo(fieldname = "chgposition_salary", precision = 10, scale = 2, caption = "调整职位工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgposition_salary; // 调整职位工资
@CFieldinfo(fieldname = "chgbase_salary", precision = 10, scale = 2, caption = "调整基本工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgbase_salary; // 调整基本工资
@CFieldinfo(fieldname = "chgotwage", precision = 10, scale = 2, caption = "调整固定加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgotwage; // 调整固定加班工资
@CFieldinfo(fieldname = "chgtech_salary", precision = 10, scale = 2, caption = "调整技能工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgtech_salary; // 调整技能工资
@CFieldinfo(fieldname = "chgachi_salary", precision = 10, scale = 2, caption = "调整绩效工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgachi_salary; // 调整绩效工资
@CFieldinfo(fieldname = "chgtech_allowance", precision = 10, scale = 2, caption = "调整技术津贴", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgtech_allowance; // 调整技术津贴
@CFieldinfo(fieldname = "chgavg_salary", precision = 10, scale = 2, caption = "调整平均工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgavg_salary; // 调整平均工资
@CFieldinfo(fieldname = "chgovt_salary", precision = 10, scale = 2, caption = "调整加班工资", defvalue = "0.00", datetype = Types.DECIMAL)
public CField chgovt_salary; // 调整加班工资
@CFieldinfo(fieldname = "salary_qcnotnull", precision = 1, scale = 0, caption = "工资额度是否必填", defvalue = "2", datetype = Types.INTEGER)
public CField salary_qcnotnull; // 工资额度是否必填
@CFieldinfo(fieldname = "salary_quotacode", precision = 16, scale = 0, caption = "可用工资额度证明编号", datetype = Types.VARCHAR)
public CField salary_quotacode; // 可用工资额度证明编号
@CFieldinfo(fieldname = "salary_quota_stand", precision = 10, scale = 2, caption = "标准工资额度", defvalue = "0.00", datetype = Types.DECIMAL)
public CField salary_quota_stand; // 标准工资额度
@CFieldinfo(fieldname = "salary_quota_appy", precision = 10, scale = 1, caption = "申请工资额度", defvalue = "0.0", datetype = Types.DECIMAL)
public CField salary_quota_appy; // 申请工资额度
@CFieldinfo(fieldname = "salary_quota_canuse", precision = 10, scale = 2, caption = "可用工资额度", defvalue = "0.00", datetype = Types.DECIMAL)
public CField salary_quota_canuse; // 可用工资额度
@CFieldinfo(fieldname = "salary_quota_used", precision = 10, scale = 2, caption = "己用工资额度", defvalue = "0.00", datetype = Types.DECIMAL)
public CField salary_quota_used; // 己用工资额度
@CFieldinfo(fieldname = "salary_quota_blance", precision = 10, scale = 2, caption = "可用工资余额", defvalue = "0.00", datetype = Types.DECIMAL)
public CField salary_quota_blance; // 可用工资余额
@CFieldinfo(fieldname = "salary_quota_ovsp", precision = 1, scale = 0, caption = "超额度审批", datetype = Types.INTEGER)
public CField salary_quota_ovsp; // 超额度审批
@CFieldinfo(fieldname = "salarydate", precision = 10, scale = 0, caption = "核薪生效日期", datetype = Types.DATE)
public CField salarydate; // 核薪生效日期
@CFieldinfo(fieldname = "istp", precision = 1, scale = 0, caption = "是否特批", defvalue = "2", datetype = Types.INTEGER)
public CField istp; // 是否特批
@CFieldinfo(fieldname = "tranamt", precision = 10, scale = 2, caption = "调拨金额", defvalue = "0.00", datetype = Types.DECIMAL)
public CField tranamt; // 调拨金额
@CFieldinfo(fieldname = "exam_title", precision = 64, scale = 0, caption = "考试课题", datetype = Types.VARCHAR)
public CField exam_title; // 考试课题
@CFieldinfo(fieldname = "exam_time", precision = 19, scale = 0, caption = "考试时间", datetype = Types.TIMESTAMP)
public CField exam_time; // 考试时间
@CFieldinfo(fieldname = "exam_score", precision = 10, scale = 2, caption = "考试分数", defvalue = "0.00", datetype = Types.DECIMAL)
public CField exam_score; // 考试分数
@CFieldinfo(fieldname = "mupexam_time", precision = 19, scale = 0, caption = "补考时间", datetype = Types.TIMESTAMP)
public CField mupexam_time; // 补考时间
@CFieldinfo(fieldname = "mupexam_score", precision = 10, scale = 2, caption = "补考分数", defvalue = "0.00", datetype = Types.DECIMAL)
public CField mupexam_score; // 补考分数
@CFieldinfo(fieldname = "exam_note", precision = 32, scale = 0, caption = "考试备注", datetype = Types.VARCHAR)
public CField exam_note; // 考试备注
@CFieldinfo(fieldname = "remark", precision = 512, scale = 0, caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "quota_over", precision = 1, scale = 0, caption = "是否超编", defvalue = "2", datetype = Types.INTEGER)
public CField quota_over; // 是否超编
@CFieldinfo(fieldname = "quota_over_rst", precision = 1, scale = 0, caption = "超编审批结果 1 允许增加编制调动 ps是否自动生成编制调整单 2 超编调动 3 不允许调动", defvalue = "0", datetype = Types.INTEGER)
public CField quota_over_rst; // 超编审批结果 1 允许增加编制调动 ps是否自动生成编制调整单 2 超编调动 3 不允许调动
@CFieldinfo(fieldname = "isdreamposition", precision = 1, scale = 0, caption = "是否梦职场调入", defvalue = "2", datetype = Types.INTEGER)
public CField isdreamposition; // 是否梦职场调入
@CFieldinfo(fieldname = "isdreamemploye", precision = 1, scale = 0, caption = "是否梦职场储备员工", defvalue = "2", datetype = Types.INTEGER)
public CField isdreamemploye; // 是否梦职场储备员工
@CFieldinfo(fieldname = "tranftype4", precision = 1, scale = 0, caption = "调动类别", datetype = Types.INTEGER)
public CField tranftype4; // 调动类别
@CFieldinfo(fieldname = "isexistsrl", precision = 1, scale = 0, caption = "关联关系 有关联关系 无关联关系", datetype = Types.INTEGER)
public CField isexistsrl; // 关联关系 有关联关系 无关联关系
@CFieldinfo(fieldname = "rlmgms", precision = 1, scale = 0, caption = "管控措施 不需管控 终止调动 申请豁免", datetype = Types.INTEGER)
public CField rlmgms; // 管控措施 不需管控 终止调动 申请豁免
@CFieldinfo(fieldname = "ismangerl", precision = 1, scale = 0, caption = "是否构成需要管控的管理关系类别", datetype = Types.INTEGER)
public CField ismangerl; // 是否构成需要管控的管理关系类别
@CFieldinfo(fieldname = "isapprlhm", precision = 1, scale = 0, caption = "是否申请关联关系豁免", datetype = Types.INTEGER)
public CField isapprlhm; // 是否申请关联关系豁免
@CFieldinfo(fieldname = "isapprlhmsp", precision = 1, scale = 0, caption = "关联关系豁免申请是否得到审批", datetype = Types.INTEGER)
public CField isapprlhmsp; // 关联关系豁免申请是否得到审批
@CFieldinfo(fieldname = "quotastand", precision = 3, scale = 0, caption = "标准配置人数", datetype = Types.INTEGER)
public CField quotastand; // 标准配置人数
@CFieldinfo(fieldname = "quotasj", precision = 3, scale = 0, caption = "实际配置人数", datetype = Types.INTEGER)
public CField quotasj; // 实际配置人数
@CFieldinfo(fieldname = "quotacq", precision = 3, scale = 0, caption = "超缺编人数(正数表示超编、负数表示缺编)", datetype = Types.INTEGER)
public CField quotacq; // 超缺编人数(正数表示超编、负数表示缺编)
@CFieldinfo(fieldname = "isallowdrmin", precision = 1, scale = 0, caption = "是否同意特批调动至梦职场职位", datetype = Types.INTEGER)
public CField isallowdrmin; // 是否同意特批调动至梦职场职位
@CFieldinfo(fieldname = "wfid", precision = 20, scale = 0, caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", precision = 20, scale = 0, caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", notnull = true, precision = 2, scale = 0, caption = "流程状态", datetype = Types.INTEGER)
public CField stat; // 流程状态
@CFieldinfo(fieldname = "idpath", notnull = true, precision = 256, scale = 0, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, precision = 5, scale = 0, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, precision = 32, scale = 0, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, precision = 19, scale = 0, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", precision = 32, scale = 0, caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", precision = 19, scale = 0, caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", precision = 32, scale = 0, caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", precision = 32, scale = 0, caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", precision = 32, scale = 0, caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", precision = 32, scale = 0, caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", precision = 32, scale = 0, caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
@CFieldinfo(fieldname = "oldhg_remark", precision = 32, scale = 0, caption = "调动前职位名称", datetype = Types.VARCHAR)
public CField oldhg_remark; // 调动前职位备注
@CFieldinfo(fieldname = "newhg_remark", precision = 32, scale = 0, caption = "调动前职位名称", datetype = Types.VARCHAR)
public CField newhg_remark; // 调动后职位备注
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;
@CLinkFieldInfo(jpaclass = Hr_employee_transfer_rl.class, linkFields = { @LinkFieldItem(lfield = "emptranf_id", mfield = "emptranf_id"),
@LinkFieldItem(lfield = "emptranfcode", mfield = "emptranfcode") })
public CJPALineData<Hr_employee_transfer_rl> hr_employee_transfer_rls;
public Hr_employee_transfer() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/generic/Shwuserparmsconst.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwuserparmsconst extends CJPA {
@CFieldinfo(fieldname = "cstparmid", caption = "cstparmid", datetype = Types.DECIMAL)
public CField cstparmid; // cstparmid
@CFieldinfo(fieldname = "parmname", caption = "parmname", datetype = Types.VARCHAR)
public CField parmname; // parmname
@CFieldinfo(fieldname = "defaultvalue", caption = "defaultvalue", datetype = Types.VARCHAR)
public CField defaultvalue; // defaultvalue
@CFieldinfo(fieldname = "language1", caption = "language1", datetype = Types.VARCHAR)
public CField language1; // language1
@CFieldinfo(fieldname = "language2", caption = "language2", datetype = Types.VARCHAR)
public CField language2; // language2
@CFieldinfo(fieldname = "language3", caption = "language3", datetype = Types.VARCHAR)
public CField language3; // language3
@CFieldinfo(fieldname = "notelanguage1", caption = "notelanguage1", datetype = Types.VARCHAR)
public CField notelanguage1; // notelanguage1
@CFieldinfo(fieldname = "notelanguage2", caption = "notelanguage2", datetype = Types.VARCHAR)
public CField notelanguage2; // notelanguage2
@CFieldinfo(fieldname = "notelanguage3", caption = "notelanguage3", datetype = Types.VARCHAR)
public CField notelanguage3; // notelanguage3
@CFieldinfo(fieldname = "action", caption = "action", datetype = Types.VARCHAR)
public CField action; // action
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwuserparmsconst() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/92/925005234884828db161d1112faa985c3a3584be.svn-base
package com.hr.perm.co;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_work;
@ACO(coname = "web.hr.employee.work")
public class COHr_employee_work {
@ACOAction(eventname = "getworklist", Authentication = true, ispublic = true, notes = "获取列表信息")
public String getrewardlist() throws Exception {
String sqlstr = "SELECT e.employee_code,e.employee_name,e.orgname,e.sp_name,e.hg_name,e.lv_num,e.idpath,l.* "
+ " FROM hr_employee e,hr_employee_work l "
+ " WHERE e.er_id=l.er_id ";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
sqlstr = sqlstr + " and l.empl_id=" + id;
} else
sqlstr = sqlstr + " order by empl_id desc";
return new CReport(sqlstr, null).findReport();
}
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "导入Excel")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Hr_employee_work er = new Hr_employee_work();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
er.clear();
er.er_id.setValue(emp.er_id.getValue());
er.company.setValue(v.get("company")); // 工作单位
er.start_date.setValue(v.get("start_date")); // 起始日期
er.end_date.setValue(v.get("end_date")); // 结束日期
er.func.setValue(v.get("func")); // 职务
er.work_type.setValue(null); // 工种
er.jobexp.setValue(v.get("jobexp")); // 工作内容
er.endsarary.setValue(v.get("endsarary")); // 离职薪资
er.position_desc.setValue(null); // 任职岗位
er.witness.setValue(v.get("witness")); // 证明人
er.witness_tel.setValue(v.get("witness_tel")); // 联系电话
er.is_group_experience.setValue("2"); // 是否集团经历
er.is_vocation_experience.setValue("2"); // 是否行业经历
er.remark.setValue(v.get("remark")); // 备注
er.save(con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("工作单位", "company", true));
efields.add(new CExcelField("起始日期", "start_date", true));
efields.add(new CExcelField("结束日期", "end_date", true));
efields.add(new CExcelField("职务", "func", true));
efields.add(new CExcelField("主要工作", "jobexp", true));
efields.add(new CExcelField("离职薪资", "endsarary", true));
efields.add(new CExcelField("证明人", "witness", true));
efields.add(new CExcelField("联系电话", "witness_tel", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
}
<file_sep>/src/com/hr/attd/entity/Hrkq_workschmonthline.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrkq_workschmonthline extends CJPA {
@CFieldinfo(fieldname = "wklid", iskey = true, notnull = true, caption = "LID", datetype = Types.INTEGER)
public CField wklid; // LID
@CFieldinfo(fieldname = "wkid", notnull = true, caption = "主表ID", datetype = Types.INTEGER)
public CField wkid; // 主表ID
@CFieldinfo(fieldname = "tid", notnull = true, caption = "目标ID", datetype = Types.INTEGER)
public CField tid; // 目标ID
@CFieldinfo(fieldname = "tcode", notnull = true, caption = "目标编码", datetype = Types.VARCHAR)
public CField tcode; // 目标编码
@CFieldinfo(fieldname = "tname", notnull = true, caption = "目标名称", datetype = Types.VARCHAR)
public CField tname; // 目标名称
@CFieldinfo(fieldname = "sp_name", caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称 ttype==3
@CFieldinfo(fieldname = "lv_num", caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级 ttype==3
@CFieldinfo(fieldname = "ttype", notnull = true, caption = "类型:1 班制组 2 部门 3 个人", datetype = Types.INTEGER)
public CField ttype; // 类型:1 班制组 2 部门 3 个人
@CFieldinfo(fieldname = "scid1", caption = "班制ID1", datetype = Types.INTEGER)
public CField scid1; // 班制ID1
@CFieldinfo(fieldname = "scid2", caption = "班制ID2", datetype = Types.INTEGER)
public CField scid2; // 班制ID2
@CFieldinfo(fieldname = "scid3", caption = "班制ID3", datetype = Types.INTEGER)
public CField scid3; // 班制ID3
@CFieldinfo(fieldname = "scid4", caption = "班制ID4", datetype = Types.INTEGER)
public CField scid4; // 班制ID4
@CFieldinfo(fieldname = "scid5", caption = "班制ID5", datetype = Types.INTEGER)
public CField scid5; // 班制ID5
@CFieldinfo(fieldname = "scid6", caption = "班制ID6", datetype = Types.INTEGER)
public CField scid6; // 班制ID6
@CFieldinfo(fieldname = "scid7", caption = "班制ID7", datetype = Types.INTEGER)
public CField scid7; // 班制ID7
@CFieldinfo(fieldname = "scid8", caption = "班制ID8", datetype = Types.INTEGER)
public CField scid8; // 班制ID8
@CFieldinfo(fieldname = "scid9", caption = "班制ID9", datetype = Types.INTEGER)
public CField scid9; // 班制ID9
@CFieldinfo(fieldname = "scid10", caption = "班制ID10", datetype = Types.INTEGER)
public CField scid10; // 班制ID10
@CFieldinfo(fieldname = "scid11", caption = "班制ID11", datetype = Types.INTEGER)
public CField scid11; // 班制ID11
@CFieldinfo(fieldname = "scid12", caption = "班制ID12", datetype = Types.INTEGER)
public CField scid12; // 班制ID12
@CFieldinfo(fieldname = "scid13", caption = "班制ID13", datetype = Types.INTEGER)
public CField scid13; // 班制ID13
@CFieldinfo(fieldname = "scid14", caption = "班制ID14", datetype = Types.INTEGER)
public CField scid14; // 班制ID14
@CFieldinfo(fieldname = "scid15", caption = "班制ID15", datetype = Types.INTEGER)
public CField scid15; // 班制ID15
@CFieldinfo(fieldname = "scid16", caption = "班制ID16", datetype = Types.INTEGER)
public CField scid16; // 班制ID16
@CFieldinfo(fieldname = "scid17", caption = "班制ID17", datetype = Types.INTEGER)
public CField scid17; // 班制ID17
@CFieldinfo(fieldname = "scid18", caption = "班制ID18", datetype = Types.INTEGER)
public CField scid18; // 班制ID18
@CFieldinfo(fieldname = "scid19", caption = "班制ID19", datetype = Types.INTEGER)
public CField scid19; // 班制ID19
@CFieldinfo(fieldname = "scid20", caption = "班制ID20", datetype = Types.INTEGER)
public CField scid20; // 班制ID20
@CFieldinfo(fieldname = "scid21", caption = "班制ID21", datetype = Types.INTEGER)
public CField scid21; // 班制ID21
@CFieldinfo(fieldname = "scid22", caption = "班制ID22", datetype = Types.INTEGER)
public CField scid22; // 班制ID22
@CFieldinfo(fieldname = "scid23", caption = "班制ID23", datetype = Types.INTEGER)
public CField scid23; // 班制ID23
@CFieldinfo(fieldname = "scid24", caption = "班制ID24", datetype = Types.INTEGER)
public CField scid24; // 班制ID24
@CFieldinfo(fieldname = "scid25", caption = "班制ID25", datetype = Types.INTEGER)
public CField scid25; // 班制ID25
@CFieldinfo(fieldname = "scid26", caption = "班制ID26", datetype = Types.INTEGER)
public CField scid26; // 班制ID26
@CFieldinfo(fieldname = "scid27", caption = "班制ID27", datetype = Types.INTEGER)
public CField scid27; // 班制ID27
@CFieldinfo(fieldname = "scid28", caption = "班制ID28", datetype = Types.INTEGER)
public CField scid28; // 班制ID28
@CFieldinfo(fieldname = "scid29", caption = "班制ID29", datetype = Types.INTEGER)
public CField scid29; // 班制ID29
@CFieldinfo(fieldname = "scid30", caption = "班制ID30", datetype = Types.INTEGER)
public CField scid30; // 班制ID30
@CFieldinfo(fieldname = "scid31", caption = "班制ID31", datetype = Types.INTEGER)
public CField scid31; // 班制ID31
@CFieldinfo(fieldname = "scdname1", caption = "班制名称1", datetype = Types.VARCHAR)
public CField scdname1; // 班制名称1
@CFieldinfo(fieldname = "scdname2", caption = "班制名称2", datetype = Types.VARCHAR)
public CField scdname2; // 班制名称2
@CFieldinfo(fieldname = "scdname3", caption = "班制名称3", datetype = Types.VARCHAR)
public CField scdname3; // 班制名称3
@CFieldinfo(fieldname = "scdname4", caption = "班制名称4", datetype = Types.VARCHAR)
public CField scdname4; // 班制名称4
@CFieldinfo(fieldname = "scdname5", caption = "班制名称5", datetype = Types.VARCHAR)
public CField scdname5; // 班制名称5
@CFieldinfo(fieldname = "scdname6", caption = "班制名称6", datetype = Types.VARCHAR)
public CField scdname6; // 班制名称6
@CFieldinfo(fieldname = "scdname7", caption = "班制名称7", datetype = Types.VARCHAR)
public CField scdname7; // 班制名称7
@CFieldinfo(fieldname = "scdname8", caption = "班制名称8", datetype = Types.VARCHAR)
public CField scdname8; // 班制名称8
@CFieldinfo(fieldname = "scdname9", caption = "班制名称9", datetype = Types.VARCHAR)
public CField scdname9; // 班制名称9
@CFieldinfo(fieldname = "scdname10", caption = "班制名称10", datetype = Types.VARCHAR)
public CField scdname10; // 班制名称10
@CFieldinfo(fieldname = "scdname11", caption = "班制名称11", datetype = Types.VARCHAR)
public CField scdname11; // 班制名称11
@CFieldinfo(fieldname = "scdname12", caption = "班制名称12", datetype = Types.VARCHAR)
public CField scdname12; // 班制名称12
@CFieldinfo(fieldname = "scdname13", caption = "班制名称13", datetype = Types.VARCHAR)
public CField scdname13; // 班制名称13
@CFieldinfo(fieldname = "scdname14", caption = "班制名称14", datetype = Types.VARCHAR)
public CField scdname14; // 班制名称14
@CFieldinfo(fieldname = "scdname15", caption = "班制名称15", datetype = Types.VARCHAR)
public CField scdname15; // 班制名称15
@CFieldinfo(fieldname = "scdname16", caption = "班制名称16", datetype = Types.VARCHAR)
public CField scdname16; // 班制名称16
@CFieldinfo(fieldname = "scdname17", caption = "班制名称17", datetype = Types.VARCHAR)
public CField scdname17; // 班制名称17
@CFieldinfo(fieldname = "scdname18", caption = "班制名称18", datetype = Types.VARCHAR)
public CField scdname18; // 班制名称18
@CFieldinfo(fieldname = "scdname19", caption = "班制名称19", datetype = Types.VARCHAR)
public CField scdname19; // 班制名称19
@CFieldinfo(fieldname = "scdname20", caption = "班制名称20", datetype = Types.VARCHAR)
public CField scdname20; // 班制名称20
@CFieldinfo(fieldname = "scdname21", caption = "班制名称21", datetype = Types.VARCHAR)
public CField scdname21; // 班制名称21
@CFieldinfo(fieldname = "scdname22", caption = "班制名称22", datetype = Types.VARCHAR)
public CField scdname22; // 班制名称22
@CFieldinfo(fieldname = "scdname23", caption = "班制名称23", datetype = Types.VARCHAR)
public CField scdname23; // 班制名称23
@CFieldinfo(fieldname = "scdname24", caption = "班制名称24", datetype = Types.VARCHAR)
public CField scdname24; // 班制名称24
@CFieldinfo(fieldname = "scdname25", caption = "班制名称25", datetype = Types.VARCHAR)
public CField scdname25; // 班制名称25
@CFieldinfo(fieldname = "scdname26", caption = "班制名称26", datetype = Types.VARCHAR)
public CField scdname26; // 班制名称26
@CFieldinfo(fieldname = "scdname27", caption = "班制名称27", datetype = Types.VARCHAR)
public CField scdname27; // 班制名称27
@CFieldinfo(fieldname = "scdname28", caption = "班制名称28", datetype = Types.VARCHAR)
public CField scdname28; // 班制名称28
@CFieldinfo(fieldname = "scdname29", caption = "班制名称29", datetype = Types.VARCHAR)
public CField scdname29; // 班制名称29
@CFieldinfo(fieldname = "scdname30", caption = "班制名称30", datetype = Types.VARCHAR)
public CField scdname30; // 班制名称30
@CFieldinfo(fieldname = "scdname31", caption = "班制名称31", datetype = Types.VARCHAR)
public CField scdname31; // 班制名称31
@CFieldinfo(fieldname = "backcolor1", caption = "背景颜色1", datetype = Types.VARCHAR)
public CField backcolor1; // 背景颜色1
@CFieldinfo(fieldname = "backcolor2", caption = "背景颜色2", datetype = Types.VARCHAR)
public CField backcolor2; // 背景颜色2
@CFieldinfo(fieldname = "backcolor3", caption = "背景颜色3", datetype = Types.VARCHAR)
public CField backcolor3; // 背景颜色3
@CFieldinfo(fieldname = "backcolor4", caption = "背景颜色4", datetype = Types.VARCHAR)
public CField backcolor4; // 背景颜色4
@CFieldinfo(fieldname = "backcolor5", caption = "背景颜色5", datetype = Types.VARCHAR)
public CField backcolor5; // 背景颜色5
@CFieldinfo(fieldname = "backcolor6", caption = "背景颜色6", datetype = Types.VARCHAR)
public CField backcolor6; // 背景颜色6
@CFieldinfo(fieldname = "backcolor7", caption = "背景颜色7", datetype = Types.VARCHAR)
public CField backcolor7; // 背景颜色7
@CFieldinfo(fieldname = "backcolor8", caption = "背景颜色8", datetype = Types.VARCHAR)
public CField backcolor8; // 背景颜色8
@CFieldinfo(fieldname = "backcolor9", caption = "背景颜色9", datetype = Types.VARCHAR)
public CField backcolor9; // 背景颜色9
@CFieldinfo(fieldname = "backcolor10", caption = "背景颜色10", datetype = Types.VARCHAR)
public CField backcolor10; // 背景颜色10
@CFieldinfo(fieldname = "backcolor11", caption = "背景颜色11", datetype = Types.VARCHAR)
public CField backcolor11; // 背景颜色11
@CFieldinfo(fieldname = "backcolor12", caption = "背景颜色12", datetype = Types.VARCHAR)
public CField backcolor12; // 背景颜色12
@CFieldinfo(fieldname = "backcolor13", caption = "背景颜色13", datetype = Types.VARCHAR)
public CField backcolor13; // 背景颜色13
@CFieldinfo(fieldname = "backcolor14", caption = "背景颜色14", datetype = Types.VARCHAR)
public CField backcolor14; // 背景颜色14
@CFieldinfo(fieldname = "backcolor15", caption = "背景颜色15", datetype = Types.VARCHAR)
public CField backcolor15; // 背景颜色15
@CFieldinfo(fieldname = "backcolor16", caption = "背景颜色16", datetype = Types.VARCHAR)
public CField backcolor16; // 背景颜色16
@CFieldinfo(fieldname = "backcolor17", caption = "背景颜色17", datetype = Types.VARCHAR)
public CField backcolor17; // 背景颜色17
@CFieldinfo(fieldname = "backcolor18", caption = "背景颜色18", datetype = Types.VARCHAR)
public CField backcolor18; // 背景颜色18
@CFieldinfo(fieldname = "backcolor19", caption = "背景颜色19", datetype = Types.VARCHAR)
public CField backcolor19; // 背景颜色19
@CFieldinfo(fieldname = "backcolor20", caption = "背景颜色20", datetype = Types.VARCHAR)
public CField backcolor20; // 背景颜色20
@CFieldinfo(fieldname = "backcolor21", caption = "背景颜色21", datetype = Types.VARCHAR)
public CField backcolor21; // 背景颜色21
@CFieldinfo(fieldname = "backcolor22", caption = "背景颜色22", datetype = Types.VARCHAR)
public CField backcolor22; // 背景颜色22
@CFieldinfo(fieldname = "backcolor23", caption = "背景颜色23", datetype = Types.VARCHAR)
public CField backcolor23; // 背景颜色23
@CFieldinfo(fieldname = "backcolor24", caption = "背景颜色24", datetype = Types.VARCHAR)
public CField backcolor24; // 背景颜色24
@CFieldinfo(fieldname = "backcolor25", caption = "背景颜色25", datetype = Types.VARCHAR)
public CField backcolor25; // 背景颜色25
@CFieldinfo(fieldname = "backcolor26", caption = "背景颜色26", datetype = Types.VARCHAR)
public CField backcolor26; // 背景颜色26
@CFieldinfo(fieldname = "backcolor27", caption = "背景颜色27", datetype = Types.VARCHAR)
public CField backcolor27; // 背景颜色27
@CFieldinfo(fieldname = "backcolor28", caption = "背景颜色28", datetype = Types.VARCHAR)
public CField backcolor28; // 背景颜色28
@CFieldinfo(fieldname = "backcolor29", caption = "背景颜色29", datetype = Types.VARCHAR)
public CField backcolor29; // 背景颜色29
@CFieldinfo(fieldname = "backcolor30", caption = "背景颜色30", datetype = Types.VARCHAR)
public CField backcolor30; // 背景颜色30
@CFieldinfo(fieldname = "backcolor31", caption = "背景颜色31", datetype = Types.VARCHAR)
public CField backcolor31; // 背景颜色31
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_workschmonthline() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/ctrl/CtrShworg.java
package com.corsair.server.ctrl;
import java.lang.reflect.Constructor;
import java.util.Date;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shwfdracl;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shworg_acthis;
import com.corsair.server.generic.Shworg_find;
import com.corsair.server.generic.Shworguser;
import com.corsair.server.util.CTreeUtil;
/**
* 机构控制器
*
* @author Administrator
*
*/
public class CtrShworg {
public static void chgOrgName(String orgid, String newname) throws Exception {
Shworg org = new Shworg();
CDBConnection con = org.pool.getCon(CTreeUtil.class);
con.startTrans();
try {
org.findByID(con, orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
org.orgname.setValue(newname);
org.save(con);
String sqlstr = "select * from shworg where idpath like '" + org.idpath.getValue() + "%'";
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(con, sqlstr, false, true);
for (CJPABase jpa : orgs) {
Shworg torg = (Shworg) jpa;
torg.extorgname.setValue(COShwUser.getOrgNamepath(con, torg.idpath.getValue()));
torg.save(con);
OnChangeOrgInfoListener oic = getOrgChgListener();
if (oic != null)
oic.OnOrgChg(con, torg.toJsonObj(), null);
}
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
}finally{
con.close();
}
}
// ///////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// 将源机构下面信息挪动到目标机构下 原机构不动
public static void putOrgData2Org(String sorgid, String dorgid) throws Exception {
Shworg sorg = new Shworg();
Shworg dorg = new Shworg();
CDBConnection con = sorg.pool.getCon(CTreeUtil.class);
con.startTrans();
try {
sorg.findByID(con, sorgid);
if (sorg.isEmpty()) {
throw new Exception("ID为【" + sorgid + "】的机构不存在");
}
dorg.findByID(con, dorgid);
if (dorg.isEmpty()) {
throw new Exception("ID为【" + dorgid + "】的机构不存在");
}
JSONObject dorg_s = dorg.toJsonObj();
putOrgData2Org(con, sorg, dorg_s);
Shworg_acthis soh = new Shworg_acthis();
soh.orgid.setValue(sorg.orgid.getValue());
soh.acttype.setAsInt(3);
soh.acttime.setAsDatetime(new Date());
soh.actcommit.setValue("合并到机构" + dorg.orgid.getValue() + "," + dorg.code.getValue() + "," + dorg.orgname.getValue());
soh.save(con);
soh.clear();
soh.orgid.setValue(dorg.orgid.getValue());
soh.acttype.setAsInt(2);
soh.acttime.setAsDatetime(new Date());
soh.actcommit.setValue("合并机构" + sorg.orgid.getValue() + "," + sorg.code.getValue() + "," + sorg.orgname.getValue());
soh.save(con);
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
}finally{
con.close();
}
}
private static void putOrgData2Org(CDBConnection con, Shworg sorg, JSONObject dorg_s) throws Exception {
String sidp = sorg.idpath.getValue();
String didp = dorg_s.getString("idpath");
if (didp.length() > sidp.length())// 只有目标长度大于源长度才有可能
if (didp.substring(0, sidp.length()).equals(sidp)) {
throw new Exception("目标机构【" + dorg_s.getString("orgname") + "】不能是源机构【" + sorg.orgname.getValue() + "】及其下属机构");
}
upData2NewOrg(con, sorg, dorg_s);
}
private static void upData2NewOrg(CDBConnection con, Shworg oldorg, JSONObject dorg_s) throws Exception {
// 文件权限
String sqlstr = "SELECT * FROM shwfdracl WHERE acltype IN(1,2) AND ownerid=" + oldorg.orgid.getValue();
CJPALineData<Shwfdracl> acls = new CJPALineData<Shwfdracl>(Shwfdracl.class);
acls.findDataBySQL(con, sqlstr, true, false, -1, 0, true);
for (CJPABase jpa : acls) {
Shwfdracl oldacl = (Shwfdracl) jpa;
sqlstr = "SELECT count(*) ct FROM shwfdracl WHERE acltype IN(1,2) AND ownerid=" + dorg_s.getString("orgid")
+ " and objid=" + oldacl.objid.getValue();
if (Integer.valueOf(con.openSql2List(sqlstr).get(0).get("ct")) == 0) {
oldacl.ownerid.setValue(dorg_s.getString("orgid"));
oldacl.idpath.setValue(dorg_s.getString("idpath"));
oldacl.ownername.setValue(dorg_s.getString("orgname"));
oldacl.save(con);
}
}
// 兼管机构
sqlstr = "SELECT * FROM shworg_find WHERE forgid=" + oldorg.orgid.getValue();
CJPALineData<Shworg_find> ofs = new CJPALineData<Shworg_find>(Shworg_find.class);
ofs.findDataBySQL(con, sqlstr, true, false, -1, 0, true);
for (CJPABase jpa : ofs) {
Shworg_find oldof = (Shworg_find) jpa;
sqlstr = "select count(*) ct from shworg_find where forgid=" + dorg_s.getString("orgid") + " and orgid=" + oldof.orgid.getValue();
if (Integer.valueOf(con.openSql2List(sqlstr).get(0).get("ct")) == 0) {
oldof.forgid.setValue(dorg_s.getString("orgid"));
oldof.forgname.setValue(dorg_s.getString("extorgname"));
oldof.fcode.setValue(dorg_s.getString("code"));
oldof.fidpath.setValue(dorg_s.getString("idpath"));
oldof.save(con);
}
}
sqlstr = "UPDATE shworg_find SET orgid=" + dorg_s.getString("orgid") + " WHERE orgid=" + oldorg.orgid.getValue();
con.execsql(sqlstr);
// 用户机构
sqlstr = "SELECT * FROM shworguser WHERE orgid=" + oldorg.orgid.getValue();
CJPALineData<Shworguser> ous = new CJPALineData<Shworguser>(Shworguser.class);
ous.findDataBySQL(con, sqlstr, true, false, -1, 0, true);
for (CJPABase jpa : ous) {
Shworguser oldou = (Shworguser) jpa;
sqlstr = "SELECT count(*) ct FROM shworguser WHERE orgid=" + dorg_s.getString("orgid") + " and userid=" + oldou.userid.getValue();
if (Integer.valueOf(con.openSql2List(sqlstr).get(0).get("ct")) == 0) {
sqlstr = "UPDATE shworguser SET orgid=" + dorg_s.getString("orgid") + " WHERE orgid=" + oldorg.orgid.getValue() + " and userid="
+ oldou.userid.getValue();
con.execsql(sqlstr);// 修改主关键字只能用SQL语句
}
}
OnChangeOrgInfoListener oic = getOrgChgListener();
if (oic != null)
oic.OnOrgData2Org(con, oldorg, dorg_s);
// 不能放前面去
sqlstr = "SELECT * FROM shworg WHERE superid =" + oldorg.orgid.getValue();
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(con, sqlstr, true, false, -1, 0, true);
for (CJPABase jpa : orgs) {
Shworg org = (Shworg) jpa;
org.superid.setValue(dorg_s.getString("orgid"));
org.idpath.setValue(dorg_s.getString("idpath") + org.orgid.getValue() + ",");
org.save(con);
setOrgParentAsOrg(con, org, dorg_s);
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////////////////////
// ///将源机构整个挪到目标机构下(改变原机构上级机构ID)
public static void setOrg2Org(String sorgid, String dorgid) throws Exception {
Shworg sorg = new Shworg();
Shworg dorg = new Shworg();
CDBConnection con = sorg.pool.getCon(CTreeUtil.class);
con.startTrans();
try {
sorg.findByID(con, sorgid);
if (sorg.isEmpty()) {
throw new Exception("ID为【" + sorgid + "】的机构不存在");
}
dorg.findByID(con, dorgid);
if (dorg.isEmpty()) {
throw new Exception("ID为【" + dorgid + "】的机构不存在");
}
JSONObject dorg_s = dorg.toJsonObj();
// dorg_s.put("extorgname", COShwUser.getOrgNamepath(dorg.idpath.getValue()));
setOrgParentAsOrg(con, sorg, dorg_s);
Shworg_acthis soh = new Shworg_acthis();
soh.orgid.setValue(sorg.orgid.getValue());
soh.acttype.setAsInt(4);
soh.acttime.setAsDatetime(new Date());
soh.actcommit.setValue("调整上级机构为" + dorg.orgid.getValue() + "," + dorg.code.getValue() + "," + dorg.orgname.getValue());
soh.save(con);
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
}finally{
con.close();
}
}
private static void setOrgParentAsOrg(CDBConnection con, Shworg sorg, JSONObject dorg_s) throws Exception {
String sidp = sorg.idpath.getValue();
String didp = dorg_s.getString("idpath");
if (didp.length() > sidp.length())// 只有目标长度大于源长度才有可能
if (didp.substring(0, sidp.length()).equals(sidp)) {
throw new Exception("目标机构【" + dorg_s.getString("orgname") + "】不能是源机构【" + sorg.orgname.getValue() + "】及其下属机构");
}
String sqlstr = "select * from shworg where idpath like '" + sorg.idpath.getValue() + "%'";
JSONArray ms = con.opensql2jsontree_o(sqlstr, "orgid", "superid", false);
if (ms.size() != 1)
throw new Exception("IDPATH为【" + sorg.idpath.getValue() + "】的机构重复或不存在");
JSONObject jorg = ms.getJSONObject(0);
jorg.put("idpath", dorg_s.getString("idpath") + jorg.getString("orgid") + ",");
jorg.put("superid", dorg_s.getString("orgid"));
updateOrgInfo(con, jorg, dorg_s);
sqlstr = "update shworg set superid=" + dorg_s.getString("orgid") + ", idpath='" + jorg.getString("idpath") + "' where orgid="
+ jorg.getString("orgid");
con.execsql(sqlstr);
CTreeUtil.reSetIDPathLev(con, new OnChangeIDPathLevListener() {
@Override
public void OnChange(CDBConnection con, JSONObject jorg, JSONObject jporg) throws Exception {
// TODO Auto-generated method stub
updateOrgInfo(con, jorg, jporg);
}
}, jorg, sorg, "orgid", "idpath", null);
}
public static OnChangeOrgInfoListener getOrgChgListener() throws Exception {
if (ConstsSw._onchgorginfolestener == null) {
Object o = ConstsSw.getAppParm("OrgInfoChangeListener");
if (o == null)
return null;
else {
String className = o.toString().trim();
Class<?> CJPAcd = Class.forName(className);
if (!OnChangeOrgInfoListener.class.isAssignableFrom(CJPAcd)) {
throw new Exception(className + "必须从 com.corsair.server.ctrl.OnChangeOrgInfoListener继承");
}
Class<?> paramTypes[] = {};
Constructor<?> cst = CJPAcd.getConstructor(paramTypes);
ConstsSw._onchgorginfolestener = (OnChangeOrgInfoListener) cst.newInstance();
}
}
return ConstsSw._onchgorginfolestener;
}
public static void updateOrgInfo(CDBConnection con, JSONObject jorg, JSONObject jporg) throws Exception {
String orgid = jorg.getString("orgid");
String idpath = jorg.getString("idpath");
jorg.put("extorgname", jporg.getString("extorgname") + "-" + jorg.getString("orgname"));
String sqlstr = "UPDATE shwfdracl SET idpath='" + idpath + "', ownername='" + jorg.getString("orgname")
+ "' WHERE ownerid=" + orgid
+ " AND acltype IN(1,2)";
con.execsql(sqlstr);
sqlstr = "UPDATE shworg_find SET fidpath='" + idpath + "' WHERE forgid=" + orgid;
con.equals(sqlstr);
OnChangeOrgInfoListener oic = getOrgChgListener();
if (oic != null)
oic.OnOrgChg(con, jorg, jporg);
}
}
<file_sep>/src/com/corsair/server/ctrl/OnChangeIDPathLevListener.java
package com.corsair.server.ctrl;
import net.sf.json.JSONObject;
import com.corsair.dbpool.CDBConnection;
/**
* 没卵用
*
* @author Administrator
*
*/
public abstract class OnChangeIDPathLevListener {
public abstract void OnChange(CDBConnection con, JSONObject jorg, JSONObject jporg) throws Exception;
}
<file_sep>/src/com/corsair/server/base/CallFounctions.java
package com.corsair.server.base;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 调用类方法
*
* @author Administrator
*
*/
public class CallFounctions {
/**
* 调用类方法
*
* @param ClassName
* @param FunctionName
* @param ParmsXML
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@SuppressWarnings({ "unchecked", "null", "rawtypes" })
public String CallFunction(String ClassName, String FunctionName,
String ParmsXML) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
java.lang.Class clazz = null;
Method cMethod = clazz.getMethod(FunctionName,
new java.lang.Class[] { ParmsXML.getClass() });
cMethod.invoke(null, new Object[] { ParmsXML });
return "";
}
}
<file_sep>/src/com/corsair/server/test/TestThreadRunable.java
package com.corsair.server.test;
public class TestThreadRunable implements Runnable {
private int thid;
private ThreadCallSourse tcs;
public TestThreadRunable(int thid) {
this.thid = thid;
}
public TestThreadRunable(ThreadCallSourse tcs, int thid) {
this.thid = thid;
this.tcs = tcs;
}
@Override
public void run() {
// TODO Auto-generated method stub
// (new ThreadCallSourse()).procedure(thid);
tcs.procedure(thid);
}
}
<file_sep>/src/com/corsair/server/eai/PropertiesHelper.java
package com.corsair.server.eai;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.corsair.dbpool.util.Logsw;
public class PropertiesHelper {
private File file = null;
public PropertiesHelper(String fname) {
if (fname != null && fname.length() > 0) {
try {
file = new File(fname);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
Logsw.error(e.getMessage());
}
}
} catch (Exception e) {
Logsw.error(e.getMessage());
}
}
}
public String getProperties(String key) {
InputStream fis = null;
try {
Properties prop = new Properties();
fis = new FileInputStream(getAbsolutePath());
prop.load(fis);
return prop.getProperty(key);
} catch (Exception e) {
Logsw.error(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
Logsw.error(e.getMessage());
}
}
return "";
}
public void setProperties(String key, String value) {
Properties prop = new Properties();
FileOutputStream outputFile = null;
InputStream fis = null;
try {
// 输入流和输出流要分开处理, 放一起会造成写入时覆盖以前的属性
fis = new FileInputStream(getAbsolutePath());
// 先载入已经有的属性文件
prop.load(fis);
// 追加新的属性
prop.setProperty(key, value);
// 写入属性
outputFile = new FileOutputStream(getAbsolutePath());
prop.store(outputFile, "");
outputFile.flush();
} catch (Exception e) {
Logsw.error(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
Logsw.error(e.getMessage());
}
try {
if (outputFile != null) {
outputFile.close();
}
} catch (Exception e) {
Logsw.error(e.getMessage());
}
}
}
public String getAbsolutePath() {
try {
return file.getAbsolutePath();
} catch (Exception e) {
Logsw.error(e.getMessage());
}
return "";
}
}
<file_sep>/src/com/hr/.svn/pristine/f3/f3193dd78c423ee6b6589f72c7a923552a7180d4.svn-base
package com.hr.util;
import java.util.Date;
import java.util.HashMap;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.hr.base.entity.Hr_orgposition;
import com.hr.canteen.co.COHr_canteen_costrecords;
import com.hr.canteen.entity.Hr_canteen_costrecordscount;
import com.hr.perm.entity.Hr_employee;
import com.hr.salary.entity.Hr_salary_chglg;
import com.hr.salary.entity.Hr_salary_list;
public class TimerTaskAUTOSetSalaryList extends TimerTask{
@Override
public void run() {
Logsw.debug("自动从薪资异动生成上个月薪资明细");
try{
Date nowdate=Systemdate.getDateByyyyy_mm_dd(Systemdate.getStrDate());
Date eddate=Systemdate.getFirstAndLastOfMonth(nowdate).date1;
Date bgdate = Systemdate.dateMonthAdd(eddate, -1);// 减一月
Date bfdate = Systemdate.dateMonthAdd(bgdate, -1);// 减一月
String ymbg=Systemdate.getStrDateByFmt(bgdate, "yyyy-MM");
String ymed=Systemdate.getStrDateByFmt(eddate, "yyyy-MM");
String ymbf=Systemdate.getStrDateByFmt(bfdate, "yyyy-MM");
String sqlstr="SELECT cl.* FROM hr_salary_chglg cl,hr_employee e WHERE cl.useable=1 AND cl.newposition_salary>0 "+
"AND cl.er_id=e.er_id AND e.pay_way='月薪' AND e.empstatid<10 "+
" AND cl.er_id NOT IN (SELECT * FROM (SELECT er_id FROM hr_salary_list WHERE wagetype=1 AND yearmonth>='"+
ymbg+"' AND yearmonth<'"+ymed+"' )tt) ";
CJPALineData<Hr_salary_list> sllists = new CJPALineData<Hr_salary_list>(Hr_salary_list.class);
CJPALineData<Hr_salary_chglg> chglgs = new CJPALineData<Hr_salary_chglg>(Hr_salary_chglg.class);
chglgs.findDataBySQL(sqlstr, true, false);
int rst=0;
for (CJPABase jpa : chglgs) {
int m=rst%2000;
if(m==0){
if (sllists.size() > 0) {
System.out.println("====================自动生成工资明细条数【" + sllists.size() + "】");
sllists.save();// 高速存储
}
sllists.clear();
}
Hr_salary_chglg cl=(Hr_salary_chglg)jpa;
Hr_employee emp = new Hr_employee();
emp.findByID(cl.er_id.getValue());
if (emp.isEmpty())
throw new Exception("id为【" + cl.er_id.getValue() + "】不存在人事资料");
Hr_orgposition sp=new Hr_orgposition();
sp.findByID(emp.ospid.getValue());
if(sp.isEmpty())
throw new Exception("员工id为【" + cl.er_id.getValue() + "】的ID为【"+emp.ospid.getValue()+"】的职位不存在");
Hr_salary_list sall = new Hr_salary_list();
sall.remark.setValue("月初异动自动生成薪资明细"); // 备注
sall.yearmonth.setValue(ymbg); // 年月
sall.er_id.setValue(emp.er_id.getValue()); // 人事档案id
sall.employee_code.setValue(emp.employee_code.getValue()); // 申请人工号
sall.employee_name.setValue(emp.employee_name.getValue()); // 姓名
sall.orgid.setValue(emp.orgid.getValue()); // 部门
sall.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
sall.orgname.setValue(emp.orgname.getValue()); // 部门名称
sall.idpath.setValue(emp.idpath.getValue()); // idpath
sall.ospid.setValue(emp.ospid.getValue()); // 职位id
sall.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(emp.lv_id.getValue()); // 职级id
sall.lv_num.setValue(emp.lv_num.getValue()); // 职级
sall.hg_id.setValue(emp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(emp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(sp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(sp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(sp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(sp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(sp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(sp.hwc_namezz.getValue()); // 职种
sall.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
sall.stru_id.setValue(cl.newstru_id.getValue()); // 工资结构id
sall.stru_name.setValue(cl.newstru_name.getValue()); // 工资结构
sall.poswage.setValue(cl.newposition_salary.getValue()); // 职位工资
sall.basewage.setValue(cl.newbase_salary.getValue()); // 基本工资
sall.baseotwage.setValue(cl.newotwage.getValue()); // 固定加班工资
sall.skillwage.setValue(cl.newtech_salary.getValue()); // 技能工资
sall.perforwage.setValue(cl.newachi_salary.getValue()); // 绩效工资
sall.skillsubs.setValue(cl.newtech_allowance.getValue()); // 技能津贴
sall.parttimesubs.setValue(cl.newparttimesubs.getValue()); // 兼职津贴
sall.postsubs.setValue(cl.newpostsubs.getValue()); // 岗位津贴
sall.wagetype.setAsInt(1);//薪资类型
sall.usable.setAsInt(1);//有效
sllists.add(sall);
rst++;
}
if (sllists.size() > 0) {
System.out.println("====================生成薪资明细记录条数【" + sllists.size() + "】");
sllists.saveBatchSimple();// 高速存储sllists
}
sllists.clear();
String sqlstr1="SELECT * FROM (SELECT * FROM hr_salary_list WHERE wagetype=1 AND yearmonth>='"+ymbf+"' AND yearmonth<'"+ymbg+
"' ) sl WHERE er_id NOT IN (SELECT DISTINCT er_id FROM hr_salary_list WHERE wagetype=1 AND yearmonth>='"+ymbg+
"' AND yearmonth<'"+ymed+"') ";
sllists.findDataBySQL(sqlstr1, true, false);
for(CJPABase jpa : sllists){
Hr_salary_list sl =(Hr_salary_list)jpa;
sl.clearAllId();
sl.yearmonth.setValue(ymbg);
sl.createtime.setValue(Systemdate.getStrDate());
sl.updatetime.setValue(Systemdate.getStrDate());
sl.save();
}
System.out.println("自动生成【" + ymbg + "】月份的薪资明细【" + Systemdate.getStrDate() + "】");
}catch(Exception e){
e.printStackTrace();
}
}
}
<file_sep>/src/com/hr/inface/entity/TXKq_Card.java
package com.hr.inface.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(dbpool = "oldtxmssql", tablename = "Kq_Card")
public class TXKq_Card extends CJPA {
@CFieldinfo(fieldname = "ID", notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField ID; // ID
@CFieldinfo(fieldname = "CardNo", notnull = true, caption = "CardNo", datetype = Types.CHAR)
public CField CardNo; // CardNo
@CFieldinfo(fieldname = "EmpID", notnull = true, caption = "EmpID", datetype = Types.INTEGER)
public CField EmpID; // EmpID
@CFieldinfo(fieldname = "Date0", notnull = true, caption = "Date0", datetype = Types.TIMESTAMP)
public CField Date0; // Date0
@CFieldinfo(fieldname = "Date1", notnull = true, caption = "Date1", datetype = Types.TIMESTAMP)
public CField Date1; // Date1
@CFieldinfo(fieldname = "FType", notnull = true, caption = "FType", datetype = Types.TINYINT)
public CField FType; // FType
@CFieldinfo(fieldname = "OldCardNo", caption = "OldCardNo", datetype = Types.CHAR)
public CField OldCardNo; // OldCardNo
@CFieldinfo(fieldname = "CardNoS", caption = "CardNoS", datetype = Types.CHAR)
public CField CardNoS; // CardNoS
@CFieldinfo(fieldname = "Note", caption = "Note", datetype = Types.VARCHAR)
public CField Note; // Note
@CFieldinfo(fieldname = "PassWord", caption = "PassWord", datetype = Types.VARCHAR)
public CField PassWord; // PassWord
@CFieldinfo(fieldname = "CardCost", caption = "CardCost", datetype = Types.NUMERIC)
public CField CardCost; // CardCost
@CFieldinfo(fieldname = "Ifzc", caption = "Ifzc", datetype = Types.BIT)
public CField Ifzc; // Ifzc
@CFieldinfo(fieldname = "MachList", caption = "MachList", datetype = Types.VARCHAR)
public CField MachList; // MachList
@CFieldinfo(fieldname = "ConIfZc", caption = "ConIfZc", datetype = Types.BIT)
public CField ConIfZc; // ConIfZc
@CFieldinfo(fieldname = "ConGroup", caption = "ConGroup", datetype = Types.TINYINT)
public CField ConGroup; // ConGroup
@CFieldinfo(fieldname = "FpCode", caption = "FpCode", datetype = Types.VARCHAR)
public CField FpCode; // FpCode
@CFieldinfo(fieldname = "PresentMoney", caption = "PresentMoney", datetype = Types.NUMERIC)
public CField PresentMoney; // PresentMoney
@CFieldinfo(fieldname = "IncMoney", caption = "IncMoney", datetype = Types.DECIMAL)
public CField IncMoney; // IncMoney
@CFieldinfo(fieldname = "IsInc", caption = "IsInc", datetype = Types.BIT)
public CField IsInc; // IsInc
@CFieldinfo(fieldname = "Czy", caption = "Czy", datetype = Types.VARCHAR)
public CField Czy; // Czy
@CFieldinfo(fieldname = "OperateDate", caption = "OperateDate", datetype = Types.TIMESTAMP)
public CField OperateDate; // OperateDate
@CFieldinfo(fieldname = "SetRightFlag", caption = "SetRightFlag", datetype = Types.NCHAR)
public CField SetRightFlag; // SetRightFlag
@CFieldinfo(fieldname = "logo1", caption = "logo1", datetype = Types.NCHAR)
public CField logo1; // logo1
@CFieldinfo(fieldname = "AttGroup", caption = "AttGroup", datetype = Types.INTEGER)
public CField AttGroup; // AttGroup
@CFieldinfo(fieldname = "PhysicsCardNo", caption = "PhysicsCardNo", datetype = Types.VARCHAR)
public CField PhysicsCardNo; // PhysicsCardNo
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public TXKq_Card() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/weixin/WXDeviceUtil.java
package com.corsair.server.weixin;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.weixin.entity.Wx_device;
public class WXDeviceUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
private static final String TransMsgUrl = "https://api.weixin.qq.com/device/transmsg?access_token=ACCESS_TOKEN";
// 设备授权
private static final String AuthorizeUrl = "https://api.weixin.qq.com/device/authorize_device?access_token=ACCESS_TOKEN";
// 设备授权新
// https://api.weixin.qq.com/device/getqrcode?access_token=ACCESS_TOKEN&product_id=PRODUCT_ID
private static final String GetQrcode = "https://api.weixin.qq.com/device/getqrcode?access_token=ACCESS_TOKEN&product_id=PRODUCT_ID";
private static final String CreateQrcode = "https://api.weixin.qq.com/device/create_qrcode?access_token=ACCESS_TOKEN";
private static final String GetStatUrl = "https://api.weixin.qq.com/device/get_stat?access_token=ACCESS_TOKEN&device_id=DEVICE_ID";
private static final String VerifyQrcodeUrl = "https://api.weixin.qq.com/device/verify_qrcode?access_token=ACCESS_TOKEN";
private static final String GetOpenidUrl = "https://api.weixin.qq.com/device/get_openid?access_token=ACCESS_TOKEN&device_type=DEVICE_TYPE&device_id=DEVICE_ID";
private static final String Create_Qrcode = "https://api.weixin.qq.com/device/create_qrcode?access_token=ACCESS_TOKEN";
// 第三方公众账号通过设备id从公众平台批量获取设备二维码。
// {
// "device_num":"2",
// "device_id_list":["01234","56789"]
// }
public static boolean create_qrcode(String appid, List<String> dids) throws Exception {
String json = "{\"device_num\":" + dids.size() + ","
+ "\"device_num\":";
String ids = "";
for (String did : dids) {
ids = "\"" + did + "\",";
}
if (ids.length() > 0)
ids = ids.substring(0, ids.length() - 1);
ids = "[" + ids + "]";
json = json + ids + "}";
System.out.println(json);
String url = Create_Qrcode.replace("ACCESS_TOKEN", WXUtil.getTonken(appid));
return false;
}
/**
* 向设备推送消息
*
* @throws Exception
*/
public static boolean sendDeviceMsg(String appid, String device_type, String device_id, String openid, String content) throws Exception {
HashMap<String, String> bdinfo = new HashMap<String, String>();
bdinfo.put("device_type", device_type);
bdinfo.put("device_id", device_id);
bdinfo.put("openid", openid);
bdinfo.put("content", content);
String json = CJSON.HashMap2Json(bdinfo, false);
String url = TransMsgUrl.replace("ACCESS_TOKEN", WXUtil.getTonken(appid));
String rst = WXHttps.postHttps(url, null, json);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
if ("0".equalsIgnoreCase(rootNode.path("ret").asText())) {
return true;
} else
throw new Exception("发送设备信息错误:" + rootNode.path("errmsg").asText());
// {"ret":0,"ret_info":"this is ok"}
// {"errcode":-1,"errmsg":""}
// System.out.println("transMsg rst=" + rst);
// return rst;
}
/**
* 根据设备id获取二维码生成串
*
* @throws Exception
*/
public static String createQrcode(String appid, List<String> deviceIds) throws Exception {
HashMap<String, String> map = new HashMap<String, String>();
map.put("device_num", String.valueOf(deviceIds.size()));
map.put("device_id_list", deviceIds.toString());
String url = CreateQrcode.replace("ACCESS_TOKEN", WXUtil.getTonken(appid));
String json = CJSON.HashMap2Json(map, false);
String rst = WXHttps.postHttps(url, null, json);
System.out.println("createQrcode rst=" + rst);
return rst;
}
/**
* 批量授权/更新设备属性
* <p>
* 授权后设备才能进行绑定操作
*
* @param devices
* 设备属性列表
* @param isCreate
* 是否首次授权: true 首次授权; false 更新设备属性
* @throws Exception
*/
public static String authorize(String appid, List<DeviceAuth> devices, boolean isCreate) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartObject();
jg.writeNumberField("device_num", devices.size());
jg.writeNumberField("op_type", isCreate ? 0 : 1);
jg.writeArrayFieldStart("device_list");
for (DeviceAuth dev : devices) {
jg.writeRawValue(objectMapper.writeValueAsString(dev));
}
jg.writeEndArray();
jg.writeEndObject();
jg.close();
String json = baos.toString("utf-8");
String url = AuthorizeUrl.replace("ACCESS_TOKEN", WXUtil.getTonken(appid));
String rst = WXHttps.postHttps(url, null, json);
System.out.println("AuthorizeUrl rst=" + rst);
return rst;
}
/**
* 设备状态查询
* <p>
* status 0:未授权 1:已经授权(尚未被用户绑定) 2:已经被用户绑定<br/>
* {"errcode":0,"errmsg":"ok","status":1,"status_info":"authorized"}
*
* @throws Exception
*/
public static String getStat(String appid, String deviceId) throws Exception {
String url = GetStatUrl.replace("DEVICE_ID", deviceId);
String rst = WXHttps.getHttps(url, null);
System.out.println("getStat rst=" + rst);
return rst;
}
/**
* 验证二维码 获取二维码对应设备属性
*
* @param ticket
* 二维码生成串
* @throws Exception
*/
public static String verifyQrcode(String appid, String ticket) throws Exception {
HashMap<String, String> map = new HashMap<String, String>();
map.put("ticket", ticket);
String json = CJSON.HashMap2Json(map, false);
String rst = WXHttps.postHttps(VerifyQrcodeUrl, null, json);
System.out.println("AuthorizeUrl rst=" + rst);
return rst;
}
/**
* 根据设备类型和设备id查询绑定的openid
*
* @throws Exception
*/
public static String getOpenId(String appid, String deviceType, String deviceId) throws Exception {
String url = GetOpenidUrl.replace("DEVICE_TYPE", deviceType).replace(
"DEVICE_ID", deviceId).replace("ACCESS_TOKEN", WXUtil.getTonken(appid));
String rst = WXHttps.getHttps(url, null);
System.out.println("getOpenId rst=" + rst);
return rst;
}
/**
* 设备授权
*
* @param authKey
* 加密key
* @param deviceId
* 设备id
* @param mac
* 设备的mac地址
* @param 是否首次授权
* : true 首次授权; false 更新设备属性
*/
public static void device_Auth(String appid, String authKey, String deviceId, String mac,
boolean isCreate) throws Exception {
DeviceAuth device = new DeviceAuth();
device.setId(deviceId); // 设备id
device.setMac(mac); //
device.setConnect_protocol("1|2");
device.setAuth_key(authKey); // 加密key <KEY>
device.setCrypt_method("0"); // auth加密方法 0:不加密 1:AES加密
device.setAuth_ver("0"); // 0:不加密的version 1:version 1
device.setConn_strategy("1"); // 连接策略
device.setClose_strategy("2");
device.setManu_mac_pos("-1");
device.setSer_mac_pos("-2");
// 调用授权
List<DeviceAuth> auths = new ArrayList<DeviceAuth>();
auths.add(device);
String rst = authorize(appid, auths, isCreate);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst).findPath("resp");
for (int i = 0; i < rootNode.size(); i++) {
JsonNode node = rootNode.get(i);
System.out.println("node:" + node.toString());
int errcode = node.findPath("errcode").asInt();
if ((errcode == 100002) || (errcode == 0)) {
String deviceid = node.findPath("base_info").findPath("device_id").asText();
String device_type = node.findPath("base_info").findPath("device_type").asText();
Wx_device dvc = new Wx_device();
dvc.findBySQL("select * from wx_device where entid=1 and device_id='" + deviceid + "'");
if (dvc.isEmpty()) {
dvc.creator.setValue("SYSTEM");
dvc.create_time.setAsDatetime(new Date());
dvc.entid.setAsInt(1);
}
dvc.appid.setValue(appid);
dvc.device_id.setValue(deviceid);
dvc.qrticket.setValue(device_type);
dvc.device_type.setAsInt(1);
dvc.save();
} else
Logsw.error("设备【" + deviceId + "】授权错误:" + node.findPath("errmsg").asText());
}
// {"resp":[{"base_info":{"device_type":"gh_1bafe245c2cb","device_id":
// "gh_1bafe245c2cb_9e081608d6d62b984edf52d5d3a50aba"},"errcode":0,"errmsg":"ok"}]}
}
// new ______________________________________________________
// 新 接口 获取设备
public static boolean getNewDeviceID(String appid, int ct, String productid) throws Exception {
// String staticQStr = "http://we.qq.com/d/";
if ((ct <= 0) || (ct > 100)) {
ct = 1;
}
String token = WXUtil.getTonken(appid);
String url = "https://api.weixin.qq.com/device/getqrcode?access_token=" + token + "&product_id=" + productid;
for (int i = 0; i < ct; i++) {
newdevice4wx(appid, url);
}
return true;
}
private static void newdevice4wx(String appid, String url) throws Exception {
String rst = WXHttps.getHttps(url, null);
// {resp_msg:{"ret_code":0," error_info":"ok"},"deviceid":"XXX","qrticket":"XXX"}
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
JsonNode rmsg = rootNode.findPath("ret_code");
// if ("ok".equalsIgnoreCase(rmsg.findPath("error_info").asText())) {
String deviceid = rootNode.findPath("deviceid").asText();
String qrticket = rootNode.findPath("qrticket").asText();
Wx_device dvc = new Wx_device();
dvc.appid.setValue(appid);
dvc.device_id.setValue(deviceid);
dvc.qrticket.setValue(qrticket);
dvc.creator.setValue("SYSTEM");
dvc.device_type.setAsInt(1);
dvc.create_time.setAsDatetime(new Date());
dvc.entid.setAsInt(1);
dvc.save();
// }
}
// 绑定设备 js调用
public static boolean bind(String appid, String ticket, String device_id, String openid) throws Exception {
String token = WXUtil.getTonken(appid);
String url = "https://api.weixin.qq.com/device/bind?access_token=" + token;
return bingorunbind(url, ticket, device_id, openid);
}
// 解绑设备 js调用
public static boolean unbind(String appid, String ticket, String device_id, String openid) throws Exception {
String token = WXUtil.getTonken(appid);
String url = "https://api.weixin.qq.com/device/unbind?access_token=" + token;
return bingorunbind(url, ticket, device_id, openid);
}
// 强制绑定
public static boolean compel_bind(String appid, String device_id, String openid) throws Exception {
String token = WXUtil.getTonken(appid);
String url = "https://api.weixin.qq.com/device/compel_bind?access_token=" + token;
return bingorunbind(url, null, device_id, openid);
}
// 强制解绑
public static boolean compel_unbind(String appid, String device_id, String openid) throws Exception {
String token = WXUtil.getTonken(appid);
String url = "https://api.weixin.qq.com/device/compel_unbind?access_token=" + token;
return bingorunbind(url, null, device_id, openid);
}
private static boolean bingorunbind(String url, String ticket, String device_id, String openid) throws Exception {
HashMap<String, String> bdinfo = new HashMap<String, String>();
if (ticket != null)
bdinfo.put("ticket", ticket);
bdinfo.put("device_id", device_id);
bdinfo.put("openid", openid);
String json = CJSON.HashMap2Json(bdinfo, false);
String rst = WXHttps.postHttps(url, null, json);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
return ("ok".equalsIgnoreCase(rootNode.findPath("base_resp").findPath("errmsg").asText())) ? true : false;
}
}
<file_sep>/src/com/corsair/server/sms/Sms_send.java
package com.corsair.server.sms;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Sms_send extends CJPA {
@CFieldinfo(fieldname = "sid", iskey = true, notnull = true, datetype = Types.FLOAT)
public CField sid; // 短信ID
@CFieldinfo(fieldname = "smstype", datetype = Types.INTEGER)
public CField smstype; // 短信类型
@CFieldinfo(fieldname = "mobile", datetype = Types.VARCHAR)
public CField mobile; // 手机号
@CFieldinfo(fieldname = "content", datetype = Types.VARCHAR)
public CField content; // 短信内容
@CFieldinfo(fieldname = "sendflag", datetype = Types.INTEGER)
public CField sendflag; // 状态 1: 已发送 2:未发送 3: 取消
@CFieldinfo(fieldname = "sendtime", datetype = Types.TIMESTAMP)
public CField sendtime; // 发送时间
@CFieldinfo(fieldname = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "creator", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "entid", notnull = true, datetype = Types.FLOAT)
public CField entid; // 组织ID
@CFieldinfo(fieldname = "entname", datetype = Types.VARCHAR)
public CField entname; // 组织名称
@CFieldinfo(fieldname = "idpath", datetype = Types.VARCHAR)
public CField idpath; // 路径
@CFieldinfo(fieldname = "property1", datetype = Types.VARCHAR)
public CField property1; //
@CFieldinfo(fieldname = "property2", datetype = Types.VARCHAR)
public CField property2; //
@CFieldinfo(fieldname = "property3", datetype = Types.VARCHAR)
public CField property3; //
@CFieldinfo(fieldname = "property4", datetype = Types.VARCHAR)
public CField property4; //
@CFieldinfo(fieldname = "property5", datetype = Types.VARCHAR)
public CField property5; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Sms_send() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/hr/attd/entity/Hrkq_special_holday.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import com.hr.attd.ctr.CtrHrkq_special_holday;
import java.sql.Types;
@CEntity(controller = CtrHrkq_special_holday.class)
public class Hrkq_special_holday extends CJPA {
@CFieldinfo(fieldname = "sphid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField sphid; // ID
@CFieldinfo(fieldname = "sphcode", codeid = 89, notnull = true, caption = "编码", datetype = Types.VARCHAR)
public CField sphcode; // 编码
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "机构编码", datetype = Types.VARCHAR)
public CField orgcode; // 机构编码
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "机构名称", datetype = Types.VARCHAR)
public CField orgname; // 机构名称
@CFieldinfo(fieldname = "sphty", dicid = 1042, caption = "类型 1 加班 2 值班", datetype = Types.INTEGER)
public CField sphty; // 类型 1 加班 2 值班
@CFieldinfo(fieldname = "sphdate", caption = "加班/值班日期", datetype = Types.TIMESTAMP)
public CField sphdate; // 加班/值班日期
@CFieldinfo(fieldname = "sphdays", caption = "加班/值班天数", datetype = Types.DECIMAL)
public CField sphdays; // 加班/值班天数
@CFieldinfo(fieldname = "valdate", notnull = true, caption = "调休到期日", datetype = Types.TIMESTAMP)
public CField valdate; // 调休到期日
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", notnull = true, caption = "表单状态", datetype = Types.INTEGER)
public CField stat; // 表单状态
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;
@CLinkFieldInfo(jpaclass = Hrkq_special_holdayline.class, linkFields = { @LinkFieldItem(lfield = "sphid", mfield = "sphid") })
public CJPALineData<Hrkq_special_holdayline> hrkq_special_holdaylines;
public Hrkq_special_holday() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/util/PackageUtil.java
package com.corsair.server.util;
/**
*
* 关于内部匿名类的BUG 待处理.....
*
* */
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.exception.CException;
import com.corsair.server.listener.SWServletContextListener;
import com.corsair.server.listener.SWSpecClass;
import com.corsair.server.listener.SWSpecClass.SwSpecClassType;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.retention.COAcitonItem;
import com.corsair.server.retention.RContextInit;
import com.corsair.server.websocket.AWebsocket;
import com.corsair.server.websocket.CWebSocket;
import com.corsair.server.websocket.CWebsocketClas;
public class PackageUtil {
@SuppressWarnings("finally")
public static void initAllCOClassName() {
List<PackageClass> alltemclasses = new ArrayList<PackageClass>();
String strpks = ConstsSw.getAppParm("ScanCoPackages").toString();
String[] pks = strpks.split(";");
for (String pk : pks) {
List<PackageClass> clses = getClassName(pk, true);
alltemclasses.addAll(clses);
}
ConstsSw._allCoClassName.clear();
List<PackageClass> allclasses = new ArrayList<PackageClass>();
for (int i = 0; i < alltemclasses.size(); i++) {// 重新赋值,去掉重复的
PackageClass pc = alltemclasses.get(i);
appendPackageClass(allclasses, pc);
// System.out.println(pc.getFname() + ":" + pc.getClaname());
}
for (int i = 0; i < allclasses.size(); i++) {
PackageClass pc = allclasses.get(i);
String cl = pc.getClaname();
//System.out.println("33333333333333333:" + cl);
Class<?> c = null;
try {
c = Class.forName(cl);
//System.out.println("0000:" + cl + ":" + c.isAnnotationPresent(ACO.class));
if ((c != null) && (c.isAnnotationPresent(ACO.class))) {
//System.out.println("1111:" + cl);
ACO ce = c.getAnnotation(ACO.class);
Method ms[] = c.getMethods();
for (Method m : ms) {
if (m.isAnnotationPresent(ACOAction.class)) {
ACOAction coe = m.getAnnotation(ACOAction.class);
checkMparm(pc, cl, m, ce, coe);
COAcitonItem ccm = new COAcitonItem(ce.coname() + "." + coe.eventname(), cl, m.getName(), coe);
ccm.setFname(pc.getFname());
ConstsSw._allCoClassName.put(ce.coname() + "." + coe.eventname(), ccm);
// if (ConstsSw.getAppParmBoolean("Debug_Mode")) {
// System.out.println(ce.coname() + "." + coe.eventname()
// + ":" + cl + "." + m.getName());
// }
}
}
}
if ((c != null) && (c.isAnnotationPresent(RContextInit.class))) {
if (SWServletContextListener.class.isAssignableFrom(c)) {
SWSpecClass sc = new SWSpecClass(SwSpecClassType.servetContextInit, c.newInstance());
ConstsSw._allSpecClass.add(sc);
} else {
Logsw.debug("警告:类【" + cl + "】标注为【RContextInit】,但是没有实现【SWServletContextListener】接口");
}
}
if ((c != null) && (c.isAnnotationPresent(AWebsocket.class))) {
AWebsocket aws = c.getAnnotation(AWebsocket.class);
if (aws.vport().isEmpty())
Logsw.debug("警告:类【" + cl + "】标注为【AWebsocket】,vport 不应为空字符串");
checkWebsocketList(cl, aws.vport());
CWebsocketClas cwkc = new CWebsocketClas((Class<CWebSocket>) c, aws.vport());
ConstsSw._allSocketClassName.put(aws.vport(), cwkc);
}
} catch (CException e) {
//System.out.println("222222222222222222");
e.printStackTrace();
} catch (ClassNotFoundException e) {
//System.out.println("1111111111111111111");
System.out.println(e.getLocalizedMessage());
} finally {
continue;
}
}
}
private static void checkMparm(PackageClass pc, String clsname, Method method, ACO ce, ACOAction coe) throws CException {
Class<?>[] pts = method.getParameterTypes();
if (pts.length != 0) {
throw new CException(method.getName() + "注解为COAction 的 function 不能有参数");
}
String key = ce.coname() + "." + coe.eventname();
COAcitonItem ccm = (COAcitonItem) ConstsSw._allCoClassName.get(key);
if (ccm != null) {
String errmsg = "文件<" + pc.getFname() + "><" + clsname + "." + method.getName() + "> 与文件<"
+ ccm.getFname() + "><" + ccm.getClassname() + "." + ccm.getMethodname() + ">";
throw new CException("CO名称 <" + key + "> 重复! " + errmsg);
}
/*
* if (coe.postparms()) { if ((pts.length != 1) || (!pts[0].isAssignableFrom(HashMap.class))) { throw new CorsairException(method.getName() +
* "注解postparms=true时候,只允许一个参数HashMap<String,String>参数"); } } else { if (pts.length != 0) { throw new CorsairException(method.getName() +
* "注解postparms=false时候,不能有参数"); } }
*/
}
private static void checkWebsocketList(String clsname, String vport) throws CException {
if ((vport == null) || (vport.isEmpty()))
throw new CException("【" + clsname + "】虚拟端口vport不能为空 ");
CWebsocketClas cwsc = (CWebsocketClas) ConstsSw._allSocketClassName.get(vport);
if (cwsc != null) {
String errmsg = "【" + clsname + "】 与 <" + cwsc.getSocketclass().getName() + "】";
throw new CException("虚拟端口vport <" + vport + "> 重复! " + errmsg);
}
}
/**
* 获取某包下所有类
*
* @param packageName
* 包名
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<PackageClass> getClassName(String packageName, boolean childPackage) {
List<PackageClass> fileNames = new ArrayList<PackageClass>();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/").replace("%20", " ");
try {
Enumeration<URL> urls = loader.getResources(packagePath);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
List<PackageClass> cls = getCalssNamesByURL(url, childPackage);
if (cls != null)
fileNames.addAll(cls);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<PackageClass> jarcls = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage);
fileNames.addAll(jarcls);
return fileNames;
}
private static List<PackageClass> getCalssNamesByURL(URL url, boolean childPackage) {
List<PackageClass> fileNames = null;
if (url != null) {
String type = url.getProtocol();
if (type.equals("file")) {
fileNames = getClassNameByFile(url.getPath(), null, childPackage);
} else if (type.equals("jar")) {
fileNames = getClassNameByJar(url.getPath(), childPackage);
}
}
return fileNames;
}
private static void appendPackageClass(List<PackageClass> pcs, PackageClass pc) {
boolean isexists = false;
for (PackageClass tpc : pcs) {
if ((tpc.getFname().equalsIgnoreCase(pc.getFname())) && (tpc.getClaname().equalsIgnoreCase(pc.getClaname()))) {
isexists = true;
break;
}
}
// System.out.println("appendPackageClass:" + pc.getClaname() + "--isexists:" + isexists);
if (!isexists) {
pcs.add(pc);
}
}
/**
* 从项目文件获取某包下所有类
*
* @param filePath
* 文件路径
* @param className
* 类名集合
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<PackageClass> getClassNameByFile(String filePath, List<PackageClass> className, boolean childPackage) {
List<PackageClass> myClassName = new ArrayList<PackageClass>();
File file = new File(filePath.replace("%20", " "));//去掉空格
File[] childFiles = file.listFiles();
for (File childFile : childFiles) {
if (childFile.isDirectory()) {
if (childPackage) {
myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage));
}
} else {
String childFilePath = childFile.getPath();
if (childFilePath.endsWith(".class")) {
childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));
childFilePath = childFilePath.replace("\\", ".");
PackageClass pc = new PackageClass(filePath, childFilePath);
// System.out.println("childFilePath:" + childFilePath);
appendPackageClass(myClassName, pc);
}
}
}
return myClassName;
}
/**
* 从jar获取某包下所有类
*
* @param jarPath
* jar文件路径
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<PackageClass> getClassNameByJar(String jarPath, boolean childPackage) {
List<PackageClass> myClassName = new ArrayList<PackageClass>();
String[] jarInfo = jarPath.split("!");
String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/"));
String packagePath = jarInfo[1].substring(1);
try {
JarFile jarFile = new JarFile(jarFilePath);
Enumeration<JarEntry> entrys = jarFile.entries();
while (entrys.hasMoreElements()) {
JarEntry jarEntry = entrys.nextElement();
String entryName = jarEntry.getName();
if (entryName.endsWith(".class")) {
if (childPackage) {
if (entryName.startsWith(packagePath)) {
entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));
// System.out.println("entryName1:" + entryName);
PackageClass pc = new PackageClass(jarFilePath, entryName);
appendPackageClass(myClassName, pc);
}
} else {
int index = entryName.lastIndexOf("/");
String myPackagePath;
if (index != -1) {
myPackagePath = entryName.substring(0, index);
} else {
myPackagePath = entryName;
}
if (myPackagePath.equals(packagePath)) {
entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));
// System.out.println("entryName2:" + entryName);
PackageClass pc = new PackageClass(jarFilePath, entryName);
appendPackageClass(myClassName, pc);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return myClassName;
}
/**
* 从所有jar中搜索该包,并获取该包下所有类
*
* @param urls
* URL集合
* @param packagePath
* 包路径
* @param childPackage
* 是否遍历子包
* @return 类的完整名称
*/
private static List<PackageClass> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) {
List<PackageClass> myClassName = new ArrayList<PackageClass>();
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
String urlPath = url.getPath().replace("%20", " ");
// 不必搜索classes文件夹
if (urlPath.endsWith("classes/")) {
continue;
}
String jarPath = urlPath + "!/" + packagePath;
myClassName.addAll(getClassNameByJar(jarPath, childPackage));
}
}
return myClassName;
}
}
<file_sep>/src/com/corsair/server/util/CReport.java
package com.corsair.server.util;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shworg;
public class CReport {
private String sqlstr;
private String orderby = null;
private String[] notnull;
private CDBPool pool = null;
public CReport() {
}
public CReport(String sqlstr, String[] notnull) {
this.sqlstr = sqlstr;
this.notnull = notnull;
}
public CReport(String sqlstr, String orderby, String[] notnull) {
this.sqlstr = sqlstr;
this.orderby = orderby;
this.notnull = notnull;
}
public CReport(CDBPool pool, String sqlstr, String orderby, String[] notnull) {
this.pool = pool;
this.sqlstr = sqlstr;
this.orderby = orderby;
this.notnull = notnull;
}
/**
* @param ignParms
* 略过的条件
* @return
* @throws Exception
*/
public String findReport(String[] ignParms, String idpathw) throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String scols = urlparms.get("cols");
if (scols == null) {
JSONObject rst = findReport2JSON_O(ignParms, true, idpathw);// 查询的数据是分页的 ,所以这里需要返回不分页的SQL语句
return rst.toString();
} else {// 导出的数据不分页
export2excel(ignParms, scols, idpathw);
return null;
}
}
/**
* @return 直接查询,不分页,自动处理idpath
* @throws Exception
*/
public String findReport() throws Exception {
return findReport(null, CSContext.getIdpathwhereNoErr());
}
/**
* 直接查询,不分页,自动处理idpath
*
* @param ignParms
* 略过的字段 ,不略过 可用 {} 或 null
* @return
* @throws Exception
*/
public String findReport(String[] ignParms) throws Exception {
return findReport(ignParms, CSContext.getIdpathwhereNoErr());
}
public JSONObject findReport2JSON_O() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String scols = urlparms.get("cols");
boolean paging = (scols == null);
String[] ignParms = new String[] {};
return findReport2JSON_O(ignParms, paging);
}
public JSONObject findReport2JSON_O(String[] ignParms, boolean paging) throws Exception {
String idpw = CSContext.getIdpathwhereNoErr();
return findReport2JSON_O((pool == null) ? DBPools.defaultPool() : pool, ignParms, idpw, paging);
}
public JSONObject findReport2JSON_O(String[] ignParms, boolean paging, String idpw) throws Exception {
return findReport2JSON_O((pool == null) ? DBPools.defaultPool() : pool, ignParms, idpw, paging);
}
// public JSONObject findReport2JSON_O(String[] ignParms, String idpw, boolean paging) throws Exception {
// return findReport2JSON_O(DBPools.defaultPool(), null, idpw, paging);
// }
public JSONObject findReport2JSON_O(String[] ignParms) throws Exception {
String idpw = CSContext.getIdpathwhereNoErr();
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String scols = urlparms.get("cols");
// System.out.println("3333333333333333333:" + scols);
boolean paging = (scols == null);
// System.out.println("22222222222222222222:" + paging);
return findReport2JSON_O((pool == null) ? DBPools.defaultPool() : pool, ignParms, idpw, paging);
}
/**
* @param pool
* @return
* @throws Exception
*/
public JSONObject findReport2JSON_O(CDBPool pool) throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String scols = urlparms.get("cols");
boolean paging = (scols == null);
String idpw = CSContext.getIdpathwhereNoErr();
return findReport2JSON_O(pool, null, idpw, paging);
}
/**
* @param pool
* @param ignParms
* @param idpw
* 传入的idpath的条件将替换默认的idpath,传“” null 一样会屏蔽默认处理
* @param paging
* true 分页 false 不分页
* @return
* @throws Exception
*/
public JSONObject findReport2JSON_O(CDBPool pool, String[] ignParms, String idpw, boolean paging) throws Exception {
return findReport2JSON_O(pool, ignParms, idpw, paging, false);
}
/**
* @param pool
* @param ignParms
* @param idpw
* 传入的idpath的条件将替换默认的idpath,传“” null 一样会屏蔽默认处理
* @param paging
* true 分页 false 不分页
* @return
* @throws Exception
*/
public JSONObject findReport2JSON_O(CDBPool pool, String[] ignParms, String idpw, boolean paging, boolean withMetaData) throws Exception {
// System.out.println("11111111111111111111111111111111111111111111111111111");
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String parms = urlparms.get("parms");
String where = CjpaUtil.buildFindSqlByJsonParms(pool, sqlstr, parms, notnull, ignParms, idpw);
String spage = urlparms.get("page");
String srows = urlparms.get("rows");
int page = (spage == null) ? 1 : Integer.valueOf(spage);
int rows = (srows == null) ? 300 : Integer.valueOf(srows);
if ((!paging) || (spage == null)) {// 不分页
page = -1;
String smax = urlparms.get("max");
if ((smax != null) && (!smax.isEmpty())) {
int max = Integer.valueOf(smax);
if (max > 0) {
page = 1;
rows = max;
}
}
}
// String scols = urlparms.get("cols");
sqlstr = "select * from (" + sqlstr + ") tb where 1=1 " + where;
if (orderby != null) {
sqlstr = sqlstr + " order by " + orderby;
}
return pool.opensql2json_O(sqlstr, page, rows, withMetaData);
}
private static JSONArray getTrueCol(String scols) {
// System.out.println("scols:" + scols);
JSONArray cols = new JSONArray();
JSONArray tcols = JSONArray.fromObject(scols);
for (int i = 0; i < tcols.size(); i++) {
Object o = tcols.get(i);
if (o instanceof JSONArray) {
JSONArray os = (JSONArray) o;
for (int j = 0; j < os.size(); j++) {
Object to = os.get(j);
if (to instanceof JSONObject) {
JSONArray tmpo = (JSONArray) o;
// ((JSONObject) to).put("title", )
if (((JSONObject) to).has("field"))
cols.add(to);
}
}
}
if (o instanceof JSONObject) {
if (((JSONObject) o).has("field"))
cols.add(o);
}
}
return cols;
}
public void export2excel(JSONArray jdatas, String scols) throws Exception {
JSONArray cols = JSONArray.fromObject(scols);
// System.out.println("cols:" + cols.toString());
HttpServletResponse rsp = CSContext.getResponse();
rsp.setContentType("application/text");
rsp.setHeader("content-disposition", "attachment; filename=" + getxlsfnane());
OutputStream os = rsp.getOutputStream();
try {
CExcel.expByJSCols(jdatas, cols, os); // .expByCols(jdatas, cols, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
os.flush();
os.close();
}
}
private static String getxlsfnane() {
String rf = ConstsSw._root_filepath;
if ((rf == null) || (rf.isEmpty())) {
return "corsair.xlsx";
} else {
String fsep = System.getProperty("file.separator");
rf = rf.replace("\\", fsep);
rf = rf.replace("/", fsep);
String f = (new File(rf.trim())).getName();
if ((f == null) || (f.isEmpty()))
return "corsair.xlsx";
else
return f + ".xlsx";
}
}
public void export2excel(String[] ignParms, String scols, String idpw) throws Exception {
export2excel(DBPools.defaultPool(), ignParms, scols, idpw);
}
public void export2excel(CDBPool pool, String[] ignParms, String scols, String idpw) throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String parms = urlparms.get("parms");
String where = CjpaUtil.buildFindSqlByJsonParms((pool == null) ? DBPools.defaultPool() : pool, sqlstr, parms, notnull, ignParms, idpw);
sqlstr = "select * from (" + sqlstr + ") tb where 1=1 " + where;
// if (orderby != null) {
// sqlstr = sqlstr + " order by " + orderby;
// }
JSONArray cols = JSONArray.fromObject(scols);
// JSONArray cols = getTrueCol(scols);
// List<HashMap<String, String>> rcols = CJSON.parArrJson(cols.toString());
HttpServletResponse rsp = CSContext.getResponse();
rsp.setContentType("application/text");
rsp.setHeader("content-disposition", "attachment; filename=" + getxlsfnane());
OutputStream os = rsp.getOutputStream();
try {
CExcel.expLargeByCols(pool, sqlstr, orderby, cols, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
os.flush();
os.close();
}
}
public void export2excel(String[] ignParms, String scols) throws Exception {
String idpw = CSContext.getIdpathwhereNoErr();
export2excel(ignParms, scols, idpw);
}
}
<file_sep>/src/com/corsair/server/base/CSContext.java
package com.corsair.server.base;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.util.CJSON;
import com.corsair.server.csession.CSession;
import com.corsair.server.generic.Shworg;
import com.corsair.server.servlet.ServletUtil;
import com.corsair.server.util.TerminalType;
import com.corsair.server.util.TerminalType.TermKink;
import com.corsair.server.websocket.CWebSocketPool;
/**
* 请求环境变量
*
* @author Administrator
*
*/
public class CSContext {
public enum ActionType {
actGet, actPost
}
private static List<HttpSession> sessions = Collections.synchronizedList(new ArrayList<HttpSession>());
private static Lock lock = new ReentrantLock();
private static ThreadLocal<HttpSession> session = new ThreadLocal<HttpSession>();
private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();
private static ThreadLocal<HashMap<String, String>> parms = new ThreadLocal<HashMap<String, String>>();
private static ThreadLocal<String> postdata = new ThreadLocal<String>();
private static ThreadLocal<Boolean> isMultipartContent = new ThreadLocal<Boolean>();
private static ThreadLocal<HttpServlet> servlet = new ThreadLocal<HttpServlet>();
private static ThreadLocal<ActionType> actionType = new ThreadLocal<ActionType>();
private static ThreadLocal<TerminalType.TermType> termType = new ThreadLocal<TerminalType.TermType>();
/**
* webscoket
*/
public static CWebSocketPool wbsktpool = new CWebSocketPool();
private static void addSession2List(HttpSession _session) {
lock.lock();
try {
sessions.add(_session);
} finally {
lock.unlock();
}
}
private static void removeSession4List(HttpSession _session) {
lock.lock();
try {
sessions.remove(_session);
} finally {
lock.unlock();
}
}
/**
* 删除session
*/
public static void removeSession() {
removeSession4List(getSession());
session.remove();
}
public static HttpSession getSession() {
return session.get();
}
public static void setSession(HttpSession _session) {
session.set(_session);
addSession2List(_session);
}
// ///////////////////////
public static void removeRequest() {
request.remove();
}
public static HttpServletRequest getRequest() {
return request.get();
}
public static void setRequest(HttpServletRequest req) {
request.set(req);
}
// ///////////////////////
public static void removeResponse() {
response.remove();
}
public static HttpServletResponse getResponse() {
return response.get();
}
public static void setResponse(HttpServletResponse resp) {
response.set(resp);
}
// ///////////////////////
public static void removeParms() {
parms.remove();
}
/**
* url parms
* +
* post 的_pjdata 字段
* +
* 并解析POST的字段
*
* @return
* @throws Exception
*/
public static HashMap<String, String> get_pjdataparms() throws Exception {
HashMap<String, String> urlparms = getParms();
HashMap<String, String> parms = new HashMap<String, String>();
for (String key : urlparms.keySet()) {
if (key.toString().equalsIgnoreCase("_pjdata")) {
HashMap<String, String> pparms = CJSON.Json2HashMap(urlparms.get(key));
parms.putAll(pparms);
} else
parms.put(key.toString(), urlparms.get(key));
}
try {
String pdata = getPostdata();
JSONObject jo = JSONObject.fromObject(pdata);
Iterator<?> iterator = jo.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jo.getString(key);
if ((key != null) && (!key.isEmpty()) && (!"_pjdata".equalsIgnoreCase(key)))
parms.put(key, value);
}
} catch (Exception e) {
// parms错误不处理
// TODO Auto-generated catch block
// e.printStackTrace();
}
return parms;
}
/**
* 获取页面get键值对参数
*
* @return
*/
public static HashMap<String, String> getParms() {
return parms.get();
}
public static void setParms(HashMap<String, String> ps) {
parms.set(ps);
}
public static void pushParm(String key, String value) {
session.get().setAttribute(key, value);
}
public static String getParm(String key) {
Object o = session.get().getAttribute(key);
if (o == null)
return null;
else
return o.toString();
}
public static void removeParm(String key) {
session.get().removeAttribute(key);
}
// ///////////////////////
public static void removePostdata() {
postdata.remove();
}
public static String getPostdata() {
return postdata.get();
}
public static void setPostdata(String pd) {
postdata.set(pd);
}
// ////////////////
public static void removeisMultipartContent() {
isMultipartContent.remove();
}
public static Boolean isMultipartContent() {
return isMultipartContent.get();
}
public static void setIsMultipartContent(Boolean value) {
isMultipartContent.set(value);
}
// ////////////////
public static void removeservlet() {
servlet.remove();
}
public static HttpServlet getservlet() {
return servlet.get();
}
public static void setservlet(HttpServlet value) {
servlet.set(value);
}
// ////////////////////////////
public static void removeactiontype() {
actionType.remove();
}
public static ActionType getActionType() {
return actionType.get();
}
public static void setactiontype(ActionType value) {
actionType.set(value);
}
// //////////////////
// ///////////////////////
public static void removeTermType() {
termType.remove();
}
public static TerminalType.TermType getTermType() {
return termType.get();
}
public static void setTermType(TerminalType.TermType tp) {
termType.set(tp);
}
// /////////
public static TermKink getTermKink() {
return TerminalType.getTermKink(getTermType());
}
/**
* 当前会话是否已经登录
*
* @return
*/
public static boolean logined() {
HttpSession session = getSession();
if (session == null)
return false;
Object o = null;
try {
o = CSession.getvalue(session.getId(), ConstsSw.session_logined);
} catch (Exception e) {
return false;
}
if (o == null)
return false;
return Boolean.valueOf(o.toString());
}
// //////////////
/**
* 前台 传入的系统参数 idpathwhere;curentid;defaultorgid;
* userid;displayname;username;defaultorg:Shworg; userorgs:
* CJPALineData<Shworg>;remotehost
*
* @param parmname
* @return
* @throws Exception
*/
public static Object getUserParmObject(String parmname) throws Exception {
HttpSession session = getSession();
if (session == null)
throw new Exception("获取系统参数<" + parmname + ">Session 未找到!");
Object o = CSession.getvalue(session.getId(), parmname);
if (o == null)
throw new Exception("获取系统参数<" + parmname + ">为空!");
return o;
}
/**
* 根据参数名获取参数
*
* @param parmname
* @return
* @throws Exception
*/
public static String getUserParmValue(String parmname) throws Exception {
Object o = getUserParmObject(parmname);
return o.toString();
}
/**
* 获取Idpath
*
* @return
* @throws Exception
*/
public static String getIdpathwhere() throws Exception {
return getUserParmValue("idpathwhere");
}
/**
* @return
* @throws Exception
*/
public static String getClientIP() {
try {
HttpSession session = getSession();
if (session == null)
return null;
Object o = session.getAttribute("clientip");
if (o == null)
return null;
else
return o.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取当前组织
*
* @return
* @throws Exception
*/
public static String getCurEntID() throws Exception {
return getUserParmValue("curentid");
}
/**
* 获取默认机构
*
* @return
* @throws Exception
*/
public static String getDefaultOrgID() throws Exception {
return getUserParmValue("defaultorgid");
}
/**
* 获取登录用户ID,未登录报错
*
* @return
* @throws Exception
*/
public static String getUserID() throws Exception {
return getUserParmValue("userid");
}
/**
* 获取登录用户显示名 未登录报错
*
* @return
* @throws Exception
*/
public static String getUserDisplayname() throws Exception {
return getUserParmValue("displayname");
}
/**
* 获取登录用户名 未登录报错
*
* @return
* @throws Exception
*/
public static String getUserName() throws Exception {
return getUserParmValue("username");
}
/**
* 获取登录用户名 未登录返回null
*
* @return
*/
public static String getUserNameEx() {
HttpSession session = getSession();
if (session == null)
return null;
Object o = null;
try {
o = CSession.getvalue(session.getId(), "username");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // session.getAttribute("");
if (o == null)
return null;
return o.toString();
}
/**
* 获取登录用户默认机构 未登录返回null
*
* @return
*/
public static Shworg getUserDefaultOrg() {
try {
Shworg org = new Shworg();
org.findByID(getDefaultOrgID());
return org;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// no errror
/**
* 获取登录用户参数,未登录不报错 返回null
*
* @param parmname
* @return
*/
public static Object getUserParmObjectNoErr(String parmname) {
HttpSession session = getSession();
if (session == null)
return null;
try {
Object o = CSession.getvalue(session.getId(), parmname);
return o;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取登录用户参数,未登录不报错 返回null
*
* @param parmname
* @return
*/
public static String getUserParmValueNoErr(String parmname) {
Object o = getUserParmObjectNoErr(parmname);
if (o == null)
return null;
else
return o.toString();
}
/**
* 获取登录用户idpath
*
* @return
*/
public static String getIdpathwhereNoErr() {
return getUserParmValueNoErr("idpathwhere");
}
/**
* 获取登录用户组织id
*
* @return
*/
public static String getCurEntIDNoErr() {
return getUserParmValueNoErr("curentid");
}
/**
* 获取登录用户默认机构
*
* @return
*/
public static String getDefaultOrgIDNoErr() {
return getUserParmValueNoErr("defaultorgid");
}
/**
* 获取登录用户ID
*
* @return
*/
public static String getUserIDNoErr() {
return getUserParmValueNoErr("userid");
}
/**
* 获取登录用户显示名称
*
* @return
*/
public static String getUserDisplaynameNoErr() {
return getUserParmValueNoErr("displayname");
}
/**
* 获取登录用户
*
* @return
*/
public static String getUserNameNoErr() {
return getUserParmValueNoErr("username");
}
/**
* 获取登录用户ID
*
* @return
*/
public static String getUserIDNotErr() {
HttpSession session = getSession();
if (session == null)
return null;
try {
Object o = CSession.getvalue(session.getId(), "userid");
if (o == null)
return null;
return o.toString();
} catch (Exception e) {
return null;
}
}
/**
* 判断登录用户是否管理员
*
* @return
*/
public static boolean isAdminNoErr() {
HttpSession session = getSession();
if (session == null)
return false;
try {
Object o = CSession.getvalue(session.getId(), "usertype");
if (o == null)
return false;
int ut = Integer.valueOf(o.toString());
return (ut == 1);
} catch (Exception e) {
return false;
}
}
/**
* 获取登录用户所属机构列表
*
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static CJPALineData<Shworg> getUserOrgs() throws Exception {
return getUserOrgs(getUserID(), getCurEntID());
}
/**
* 获取登录用户所属机构ID列表
*
* @return
* @throws Exception
*/
public static String getUserOrgIDs() throws Exception {
return getUserParmValue("curorgids");
}
/**
* 获取登录用户所属机构所有idpath
*
* @return
* @throws Exception
*/
public static String[] getUserIdpaths() throws Exception {
String sidps = getUserParmValue("idpaths");
return sidps.split("#");
}
/**
* 获取登录用户所属机构列表
*
* @param userid
* @param entid
* @return
* @throws Exception
*/
public static CJPALineData<Shworg> getUserOrgs(String userid, String entid) throws Exception {
CJPALineData<Shworg> userorgs = new CJPALineData<Shworg>(Shworg.class);
String sqlstr = "select a.* from shworg a,shworguser b where a.orgid=b.orgid and a.entid=" + entid + " and b.userid=" + userid;
userorgs.findDataBySQL(sqlstr, true, true);
return userorgs;
}
/**
* 获取远程主机名(如果使用了代理是无法获取远程主机名的)
*
* @return
* @throws Exception
*/
public static String getRemoteHost() throws Exception {
return getUserParmValue("remotehost");
}
/**
* 获取远程IP
*
* @return
*/
public static String getTrueRemoteHostIP() {
return ServletUtil.getIpAddr(getRequest());
}
/**
* 解析前端提交的参数
*
* @return
* @throws Exception
*/
public static HashMap<String, String> parPostDataParms() throws Exception {
return CJSON.Json2HashMap(getPostdata());
}
/**
* 将前端提交的参数专为JSON对象
*
* @return
*/
public static JSONObject parPostData2JSONObject() {
return JSONObject.fromObject(getPostdata());
}
/**
* 将前端提交的参数专为JSON数组对象
*
* @return
*/
public static JSONArray parPostData2JSONArray() {
return JSONArray.fromObject(getPostdata());
}
/**
* 获取所有session
*
* @return
*/
public static List<HttpSession> getSessions() {
return sessions;
}
/**
* 返回处理成功的JSON对象
*
* @return
*/
public static String getJSON_OK() {
JSONObject rst = new JSONObject();
rst.put("errcode", 0);
return rst.toString();
}
/**
* 返回错误JSON对象
*
* @return
*/
public static String getJSON_Err() {
return getJSON_Err(-1, null);
}
/**
* 返回错误JSON对象
*
* @param errcode
* @return
*/
public static String getJSON_Err(int errcode) {
return getJSON_Err(errcode, null);
}
/**
* 返回错误JSON对象
*
* @param errcode
* @param errmsg
* @return
*/
public static String getJSON_Err(int errcode, String errmsg) {
JSONObject rst = new JSONObject();
rst.put("errcode", errcode);
if (errmsg != null)
rst.put("errmsg", errmsg);
return rst.toString();
}
}
<file_sep>/src/com/corsair/server/wordflow/Shwwf.java
package com.corsair.server.wordflow;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwwf extends CJPA {
@CFieldinfo(fieldname = "wfid", iskey = true, notnull = true, caption = "", datetype = Types.INTEGER)
public CField wfid; //
@CFieldinfo(fieldname = "wfname", caption = "流程名称", datetype = Types.VARCHAR)
public CField wfname; // 流程名称
@CFieldinfo(fieldname = "code", caption = "流程编码", datetype = Types.VARCHAR)
public CField code; // 流程编码
@CFieldinfo(fieldname = "codeid", caption = "编码ID", datetype = Types.INTEGER)
public CField codeid; // 编码ID
@CFieldinfo(fieldname = "frmclassname", caption = "", datetype = Types.VARCHAR)
public CField frmclassname; //
@CFieldinfo(fieldname = "clas", caption = "JPA Class", datetype = Types.VARCHAR)
public CField clas; // JPA Class
@CFieldinfo(fieldname = "stat", caption = "1 待审批 2 当前 3 完成", datetype = Types.INTEGER)
public CField stat; // 1 待审批 2 当前 3 完成
@CFieldinfo(fieldname = "submitctrl", caption = "提交控制", datetype = Types.INTEGER)
public CField submitctrl; // 提交控制
@CFieldinfo(fieldname = "actived", caption = "活动", datetype = Types.INTEGER)
public CField actived; // 活动
@CFieldinfo(fieldname = "period", caption = "", datetype = Types.INTEGER)
public CField period; //
@CFieldinfo(fieldname = "ojcectid", caption = "对象ID", datetype = Types.INTEGER)
public CField ojcectid; // 对象ID
@CFieldinfo(fieldname = "breakprocid", caption = "中断过程ID", datetype = Types.INTEGER)
public CField breakprocid; // 中断过程ID
@CFieldinfo(fieldname = "keephistory", caption = "保存历史", datetype = Types.INTEGER)
public CField keephistory; // 保存历史
@CFieldinfo(fieldname = "managers", caption = "管理员", datetype = Types.VARCHAR)
public CField managers; // 管理员
@CFieldinfo(fieldname = "canselect", caption = "允许选择", datetype = Types.INTEGER)
public CField canselect; // 允许选择
@CFieldinfo(fieldname = "submituserid", caption = "提交用户ID", datetype = Types.INTEGER)
public CField submituserid; // 提交用户ID
@CFieldinfo(fieldname = "issecret", caption = "", datetype = Types.INTEGER)
public CField issecret; //
@CFieldinfo(fieldname = "comporgid", caption = "机构ID", datetype = Types.INTEGER)
public CField comporgid; // 机构ID
@CFieldinfo(fieldname = "frmclass", caption = "窗体类名", datetype = Types.VARCHAR)
public CField frmclass; // 窗体类名
@CFieldinfo(fieldname = "breakfunc", caption = "中断函数", datetype = Types.VARCHAR)
public CField breakfunc; // 中断函数
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "updatereason", caption = "更新原因", datetype = Types.VARCHAR)
public CField updatereason; // 更新原因
@CFieldinfo(fieldname = "idpath", caption = "路径", datetype = Types.VARCHAR)
public CField idpath; // 路径
@CFieldinfo(fieldname = "typepath", caption = "类型路径", datetype = Types.VARCHAR)
public CField typepath; // 类型路径
@CFieldinfo(fieldname = "note", caption = "备注", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "modifyperiod", caption = "允许编辑", datetype = Types.SMALLINT)
public CField modifyperiod; // 允许编辑
@CFieldinfo(fieldname = "canmodifytime", caption = "允许边界时间", datetype = Types.INTEGER)
public CField canmodifytime; // 允许边界时间
@CFieldinfo(fieldname = "fdrid", caption = "文件ID", datetype = Types.INTEGER)
public CField fdrid; // 文件ID
@CFieldinfo(fieldname = "entid", caption = "组织", datetype = Types.INTEGER)
public CField entid; // 组织
@CFieldinfo(fieldname = "subject", caption = "主题", datetype = Types.VARCHAR)
public CField subject; // 主题
@CFieldinfo(fieldname = "wftemid", caption = "模板ID", datetype = Types.INTEGER)
public CField wftemid; // 模板ID
@CFieldinfo(fieldname = "formurl", caption = "窗体路径", datetype = Types.VARCHAR)
public CField formurl; // 窗体路径
@CFieldinfo(fieldname = "mwwfstype", caption = "流程中中心显示方式 1 流程+表单 2 流程 3 表单", defvalue = "1", datetype = Types.INTEGER)
public CField mwwfstype; // 流程中中心显示方式 1 流程+表单 2 流程 3 表单
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
@CLinkFieldInfo(jpaclass = Shwwfproc.class, linkFields = { @LinkFieldItem(lfield = "wfid", mfield = "wfid") })
public CJPALineData<Shwwfproc> shwwfprocs;
@CLinkFieldInfo(jpaclass = Shwwflinkline.class, linkFields = { @LinkFieldItem(lfield = "wfid", mfield = "wfid") })
public CJPALineData<Shwwflinkline> shwwflinklines;
// @CLinkFieldInfo(jpaclass = Shwwfproclog.class, linkFields = { @LinkFieldItem(lfield = "wfid", mfield = "wfid") })
// public CJPALineData<Shwwfproclog> shwwfproclogs;
// 自关联数据定义
public Shwwf() throws Exception {
}
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/generic/Shwusertoken.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwusertoken extends CJPA {
@CFieldinfo(fieldname = "userid", notnull = true, caption = "userid", datetype = Types.INTEGER)
public CField userid; // userid
@CFieldinfo(fieldname = "token", iskey = true, notnull = true, caption = "token", datetype = Types.VARCHAR)
public CField token; // token
@CFieldinfo(fieldname = "sessionid", caption = "sessionid", datetype = Types.VARCHAR)
public CField sessionid; // sessionid
@CFieldinfo(fieldname = "username", notnull = true, caption = "用户名", datetype = Types.VARCHAR)
public CField username; // 用户名
@CFieldinfo(fieldname = "userpass", caption = "密码", datetype = Types.VARCHAR)
public CField userpass; // 密码
@CFieldinfo(fieldname = "starttime", caption = "创建时间", datetype = Types.INTEGER)
public CField starttime; // 创建时间
@CFieldinfo(fieldname = "timeout", caption = "超时时间", datetype = Types.INTEGER)
public CField timeout; // 超时时间
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwusertoken() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/util/hrmail/SOAPUtil.java
package com.hr.util.hrmail;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.dom4j.Element;
public class SOAPUtil {
/**
* 获取POJO某个字段SOAP值
*
* @param pojo
* @param fdname
* @return
*/
public static String getFieldXMLStr(Object pojo, String fdname) {
String value = null;
try {
Field field = pojo.getClass().getDeclaredField(fdname);
if (field != null) {
PropertyDescriptor pd = new PropertyDescriptor(fdname, pojo.getClass());
Method getMethod = pd.getReadMethod();
if (getMethod != null) {
Object o = getMethod.invoke(pojo);
if (o != null)
value = o.toString();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ((value == null) || value.isEmpty()) {
return "<eip:" + fdname + " xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>";
} else {
return "<eip:" + fdname + ">" + value + "</eip:Address>";
}
}
public static void putField2XML(Object pojo, Element em) {
try {
Field[] fields = pojo.getClass().getDeclaredFields();
for (Field field : fields) {
if (field != null) {
String value = null;
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), pojo.getClass());
Method getMethod = pd.getReadMethod();
if (getMethod != null) {
Object o = getMethod.invoke(pojo);
if (o != null) {
value = o.toString();
}
}
if ((value == null) || value.isEmpty()) {
// rst = rst + "<eip:" + field.getName() + " xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>";
} else {
em.addElement("eip:" + field.getName()).setText(value);
// rst = rst + "<eip:" + field.getName() + ">" + value + "</eip:" + field.getName() + ">";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取POJO所有字段SOAP值
*
* @param pojo
* @return
*/
public static String getFieldXMLStr(Object pojo) {
String rst = "";
try {
Field[] fields = pojo.getClass().getDeclaredFields();
for (Field field : fields) {
if (field != null) {
String value = null;
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), pojo.getClass());
Method getMethod = pd.getReadMethod();
if (getMethod != null) {
Object o = getMethod.invoke(pojo);
if (o != null) {
value = o.toString();
}
}
if ((value == null) || value.isEmpty()) {
// rst = rst + "<eip:" + field.getName() + " xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>";
} else {
rst = rst + "<eip:" + field.getName() + ">" + value + "</eip:" + field.getName() + ">";
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return rst;
}
}
<file_sep>/src/com/hr/.svn/pristine/f5/f55bab090090213250c44d9c09af7b9bcb548af1.svn-base
package com.hr.perm.ctr;
import com.corsair.dbpool.CDBConnection;
import com.hr.base.entity.Hr_standposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_transfer;
/**
* 调动辅助类
*
* 调动单据 ①调动前为正式状态,调动后根据调动单的填写确认调动后的状态。调动后若有考察期则状态变成考察,若无考察期则调动后为正式状态。
* ②调动前为考察状态,调动后根据调动单的填写确认调动后的状态。调动后若有考察期则前一次考察期结束,开展新的考察期,人事状态为考察;若无考察期则原考察期结束,调动后为正式状态。
* ③调动前为试用状态,若调动前与调动后职位一致,调动后状态仍为试用;调动前与调动后职位发生变化,调动后若有考察期则试用期结束,状态变成考察,若无考察期则调动后仍为试用。
*
* 年度组织架构调整 使用机构合并拆分功能时,调动前与调动后人事状态保持一致。 调动后,若填写调动单,则按调动单规则决定调动后人事状态。
* 调动后,若填写转正单,则按转正单规则决定调动后人事状态。
*
*
* @author shangwen
*
*/
public class CtrHr_employee_transferUtil {
/**
* @param ep
* @param emp
* @return 返回是否需要生成考察期列表 1生成 2 不生成
* @throws Exception
*/
public static int setEmpState(CDBConnection con, Hr_employee_transfer ep, Hr_employee emp) throws Exception {
Hr_standposition osop = new Hr_standposition();
Hr_standposition nsop = new Hr_standposition();
String sqlstr = "SELECT s.* FROM hr_standposition s,hr_orgposition o WHERE s.sp_id=o.sp_id AND o.ospid=%s";
osop.findBySQL(con, String.format(sqlstr, ep.odospid.getValue()), false);
nsop.findBySQL(con, String.format(sqlstr, ep.newospid.getValue()), false);
if (osop.isEmpty())
throw new Exception("调动前标准职位不存在");
if (nsop.isEmpty())
throw new Exception("调动后标准职位不存在");
boolean isSameoption = (osop.sp_id.getAsInt() == nsop.sp_id.getAsInt());// 相同标准职位
int rst = 2;
int attribute1 = ep.attribute1.getAsIntDefault(0);
if (attribute1 != 1) {
int empstatid = emp.empstatid.getAsIntDefault(0);// 2 试用 3考察 4 正式
if (empstatid == 4) {
if (ep.probation.getAsInt() == 0) {// 无考察期 1
ep.ispromotioned.setAsInt(1);
} else {
emp.empstatid.setAsInt(3);
rst = 1;
}
}
if (empstatid == 2) {// 试用
if (isSameoption) {// 调动前为试用状态,若调动前与调动后职位一致,调动后状态仍为试用?
// 若设置了考察期呢??????????????
} else {
if (ep.probation.getAsInt() == 0) {// 无考察期 1 无考察期则调动后仍为试用
ep.ispromotioned.setAsInt(1);
} else {
emp.empstatid.setAsInt(3);// 有考察期则试用期结束,状态变成考察
endPerShiyong(con, ep, emp);// 结束之前试用期
rst = 1;
}
}
}
if (empstatid == 3) {
if (ep.probation.getAsInt() == 0) {// 无考察期 1
ep.ispromotioned.setAsInt(1);
} else {
emp.empstatid.setAsInt(3);
rst = 1;
}
endPerKaocha(con, ep, emp);// 结束之前考察期
}
}
return rst;
}
/**
* 结束所有试用期
*
* @param emp
* @throws Exception
*/
private static void endPerShiyong(CDBConnection con, Hr_employee_transfer ep, Hr_employee emp) throws Exception {
String sqlstr = "UPDATE hr_entry_try SET trystat=4,promotiondaytrue=IF(promotiondaytrue=NULL,NOW(),promotiondaytrue),"
+ "delaypromotiondaytrue=IF(delaypromotiondaytrue=NULL,NOW(),delaypromotiondaytrue)," // 修改试用期列表
+ "attribute1='调动自动转正" + ep.emptranf_id.getValue() + "' WHERE trystat<>4 AND er_id=" + ep.er_id.getValue();
con.execsql(sqlstr);
sqlstr = "UPDATE hr_entry SET ispromotioned=1 ,promotionday=NOW(),attribute1='调动自动转正" + ep.emptranf_id.getValue() + "' WHERE er_id="
+ ep.er_id.getValue() + " AND ispromotioned<>1";
con.execsql(sqlstr);
}
/**
* 结束所有考察期
*
* @param emp
* @throws Exception
*/
private static void endPerKaocha(CDBConnection con, Hr_employee_transfer ep, Hr_employee emp) throws Exception {
String sqlstr = "UPDATE hr_transfer_try SET trystat=4,probationdatetrue=IF(probationdatetrue=NULL,NOW(),probationdatetrue),"
+ "delaypromotiondaytrue=IF(delaypromotiondaytrue=NULL,NOW(),delaypromotiondaytrue) ," + "attribute1='调动自动转正" + ep.emptranf_id.getValue()
+ "' WHERE trystat<>4 AND er_id=" + ep.er_id.getValue();
con.execsql(sqlstr);
sqlstr = "UPDATE hr_employee_transfer SET ispromotioned=1,attribute2='调动自动转正" + ep.emptranf_id.getValue() + "' WHERE ispromotioned<>1 AND er_id="
+ ep.er_id.getValue() + " AND emptranf_id<>" + ep.emptranf_id.getValue();
con.execsql(sqlstr);
}
}
<file_sep>/src/com/hr/salary/entity/Hr_salary_hotsub.java
package com.hr.salary.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import com.hr.salary.ctr.CtrHr_salary_hotsub;
import java.sql.Types;
@CEntity(caption="高温补贴申请",tablename="hr_salary_hotsub",controller=CtrHr_salary_hotsub.class)
public class Hr_salary_hotsub extends CJPA {
@CFieldinfo(fieldname="hs_id",iskey=true,notnull=true,precision=20,scale=0,caption="高温补贴申请ID",datetype=Types.INTEGER)
public CField hs_id; //高温补贴申请ID
@CFieldinfo(fieldname="hs_code",notnull=true,codeid=127,precision=16,scale=0,caption="高温补贴申请编码",datetype=Types.VARCHAR)
public CField hs_code; //高温补贴申请编码
@CFieldinfo(fieldname="orgid",notnull=true,precision=10,scale=0,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,precision=16,scale=0,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,precision=128,scale=0,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="substype",notnull=true,precision=1,scale=0,caption="津贴类型",defvalue="3",datetype=Types.INTEGER)
public CField substype; //津贴类型
@CFieldinfo(fieldname="applydate",precision=19,scale=0,caption="申请月份",datetype=Types.TIMESTAMP)
public CField applydate; //申请月份
@CFieldinfo(fieldname="sp_id",precision=20,scale=0,caption="职位ID",datetype=Types.INTEGER)
public CField sp_id; //职位ID
@CFieldinfo(fieldname="sp_code",precision=16,scale=0,caption="职位编码",datetype=Types.VARCHAR)
public CField sp_code; //职位编码
@CFieldinfo(fieldname="sp_name",precision=128,scale=0,caption="标准职位名称",datetype=Types.VARCHAR)
public CField sp_name; //标准职位名称
@CFieldinfo(fieldname="remark",precision=512,scale=0,caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname="wfid",precision=20,scale=0,caption="wfid",datetype=Types.INTEGER)
public CField wfid; //wfid
@CFieldinfo(fieldname="attid",precision=20,scale=0,caption="attid",datetype=Types.INTEGER)
public CField attid; //attid
@CFieldinfo(fieldname="stat",notnull=true,precision=2,scale=0,caption="流程状态",datetype=Types.INTEGER)
public CField stat; //流程状态
@CFieldinfo(fieldname="entid",notnull=true,precision=5,scale=0,caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname="idpath",notnull=true,precision=256,scale=0,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="creator",notnull=true,precision=32,scale=0,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname="createtime",notnull=true,precision=19,scale=0,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="updator",precision=32,scale=0,caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname="updatetime",precision=19,scale=0,caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
@CFieldinfo(fieldname="property1",precision=32,scale=0,caption="备用字段1",datetype=Types.VARCHAR)
public CField property1; //备用字段1
@CFieldinfo(fieldname="property2",precision=64,scale=0,caption="备用字段2",datetype=Types.VARCHAR)
public CField property2; //备用字段2
@CFieldinfo(fieldname="property3",precision=32,scale=0,caption="备用字段3",datetype=Types.VARCHAR)
public CField property3; //备用字段3
@CFieldinfo(fieldname="property4",precision=32,scale=0,caption="备用字段4",datetype=Types.VARCHAR)
public CField property4; //备用字段4
@CFieldinfo(fieldname="property5",precision=32,scale=0,caption="备用字段5",datetype=Types.VARCHAR)
public CField property5; //备用字段5
@CFieldinfo(fieldname="usable",notnull=true,precision=1,scale=0,caption="有效",defvalue="1",datetype=Types.INTEGER)
public CField usable; //有效
@CFieldinfo(fieldname="orghrlev",caption="机构人事层级",datetype=Types.INTEGER)
public CField orghrlev; //机构人事层级
@CFieldinfo(fieldname = "emplev", caption = "人事层级", datetype = Types.INTEGER)
public CField emplev; // 人事层级
@CFieldinfo(fieldname = "isqual", caption = "是否资格内", datetype = Types.INTEGER)
public CField isqual; // 是否资格内
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;
@CLinkFieldInfo(jpaclass = Hr_salary_hotsub_line.class, linkFields = { @LinkFieldItem(lfield = "hs_id", mfield = "hs_id") })
public CJPALineData<Hr_salary_hotsub_line> hr_salary_hotsub_lines;
public Hr_salary_hotsub() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/icefall.min.js
/**
* Created by Administrator on 2014-09-16.
*/
easyloader.locale = 'zh_CN';
var _contextPath = undefined;
var _serUrl = getURLStr();
var _notshowajaxprocform = false;//全局禁止显示加载进度框
/*
*将以下三种格式字符串转成日期
yyyy-MM-dd hh:mm:ss
yyyy-MM-dd
yyy-MM
*/
function $getDate4Str(str) {
if (!str) return new Date();
if ((typeof str) == "object")
return new Date();
if (str.indexOf(":") < 0) {
str = str + " 00:00:00";
}
var rst = new Date();
var ymdhms = str.split(" ");
var ymd = ymdhms[0].split("-");
var hms = ymdhms[1].split(":");
if (!ymd[2]) ymd[2] = '01';
rst.setFullYear(ymd[0], ymd[1] - 1, ymd[2]);
if (!hms[1]) hms[1] = "00";
if (!hms[2]) hms[2] = "00";
rst.setHours(hms[0], hms[1], hms[2]);
return rst;
}
function getURLStr() {
var contextPath = document.location.pathname;
var index = contextPath.substr(1).indexOf("/");
contextPath = contextPath.substr(0, index + 1);
_contextPath = contextPath.substr(1, index);
return document.location.protocol + "//" + location.host + contextPath;
}
if (typeof JSON == 'undefined') {
$('head').append($("<script type='text/javascript' src='" + _serUrl + "/webapp/js/json2.js'>"));
}
Array.prototype.indexOf = function (e) {
for (var i = 0, j; j = this[i]; i++) {
if (j == e) {
return i;
}
}
return -1;
};
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
/*
*将以下三种格式字符串转成日期
yyyy-MM-dd hh:mm:ss
yyyy-MM-dd
yyy-MM
*/
Date.prototype.fromStr = function (str) {
if (!str) return new Date();
if ((typeof str) == "object")
return new Date();
if (str.indexOf(":") < 0) {
str = str + " 00:00:00";
}
var ymdhms = str.split(" ");
var ymd = ymdhms[0].split("-");
var hms = ymdhms[1].split(":");
if (!ymd[2]) ymd[2] = '01';
this.setFullYear(ymd[0], ymd[1] - 1, ymd[2]);
if (!hms[1]) hms[1] = "00";
if (!hms[2]) hms[2] = "00";
this.setHours(hms[0], hms[1], hms[2]);
return this;
};
Date.prototype.toUIDatestr = function () {
//return this.format("MM/dd/yyyy hh:mm:ss");
return this.format("yyyy-MM-dd hh:mm:ss");
};
Date.prototype.addMonth = function (month) {
var y = this.getFullYear();
var m = this.getMonth();
m = m + month;
y = y + Math.floor(m / 12);
m = m % 12;
this.setFullYear(y);
this.setMonth(m);
return this;
};
Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
};
function $getLastDay(year, month) {
var new_year = year; //取当前的年份
var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定)
if (month > 12) { //如果当前大于12月,则年份转到下一年
new_month -= 12; //月份减
new_year++; //年份增
}
var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();//获取当月最后一天日期
}
function $date4str(s) {
return new Date().fromStr(s);
}
function $getDateNotKnow(v) {
if (!v)
return undefined;
if (v instanceof Date)
return v;
if ((typeof v == 'string'))
return $date4str(v);
return v;
}
function $dateformattostr(dt) {
dt = $getDateNotKnow(dt);
if ((!dt) || (!(dt instanceof Date))) return undefined;
return dt.format("yyyy-MM-dd hh:mm:ss");//window.cancel_proc();
}
function $dateformatorYYYY_MM(dt) {
dt = $getDateNotKnow(dt);
if ((!dt) || (!(dt instanceof Date))) return undefined;
var rst = dt.format("yyyy-MM");
return rst;
}
function $dateformattostrrYYYY_MM_DD(dt) {
dt = $getDateNotKnow(dt);
if ((!dt) || (!(dt instanceof Date))) return undefined;
return dt.format("yyyy-MM-dd");
}
function $dateformattostrrYYYY_MM(dt) {
dt = $getDateNotKnow(dt);
if ((!dt) || (!(dt instanceof Date))) return undefined;
var rst = dt.format("yyyy-MM");
return rst;
}
function $dateformattostrrYYYY_MM_DD_HH_MM(dt) {
dt = $getDateNotKnow(dt);
if ((!dt) || (!(dt instanceof Date))) return undefined;
var rst = dt.format("yyyy-MM-dd hh:mm");
return rst;
}
function $fieldDateFormatorYYYY_MM(value, row, index) {
if ((!value) || (value.length == 0) || ((typeof str) == "object"))
return value;
var dt = (new Date()).fromStr(value);
return $dateformatorYYYY_MM(dt);
}
function $fieldDateFormatorYYYY_MM_DD(value, row, index) {
if ((!value) || (value.length == 0) || ((typeof str) == "object"))
return value;
var dt = (new Date()).fromStr(value);
return $dateformattostrrYYYY_MM_DD(dt);
}
function $fieldDateFormatorYYYY_MM_DD_HH_MM(value, row, index) {
if ((!value) || (value.length == 0) || ((typeof str) == "object"))
return value;
var dt = (new Date()).fromStr(value);
return $dateformattostrrYYYY_MM_DD_HH_MM(dt);
}
function $fieldDateFormator(value, row, index) {
if ((!value) || (value.length == 0) || ((typeof str) == "object"))
return value;
var dt = (new Date()).fromStr(value);
return $dateformattostr(dt);
}
function $moneyFormatorWithY(value, row, index) {
var v = parseFloat(value);
if (isNaN(v))
return "";
return "¥" + v.toFixed(2);
}
function $moneyFormator(value, row, index) {
var v = parseFloat(value);
if (isNaN(v))
return "";
return v.toFixed(2);
}
//数组是否存在某个元素
Array.prototype.contains = function (arr) {
for (var i = 0; i < this.length; i++) {//this指向真正调用这个方法的对象
if ((this[i] + "") == (arr + "")) {
return true;
}
}
return false;
};
//根据ComURL,指定值
function $getNewComboxParmsByComUrl(comurl, values) {
var rst = {
valueField: comurl.valueField,
textField: comurl.textField
};
var data = [];
var oddata = comurl.jsondata;
for (var i = 0; i < oddata.length; i++) {
var odrow = oddata[i];
if (values.contains(odrow[comurl.valueField])) {
var nrow = {};
nrow[comurl.textField] = odrow[comurl.textField];
nrow[comurl.valueField] = odrow[comurl.valueField];
data.push(nrow);
}
}
rst.data = data;
return rst;
}
function $isEmpty(parm) {
return ((parm == undefined) || (parm == null) || (parm.length == 0));
}
var $urlparms = $getPageParms();
function $getPageParms() {
qs = document.location.search.split("+").join(" ");
if(qs.indexOf("&edittps=")>0){
qs=qs.substring(0,qs.indexOf("&edittps="))+qs.substring(qs.indexOf("&title"),qs.length);
}
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
function delParam(url, paramKey) {
var urlParam = url.substr(url.indexOf("?") + 1);
var beforeUrl = url.substr(0, url.indexOf("?"));
var nextUrl = "";
var arr = new Array();
if (urlParam != "") {
var urlParamArr = urlParam.split("&");
for (var i = 0; i < urlParamArr.length; i++) {
var paramArr = urlParamArr[i].split("=");
if (paramArr[0] != paramKey) {
arr.push(urlParamArr[i]);
}
}
}
if (arr.length > 0) {
nextUrl = "?" + arr.join("&");
}
url = beforeUrl + nextUrl;
return url;
}
// 将分钟数量转换为小时和分钟字符串
function $toHourMinute(minutes) {
return (Math.floor(minutes / 60) + ":" + (minutes % 60));
// 也可以转换为json,以方便外部使用
// return {hour:Math.floor(minutes/60),minute:(minutes%60)};
}
function $toHourMinuteJSON(minutes) {
return {hour: Math.floor(minutes / 60), minute: (minutes % 60)};
}
function $toMinute(hm) {
if (!hm) return 0;
var idx = hm.indexOf(":");
if (idx < 0) return 0;
var ext = parseInt(hm.substr(0, idx)) * 60 + parseInt(hm.substr(idx + 1, hm.length - 1));
if (!isNaN(ext))
return ext;
else return 0;
}
//删除comdic 词汇表 值为 value 的条目
function $removeDicValue(comdic, value) {
var jsondata = comdic.jsondata;
var type = comdic.type;
if (type != 'combobox') {
alert("只能删除combobox的值");
return;
}
var valueField = comdic.valueField;
for (var i = 0; i < jsondata.length; i++) {
if (jsondata[i][valueField] == value) {
jsondata.splice(i, 1);
return;
}
}
}
function showWaitForm() {
var allppwids = "<div id='all_ppw_id'></div>";
var allppwid = window.top.$("#all_ppw_id");
if (!allppwid[0]) {
$(allppwids).appendTo(window.top.document.body);
allppwid = window.top.$("#all_ppw_id");
}
var wpws = "<div id='wait_pw_id' class='easyui-window' title=''"
+ " data-options='modal:true,closed:true,border:false,collapsible:false,minimizable:false,closable:false,maximizable:false,resizable:false'"
+ " style='width:250px;height:90px;padding: 0px;overflow: hidden'>"
+ " <div style='width: 100%;height: 100%; border-top:1px solid #95B8E7;vertical-align:middle;text-align: center;padding: 5px;'>"
+ " <div class='icon-wait'"
+ " style='position:relative; width: 80%;height: 100%;text-align: center;text-align: center;"
+ " line-height:80px;margin: 0 auto '>"
+ " 载入数据,稍候......"
+ " </div>"
+ " </div>"
+ " <div></div>"
+ " </div>";
var pp = window.top.$("#wait_pw_id");
if (!pp[0]) {
$(wpws).appendTo(allppwid);
pp = window.top.$("#wait_pw_id");
window.top.$.parser.parse(pp.parent());
}
pp.window("open");
}
function closeWaitForm() {
var pp = window.top.$("#wait_pw_id");
if (pp[0])
pp.window("close");
}
function onreturnjsondata(data, sucprc, userdata, errprc) {
var allppwids = "<div id='all_ppw_id'></div>";
var allppwid = window.top.$("#all_ppw_id");
if (!allppwid[0]) {
$(allppwids).appendTo(window.top.document.body);
allppwid = window.top.$("#all_ppw_id");
}
var logins = "<div id='login_window' class='easyui-window' title='登录'"
+ "data-options='modal:true,closed:true,border:false,collapsible:false,minimizable:false'"
+ "style='width:300px;height:250px;padding: 0px'>"
+ " <iframe scrolling='no' frameborder='0' src='" + _serUrl + "/webapp/common/login.html" + "' style='width: 100%;height: 98%'></iframe>"
+ "</div>";
if (data.errmsg != undefined) {
if (data.errmsg.indexOf("未登录用户不允许执行") >= 0) {
var token = $getPageParms().token;
//alert(token);
if (!$isEmpty(token)) {
var url = _serUrl + "/web/login/loginByToken.co?token=" + token;
$ajaxjsonget(url, function (jsdata) {
//alert(JSON.stringify(jsdata));
var nurl = window.location.href;
nurl = delParam(nurl, "token");
window.location = nurl;
}, function (err) {
$.messager.alert('错误', err, 'error');
});
} else {
$.messager.alert('错误', '您还未登录或登录已经过期,请重新登录!', 'error', function () {
if ((window.top._loginURL != undefined) && (window.top._loginURL.length > 0)) {
window.top.location = window.top._loginURL;
} else {
var pp = window.top.$("#login_window");
if (!pp[0]) {
$(logins).appendTo(allppwid);
pp = window.top.$("#login_window");
window.top.$.parser.parse(pp.parent());
}
pp.window("open");
}
});
}
} else {
if (errprc)
errprc(data);
else
$.messager.alert('错误', data.errmsg, 'error');
}
} else {
sucprc(data, userdata);
}
}
function $ajaxjsonpost(url, data, sucprc, errprc, ayc, userdata, noshowprc) {
if ((!noshowprc) && (!_notshowajaxprocform))
showWaitForm();
if (ayc == undefined)
ayc = true;
$.ajax(
{
url: url,
type: 'post',
dataType: 'json',
data: data,
cache: false,
async: ayc,
contentType: "application/json; charset=utf-8",
success: function (jsondata) {
if (!noshowprc)
closeWaitForm();
onreturnjsondata(jsondata, sucprc, userdata, errprc);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
closeWaitForm();
errprc(XMLHttpRequest, textStatus, errorThrown);
}
}
)
}
function $ajaxjsonget(url, sucprc, errprc, ayc, userdata, noshowprc) {
if ((!noshowprc) && (!_notshowajaxprocform))
showWaitForm();
if (ayc == undefined)
ayc = true;
$.ajax(
{
url: url,
type: 'get',
dataType: 'json',
cache: false,
async: ayc,
contentType: "application/json; charset=utf-8",
success: function (jsondata) {
if (!noshowprc)
closeWaitForm();
onreturnjsondata(jsondata, sucprc, userdata, errprc);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (!noshowprc)
closeWaitForm();
errprc(XMLHttpRequest, textStatus, errorThrown);
}
}
)
}
function $ajaxhtmlget(url) {
var rst = undefined;
$.ajax({
url: url,
type: 'get',
dataType: 'text',
cache: false,
async: false,
contentType: "text/HTML; charset=utf-8",
success: function (data) {
rst = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$.messager.alert('错误', '获取模板文件错误!', 'error');
}
});
return rst;
}
function $getHtmlFragment(filter) {
var s = "<div>" + $ajaxhtmlget("../templet/default/html_gragments.html") + "</div>";
return $(s).find(filter).html();
}
function $generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
function getservdate() {
var dt;
$ajaxjsonget(_serUrl + "/web/common/getserverdate.co", function (jsondata) {
dt = jsondata.date;
return dt;
}, function () {
dt = undefined;
alert("错误");
}, false);
return dt;
}
function getnewid(tbname) {
var dt;
$ajaxjsonget(_serUrl + "/web/common/getnewid.co?tbname=" + tbname, function (jsondata) {
dt = jsondata.newid;
return dt;
}, function () {
dt = undefined;
alert("错误");
}, false);
return dt;
}
function $getDBTime() {
var func = arguments[0];
if ((typeof func) == "function") {
$ajaxjsonget(_serUrl + "/web/common/getDBDatetime.co", function (jsondata) {
var dt = (new Date()).fromStr(jsondata.rst);
func(dt);
}, function () {
dt = undefined;
alert("错误");
});
} else {
var dt = undefined;
$ajaxjsonget(_serUrl + "/web/common/getDBDatetime.co", function (jsondata) {
dt = (new Date()).fromStr(jsondata.rst);
return dt;
}, function () {
dt = undefined;
alert("错误");
}, false);
return dt;
}
}
/*
type: tree,grid,list
data:
title:
msg:
afterLoadData:
onOK:
onCancel:
*/
/*function SelectTreeOrList(options) {
var pdivid = "divid_" + (new Date()).getTime();
var devid = "select_" + (new Date()).getTime();
var inputID = "input_" + (new Date()).getTime();
var btid = "buttons_" + (new Date()).getTime();
var title = (options.title) ? options.title : "选择";
var msg = (options.msg) ? options.msg : "选择数据";
var stype = options.type;
var sipt = undefined;
if (stype == "tree") {
sipt = "<input id='" + inputID + "' class='easyui-combotree' style='width:100%;'/>";
}
if (stype == "list") { //需要id field value field
sipt = "<input id='" + inputID + "' class='easyui-combobox' style='width:100%;'/>";
}
if (stype == "grid") {//需要id field value field columns
sipt = "<input id='" + inputID + "' class='easyui-combogrid' style='width:100%;'/>";
}
var selectOrgUser_str = "<div id='" + pdivid + "'><div id='" + devid + "' class='easyui-dialog' title='" + title + "' style='width:300px;height:150px;padding:10px' data-options=\"modal:true,closed:true,iconCls: 'icon-search',buttons: '#" + btid + "'\">"
+ "<div style='margin: 5px auto'>" + msg + "</div>" + sipt
+ "<div id='" + btid + "'><a class='easyui-linkbutton' style='width: 80px'>确定</a><a class='easyui-linkbutton' style='width: 80px'>取消</a></div></div></div>";
this.options = options;
this.so = function () {
return so;
}
var devobj = $(selectOrgUser_str);
//$.parser.auto = false;
devobj.appendTo("body");
//$.parser.parse("#" + pdivid);
var so = $("#" + devid)
so.find(".easyui-linkbutton:eq(0)")[0].onclick = function () {
var txtobj = $("#" + inputID);
var data = undefined;
if (stype == "tree") {
var v = txtobj.combotree("getValue");
if ((v == null) || (v == undefined) || (v == '')) {
$.messager.alert('错误', '没有选择的数据', 'error');
return;
}
data = txtobj.combotree("tree").tree("getSelected");
}
if (stype == "list") {
var v = txtobj.combobox("getValue");
if ((v == null) || (v == undefined) || (v == '')) {
$.messager.alert('错误', '没有选择的数据', 'error');
return;
}
var dt = txtobj.combobox("getData");
for (var i = 0; i < dt.length; i++) {
if (dt[i][options.valueField] == v) {
data = dt[i];
break;
}
}
}
if (options.onOk) {
options.onOk(data);
}
so.dialog("close");
};
so.find(".easyui-linkbutton:eq(1)")[0].onclick = function () {
if (options.onCancel) {
options.onCancel();
}
so.dialog("close");
};
//$.parser.onComplete = initData;
function initData() {
var data = options.data;
if (data) {
if (stype == "tree") {
$C.tree.setTree1OpendOtherClosed(data);//输展开第一层
alert("1111111111111");
$("#" + inputID).combotree("loadData", data);
alert("2222222222");
}
if (stype == "list") {
$("#" + inputID).combobox({valueField: options.valueField, textField: options.textField, data: data});
}
} else {
alert("没有数据");
}
}
this.pop = function (NsfrmOptions) {
if (NsfrmOptions != undefined)
options = $.extend({}, options, NsfrmOptions);
initData();
so.dialog("open");
}
}*/
function $accMul(arg1, arg2)//乘法
{
var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
try {
m += s1.split(".")[1].length
} catch (e) {
}
try {
m += s2.split(".")[1].length
} catch (e) {
}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
function $accAdd(arg1, arg2) {//加法
var r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m;
}
function $accDiv(arg1, arg2) {//除法
var t1 = 0, t2 = 0, r1, r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {
}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {
}
with (Math) {
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * pow(10, t2 - t1);
}
}
function $accSub(arg1, arg2) {//减法
return $accAdd(arg1, -arg2);
}
function $getTreeTextById(nodes, value) {
if ((value == null) || (value == undefined))
return value;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.id == value)
return node.text;
if (node.children) {
var txt = $getTreeTextById(node.children, value);
if (txt != undefined) return txt;
}
}
return undefined;
}
var $C = {
action: {
New: 1,
New2: 9,
Del: 2,
Edit: 3,
Submit: 4,
Print: 5,
Append: 6,
Save: 7,
Cancel: 8,
Find: 10,
Detail: 11,
Reload: 12,
Export: 13,
ExportList: 19,
Exit: 14,
Upload: 15,
Download: 16,
DelAtt: 17,
Copy: 18,
ColsFilter: 20,
Void: 21,
WFSubmit: 22,
WFReject: 23,
WFBreak: 24,
WFRefer: 25,
WFUnSubmit: 26,
ExportChart: 27,
PrintNew: 28,
PrintPreview: 29,
PrintDesign: 30,
Prev: 31,
Next: 32
},
cos: {
myworkflows: _serUrl + "/web/common/getmyworkwflist.co",
commonfind: _serUrl + "/web/common/find.co",
commonsave: _serUrl + "/web/common/save.co",
commondelete: _serUrl + "/web/common/delete.co",
commoncreateWF: _serUrl + "/web/common/createWF.co",
commonsubmitWF: _serUrl + "/web/common/submitWF.co",
commonrejectWF: _serUrl + "/web/common/rejectWF.co",
commonbreakWF: _serUrl + "/web/common/breakWF.co",
commontransferWF: _serUrl + "/web/common/transferWF.co",
commondowloadExcelByModel: _serUrl + "/web/common/dowloadExcelByModel.co",
commonUpLoadFile: _serUrl + "/web/common/upLoadFile.co",
commonupLoadFileProress: _serUrl + "/web/common/upLoadFileProress.co",
commonCopy: _serUrl + "/web/common/copy.co",
mps: {
importexcel: _serUrl + "/mps/bom/impexcel.co",
bomlines: _serUrl + "/mps/bom/bomlines.co",
bomlinesbyid: _serUrl + "/mps/bom/bomlinesbyid.co",
bomitemr: _serUrl + "/mps/bom/bomitemr.co"
},
inv: {
ledgeritem: _serUrl + "/inv/stockallocate/ledgeritem.co",
impfromexcel: _serUrl + "/inv/stockin/impfromexcel.co",
ledgercprice: _serUrl + "/web/inv/ledger/ledgercprice.co"
},
css: {
outletquta: _serUrl + "/css/partapply/outletquta.co",
submitsw: _serUrl + "/web/install/submitsw.co",
submitrv: _serUrl + "/web/install/submitrv.co",
submitdc: _serUrl + "/web/install/submitdc.co",
submitmatsw: _serUrl + "/web/maintenance/submitmatsw.co",
submitmatrv: _serUrl + "/web/maintenance/submitmatrv.co",
submitmatdc: _serUrl + "/web/maintenance/submitmatdc.co",
submitfixsw: _serUrl + "/web/fix/submitfixsw.co",
submitfixrv: _serUrl + "/web/fix/submitfixrv.co",
submitfixdc: _serUrl + "/web/fix/submitfixdc.co"
},
findAreaPath: _serUrl + "/web/shwarea/findAreaPath.co",
getWffds: _serUrl + "/web/wf/getWffds.co",
getWftemps: _serUrl + "/web/wf/getWftemps.co",
getWftemp: _serUrl + "/web/wf/getWftemp.co",
saveWfTemp: _serUrl + "/web/wf/saveWfTemp.co",
getorgs: _serUrl + "/web/user/getorgs.co",
delOrg: _serUrl + "/web/user/delOrg.co",
delUser: _serUrl + "/web/user/delUser.co",
saveRole: _serUrl + "/web/role/saveRole.co",
delRole: _serUrl + "/web/role/delRole.co",
findPositions: _serUrl + "/web/position/findPositions.co",
findUsersByPosition: _serUrl + "/web/position/findUsersByPosition.co",
savePosition: _serUrl + "/web/position/savePosition.co",
delPosition: _serUrl + "/web/position/delPosition.co",
getModTree: _serUrl + "/web/menu/getModTree.co",
getModMenuTree: _serUrl + "/web/menu/getModMenuTree.co",
saveMod: _serUrl + "/web/menu/saveMod.co",
delMod: _serUrl + "/web/menu/delMod.co",
saveMenu: _serUrl + "/web/menu/saveMenu.co",
delMenu: _serUrl + "/web/menu/delMenu.co",
getDicTree: _serUrl + "/web/dict/getDicTree.co",
saveDict: _serUrl + "/web/dict/saveDict.co",
delDict: _serUrl + "/web/dict/delDict.co",
login: function () {
return _serUrl + "/web/login/dologin.co";
},
loginout: function () {
return _serUrl + "/web/login/loginout.co";
},
notices: function () {
return _serUrl + "/web/common/getnotices.co";
},
getWfCount: function () {
return _serUrl + "/web/wf/wfcount.co";
},
getattach: function () {
return _serUrl + "/web/common/getshw_attachbyid.co";
},
downattfile: function () {
return _serUrl + "/web/common/downattfile.co";
},
delattfile: function () {
return _serUrl + "/web/common/delattfile.co";
},
userparms: function () {
return _serUrl + "/web/user/getuserparms.co";
},
userlistbyorg: function () {
return _serUrl + "/web/user/userListByOrg.co";
},
saveOrg: function () {
return _serUrl + "/web/user/saveOrg.co";
},
saveUser: function () {
return _serUrl + "/web/user/saveUser.co";
},
getmods: function () {
return _serUrl + "/web/menu/getmods.co";
},
getmenusbymod: function () {
return _serUrl + "/web/menu/getmenus.co";
},
getOrgsByUserID: function () {
return _serUrl + "/web/user/getOrgsByUserID.co";
},
getRolesByUserID: function () {
return _serUrl + "/web/user/getRolesByUserID.co";
},
getOptionsByUserID: function () {
return _serUrl + "/web/user/getOptionsByUserID.co";
},
getRoles: function () {
return _serUrl + "/web/role/getRoles.co";
},
getUsersByRoleid: function () {
return _serUrl + "/web/role/getUsers.co";
}
},
grid: {
initComFormaters: function (comOptions) {
var comUrls = comOptions.comUrls;
if (comUrls.length == 0)
if (comOptions.onOK) comOptions.onOK();
for (var i = 0; i < comUrls.length; i++) {
var comurl = comUrls[i];
$ajaxjsonget(comurl.url, function (jsondata, comurl) {
if (comurl.afterGetData)
comurl.afterGetData(jsondata);
var edtor = {type: comurl.type, options: {}};
if (comurl.type == "combobox") {
edtor.options.valueField = comurl.valueField;
edtor.options.textField = comurl.textField;
}
if (comurl.type == "combotree") {
$C.tree.setTree1OpendOtherClosed(jsondata);//第一级开着 第二级后全关上
}
edtor.options.data = jsondata;
$C.grid.comEditors[comurl.index] = edtor;
comurl.data = jsondata;
$C.grid.comDatas[comurl.index] = comurl;
$C.grid.comFormaters[comurl.index] = function (value, row) {
if (value == "get_com_data") {
return jsondata;
}
if (value == "get_com_url") {
return comurl;
}
// alert(comurl.index + ":" + value + ":" + JSON.stringify(jsondata));
if (comurl.type == "combobox") {
for (var i = 0; i < jsondata.length; i++) {
if (value == jsondata[i][comurl.valueField])
return jsondata[i][comurl.textField];
}
}
if (comurl.type == "combotree") {
var txt = $getTreeTextById(jsondata, value);
if (txt == undefined) txt = value;
return txt;
}
return value;
};
comurl.succ = true;
if (checkAllSuccess()) {
if (comOptions.onOK) comOptions.onOK();
}
}, function (err) {
$.messager.alert('错误', '初始化Grid Combobox错误:' + err.errmsg, 'error');
}, true, comurl);
}
function checkAllSuccess() {
for (var i = 0; i < comUrls.length; i++) {
if (!comUrls[i].succ)
return false;
}
return true;
}
},
comFormaters: [],
comEditors: [],
comDatas: [],
dateFormater: function (value, row) {
if ((!value) || (value == null) || (value.length = 0))
return "";
var date = new Date().fromStr(value);
return date.format("yyyy-MM-dd hh:mm:ss");
},
dateEditor: {type: 'datebox'},
clearData: function (GridID) {
var oGrid = undefined;
if (typeof(GridID) == "object") {
oGrid = GridID;
} else {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
oGrid = $(GridID);
}
if (oGrid.length <= 0) {
//alert("页面没ID为:" + GridID + "的对象!");
}
if (!oGrid) return false;
var rows = oGrid.datagrid("getRows");
for (var i = rows.length - 1; i >= 0; i--) {
oGrid.datagrid('deleteRow', i);
}
return true;
},
endEditing: function (GridID) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
var rows = oGrid.datagrid("getRows");
for (var i = 0; i < rows.length; i++) {
oGrid.datagrid('endEdit', i);
}
return true;
},
edit: function (GridID) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
if ($C.grid.endEditing(GridID)) {
var row = oGrid.datagrid('getSelected');
if (!row) {
$.messager.alert('错误', '没选择的行', 'error');
return false;
}
var index = oGrid.datagrid('getRowIndex', row);
oGrid.datagrid('selectRow', index).datagrid('beginEdit', index);
return true;
}
},
append: function (GridID, RowData, Editing) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
if ($C.grid.endEditing(GridID)) {
if (!RowData) RowData = {};
oGrid.datagrid('appendRow', RowData);
var newIndex = oGrid.datagrid('getRows').length - 1;
oGrid.datagrid('selectRow', newIndex);
if (Editing) oGrid.datagrid("beginEdit", newIndex);
return true;
}
},
remove: function (GridID) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
if ($C.grid.endEditing(GridID)) {
var row = oGrid.datagrid('getSelected');
if (!row) {
$.messager.alert('错误', '没选择的行', 'error');
return false;
}
var index = oGrid.datagrid('getRowIndex', row);
oGrid.datagrid('deleteRow', index);
return true;
}
},
accept: function (GridID) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
if ($C.grid.endEditing(GridID)) {
oGrid.datagrid('acceptChanges');
}
},
reject: function (GridID) {
if (GridID.charAt(0) != "#")
GridID = "#" + GridID;
var oGrid = $(GridID);
if (!oGrid) return false;
oGrid.datagrid('rejectChanges');
},
removeByField: function (filter, fdvalue, fdname) {
var rows = $(filter).datagrid("getRows");
var row = undefined;
for (var i = 0; i < rows.length; i++) {
row = rows[i];
if (row[fdname] == fdvalue)
break;
}
if (!row) return;
var index = $(filter).datagrid('getRowIndex', row);
$(filter).datagrid('deleteRow', index);
return true;
},
getRowByField: function (filter, fdvalue, fdname) {
var rows = $(filter).datagrid("getRows");
//console.error(JSON.stringify(rows));
var row = undefined;
for (var i = 0; i < rows.length; i++) {
row = rows[i];
// console.error("row v:" + row[fdname] + " | v:" + fdvalue);
if (row[fdname] == fdvalue)
return row;
}
return undefined;
},
getRowByFields: function (filter, fdvalues, fdnames) {
var rows = $(filter).datagrid("getRows");
if (fdvalues.length != fdnames.length)
return false;
if (fdvalues.length == 0)
return false;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var fd = true;
for (var j = 0; j < fdvalues.length; j++) {
if (row[fdnames[j]] != fdvalues[j]) {
fd = false;
break;
}
}
if (fd) return row;
}
return false;
}
},
UserInfo: {
userid: function () {
return localStorage.getItem(_contextPath + ".userid");
},
username: function () {
return localStorage.getItem(_contextPath + ".username");
},
displayname: function () {
return localStorage.getItem(_contextPath + ".displayname");
},
entid: function () {
return localStorage.getItem(_contextPath + ".entid");
},
languageid: function () {
return localStorage.getItem(_contextPath + ".languageid");
},
dforgid: function () {
return localStorage.getItem(_contextPath + ".dforgid");
},
dforgidpath: function () {
return localStorage.getItem(_contextPath + ".dforgidpath");
},
usertype: function () {
return localStorage.getItem(_contextPath + ".usertype");
},
removelogininfos: function () {
localStorage.removeItem(_contextPath + ".userid");
localStorage.removeItem(_contextPath + ".username");
localStorage.removeItem(_contextPath + ".displayname");
localStorage.removeItem(_contextPath + ".entid");
localStorage.removeItem(_contextPath + ".languageid");
localStorage.removeItem(_contextPath + ".dforgid");
localStorage.removeItem(_contextPath + ".dforgidpath");
localStorage.removeItem(_contextPath + ".usertype");
}
},
tree: {
setTree1OpendOtherClosed: function (nodes) {//打开第一层
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.children) {
node.state = "opend";
$C.tree.setTreeNodesState(node.children, "closed");
}
}
return nodes;
},
setTreeNodesState: function (nodes, state) {
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.children) {
node.state = state;
$C.tree.setTreeNodesState(node.children, state);
}
}
}
}
};
function $getfileicobyfileext(ext) {
var fileexttys = [{
exts: [".vb", ".vbs", ".reg", ".pl", ".pm", ".cgi", ".as", ".clj", ".cbl", ".cfm", ".d", ".diff", ".dot", ".ejs", ".erl", ".ftl", ".go", ".hs", ".hbs", ".haml", ".erb", ".jade", ".json", ".jq", ".jsx", ".ji", ".tex", ".lisp", ".ls", ".lsl", ".lua", ".lp", ".matlab", ".mel", ".r", ".yaml", ".vb", ".vbs", ".reg", ".pl", ".pm", ".cgi", ".as", ".clj", ".cbl", ".cfm", ".d", ".diff", ".dot", ".ejs", ".erl", ".ftl", ".go", ".hs", ".hbs", ".haml", ".erb", ".jade", ".json", ".jq", ".jsx", ".ji", ".tex", ".lisp", ".ls", ".lsl", ".lua", ".lp", ".matlab", ".mel", ".r", ".yaml"],
cls: "icon-file-code32"
},
{exts: [".folder", ".folder"], cls: "icon-file-folder32"},
{exts: [".txt", ".md", ".markdown", ".log", ".txt", ".md", ".markdown", ".log"], cls: "icon-file-txt32"},
{
exts: [".html", ".htm", ".url", ".tpl", ".lnk", ".haml", ".shtml", ".webloc", ".hta", ".html", ".htm", ".url", ".tpl", ".lnk", ".haml", ".shtml", ".webloc", ".hta"],
cls: "icon-file-html32"
},
{exts: [".css", ".less", ".sass", ".css", ".less", ".sass"], cls: "icon-file-css32"},
{exts: [".js", ".coffee", ".js", ".coffee"], cls: "icon-file-js32"},
{
exts: [".xml", ".config", ".manifest", ".xaml", ".csproj", ".vbproj", ".xml", ".config", ".manifest", ".xaml", ".csproj", ".vbproj"],
cls: "icon-file-xml32"
},
{exts: [".cs", ".asp", ".aspx", ".cs", ".asp", ".aspx"], cls: "icon-file-cs32"},
{exts: [".java", ".jsp", ".java", ".jsp"], cls: "icon-file-java32"},
{exts: [".sql", ".sql"], cls: "icon-file-sql32"},
{exts: [".oexe", ".oexe"], cls: "icon-file-oexe32"},
{exts: [".php", ".php"], cls: "icon-file-php32"},
{exts: [".py", ".py"], cls: "icon-file-py32"},
{exts: [".rb", ".rb"], cls: "icon-file-rb32"},
{
exts: [".mm", ".cc", ".cxx", ".cpp", ".c", ".m", ".mm", ".cc", ".cxx", ".cpp", ".c", ".m"],
cls: "icon-file-cpp32"
},
{exts: [".h", ".hpp", ".hh", ".pch", ".h", ".hpp", ".hh", ".pch"], cls: "icon-file-h32"},
{exts: [".jpg", ".jpeg", ".bmp", ".gif", , ".jpg", ".jpeg", ".bmp", ".gif"], cls: "icon-file-jpg32"},
{exts: [".asm", ".asm"], cls: "icon-file-asm32"},
{
exts: [".Makefile", ".makefile", ".GNUmakefile", ".makefile", ".OCamlMakefile", ".make", ".Makefile", ".makefile", ".GNUmakefile", ".makefile", ".OCamlMakefile", ".make"],
cls: "icon-file-makefile32"
},
{exts: [".sln", ".sln"], cls: "icon-file-sln32"},
{exts: [".pdf", ".pdf"], cls: "icon-file-pdf32"},
{exts: [".psd", ".psd"], cls: "icon-file-psd32"},
{exts: [".flv", ".f4v", ".flv", ".f4v"], cls: "icon-file-flv32"},
{exts: [".fla", ".fla"], cls: "icon-file-fla32"},
{exts: [".swf", ".swf"], cls: "icon-file-swf32"},
{exts: [".air", ".air"], cls: "icon-file-air32"},
{exts: [".svg", ".svg"], cls: "icon-file-svg32"},
{exts: [".ai", ".ai"], cls: "icon-file-ai32"},
{exts: [".chm", ".chm"], cls: "icon-file-chm32"},
{exts: [".numbers", ".numbers"], cls: "icon-file-numbers32"},
{exts: [".pages", ".pages"], cls: "icon-file-pages32"},
{exts: [".ipa", ".ipa"], cls: "icon-file-ipa32"},
{exts: [".iso", ".dvd", ".iso", ".dvd"], cls: "icon-file-iso32"},
{exts: [".dmg", ".dmg"], cls: "icon-file-dmg32"},
{exts: [".key", ".key"], cls: "icon-file-key32"},
{exts: [".package", ".framework", ".package", ".framework"], cls: "icon-file-package32"},
{
exts: [".zip", ".apk", ".tar", ".gzip", ".jar", ".cxr", ".tar", ".gz", ".cab", ".tbz", ".tbz2", ".bz2", ".zip", ".apk", ".tar", ".gzip", ".jar", ".cxr", ".tar", ".gz", ".cab", ".tbz", ".tbz2", ".bz2"],
cls: "icon-file-zip32"
},
{exts: [".rar", ".rar"], cls: "icon-file-rar32"},
{exts: [".dll", ".dll"], cls: "icon-file-dll32"},
{exts: [".exe", ".bin", ".exe", ".bin"], cls: "icon-file-exe32"},
{
exts: [".ttf", ".otf", ".eot", ".woff", ".tiff", ".ttc", ".ttf", ".otf", ".eot", ".woff", ".tiff", ".ttc"],
cls: "icon-file-ttf32"
},
{
exts: [".bat", ".cmd", ".sh", ".bash", ".bashrc", ".bat", ".cmd", ".sh", ".bash", ".bashrc"],
cls: "icon-file-cmd32"
},
{
exts: [".ini", ".conf", ".meta", ".gitignore", ".plist", ".htaccess", ".localized", ".xcscheme", ".storyboard", ".xib", ".strings", ".pbxproj", ".ini", ".conf", ".meta", ".gitignore", ".plist", ".htaccess", ".localized", ".xcscheme", ".storyboard", ".xib", ".strings", ".pbxproj"],
cls: "icon-file-ini32"
},
{
exts: [".mp3", ".wma", ".mp2", ".mid", ".aac", ".wav", ".m4a", ".mp3", ".wma", ".mp2", ".mid", ".aac", ".wav", ".m4a"],
cls: "icon-file-mp332"
},
{
exts: [".avi", ".rm", ".rmvb", ".mpg", ".mkv", ".wmv", ".mov", ".mp4", ".avi", ".rm", ".rmvb", ".mpg", ".mkv", ".wmv", ".mov", ".mp4"],
cls: "icon-file-avi32"
},
{exts: [".doc", ".docx", ".wps", ".doc", ".docx", ".wps"], cls: "icon-file-doc32"},
{exts: [".xls", ".xlsx", ".csv", ".xls", ".xlsx", ".csv"], cls: "icon-file-xls32"},
{exts: [".ppt", ".pptx", ".ppt", ".pptx"], cls: "icon-file-ppt32"},
{exts: [".recycle", ".recycle"], cls: "icon-file-recycle_image32"},
{exts: [".share", ".share"], cls: "icon-file-share_image32"}];
for (var i = 0; i < fileexttys.length; i++) {
var exttp = fileexttys[i];
if ($.inArray(ext, exttp.exts) > -1)
return exttp.cls;
}
return "icon-file-file32";
}
//options
//
function $uploadfile(serco, upfhtml, onerr, onsucc, onstart) {
$uploadfileEx({
serco: serco,
upfhtml: upfhtml,
onerr: onerr,
onsucc: onsucc,
onstart: onstart
});
}
function $uploadfileEx(options) {
var serco = (options.serco) ? options.serco : _serUrl + "/web/common/upLoadFile.co?timestamp=" + (new Date()).valueOf();
var upfhtml = (options.upfhtml) ? options.upfhtml : _serUrl + "/webapp/templet/default/uploadfile.html";
var onerr = options.onerr;
var onsucc = options.onsucc;
var onstart = options.onstart;
var multifile = (options.multifile == undefined) ? true : options.multifile;
var acceptfile = options.acceptfile;
if ($("#common_divs_id").length <= 0) {
$("<div id='common_divs_id'></div>").appendTo("body");
}
if ($("#pw_uploadfile").length <= 0) {
var athm = "<div id='pw_uploadfile' class='easyui-window' title='上传文件'"
+ " data-options='modal:true,closed:true,iconCls:\"icon-save\"'"
+ " style='width:400px;height:400px;padding:0px;'>"
+ " <iframe frameborder='0' style='width: 100%;height: 95%'></iframe>"
+ " </div>";
$(athm).appendTo("#common_divs_id");
$.parser.parse('#common_divs_id');
}
var wd = $("#pw_uploadfile iframe");
var action = encodeURI(serco);
wd.attr("src", upfhtml);
var iframe = wd[0];
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
setAttPWCallback(iframe, action, onstart);
});
} else {
iframe.onload = function () {
setAttPWCallback(iframe, action, onstart);
};
}
$("#pw_uploadfile").window("open");
function setAttPWCallback(iframe, action, onstart) {
iframe.contentWindow._acceptfile = acceptfile;
iframe.contentWindow._multifile = multifile;
iframe.contentWindow._action = action;
iframe.contentWindow._onstart = onstart;
iframe.contentWindow._callback = function (rst) {
var bis = JSON.parse(rst);
if (bis.errmsg) {
$("#pw_uploadfile").window("close");
if (onerr) {
onerr(bis.errmsg);
} else
$.messager.alert('错误', bis.errmsg, 'error');
return;
} else {
if (onsucc)onsucc(bis);
}
$("#pw_uploadfile").window("close");
};
}
}
function $shw_attachinfo(options) {
var pw_data_options = (options.pw_data_options) ? options.pw_data_options : "data-options='modal:true,closed:true'";
var pw_style = (options.pw_style) ? options.pw_style : "style='width:800px;height:500px;padding:0px;'>";
var pw_title = (options.pw_title) ? options.pw_title : "附件";
var jpaclass = (options.jpaclass) ? options.jpaclass : undefined;
var allowscan = (options.allowscan != undefined) ? options.allowscan : false;
options.jpaclass = jpaclass;
var onerr = (options.onerr) ? options.onerr : undefined;
var onsucc = (options.onsucc) ? options.onsucc : undefined;
var onclose = (options.onclose) ? options.onclose : undefined;
var imgthb = (options.imgthb == undefined) ? false : options.imgthb;
options.imgthb = imgthb;
var id = (options.id) ? options.id : id;
options.id = id;
var downurl = undefined;
if (options.downurl) {
downurl = options.downurl;
if (downurl.indexOf("?") < 0)
downurl = downurl + "?timestamp=" + (new Date()).valueOf();
} else {
downurl = _serUrl + "/web/common/getshw_attachbyid.co?timestamp=" + (new Date()).valueOf();
}
if ($("#common_divs_id").length <= 0) {
$("<div id='common_divs_id'></div>").appendTo("body");
}
if ($("#pw_shw_attach_info").length <= 0) {
var athm = "<div id='pw_shw_attach_info' class='easyui-window' title='" + pw_title + "'"
+ pw_data_options
+ pw_style
+ "<iframe frameborder='0' style='width: 100%;height: 95%'></iframe>"
+ "</div>";
$(athm).appendTo("#common_divs_id");
$.parser.parse('#common_divs_id');
}
var wd = $("#pw_shw_attach_info iframe");
var infhtm = (options.infhtm) ? options.infhtm : _serUrl + "/webapp/templet/default/shw_attach.html?timestamp=" + (new Date()).valueOf();
var iframe = wd[0];
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
setAttPWCallback(iframe, options);
if (!allowscan)
$(iframe).contents().find("#btn_scan").css("display", "none");
// $("#btn_scan", wd.document).css("display", "none");
});
} else {
iframe.onload = function () {
setAttPWCallback(iframe, options);
if (!allowscan)
$(iframe).contents().find("#btn_scan").css("display", "none");
};
}
wd.attr("src", infhtm);
$("#pw_shw_attach_info").window({
onClose: function () {
if (onclose)onclose();
}
});
$("#pw_shw_attach_info").window("open");
function setAttPWCallback(iframe, options) {
iframe.contentWindow._options = options;
iframe.contentWindow._callback = function (rst) {
//alert(JSON.stringify(rst));
var bis = JSON.parse(rst);
if (bis.errmsg) {
$("#pw_shw_attach_info").window("close");
if (onerr) {
onerr(bis.errmsg);
} else
$.messager.alert('错误', bis.errmsg, 'error');
return;
} else {
if (onsucc)onsucc(bis);
}
$("#pw_shw_attach_info").window("close");
};
}
}
function $parserDatebox2YearMonth(input) {
var db = input;
db.datebox({
onShowPanel: function () {//显示日趋选择对象后再触发弹出月份层的事件,初始化时没有生成月份层
span.trigger('click'); //触发click事件弹出月份层
if (!tds) setTimeout(function () {//延时触发获取月份对象,因为上面的事件触发和对象生成有时间间隔
tds = p.find('div.calendar-menu-month-inner td');
tds.click(function (e) {
e.stopPropagation(); //禁止冒泡执行easyui给月份绑定的事件
var year = /\d{4}/.exec(span.html())[0]//得到年份
, month = parseInt($(this).attr('abbr'), 10); //月份,这里不需要+1
db.datebox('hidePanel')//隐藏日期对象
.datebox('setValue', year + '-' + month); //设置日期的值
});
}, 0);
yearIpt.unbind();//解绑年份输入框中任何事件
},
parser: function (s) {
if (!s) return new Date();
var arr = s.split('-');
return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
},
formatter: function (d) {
var m = (d.getMonth() + 1);
if (m.toString().length == 1)
m = '0' + m;
return d.getFullYear() + '-' + m;
/*getMonth返回的是0开始的,忘记了。。已修正*/
}
});
var p = db.datebox('panel'), //日期选择对象
tds = false, //日期选择对象中月份
aToday = p.find('a.datebox-current'),
yearIpt = p.find('input.calendar-menu-year'),//年份输入框
//显示月份层的触发控件
span = aToday.length ? p.find('div.calendar-title span') ://1.3.x版本
p.find('span.calendar-text'); //1.4.x版本
p.find('.calendar-menu-year-inner').css("display", "none");
if (aToday.length) {//1.3.x版本,取消Today按钮的click事件,重新绑定新事件设置日期框为今天,防止弹出日期选择面板
aToday.unbind('click').click(function () {
var now = new Date();
db.datebox('hidePanel').datebox('setValue', now.getFullYear() + '-' + (now.getMonth() + 1));
});
}
}
function $getRowByFields(rows, fdvalues, fdnames) {
//alert($getRowByFields);
if (fdvalues.length != fdnames.length)
return false;
if (fdvalues.length == 0)
return false;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var fd = true;
//alert(JSON.stringify(row));
for (var j = 0; j < fdvalues.length; j++) {
//alert(row[fdnames[j]] + " " + fdvalues[j]);
if (row[fdnames[j]] != fdvalues[j]) {
fd = false;
break;
}
}
if (fd) return row;
}
return false;
}
//var m = [1,2,3,4,4,12,3]; 删除重复元素
function unique(arr) {
var result = [], hash = {};
for (var i = 0, elem; (elem = arr[i]) != null; i++) {
if (!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
}
function $InitGridColFields(fields, gridkey) {
var htmlurl = document.location.href.split("?")[0];
var index = htmlurl.substr(1).indexOf("//");
var key = htmlurl.substr(index + 3, htmlurl.length) + gridkey;
key = key.replace(/\//g, "-");
var filters = localStorage.getItem(key);
if (!filters)
return fields;
filters = eval(filters);
return getColFieldsByColFilter(fields, filters);
}
var halignedata = [
{caption: "居中", value: "center"},
{caption: "居左", value: "left"},
{caption: "居右", value: "right"}
];
function $showGridColFilter(grid, defaultfields, fields, gridkey, onOK, onCancel) {
var haligneditor = {
type: 'combobox',
options: {
valueField: "value",
textField: "caption",
data: halignedata
}
};
var haligneformator = function (value, row, index) {
for (var i = 0; i < halignedata.length; i++) {
if (value == halignedata[i].value) return halignedata[i].caption;
}
};
var htmlurl = document.location.href.split("?")[0];
var index = htmlurl.substr(1).indexOf("//");
var key = htmlurl.substr(index + 3, htmlurl.length) + gridkey;
key = key.replace(/\//g, "-");
//读取存储的数据
var filters = localStorage.getItem(key);
filters = (filters == undefined) ? createFitlters(fields) : eval(filters);
var setWindow = $("#gridcolfilterpw_id");
var setGrid = setWindow.find(".easyui-datagrid");
var setGridFeids = [
{field: 'chked', checkbox: true},
{field: 'sidx', title: '序号', width: 40},
//{field: 'field', title: '字段', width: 100},
{field: 'title', title: '标题', width: 100},
{field: 'halign', title: '标题对齐', width: 100, editor: haligneditor, formatter: haligneformator},
{field: 'width', title: '宽度', editor: 'numberbox', width: 80}
];
var editingidx = -1;
setGrid.datagrid({
columns: [setGridFeids],
onDblClickRow: function (index, row) {
setGrid.datagrid("beginEdit", index);
editingidx = index;
},
onCheck: function (index, row) {
setGrid.datagrid("unselectAll");
setGrid.datagrid("selectRow", index);
},
onClickRow: function (index, row) {
if (editingidx != -1)
setGrid.datagrid("endEdit", editingidx);
editingidx = -1;
setGrid.datagrid("unselectAll");
setGrid.datagrid("selectRow", index);
}
});
setGrid.datagrid("loadData", filters);
for (var i = 0; i < filters.length; i++) {
if (filters[i].chked) {
var idx = setGrid.datagrid("getRowIndex", filters[i]);
setGrid.datagrid("checkRow", idx);
}
}
setWindow.find("a[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
el.onclick = function () {
if (onOK) {
$endGridEdit(setGrid);
var chks = setGrid.datagrid("getChecked");
var filters = setGrid.datagrid("getRows");
setFiltersChk(filters, chks);//根据选择框数据设置filters
saveColFilterParms(key, JSON.stringify(filters));
setCol2Grid(setGrid, fields, filters, grid);
onOK(filters);
setWindow.window('close');
}
};
}
if (co.caction == "act_cancel") {
el.onclick = function () {
setWindow.window('close');
}
}
if (co.caction == 'act_select') {
el.onclick = function () {
var selecteds = setGrid.datagrid('getChecked');
if (selecteds.length == 0) {
setGrid.datagrid("checkAll");
} else {
setGrid.datagrid("uncheckAll");
}
}
}
if (co.caction == 'act_moveDown') {
el.onclick = function () {
var strow = setGrid.datagrid('getSelected');
if (strow == null)
return;
var datas = setGrid.datagrid("getRows");
var idx = setGrid.datagrid("getRowIndex", strow);
if (idx < 0) return;
if (idx >= (datas.length - 1)) return;
var rtem = datas[idx + 1];
strow.sidx = strow.sidx + 1;
datas[idx + 1] = strow;
rtem.sidx = rtem.sidx - 1;
datas[idx] = rtem;
setGrid.datagrid("loadData", datas);
setGrid.datagrid("selectRow", idx + 1);
}
}
if (co.caction == 'act_moveUp') {
el.onclick = function () {
var strow = setGrid.datagrid('getSelected');
if (strow == null)
return;
var datas = setGrid.datagrid("getRows");
var idx = setGrid.datagrid("getRowIndex", strow);
if (idx <= 0) return;
var rtem = datas[idx - 1];
strow.sidx = strow.sidx - 1;
datas[idx - 1] = strow;
rtem.sidx = rtem.sidx + 1;
datas[idx] = rtem;
setGrid.datagrid("loadData", datas);
setGrid.datagrid("selectRow", idx - 1);
}
}
if (co.caction == 'act_reset') {
el.onclick = function () {
var filters = createFitlters(defaultfields);
setGrid.datagrid("loadData", filters);
}
}
});
setWindow.window("open");
}
function createFitlters(fields) {
var rows = [];
var idx = 0;
for (var i = 0; i < fields.length; i++) {
for (var j = 0; j < fields[i].length; j++) {
var row = {};
row.sidx = idx++;
row.field = fields[i][j].field;
row.title = fields[i][j].title;
row.width = fields[i][j].width;
row.chked = fields[i][j].hidden;
row.halign = (fields[i][j].halign) ? fields[i][j].halign : "center";
rows.push(row);
}
}
return rows;
}
function setFiltersChk(filters, chks) {
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
filter.chked = isChecked(filter.field);
}
function isChecked(fdname) {
for (var i = 0; i < chks.length; i++) {
if (chks[i].field == fdname) {
return true;
}
}
return false;
}
}
function setCol2Grid(setGrid, fields, filters, grid) {
fields = getColFieldsByColFilter(fields, filters);
grid.datagrid({columns: fields});
}
function saveColFilterParms(key, value) {
localStorage.setItem(key, value);
}
function getColFieldsByColFilter(fields, filters) {
for (var i = 0; i < fields.length; i++) {
for (var j = 0; j < fields[i].length; j++) {
var field = fields[i][j];
var filter = getFilterByFdname(field.field);
if (filter) {
field.title = filter.title;
field.width = filter.width;
field.hidden = filter.chked;
field.halign = (filter.halign) ? filter.halign : 'center';
}
}
}
return fields;
function getFilterByFdname(fdname) {
for (var i = 0; i < filters.length; i++) {
if (fdname == filters[i].field)
return filters[i];
}
return null;
}
}
function $endGridEdit(oGrid) {
var rows = oGrid.datagrid("getRows");
for (var i = 0; i < rows.length; i++) {
oGrid.datagrid('endEdit', i);
}
}
function $HeartBeat(parms) {
var url = (parms && parms.url) ? parms.url : _serUrl + "/web/common/heartbeat.co";
var delay = (parms && parms.delay) ? parms.delay : 1000 * 60 * 5;//默认5分钟
var istoped = false;
function getajaxhb() {
//alert(getajaxhb);
$ajaxjsonget(url, function (jsdata) {
if (!istoped) {
window.setTimeout(function () {
getajaxhb();
}, delay);
}
}, function (msg) {
return;
}, true, undefined, true);
}
this.start = start;
function start(dly) {
istoped = false;
if (dly != undefined)
window.setTimeout(function () {
getajaxhb();
}, dly);
else
getajaxhb();
}
this.stop = stop;
function stop() {
istoped = true;
}
}
//console.log(unique(m));
<file_sep>/src/com/hr/.svn/pristine/fb/fbf6890ebfcd92455e4be006d7b84411eb283550.svn-base
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "批量补签申请行")
public class Hrkq_resignbatchline extends CJPA {
@CFieldinfo(fieldname = "resblid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "补签行ID", datetype = Types.INTEGER)
public CField resblid; // 补签行ID
@CFieldinfo(fieldname = "resbid", notnull = true, precision = 10, scale = 0, caption = "补签ID", datetype = Types.INTEGER)
public CField resbid; // 补签ID
@CFieldinfo(fieldname = "er_id", notnull = true, precision = 10, scale = 0, caption = "申请人档案ID", datetype = Types.INTEGER)
public CField er_id; // 申请人档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, precision = 16, scale = 0, caption = "申请人工号", datetype = Types.VARCHAR)
public CField employee_code; // 申请人工号
@CFieldinfo(fieldname = "employee_name", notnull = true, precision = 64, scale = 0, caption = "申请人姓名", datetype = Types.VARCHAR)
public CField employee_name; // 申请人姓名
@CFieldinfo(fieldname = "orgid", notnull = true, precision = 10, scale = 0, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, precision = 16, scale = 0, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, precision = 128, scale = 0, caption = "部门名称", datetype = Types.VARCHAR)
public CField orgname; // 部门名称
@CFieldinfo(fieldname = "ospid", notnull = true, precision = 20, scale = 0, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, precision = 16, scale = 0, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, precision = 128, scale = 0, caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称
@CFieldinfo(fieldname = "lv_num", notnull = true, precision = 4, scale = 1, caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "kqdate", precision = 10, scale = 0, caption = "考勤日期", datetype = Types.DATE)
public CField kqdate; // 考勤日期
@CFieldinfo(fieldname = "bcno", precision = 64, scale = 0, caption = "班次号", datetype = Types.VARCHAR)
public CField bcno; // 班次号
@CFieldinfo(fieldname = "rgtime", notnull = true, precision = 5, scale = 0, caption = "打卡时间", datetype = Types.VARCHAR)
public CField rgtime; // 打卡时间
@CFieldinfo(fieldname = "sclid", precision = 10, scale = 0, caption = "班次行ID", defvalue = "1", datetype = Types.INTEGER)
public CField sclid; // 班次行ID
@CFieldinfo(fieldname = "scid", precision = 10, scale = 0, caption = "班次ID", datetype = Types.INTEGER)
public CField scid; // 班次ID
@CFieldinfo(fieldname = "scdname", precision = 16, scale = 0, caption = "班次名", datetype = Types.VARCHAR)
public CField scdname; // 班次名
@CFieldinfo(fieldname = "sxb", precision = 1, scale = 0, caption = "1 上班 2 下班", defvalue = "1", datetype = Types.INTEGER)
public CField sxb; // 1 上班 2 下班
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_resignbatchline() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/salary/co/COHr_salary_list.java
package com.hr.salary.co;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CJPASqlUtil;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.salary.entity.Hr_salary_chglg;
import com.hr.salary.entity.Hr_salary_list;
import com.hr.salary.entity.Hr_salary_orgminstandard;
import com.hr.salary.entity.Hr_salary_structure;
import com.hr.util.HRUtil;
@ACO(coname = "web.hrsalary.list")
public class COHr_salary_list {
@ACOAction(eventname = "impsalarylistexcel", Authentication = true, ispublic = false, notes = "导入薪资明细")
public String impsalarylistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_salary_list(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_salary_list(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_salary_list(aSheet, batchno);
}
private int parserExcelSheet_salary_list(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_salary_list();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
CJPALineData<Hr_salary_list> newsllists = new CJPALineData<Hr_salary_list>(Hr_salary_list.class);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
int rst = 0;
for (Map<String, String> v : values) {
int m=rst%2000;
if(m==0){
if (newsllists.size() > 0) {
System.out.println("====================导入工资明细条数【" + newsllists.size() + "】");
newsllists.saveBatchSimple();// 高速存储
}
newsllists.clear();
}
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("薪资明细上的工号不能为空");
int wgtype = Integer.valueOf(dictemp.getVbCE("1447", v.get("wagetype"), false, "员工【" + employee_code + "】薪资类型【" + v.get("wagetype")
+ "】不存在"));//薪资类型
if(wgtype==2){
throw new Exception("工号为【"+employee_code+"】的薪资类型为非月薪人员,不正确!");
}
Hr_employee emp = new Hr_employee();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
Hr_orgposition sp=new Hr_orgposition();
sp.findByID(emp.ospid.getValue());
if(sp.isEmpty())
throw new Exception("工号【" + employee_code + "】的ID为【"+emp.ospid.getValue()+"】的职位不存在");
Hr_salary_list sall = new Hr_salary_list();
sall.remark.setValue(v.get("remark")); // 备注
sall.yearmonth.setValue(v.get("yearmonth")); // 年月
sall.er_id.setValue(emp.er_id.getValue()); // 人事档案id
sall.employee_code.setValue(emp.employee_code.getValue()); // 申请人工号
sall.employee_name.setValue(emp.employee_name.getValue()); // 姓名
sall.orgid.setValue(emp.orgid.getValue()); // 部门
sall.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
sall.orgname.setValue(emp.orgname.getValue()); // 部门名称
sall.idpath.setValue(emp.idpath.getValue()); // idpath
sall.ospid.setValue(emp.ospid.getValue()); // 职位id
sall.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(emp.lv_id.getValue()); // 职级id
sall.lv_num.setValue(emp.lv_num.getValue()); // 职级
sall.hg_id.setValue(emp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(emp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(sp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(sp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(sp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(sp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(sp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(sp.hwc_namezz.getValue()); // 职种
sall.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
String imporgname = v.get("orgname");
String impspname = v.get("sp_name");
if (((imporgname != null))&&((impspname != null) )){
//if(!imporgname.equals(emp.orgname.getValue())){
Shworg imporg=new Shworg();
imporg.findBySQL("select * from shworg where extorgname='"+imporgname+"'");
if(!imporg.isEmpty()){
sall.orgid.setValue(imporg.orgid.getValue()); // 部门
sall.orgcode.setValue(imporg.code.getValue()); // 部门编码
sall.orgname.setValue(imporg.extorgname.getValue()); // 部门名称
sall.idpath.setValue(imporg.idpath.getValue()); // idpath
}
//}
Hr_orgposition impsp=new Hr_orgposition();
impsp.findBySQL("SELECT * FROM `hr_orgposition` WHERE sp_name='"+impspname+"' AND idpath ='"+imporg.idpath.getValue()+"'");
if(!impsp.isEmpty()){
sall.ospid.setValue(impsp.ospid.getValue()); // 职位id
sall.ospcode.setValue(impsp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(impsp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(impsp.lv_id.getValue()); // 职级id
sall.lv_num.setValue(impsp.lv_num.getValue()); // 职级
sall.hg_id.setValue(impsp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(impsp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(impsp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(impsp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(impsp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(impsp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(impsp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(impsp.hwc_namezz.getValue()); // 职种
}
}
String struname=v.get("stru_name");
Hr_salary_structure ss=new Hr_salary_structure();
ss.findBySQL("select * from hr_salary_structure where stat=9 and stru_name='"+struname+"'");
if(ss.isEmpty()){
throw new Exception("工号为【"+employee_code+"】的工资结构【"+struname+"】不存在!");
}
sall.stru_id.setValue(ss.stru_id.getValue()); // 工资结构id
sall.stru_name.setValue(ss.stru_name.getValue()); // 工资结构
sall.poswage.setValue(v.get("poswage")); // 职位工资
float poswage=Float.parseFloat(v.get("poswage"));
if(ss.strutype.getAsInt()==1){
float minstand=0;
String sqlstr="SELECT * FROM `hr_salary_orgminstandard` WHERE stat=9 AND usable=1 AND INSTR('"+emp.idpath.getValue()+"',idpath)=1 ORDER BY idpath DESC ";
Hr_salary_orgminstandard oms=new Hr_salary_orgminstandard();
oms.findBySQL(sqlstr);
if(oms.isEmpty()){
minstand=0;
}else{
minstand=oms.minstandard.getAsFloatDefault(0);
}
float bw=(poswage*ss.basewage.getAsFloatDefault(0))/100;
float bow=(poswage*ss.otwage.getAsFloatDefault(0))/100;
float sw=(poswage*ss.skillwage.getAsFloatDefault(0))/100;
float pw=(poswage*ss.meritwage.getAsFloatDefault(0))/100;
if(minstand>bw){
if((bw+bow)>minstand){
bow=bw+bow-minstand;
bw=minstand;
}else if((bw+bow+sw)>minstand){
sw=bw+bow+sw-minstand;
bow=0;
bw=minstand;
}else if((bw+bow+sw+pw)>minstand){
pw=bw+bow+sw+pw-minstand;
sw=0;
bow=0;
bw=minstand;
}else{
bw=poswage;
pw=0;
sw=0;
bow=0;
}
}
DecimalFormat df=new DecimalFormat(".00");
sall.basewage.setValue(df.format(bw)); // 基本工资
sall.baseotwage.setValue(df.format(bow)); // 固定加班工资
sall.skillwage.setValue(df.format(sw)); // 技能工资
sall.perforwage.setValue(df.format(pw)); // 绩效工资
}else{
sall.basewage.setValue(v.get("basewage")); // 基本工资
sall.baseotwage.setValue(v.get("baseotwage")); // 固定加班工资
sall.skillwage.setValue(v.get("skillwage")); // 技能工资
sall.perforwage.setValue(v.get("perforwage")); // 绩效工资
}
sall.skillsubs.setValue(v.get("skillsubs")); // 技能津贴
sall.parttimesubs.setValue(v.get("parttimesubs")); // 兼职津贴
sall.postsubs.setValue(v.get("postsubs")); // 岗位津贴
sall.wagetype.setValue(wgtype);//薪资类型
sall.usable.setAsInt(1);//有效
newsllists.add(sall);
rst++;
}
if (newsllists.size() > 0) {
System.out.println("====================导入月薪人员工资明细条数【" + newsllists.size() + "】");
newsllists.saveBatchSimple();// 高速存储
}
newsllists.clear();
return rst;
}
private List<CExcelField> initExcelFields_salary_list() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("年月", "yearmonth", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("工资结构", "stru_name", true));
efields.add(new CExcelField("薪资类型", "wagetype", true));
efields.add(new CExcelField("职位工资", "poswage", true));
efields.add(new CExcelField("基本工资", "basewage", true));
efields.add(new CExcelField("固定加班工资", "baseotwage", true));
efields.add(new CExcelField("技能工资", "skillwage", true));
efields.add(new CExcelField("绩效工资", "perforwage", true));
efields.add(new CExcelField("技术津贴", "skillsubs", true));
efields.add(new CExcelField("兼职津贴", "parttimesubs", true));
efields.add(new CExcelField("岗位津贴", "postsubs", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "impsalarynotmonthlistexcel", Authentication = true, ispublic = false, notes = "导入非月薪人员薪资明细")
public String impsalarynotmonthlistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_salarynotmonth_list(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_salarynotmonth_list(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_salarynoymonth_list(aSheet, batchno);
}
private int parserExcelSheet_salarynoymonth_list(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_salarynotmonth_list();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
CJPALineData<Hr_salary_list> newsllists = new CJPALineData<Hr_salary_list>(Hr_salary_list.class);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
int rst = 0;
for (Map<String, String> v : values) {
int m=rst%2000;
if(m==0){
if (newsllists.size() > 0) {
System.out.println("====================导入工资明细条数【" + newsllists.size() + "】");
newsllists.saveBatchSimple();// 高速存储
}
newsllists.clear();
}
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("薪资明细上的工号不能为空");
int wgtype = Integer.valueOf(dictemp.getVbCE("1447", v.get("wagetype"), false, "员工【" + employee_code + "】薪资类型【" + v.get("wagetype")
+ "】不存在"));//薪资类型
if(wgtype==1){
throw new Exception("工号为【"+employee_code+"】的薪资类型为月薪人员,不正确!");
}
Hr_employee emp = new Hr_employee();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
Hr_orgposition sp=new Hr_orgposition();
sp.findByID(emp.ospid.getValue());
if(sp.isEmpty())
throw new Exception("工号【" + employee_code + "】的ID为【"+emp.ospid.getValue()+"】的职位不存在");
Hr_salary_list sall = new Hr_salary_list();
sall.remark.setValue(v.get("remark")); // 备注
sall.yearmonth.setValue(v.get("yearmonth")); // 年月
sall.er_id.setValue(emp.er_id.getValue()); // 人事档案id
sall.employee_code.setValue(emp.employee_code.getValue()); // 申请人工号
sall.employee_name.setValue(emp.employee_name.getValue()); // 姓名
sall.orgid.setValue(emp.orgid.getValue()); // 部门
sall.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
sall.orgname.setValue(emp.orgname.getValue()); // 部门名称
sall.ospid.setValue(emp.ospid.getValue()); // 职位id
sall.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(emp.lv_id.getValue()); // 职级id
sall.idpath.setValue(emp.idpath.getValue()); // idpath
sall.lv_num.setValue(emp.lv_num.getValue()); // 职级
sall.hg_id.setValue(emp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(emp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(sp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(sp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(sp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(sp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(sp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(sp.hwc_namezz.getValue()); // 职种
sall.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
String imporgname = v.get("orgname");
String impspname = v.get("sp_name");
if (((imporgname != null) )&&((impspname != null) )){
//if(!imporgname.equals(emp.orgname.getValue())){
Shworg imporg=new Shworg();
imporg.findBySQL("select * from shworg where extorgname='"+imporgname+"'");
if(!imporg.isEmpty()){
sall.orgid.setValue(imporg.orgid.getValue()); // 部门
sall.orgcode.setValue(imporg.code.getValue()); // 部门编码
sall.orgname.setValue(imporg.extorgname.getValue()); // 部门名称
sall.idpath.setValue(imporg.idpath.getValue()); // idpath
}
//}
Hr_orgposition impsp=new Hr_orgposition();
impsp.findBySQL("SELECT * FROM `hr_orgposition` WHERE sp_name='"+impspname+"' AND idpath ='"+imporg.idpath.getValue()+"'");
if(!impsp.isEmpty()){
sall.ospid.setValue(impsp.ospid.getValue()); // 职位id
sall.ospcode.setValue(impsp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(impsp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(impsp.lv_id.getValue()); // 职级id
sall.lv_num.setValue(impsp.lv_num.getValue()); // 职级
sall.hg_id.setValue(impsp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(impsp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(impsp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(impsp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(impsp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(impsp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(impsp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(impsp.hwc_namezz.getValue()); // 职种
}
}
String fullattend = dictemp.getVbCE("5", v.get("isfullattend"), false, "员工【" + emp.employee_name.getValue() + "】是否满勤【" + v.get("isfullattend")
+ "】不存在");
sall.isfullattend.setValue(fullattend); // 是否满勤
sall.baseattend.setValue(v.get("baseattend")); // 基本出勤
sall.normalot.setValue(v.get("normalot")); // 平时加班工资
sall.restot.setValue(v.get("restot")); // 休息加班工资
sall.tworkhours.setValue(v.get("tworkhours")); // 总工时
sall.paynosubs.setValue(v.get("paynosubs")); // 无津贴应发
sall.paywsubs.setValue(v.get("paywsubs")); // 有津贴应发
sall.wagetype.setValue(wgtype);//薪资类型
sall.usable.setAsInt(1);//有效
newsllists.add(sall);
rst++;
}
if (newsllists.size() > 0) {
System.out.println("====================导入工资明细条数【" + newsllists.size() + "】");
newsllists.saveBatchSimple();// 高速存储
}
newsllists.clear();
return rst;
}
private List<CExcelField> initExcelFields_salarynotmonth_list() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("年月", "yearmonth", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("薪资类型", "wagetype", true));
efields.add(new CExcelField("是否满勤", "isfullattend", true));
efields.add(new CExcelField("基本出勤", "baseattend", true));
efields.add(new CExcelField("平时加班工时", "normalot", true));
efields.add(new CExcelField("休息加班工时", "restot", true));
efields.add(new CExcelField("总工时", "tworkhours", true));
efields.add(new CExcelField("不含津贴应发", "paynosubs", true));
efields.add(new CExcelField("含津贴应发", "paywsubs", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "findsalarylists", Authentication = true, ispublic = true, notes = "获取月薪人员薪资明细")
public String findsalarylists() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jpym = CjpaUtil.getParm(jps, "yearmonth");
if (jpym == null)
throw new Exception("需要参数【yearmonth】");
String yearmonth = jpym.getParmvalue();
String ymrelator=jpym.getReloper();
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
Shworg org = new Shworg();
if (jporgcode != null){
String orgcode = jporgcode.getParmvalue();
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
}
boolean hasaccessed=true;
if (!HRUtil.hasRoles("71")) {// 薪酬管理角色
hasaccessed= false; // 不是薪酬管理角色
}
String[] ignParms = { "wgtype","yearmonth","orgcode" };// 忽略的查询条件
String[] notnull = {};
String sqlstr="SELECT * FROM hr_salary_list sl WHERE wagetype=1 AND yearmonth";
if(ymrelator.equals("<=")){
sqlstr=sqlstr+"<=";
}
if(ymrelator.equals(">=")){
sqlstr=sqlstr+">=";
}
if(ymrelator.equals("=")){
sqlstr=sqlstr+"=";
}
sqlstr=sqlstr+"'"+yearmonth+"' "+ CSContext.getIdpathwhere();
if (jporgcode != null){
sqlstr=sqlstr+" and sl.idpath LIKE '"+org.idpath.getValue()+"%' ";
}
if(!hasaccessed){
sqlstr=sqlstr+" and employee_code='"+CSContext.getUserName()+"' ";
}
sqlstr=sqlstr+" ORDER BY orgid";
return new CReport(sqlstr, notnull).findReport(ignParms,null);
}
@ACOAction(eventname = "findsalarylistsnotmonth", Authentication = true, ispublic = true, notes = "获取非月薪人员薪资明细")
public String findsalarylistsnotmonth() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jpym = CjpaUtil.getParm(jps, "yearmonth");
if (jpym == null)
throw new Exception("需要参数【yearmonth】");
String yearmonth = jpym.getParmvalue();
String ymrelator=jpym.getReloper();
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
Shworg org = new Shworg();
if (jporgcode != null){
String orgcode = jporgcode.getParmvalue();
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
}
boolean hasaccessed=true;
if (!HRUtil.hasRoles("71")) {// 薪酬管理角色
hasaccessed= false; // 不是薪酬管理角色
}
String[] ignParms = { "wgtype","yearmonth","orgcode" };// 忽略的查询条件
String[] notnull = {};
String sqlstr="SELECT * FROM hr_salary_list sl WHERE wagetype=2 AND yearmonth";
if(ymrelator.equals("<=")){
sqlstr=sqlstr+"<=";
}
if(ymrelator.equals(">=")){
sqlstr=sqlstr+">=";
}
if(ymrelator.equals("=")){
sqlstr=sqlstr+"=";
}
sqlstr=sqlstr+"'"+yearmonth+"' "+ CSContext.getIdpathwhere();
if (jporgcode != null){
sqlstr=sqlstr+" and sl.idpath LIKE '"+org.idpath.getValue()+"%' ";
}
if(!hasaccessed){
sqlstr=sqlstr+" and employee_code='"+CSContext.getUserName()+"' ";
}
sqlstr=sqlstr+" ORDER BY orgid";
return new CReport(sqlstr, notnull).findReport(ignParms,null);
}
@ACOAction(eventname = "findsalarychglgs", Authentication = true, ispublic = true, notes = "获取薪资变更记录")
public String findsalarychglgs() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
Date bgdate=null;
String bgymrelator=null;
Date eddate=null;
String edymrelator=null;
for(JSONParm param :jps){
String parmname = param.getParmname();
int idx = parmname.lastIndexOf('.');
String fn = (idx == -1) ? parmname : parmname.substring(idx + 1);
if ("chgdate".equalsIgnoreCase(fn)){
String yearmonth = param.getParmvalue();
String ymrelator=param.getReloper();
//Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
if(ymrelator.equals("<")||ymrelator.equals("<=")){
//if(ymrelator.equals("<")){
edymrelator=ymrelator;
eddate=Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
// }
}
else if(ymrelator.equals(">")||ymrelator.equals(">=")){
// if(ymrelator.equals(">")){
bgymrelator=ymrelator;
bgdate=Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
// }
}
else{
bgymrelator=ymrelator;
bgdate=Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
}
}
}
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
Shworg org = new Shworg();
if (jporgcode != null){
String orgcode = jporgcode.getParmvalue();
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
}
boolean hasaccessed=true;
if (!HRUtil.hasRoles("71")) {// 薪酬管理角色
hasaccessed= false; // 不是薪酬管理角色
}
String[] ignParms = { "chgdate","orgcode" };// 忽略的查询条件
String[] notnull = {};
String sqlstr=null;
if(bgdate==null && eddate==null){
sqlstr="SELECT cl.*,emp.employee_code,emp.employee_name,emp.hiredday,emp.idpath "+
" FROM `hr_salary_chglg` cl,`hr_employee` emp WHERE cl.er_id=emp.er_id AND emp.pay_way='月薪'"+ CSContext.getIdpathwhere();
}
else if(bgdate!=null && eddate!=null){
sqlstr="SELECT cl.*,emp.employee_code,emp.employee_name,emp.hiredday,emp.idpath "+
" FROM `hr_salary_chglg` cl,`hr_employee` emp WHERE cl.er_id=emp.er_id AND emp.pay_way='月薪' AND cl.chgdate"+bgymrelator+"'"+
Systemdate.getStrDateyyyy_mm_dd(bgdate)+"' and cl.chgdate"+edymrelator+"'"+Systemdate.getStrDateyyyy_mm_dd(eddate)+"' "+ CSContext.getIdpathwhere();
}else if(bgdate!=null && eddate==null){
sqlstr="SELECT cl.*,emp.employee_code,emp.employee_name,emp.hiredday,emp.idpath "+
" FROM `hr_salary_chglg` cl,`hr_employee` emp WHERE cl.er_id=emp.er_id AND emp.pay_way='月薪' AND cl.chgdate"+bgymrelator+"'"+
Systemdate.getStrDateyyyy_mm_dd(bgdate)+"'" + CSContext.getIdpathwhere();
}else if(bgdate==null && eddate!=null){
sqlstr="SELECT cl.*,emp.employee_code,emp.employee_name,emp.hiredday,emp.idpath "+
" FROM `hr_salary_chglg` cl,`hr_employee` emp WHERE cl.er_id=emp.er_id AND emp.pay_way='月薪' AND cl.chgdate"+edymrelator+"'"+Systemdate.getStrDateyyyy_mm_dd(eddate)+"' "+ CSContext.getIdpathwhere();
}
if (jporgcode != null){
sqlstr=sqlstr+" and emp.idpath LIKE '"+org.idpath.getValue()+"%' ";
}
if(!hasaccessed){
sqlstr=sqlstr+" and emp.employee_code='"+CSContext.getUserName()+"' ";
}
sqlstr=sqlstr+" ORDER BY emp.orgid,emp.er_id";
String orderstr="chgdate desc";
return new CReport(sqlstr,orderstr, notnull).findReport(ignParms,null);
}
@ACOAction(eventname = "impsalarychglgexcel", Authentication = true, ispublic = false, notes = "导入薪资变动记录")
public String impsalarychglgexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
/*JSONObject result = new JSONObject();
if (!HRUtil.hasRoles("19")) {// 薪酬管理员
result.put("accessed", 2);
//return result.toString();
throw new Exception("当前登录用户没有权限使用该功能!");
}*/
HashMap<String, String> parms = CSContext.getParms();
String chgdate = CorUtil.hashMap2Str(parms, "chgdate", "需要参数chgdate");
String imptype = CorUtil.hashMap2Str(parms, "imptype");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_salary_chglg(p, batchno,chgdate,imptype);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_salary_chglg(Shw_physic_file pf, String batchno,String chgdate,String imptype) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_salary_chglg(aSheet, batchno,chgdate,imptype);
}
private int parserExcelSheet_salary_chglg(Sheet aSheet, String batchno,String chgdate,String imptype) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_salary_chglg();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
CJPALineData<Hr_salary_chglg> newchglgs = new CJPALineData<Hr_salary_chglg>(Hr_salary_chglg.class);
int rst = 0;
Date cd = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(chgdate)));// 去除时分秒
Date bgdate=Systemdate.getFirstAndLastOfMonth(cd).date1;
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
int ipt= imptype != null? Integer.parseInt(imptype):1; //导入类型。 1、按工资结构核算;2、历史数据,无工资结构
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
Shworg org = new Shworg();
CDBConnection con = org.pool.getCon(this);
con.startTrans();
try{
for (Map<String, String> v : values) {
int m=rst%2000;
if(m==0){
if (newchglgs.size() > 0) {
System.out.println("====================导入工资明细条数【" + newchglgs.size() + "】");
if(ipt==1){
newchglgs.save(con);// 高速存储
}else if(ipt==2){
newchglgs.saveBathcSiple(con);
}
}
newchglgs.clear();
}
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("薪资明细上的工号不能为空");
Hr_employee emp = new Hr_employee();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
Hr_salary_chglg cgl = new Hr_salary_chglg();
Hr_salary_chglg oldcgl = new Hr_salary_chglg();
cgl.remark.setValue(v.get("remark")); // 备注
cgl.er_id.setValue(emp.er_id.getValue()); // 人事档案id
cgl.orgid.setValue(emp.orgid.getValue()); // 机构id
cgl.orgname.setValue(emp.orgname.getValue()); // 机构
cgl.lv_num.setValue(emp.lv_num.getValue()); // 职级
cgl.ospid.setValue(emp.ospid.getValue()); // 职位id
cgl.sp_name.setValue(emp.sp_name.getValue()); // 职位
cgl.newcalsalarytype.setValue(emp.pay_way.getValue()); // 调薪后计薪方式
String chgreason="导入薪资变动记录";
cgl.sid.setValue(0); //
cgl.scode.setValue(0); //
int stype = Integer.valueOf(dictemp.getVbCE("1482", v.get("stype"), false, "员工【" + emp.employee_name.getValue() + "】的异动类型【" + v.get("stype")
+ "】不存在"));
int scatype=0;
if(stype==1){
scatype=0;
}
if(stype==3){
scatype=1;
chgreason=chgreason+"-入职定薪";
}
if(stype==4){
scatype=2;
chgreason=chgreason+"-调动核薪";
}
if((stype==5)||(stype==6)){
scatype=3;
chgreason=chgreason+"-入职转正/调动转正";
}
if((stype==7)||(stype==9)){
scatype=5;
chgreason=chgreason+"-特殊调薪";
}
if(stype==12){
scatype=4;
chgreason=chgreason+"-年度调薪";
}
if(stype==8){
chgreason=chgreason+"-兼职津贴";
}
if(stype==10){
chgreason=chgreason+"-技术津贴";
}
if(stype==11){
chgreason=chgreason+"-岗位津贴";
}
cgl.scatype.setAsInt(scatype); // 变更类型 导入无类型
cgl.stype.setAsInt(stype); // 来源类型 历史数据
cgl.useable.setAsInt(1);//有效
cgl.chgdate.setValue(Systemdate.getStrDateyyyy_mm_dd(bgdate));//调薪日期
cgl.chgreason.setValue(chgreason);//调薪原因
BigDecimal poswage=new BigDecimal(v.get("poswage"));// 职位工资
if(ipt==1){
String struname=v.get("stru_name");
Hr_salary_structure ss=new Hr_salary_structure();
ss.findBySQL("select * from hr_salary_structure where stat=9 and stru_name='"+struname+"'");
if(ss.isEmpty()){
throw new Exception("工号为【"+employee_code+"】的工资结构【"+struname+"】不存在!");
}
cgl.newstru_id.setValue(ss.stru_id.getValue()); // 工资结构id
cgl.newstru_name.setValue(ss.stru_name.getValue()); // 工资结构
cgl.newchecklev.setValue(ss.checklev.getValue()); // 工资结构id
cgl.newattendtype.setValue(ss.kqtype.getValue()); // 工资结构
cgl.newposition_salary.setValue(v.get("poswage")); // 职位工资
if(ss.strutype.getAsInt()==1){
BigDecimal minstand=BigDecimal.ZERO;
String minsqlstr="SELECT * FROM `hr_salary_orgminstandard` WHERE stat=9 AND usable=1 AND INSTR('"+emp.idpath.getValue()+"',idpath)=1 ORDER BY idpath DESC ";
Hr_salary_orgminstandard oms=new Hr_salary_orgminstandard();
oms.findBySQL(minsqlstr);
if(oms.isEmpty()){
minstand=BigDecimal.ZERO;
}else{
minstand=new BigDecimal(oms.minstandard.getValue());
}
BigDecimal hd=new BigDecimal("100");
BigDecimal bw=poswage.multiply(new BigDecimal(ss.basewage.getValue())).divide(hd);
BigDecimal bow=poswage.multiply(new BigDecimal(ss.otwage.getValue())).divide(hd);
BigDecimal sw=poswage.multiply(new BigDecimal(ss.skillwage.getValue())).divide(hd);
BigDecimal pw=poswage.multiply(new BigDecimal(ss.meritwage.getValue())).divide(hd);
if(minstand.compareTo(bw)==1){
if((bw.add(bow)).compareTo(minstand)==1){
bow=bw.add(bow).subtract(minstand);
bw=minstand;
}else if((bw.add(bow).add(sw)).compareTo(minstand)==1){
sw=bw.add(bow).add(sw).subtract(minstand);
bow=BigDecimal.ZERO;
bw=minstand;
}else if((bw.add(bow).add(sw).add(pw)).compareTo(minstand)==1){
pw=bw.add(bow).add(sw).add(pw).subtract(minstand);
sw=BigDecimal.ZERO;
bow=BigDecimal.ZERO;
bw=minstand;
}else{
bw=poswage;
pw=BigDecimal.ZERO;
sw=BigDecimal.ZERO;
bow=BigDecimal.ZERO;
}
}
//DecimalFormat df=new DecimalFormat(".00");
cgl.newbase_salary.setValue(bw.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // 基本工资
cgl.newotwage.setValue(bow.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // 固定加班工资
cgl.newtech_salary.setValue(sw.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // 技能工资
cgl.newachi_salary.setValue(pw.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // 绩效工资
}else{
cgl.newbase_salary.setValue(v.get("basewage")); // 基本工资
cgl.newotwage.setValue(v.get("baseotwage")); // 固定加班工资
cgl.newtech_salary.setValue(v.get("skillwage")); // 技能工资
cgl.newachi_salary.setValue(v.get("perforwage")); // 绩效工资
}
}else if(ipt==2){
cgl.orgid.setValue("0"); // 机构id
cgl.orgname.setValue(v.get("orgname")); // 机构
cgl.lv_num.setValue(v.get("lv_num")); // 职级
cgl.ospid.setValue("0"); // 职位id
cgl.sp_name.setValue(v.get("sp_name")); // 职位
cgl.oldstru_id.setValue("0"); // 工资结构id
cgl.oldstru_name.setValue(v.get("oldstru_name")); // 工资结构
cgl.oldchecklev.setValue("0"); // 绩效层级
cgl.oldattendtype.setValue("0"); // 出勤类别
cgl.oldposition_salary.setValue(v.get("oldposwage")); // 职位工资
cgl.oldbase_salary.setValue(v.get("oldbasewage")); // 基本工资
cgl.oldotwage.setValue(v.get("oldbaseotwage")); // 固定加班工资
cgl.oldtech_salary.setValue(v.get("oldskillwage")); // 技能工资
cgl.oldachi_salary.setValue(v.get("oldperforwage")); // 绩效工资
cgl.oldtech_allowance.setValue(v.get("oldskillsubs")); // 技能津贴
cgl.oldparttimesubs.setValue(v.get("oldparttimesubs")); // 兼职津贴
cgl.oldpostsubs.setValue(v.get("oldpostsubs")); // 岗位津贴
cgl.newstru_id.setValue("0"); // 工资结构id
cgl.newstru_name.setValue(v.get("stru_name")); // 工资结构
cgl.newchecklev.setValue("0"); // 工资结构id
cgl.newattendtype.setValue("0"); // 工资结构
cgl.newposition_salary.setValue(v.get("poswage")); // 职位工资
cgl.newbase_salary.setValue(v.get("basewage")); // 基本工资
cgl.newotwage.setValue(v.get("baseotwage")); // 固定加班工资
cgl.newtech_salary.setValue(v.get("skillwage")); // 技能工资
cgl.newachi_salary.setValue(v.get("perforwage")); // 绩效工资
cgl.useable.setAsInt(2);//有效
cgl.chgdate.setValue(v.get("chgdate")); // 生效月份
String oldstru=v.get("oldstru_name");
String newstru=v.get("stru_name");
Hr_salary_structure tss=new Hr_salary_structure();
tss.findBySQL("select * from hr_salary_structure where stat=9 and stru_name='"+newstru+"'");
if(!tss.isEmpty()){
cgl.newstru_id.setValue(tss.stru_id.getValue()); // 工资结构id
cgl.newstru_name.setValue(v.get("stru_name")); // 工资结构
cgl.newchecklev.setValue(tss.checklev.getValue()); // 工资结构id
cgl.newattendtype.setValue(tss.kqtype.getValue()); // 工资结构
}
tss.clear();
tss.findBySQL("select * from hr_salary_structure where stat=9 and stru_name='"+oldstru+"'");
if(!tss.isEmpty()){
cgl.oldstru_id.setValue(tss.stru_id.getValue()); // 工资结构id
cgl.oldstru_name.setValue(v.get("oldstru_name")); // 工资结构
cgl.oldchecklev.setValue(tss.checklev.getValue()); // 工资结构id
cgl.oldattendtype.setValue(tss.kqtype.getValue()); // 工资结构
}
}
cgl.newtech_allowance.setValue(v.get("skillsubs")); // 技能津贴
cgl.newparttimesubs.setValue(v.get("parttimesubs")); // 兼职津贴
cgl.newpostsubs.setValue(v.get("postsubs")); // 岗位津贴
String skillsubstr=(v.get("skillsubs")==null)?"0":v.get("skillsubs");
String ptsubstr=(v.get("parttimesubs")==null)?"0":v.get("parttimesubs");
String postsubstr=(v.get("postsubs")==null)?"0":v.get("postsubs");
String opw=(v.get("oldposwage")==null)?"0":v.get("oldposwage");
String oss=(v.get("oldskillsubs")==null)?"0":v.get("oldskillsubs");
String opts=(v.get("oldparttimesubs")==null)?"0":v.get("oldparttimesubs");
String ops=(v.get("oldpostsubs")==null)?"0":v.get("oldpostsubs");
BigDecimal skillsubs=new BigDecimal(skillsubstr);
BigDecimal parttimesubs=new BigDecimal(ptsubstr);
BigDecimal postsubs=new BigDecimal(postsubstr);
BigDecimal tt=poswage.add(skillsubs).add(parttimesubs).add(postsubs);
BigDecimal oldposwage=new BigDecimal(opw);
BigDecimal oldskillsubs=new BigDecimal(oss);
BigDecimal oldparttimesubs=new BigDecimal(opts);
BigDecimal oldpostsubs=new BigDecimal(ops);
if(ipt==1){
oldcgl.findBySQL("SELECT * FROM `hr_salary_chglg` WHERE er_id="+emp.er_id.getValue()+
" and useable=1 ORDER BY createtime DESC");
if(!oldcgl.isEmpty()){
cgl.oldstru_id.setValue(oldcgl.newstru_id.getValue()); // 工资结构id
cgl.oldstru_name.setValue(oldcgl.newstru_name.getValue()); // 工资结构
cgl.oldchecklev.setValue(oldcgl.newchecklev.getValue()); // 工资结构id
cgl.oldattendtype.setValue(oldcgl.newattendtype.getValue()); // 工资结构
cgl.oldposition_salary.setValue(oldcgl.newposition_salary.getValue()); // 职位工资
cgl.oldbase_salary.setValue(oldcgl.newbase_salary.getValue()); // 基本工资
cgl.oldotwage.setValue(oldcgl.newotwage.getValue()); // 固定加班工资
cgl.oldtech_salary.setValue(oldcgl.newtech_salary.getValue()); // 技能工资
cgl.oldachi_salary.setValue(oldcgl.newachi_salary.getValue()); // 绩效工资
cgl.oldtech_allowance.setValue(oldcgl.newtech_allowance.getValue()); // 技能津贴
cgl.oldparttimesubs.setValue(oldcgl.newparttimesubs.getValue()); // 兼职津贴
cgl.oldpostsubs.setValue(oldcgl.newpostsubs.getValue()); // 岗位津贴
cgl.oldcalsalarytype.setValue(oldcgl.newcalsalarytype.getValue()); // 计薪方式
oldposwage=new BigDecimal(oldcgl.newposition_salary.getValue());
oldskillsubs=new BigDecimal(oldcgl.newtech_allowance.getValue());
oldparttimesubs=new BigDecimal(oldcgl.newparttimesubs.getValue());
oldpostsubs=new BigDecimal(oldcgl.newpostsubs.getValue());
//cgl.chgdate.setValue(oldcgl.chgdate.getValue());//调薪日期
}
}
BigDecimal sc=tt.subtract(oldposwage).subtract(oldskillsubs).subtract(oldpostsubs).subtract(oldparttimesubs);
sc=sc.setScale(2, BigDecimal.ROUND_HALF_UP);
cgl.sacrage.setValue(sc.toString());//调薪幅度
newchglgs.add(cgl);
rst++;
}
if (newchglgs.size() > 0) {
System.out.println("====================导入工资变动记录条数【" + newchglgs.size() + "】");
if(ipt==1){
newchglgs.save(con);// 高速存储
}else if(ipt==2){
newchglgs.saveBathcSiple(con);
}
}
newchglgs.clear();
con.submit();
return rst;
}catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields_salary_chglg() {
List<CExcelField> efields = new ArrayList<CExcelField>();
//efields.add(new CExcelField("年月", "yearmonth", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("异动类型", "stype", true));
efields.add(new CExcelField("生效月份", "chgdate", true));
efields.add(new CExcelField("工资结构", "stru_name", true));
efields.add(new CExcelField("职位工资", "poswage", true));
efields.add(new CExcelField("基本工资", "basewage", true));
efields.add(new CExcelField("固定加班工资", "baseotwage", true));
efields.add(new CExcelField("技能工资", "skillwage", true));
efields.add(new CExcelField("绩效工资", "perforwage", true));
efields.add(new CExcelField("技术津贴", "skillsubs", true));
efields.add(new CExcelField("兼职津贴", "parttimesubs", true));
efields.add(new CExcelField("岗位津贴", "postsubs", true));
efields.add(new CExcelField("调薪前工资结构", "oldstru_name", false));
efields.add(new CExcelField("调薪前职位工资", "oldposwage", false));
efields.add(new CExcelField("调薪前基本工资", "oldbasewage", false));
efields.add(new CExcelField("调薪前固定加班工资", "oldbaseotwage", false));
efields.add(new CExcelField("调薪前技能工资", "oldskillwage", false));
efields.add(new CExcelField("调薪前绩效工资", "oldperforwage", false));
efields.add(new CExcelField("调薪前技术津贴", "oldskillsubs", false));
efields.add(new CExcelField("调薪前兼职津贴", "oldparttimesubs", false));
efields.add(new CExcelField("调薪前岗位津贴", "oldpostsubs", false));
return efields;
}
@ACOAction(eventname = "setSalaryList", Authentication = true, ispublic = true, notes = "生成某月工资明细")
public String setSalaryList() throws Exception {
/*HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jpym = CjpaUtil.getParm(jps, "chgdate");
if (jpym == null)
throw new Exception("需要参数【chgdate】");
String yearmonth = jpym.getParmvalue();*/
HashMap<String, String> parms = CSContext.getParms();
String yearmonth = CorUtil.hashMap2Str(parms, "chgdate", "需要参数chgdate");
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
Date bfdate = Systemdate.dateMonthAdd(bgdate, -1);// 减一月
String ymbg=Systemdate.getStrDateByFmt(bgdate, "yyyy-MM");
String ymed=Systemdate.getStrDateByFmt(eddate, "yyyy-MM");
String ymbf=Systemdate.getStrDateByFmt(bfdate, "yyyy-MM");
Shworg org = new Shworg();
//String[] ignParms = { "chgdate","orgcode" };// 忽略的查询条件
//String[] notnull = {};
String sqlstr="SELECT cl.* FROM hr_salary_chglg cl,hr_employee e WHERE cl.useable=1 AND cl.newposition_salary>0 "+
"AND cl.er_id=e.er_id AND e.pay_way='月薪' AND e.empstatid<10 "+
" AND cl.er_id NOT IN (SELECT * FROM (SELECT er_id FROM hr_salary_list WHERE wagetype=1 AND yearmonth>='"+
ymbg+"' AND yearmonth<'"+ymed+"' )tt) ";
CJPALineData<Hr_salary_list> sllists = new CJPALineData<Hr_salary_list>(Hr_salary_list.class);
CJPALineData<Hr_salary_chglg> chglgs = new CJPALineData<Hr_salary_chglg>(Hr_salary_chglg.class);
chglgs.findDataBySQL(sqlstr, true, false);
CDBConnection con = org.pool.getCon(this);
con.startTrans();
int addnums=0;
try {
for (CJPABase jpa : chglgs) {
Hr_salary_chglg cl=(Hr_salary_chglg)jpa;
int m=addnums%2000;
if(m==0){
if (sllists.size() > 0) {
System.out.println("====================生成工资明细条数【" + sllists.size() + "】");
sllists.saveBatchSimple();// 高速存储
}
sllists.clear();
}
Hr_employee emp = new Hr_employee();
emp.findByID(cl.er_id.getValue());
if (emp.isEmpty())
throw new Exception("id为【" + cl.er_id.getValue() + "】不存在人事资料");
Hr_orgposition sp=new Hr_orgposition();
sp.findByID(emp.ospid.getValue());
if(sp.isEmpty())
throw new Exception("员工id为【" + cl.er_id.getValue() + "】的ID为【"+emp.ospid.getValue()+"】的职位不存在");
Hr_salary_list sall = new Hr_salary_list();
sall.remark.setValue("异动生成薪资明细"); // 备注
sall.yearmonth.setValue(yearmonth); // 年月
sall.er_id.setValue(emp.er_id.getValue()); // 人事档案id
sall.employee_code.setValue(emp.employee_code.getValue()); // 申请人工号
sall.employee_name.setValue(emp.employee_name.getValue()); // 姓名
sall.orgid.setValue(emp.orgid.getValue()); // 部门
sall.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
sall.orgname.setValue(emp.orgname.getValue()); // 部门名称
sall.idpath.setValue(emp.idpath.getValue()); // idpath
sall.ospid.setValue(emp.ospid.getValue()); // 职位id
sall.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
sall.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
sall.lv_id.setValue(emp.lv_id.getValue()); // 职级id
sall.lv_num.setValue(emp.lv_num.getValue()); // 职级
sall.hg_id.setValue(emp.hg_id.getValue()); // 职等id
sall.hg_name.setValue(emp.hg_name.getValue()); // 职等
sall.hwc_idzl.setValue(sp.hwc_idzl.getValue()); // 职类id
sall.hwc_namezl.setValue(sp.hwc_namezl.getValue()); // 职类
sall.hwc_idzq.setValue(sp.hwc_idzq.getValue()); // 职群id
sall.hwc_namezq.setValue(sp.hwc_namezq.getValue()); // 职群
sall.hwc_idzz.setValue(sp.hwc_idzz.getValue()); // 职种id
sall.hwc_namezz.setValue(sp.hwc_namezz.getValue()); // 职种
sall.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
sall.stru_id.setValue(cl.newstru_id.getValue()); // 工资结构id
sall.stru_name.setValue(cl.newstru_name.getValue()); // 工资结构
sall.poswage.setValue(cl.newposition_salary.getValue()); // 职位工资
sall.basewage.setValue(cl.newbase_salary.getValue()); // 基本工资
sall.baseotwage.setValue(cl.newotwage.getValue()); // 固定加班工资
sall.skillwage.setValue(cl.newtech_salary.getValue()); // 技能工资
sall.perforwage.setValue(cl.newachi_salary.getValue()); // 绩效工资
sall.skillsubs.setValue(cl.newtech_allowance.getValue()); // 技能津贴
sall.parttimesubs.setValue(cl.newparttimesubs.getValue()); // 兼职津贴
sall.postsubs.setValue(cl.newpostsubs.getValue()); // 岗位津贴
sall.wagetype.setAsInt(1);//薪资类型
sall.usable.setAsInt(1);//有效
sllists.add(sall);
addnums++;
}
if (sllists.size() > 0) {
System.out.println("====================生成薪资明细记录条数【" + sllists.size() + "】");
sllists.saveBatchSimple();// 高速存储sllists
}
sllists.clear();
String sqlstr1="SELECT * FROM (SELECT sl.* FROM hr_salary_list sl,hr_employee e WHERE sl.wagetype=1 AND sl.yearmonth>='"+ymbf+"' AND sl.yearmonth<'"+ymbg+
"' AND sl.er_id=e.er_id AND e.empstatid<10 AND e.pay_way='月薪') sl WHERE er_id NOT IN (SELECT DISTINCT er_id FROM hr_salary_list WHERE wagetype=1 AND yearmonth>='"+ymbg+
"' AND yearmonth<'"+ymed+"') ";
sllists.findDataBySQL(sqlstr1, true, false);
for(CJPABase jpa : sllists){
Hr_salary_list sl =(Hr_salary_list)jpa;
sl.clearAllId();
sl.yearmonth.setValue(yearmonth);
sl.createtime.setValue(Systemdate.getStrDate());
sl.updatetime.setValue(Systemdate.getStrDate());
sl.save(con);
}
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
JSONObject rst = new JSONObject();
rst.put("rst", "ok");
return rst.toString();
}
@ACOAction(eventname = "findSalaryEmoloyeeList", Authentication = true, ispublic = false, notes = "根据登录薪酬权限查询员工资料")
public String findSalaryEmoloyeeList() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
String spcetype = parms.get("spcetype");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String orgid = parms.get("orgid");
if ((orgid != null) && (!orgid.isEmpty())) {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("没发现ID为【" + orgid + "】的机构");
where = where + " and idpath like '" + org.idpath.getValue() + "%'";
}
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
where = where + " and employee_code='" + CSContext.getUserName() + "'";
}
String strincludelv = parms.get("includelv");
boolean includelv = (strincludelv == null) ? false : Boolean.valueOf(strincludelv);
//String llvdate = parms.get("llvdate");// 最晚离职日期
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
String sqlstr = "select * from hr_employee where usable=1";
if (!includelv)
sqlstr = sqlstr + " and empstatid<=10 ";
sqlstr = sqlstr + CSContext.getIdpathwhere() + where + " limit 0," + max;
return he.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findsalarylist", Authentication = true, ispublic = true, notes = "替换通用查询")
public String findsalarylist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String jpaclass = CorUtil.hashMap2Str(urlparms, "jpaclass", "需要参数jpaclass");
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String disidpath = (String)urlparms.get("disidpath");
boolean disi = disidpath != null ? Boolean.valueOf(disidpath).booleanValue() : false;
disi = (disi) && (ConstsSw.getSysParmIntDefault("ALLCLIENTCHGIDPATH", 2) == 1);
String sqlwhere = (String)urlparms.get("sqlwhere");
String selflines = (String)urlparms.get("selfline");
boolean selfline = selflines != null ? Boolean.valueOf(selflines).booleanValue() : true;
if (("list".equalsIgnoreCase(type)) || ("tree".equalsIgnoreCase(type)))
{
selfline = false;
String parms = (String)urlparms.get("parms");
String edittps = CorUtil.hashMap2Str(urlparms, "edittps", "需要参数edittps");
String activeprocname = (String)urlparms.get("activeprocname");
HashMap<String, String> edts = CJSON.Json2HashMap(edittps);
String smax = (String)urlparms.get("max");
String order = (String)urlparms.get("order");
String spage = (String)urlparms.get("page");
String srows = (String)urlparms.get("rows");
boolean needpage = false;
int page = 0;int rows = 0;
if (spage == null)
{
if (smax == null)
{
needpage = false;
}
else
{
needpage = true;
page = 1;
rows = Integer.valueOf(smax).intValue();
}
}
else
{
needpage = true;
page = Integer.valueOf(spage).intValue();
rows = srows == null ? 300 : Integer.valueOf(srows).intValue();
}
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
List<JSONParm> jps = CJSON.getParms(parms);
String where = CjpaUtil.buildFindSqlByJsonParms(jpa, jps);
if ((jpa.cfield("idpath") != null) && (!disi)) {
where = where + CSContext.getIdpathwhere();
}
if ((sqlwhere != null) && (sqlwhere.length() > 0)) {
where = where + " and " + sqlwhere + " ";
}
if (jpa.getPublicControllerBase() != null)
{
String w = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.getController() != null)
{
String w = ((JPAController)jpa.getController()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.cfieldbycfieldname("stat") != null)
{
String sqlstat = "";
if (Obj2Bl(edts.get("isedit"))) {
sqlstat = sqlstat + " (stat=1) or";
}
if (Obj2Bl(edts.get("issubmit"))) {
sqlstat = sqlstat + " (stat>1 and stat<9) or";
}
if (Obj2Bl(edts.get("isview"))) {
sqlstat = sqlstat + " ( 1=1 ) or";
}
if ((Obj2Bl(edts.get("isupdate"))) || (Obj2Bl(edts.get("isfind")))) {
sqlstat = sqlstat + " (stat=9) or";
}
if (sqlstat.length() > 0)
{
sqlstat = sqlstat.substring(1, sqlstat.length() - 2);
where = where + " and (" + sqlstat + ")";
}
}
if ((activeprocname != null) && (!activeprocname.isEmpty()))
{
String idfd = jpa.getIDField().getFieldname();
String ew = "SELECT " + idfd + " FROM " + jpa.tablename + " t,shwwf wf,shwwfproc wfp" +
" WHERE t.stat>1 AND t.stat<9 AND t.wfid=wf.wfid AND wf.wfid=wfp.wfid " +
" AND wfp.stat=2 AND wfp.procname='" + activeprocname + "'";
ew = " and " + idfd + " in (" + ew + ")";
where = where + ew;
}
String sqltr = null;
String textfield = (String)urlparms.get("textfield");
String pidfd = null;
if ("tree".equalsIgnoreCase(type)) {
pidfd = CorUtil.hashMap2Str(urlparms, "parentid", "需要参数parentid");
}
if (("tree".equalsIgnoreCase(type)) && (textfield != null) && (textfield.length() > 0))
{
String idfd = jpa.getIDField().getFieldname();
sqltr = "select " + idfd + " as id," + textfield +
" as text," + idfd + "," + textfield + "," + pidfd +
",a.* from " + jpa.tablename + " a where 1=1 " + where;
}
else
{
sqltr = "select * from " + jpa.tablename + " where 1=1 " + where;
}
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
sqltr = sqltr + " and employee_code='" + CSContext.getUserName() + "'";
}
if ((order != null) && (!order.isEmpty())) {
sqltr = sqltr + " order by " + order;
} else {
sqltr = sqltr + " order by " + jpa.getIDFieldName() + " desc ";
}
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if ("list".equalsIgnoreCase(type))
{
String scols = (String)urlparms.get("cols");
if (scols != null)
{
String[] ignParms = new String[0];
new CReport(sqltr, null).export2excel(ignParms, scols);
return null;
}
if (!needpage)
{
JSONArray js = jpa.pool.opensql2json_O(sqltr);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), js, 0, 0);
if (rst != null) {
return rst;
}
}
return js.toString();
}
JSONObject jo = jpa.pool.opensql2json_O(sqltr, page, rows);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), jo, page, rows);
if (rst != null) {
return rst;
}
}
return jo.toString();
}
if ("tree".equalsIgnoreCase(type)) {
return jpa.pool.opensql2jsontree(sqltr, jpa.getIDField().getFieldname(), pidfd, false);
}
}
if ("byid".equalsIgnoreCase(type))
{
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
CJPA jpa = (CJPA)CjpaUtil.newJPAObjcet(jpaclass);
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
CField idfd = jpa.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA<" + jpa.getClass().getSimpleName() + ">数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(jpa.pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(jpa.pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + jpa.tablename + " where " + sqlfdname + "=" + sqlvalue;
jpa.findBySQL(sqlstr, selfline);
if (jpa.isEmpty()) {
return "{}";
}
return jpa.tojson();
}
return "";
}
private static boolean Obj2Bl(Object o) {
if (o == null)
return false;
return Boolean.valueOf(o.toString());
}
@ACOAction(eventname = "findtechsublist", Authentication = true, ispublic = true, notes = "替换技术津贴通用查询")
public String findtechsublist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String jpaclass = CorUtil.hashMap2Str(urlparms, "jpaclass", "需要参数jpaclass");
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String disidpath = (String)urlparms.get("disidpath");
boolean disi = disidpath != null ? Boolean.valueOf(disidpath).booleanValue() : false;
disi = (disi) && (ConstsSw.getSysParmIntDefault("ALLCLIENTCHGIDPATH", 2) == 1);
String sqlwhere = (String)urlparms.get("sqlwhere");
String selflines = (String)urlparms.get("selfline");
boolean selfline = selflines != null ? Boolean.valueOf(selflines).booleanValue() : true;
if (("list".equalsIgnoreCase(type)) || ("tree".equalsIgnoreCase(type)))
{
selfline = false;
String parms = (String)urlparms.get("parms");
String edittps = CorUtil.hashMap2Str(urlparms, "edittps", "需要参数edittps");
String activeprocname = (String)urlparms.get("activeprocname");
HashMap<String, String> edts = CJSON.Json2HashMap(edittps);
String smax = (String)urlparms.get("max");
String order = (String)urlparms.get("order");
String spage = (String)urlparms.get("page");
String srows = (String)urlparms.get("rows");
boolean needpage = false;
int page = 0;int rows = 0;
if (spage == null)
{
if (smax == null)
{
needpage = false;
}
else
{
needpage = true;
page = 1;
rows = Integer.valueOf(smax).intValue();
}
}
else
{
needpage = true;
page = Integer.valueOf(spage).intValue();
rows = srows == null ? 300 : Integer.valueOf(srows).intValue();
}
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
List<JSONParm> jps = CJSON.getParms(parms);
String where = CjpaUtil.buildFindSqlByJsonParms(jpa, jps);
if ((jpa.cfield("idpath") != null) && (!disi)) {
where = where + CSContext.getIdpathwhere();
}
if ((sqlwhere != null) && (sqlwhere.length() > 0)) {
where = where + " and " + sqlwhere + " ";
}
if (jpa.getPublicControllerBase() != null)
{
String w = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.getController() != null)
{
String w = ((JPAController)jpa.getController()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.cfieldbycfieldname("stat") != null)
{
String sqlstat = "";
if (Obj2Bl(edts.get("isedit"))) {
sqlstat = sqlstat + " (stat=1) or";
}
if (Obj2Bl(edts.get("issubmit"))) {
sqlstat = sqlstat + " (stat>1 and stat<9) or";
}
if (Obj2Bl(edts.get("isview"))) {
sqlstat = sqlstat + " ( 1=1 ) or";
}
if ((Obj2Bl(edts.get("isupdate"))) || (Obj2Bl(edts.get("isfind")))) {
sqlstat = sqlstat + " (stat=9) or";
}
if (sqlstat.length() > 0)
{
sqlstat = sqlstat.substring(1, sqlstat.length() - 2);
where = where + " and (" + sqlstat + ")";
}
}
if ((activeprocname != null) && (!activeprocname.isEmpty()))
{
String idfd = jpa.getIDField().getFieldname();
String ew = "SELECT " + idfd + " FROM " + jpa.tablename + " t,shwwf wf,shwwfproc wfp" +
" WHERE t.stat>1 AND t.stat<9 AND t.wfid=wf.wfid AND wf.wfid=wfp.wfid " +
" AND wfp.stat=2 AND wfp.procname='" + activeprocname + "'";
ew = " and " + idfd + " in (" + ew + ")";
where = where + ew;
}
String sqltr = null;
String textfield = (String)urlparms.get("textfield");
String pidfd = null;
if ("tree".equalsIgnoreCase(type)) {
pidfd = CorUtil.hashMap2Str(urlparms, "parentid", "需要参数parentid");
}
if (("tree".equalsIgnoreCase(type)) && (textfield != null) && (textfield.length() > 0))
{
String idfd = jpa.getIDField().getFieldname();
sqltr = "select " + idfd + " as id," + textfield +
" as text," + idfd + "," + textfield + "," + pidfd +
",a.* from " + jpa.tablename + " a where 1=1 " + where;
}
else
{
sqltr = "select * from " + jpa.tablename + " where 1=1 " + where;
}
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
sqltr = sqltr + " AND EXISTS (SELECT * FROM `hr_salary_techsub_line` tsl WHERE tsl.`ts_id`=ts_id AND employee_code='" + CSContext.getUserName() + "')";
}
if ((order != null) && (!order.isEmpty())) {
sqltr = sqltr + " order by " + order;
} else {
sqltr = sqltr + " order by " + jpa.getIDFieldName() + " desc ";
}
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if ("list".equalsIgnoreCase(type))
{
String scols = (String)urlparms.get("cols");
if (scols != null)
{
String[] ignParms = new String[0];
new CReport(sqltr, null).export2excel(ignParms, scols);
return null;
}
if (!needpage)
{
JSONArray js = jpa.pool.opensql2json_O(sqltr);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), js, 0, 0);
if (rst != null) {
return rst;
}
}
return js.toString();
}
JSONObject jo = jpa.pool.opensql2json_O(sqltr, page, rows);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), jo, page, rows);
if (rst != null) {
return rst;
}
}
return jo.toString();
}
if ("tree".equalsIgnoreCase(type)) {
return jpa.pool.opensql2jsontree(sqltr, jpa.getIDField().getFieldname(), pidfd, false);
}
}
if ("byid".equalsIgnoreCase(type))
{
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
CJPA jpa = (CJPA)CjpaUtil.newJPAObjcet(jpaclass);
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
CField idfd = jpa.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA<" + jpa.getClass().getSimpleName() + ">数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(jpa.pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(jpa.pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + jpa.tablename + " where " + sqlfdname + "=" + sqlvalue;
jpa.findBySQL(sqlstr, selfline);
if (jpa.isEmpty()) {
return "{}";
}
return jpa.tojson();
}
return "";
}
@ACOAction(eventname = "findpostsublist", Authentication = true, ispublic = true, notes = "替换岗位津贴通用查询")
public String findpostsublist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String jpaclass = CorUtil.hashMap2Str(urlparms, "jpaclass", "需要参数jpaclass");
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String disidpath = (String)urlparms.get("disidpath");
boolean disi = disidpath != null ? Boolean.valueOf(disidpath).booleanValue() : false;
disi = (disi) && (ConstsSw.getSysParmIntDefault("ALLCLIENTCHGIDPATH", 2) == 1);
String sqlwhere = (String)urlparms.get("sqlwhere");
String selflines = (String)urlparms.get("selfline");
boolean selfline = selflines != null ? Boolean.valueOf(selflines).booleanValue() : true;
if (("list".equalsIgnoreCase(type)) || ("tree".equalsIgnoreCase(type)))
{
selfline = false;
String parms = (String)urlparms.get("parms");
String edittps = CorUtil.hashMap2Str(urlparms, "edittps", "需要参数edittps");
String activeprocname = (String)urlparms.get("activeprocname");
HashMap<String, String> edts = CJSON.Json2HashMap(edittps);
String smax = (String)urlparms.get("max");
String order = (String)urlparms.get("order");
String spage = (String)urlparms.get("page");
String srows = (String)urlparms.get("rows");
boolean needpage = false;
int page = 0;int rows = 0;
if (spage == null)
{
if (smax == null)
{
needpage = false;
}
else
{
needpage = true;
page = 1;
rows = Integer.valueOf(smax).intValue();
}
}
else
{
needpage = true;
page = Integer.valueOf(spage).intValue();
rows = srows == null ? 300 : Integer.valueOf(srows).intValue();
}
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
List<JSONParm> jps = CJSON.getParms(parms);
String where = CjpaUtil.buildFindSqlByJsonParms(jpa, jps);
if ((jpa.cfield("idpath") != null) && (!disi)) {
where = where + CSContext.getIdpathwhere();
}
if ((sqlwhere != null) && (sqlwhere.length() > 0)) {
where = where + " and " + sqlwhere + " ";
}
if (jpa.getPublicControllerBase() != null)
{
String w = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.getController() != null)
{
String w = ((JPAController)jpa.getController()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null) {
where = where + " " + w;
}
}
if (jpa.cfieldbycfieldname("stat") != null)
{
String sqlstat = "";
if (Obj2Bl(edts.get("isedit"))) {
sqlstat = sqlstat + " (stat=1) or";
}
if (Obj2Bl(edts.get("issubmit"))) {
sqlstat = sqlstat + " (stat>1 and stat<9) or";
}
if (Obj2Bl(edts.get("isview"))) {
sqlstat = sqlstat + " ( 1=1 ) or";
}
if ((Obj2Bl(edts.get("isupdate"))) || (Obj2Bl(edts.get("isfind")))) {
sqlstat = sqlstat + " (stat=9) or";
}
if (sqlstat.length() > 0)
{
sqlstat = sqlstat.substring(1, sqlstat.length() - 2);
where = where + " and (" + sqlstat + ")";
}
}
if ((activeprocname != null) && (!activeprocname.isEmpty()))
{
String idfd = jpa.getIDField().getFieldname();
String ew = "SELECT " + idfd + " FROM " + jpa.tablename + " t,shwwf wf,shwwfproc wfp" +
" WHERE t.stat>1 AND t.stat<9 AND t.wfid=wf.wfid AND wf.wfid=wfp.wfid " +
" AND wfp.stat=2 AND wfp.procname='" + activeprocname + "'";
ew = " and " + idfd + " in (" + ew + ")";
where = where + ew;
}
String sqltr = null;
String textfield = (String)urlparms.get("textfield");
String pidfd = null;
if ("tree".equalsIgnoreCase(type)) {
pidfd = CorUtil.hashMap2Str(urlparms, "parentid", "需要参数parentid");
}
if (("tree".equalsIgnoreCase(type)) && (textfield != null) && (textfield.length() > 0))
{
String idfd = jpa.getIDField().getFieldname();
sqltr = "select " + idfd + " as id," + textfield +
" as text," + idfd + "," + textfield + "," + pidfd +
",a.* from " + jpa.tablename + " a where 1=1 " + where;
}
else
{
sqltr = "select * from " + jpa.tablename + " where 1=1 " + where;
}
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
sqltr = sqltr + " AND EXISTS (SELECT * FROM `hr_salary_postsub_line` psl WHERE psl.`ps_id`=ps_id AND employee_code='" + CSContext.getUserName() + "')";
}
if ((order != null) && (!order.isEmpty())) {
sqltr = sqltr + " order by " + order;
} else {
sqltr = sqltr + " order by " + jpa.getIDFieldName() + " desc ";
}
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null) {
return rst;
}
}
if ("list".equalsIgnoreCase(type))
{
String scols = (String)urlparms.get("cols");
if (scols != null)
{
String[] ignParms = new String[0];
new CReport(sqltr, null).export2excel(ignParms, scols);
return null;
}
if (!needpage)
{
JSONArray js = jpa.pool.opensql2json_O(sqltr);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), js, 0, 0);
if (rst != null) {
return rst;
}
}
return js.toString();
}
JSONObject jo = jpa.pool.opensql2json_O(sqltr, page, rows);
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), jo, page, rows);
if (rst != null) {
return rst;
}
}
return jo.toString();
}
if ("tree".equalsIgnoreCase(type)) {
return jpa.pool.opensql2jsontree(sqltr, jpa.getIDField().getFieldname(), pidfd, false);
}
}
if ("byid".equalsIgnoreCase(type))
{
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
CJPA jpa = (CJPA)CjpaUtil.newJPAObjcet(jpaclass);
if (jpa.getPublicControllerBase() != null)
{
String rst = ((JPAController)jpa.getPublicControllerBase()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
if (jpa.getController() != null)
{
String rst = ((JPAController)jpa.getController()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null) {
return rst;
}
}
CField idfd = jpa.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA<" + jpa.getClass().getSimpleName() + ">数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(jpa.pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(jpa.pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + jpa.tablename + " where " + sqlfdname + "=" + sqlvalue;
jpa.findBySQL(sqlstr, selfline);
if (jpa.isEmpty()) {
return "{}";
}
return jpa.tojson();
}
return "";
}
}
<file_sep>/src/com/corsair/server/util/UpLoadFileEx.java
package com.corsair.server.util;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.baiduueditor.FileType;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
/**
* 上传文件
*
* @author Administrator
*
*/
public class UpLoadFileEx {
/**
* 上传BASE 64 文件
*
* var dataUrl = cvs.toDataURL('image/jpeg', 1);
* var dataUrl = dataUrl.replace("data:" + fileType + ";base64,", '');
*
* @param str64
* @param pfname
* 文件名,显示到数据库的文件名
* @param extfname
* 扩展文件名 jpg||.jpg
* @return
* @throws Exception
*/
public static Shw_physic_file douploadBase64File(String str64, String pfname, String extfname) throws Exception {
Shw_physic_file rst = new Shw_physic_file();
byte[] datasave = Base64.decodeBase64(str64.getBytes());// VclZip.gunzip(str64).getBytes();//
String fsep = System.getProperty("file.separator");
String filePath = "";
if ((ConstsSw.geAppParmStr("UDFilePath") == null) || (ConstsSw.geAppParmStr("UDFilePath").length() == 0))
filePath = ConstsSw._root_filepath;
else
filePath = ConstsSw.geAppParmStr("UDFilePath");
if (!filePath.substring(filePath.length() - 1).equalsIgnoreCase(fsep))
filePath = filePath + fsep;
String apath = Systemdate.getStrDateNowYYMM();// 相对路径
filePath = filePath + apath + fsep;
if (filePath.trim().isEmpty()) {
throw new Exception("没有找到合适的文件夹");
}
if (extfname == null)
extfname = "";
if (!extfname.isEmpty()) {
if (!extfname.substring(0, 1).equals("."))
extfname = "." + extfname;
}
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory() && !dir.mkdirs())
throw new Exception("创建文件夹<" + filePath + ">错误,联系管理员!");
String tfname = ((pfname == null) ? "_base64" : pfname);
// String fname = un + "_" + Systemdate.getStrDateByFmt(new Date(), "hhmmss") + tfname + extfname;
String fname = getNoReptFileName(extfname);// 数据库里面存的文件名
String fullfname = filePath + fname;// 物理文件
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
File file = new File(fullfname);
synchronized (file) {
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(fullfname, false));
fos.write(datasave);
fos.flush();
fos.close();
}
rst.ppath.setValue(apath);
rst.pfname.setValue(fname);
rst.create_time.setAsDatetime(new Date());
rst.creator.setValue(un);
rst.displayfname.setValue(tfname + extfname);// 数据库里面显示的文件名
rst.filesize.setValue("0");// K
rst.extname.setValue(getExtention(tfname + extfname));
rst.fsid.setAsInt(0);
rst.setJpaStat(CJPAStat.RSINSERT);
rst.save();
return rst;
}
/**
* @return 获取文件夹路径 配置路径+YYMM(日期) 如果未配置,用基准路径
* @throws Exception
*/
private static String getfilepath(String apath) throws Exception {
String fsep = System.getProperty("file.separator");
String filePath = "";
if ((ConstsSw.geAppParmStr("UDFilePath") == null) || (ConstsSw.geAppParmStr("UDFilePath").length() == 0))
filePath = ConstsSw._root_filepath;
else
filePath = ConstsSw.geAppParmStr("UDFilePath");
if (!filePath.substring(filePath.length() - 1).equalsIgnoreCase(fsep))
filePath = filePath + fsep;
filePath = filePath + apath + fsep;// 相对路径
if (filePath.trim().isEmpty()) {
throw new Exception("没有找到合适的文件夹");
}
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory() && !dir.mkdirs())
throw new Exception("创建文件夹<" + filePath + ">错误,联系管理员!");
return filePath;
}
/**
* 获取上传文件存到指定目录,比如上传微信证书文件等,与附件管理无关
*
* @param filepath
* @return 返回不包含路径的文件名
* @throws Exception
*/
public static String doupload(String filepath) throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String fsep = System.getProperty("file.separator");
String fileTem = (filepath.endsWith(fsep)) ? filepath : filepath + fsep;
File dir = new File(fileTem);
if (!dir.exists() && !dir.isDirectory() && !dir.mkdirs())
throw new Exception("创建文件夹<" + fileTem + ">错误,联系管理员!");
long MAXFILESIZE = 2 * 1024 * 1024 * 1024; // 允许的最大文件尺寸 2*1000M
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024); // 设置缓冲区
factory.setRepository(new File(fileTem)); // 文件临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAXFILESIZE);// 设置最大文件
upload.setProgressListener(new UpLoadFileExProgressListener());
upload.setHeaderEncoding("UTF-8");
List<?> items = upload.parseRequest(CSContext.getRequest());
HashMap<String, String> parms = CSContext.getParms();
for (int i = 0; i < items.size(); i++) {
FileItem fi = (FileItem) items.get(i);
if (!fi.isFormField()) {// 如果是文件
String displayfname = fi.getName();
String fname = fileTem + displayfname;
File file = new File(fname);
if ((file.isFile()) && (!file.delete()))
throw new Exception("文件【" + fname + "】已经存在且删除错误,联系管理员!");
fi.write(new File(fname));
return displayfname;// 只处理第一个文件
} else {
parms.put(fi.getFieldName(), fi.getString("UTF-8"));
}
}
return null;
}
public static CJPALineData<Shw_physic_file> doupload(boolean imgthb) throws Exception {
return doupload(imgthb, null);
}
/**
* 上传文件到 系统文档文件夹
*
* @param imgthb
* 是否生成缩略图
* @return
* @throws Exception
*/
public static CJPALineData<Shw_physic_file> doupload(boolean imgthb, String filetitle) throws Exception {
long MAXFILESIZE = 2 * 1024 * 1024 * 1024; // 默认允许的最大文件尺寸 2*1000M
return doupload(imgthb, filetitle, null, MAXFILESIZE);
}
/**
* @param imgthb
* @param allowTypes
* 允许的文件类型 [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
* @param maxSize
* 文件大小
* @return
* @throws Exception
*/
public static CJPALineData<Shw_physic_file> doupload(boolean imgthb, String filetitle, String[] allowTypes, long maxSize) throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
FilePath fpath = getFilePath();
return writefiles(fpath.FilePath, fpath.aPath, fpath.TempPath, imgthb, filetitle, allowTypes, maxSize);
}
/**
* 获取上传文件的文件路径(附件)
*
* @return
* @throws Exception
*/
public static FilePath getFilePath() throws Exception {
FilePath rst = new FilePath();
String fsep = System.getProperty("file.separator");
String filePath = "";
if ((ConstsSw.geAppParmStr("UDFilePath") == null) || (ConstsSw.geAppParmStr("UDFilePath").length() == 0))
filePath = ConstsSw._root_filepath;
else
filePath = ConstsSw.geAppParmStr("UDFilePath");
if (!filePath.substring(filePath.length() - 1).equalsIgnoreCase(fsep))
filePath = filePath + fsep;
String fileTem = filePath + "temp" + fsep;
String apath = Systemdate.getStrDateNowYYMM();// 相对路径
filePath = filePath + apath + fsep;
if (filePath.trim().isEmpty()) {
throw new Exception("没有找到合适的文件夹");
}
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory() && !dir.mkdirs())
throw new Exception("创建文件夹<" + filePath + ">错误,联系管理员!");
dir = new File(fileTem);
if (!dir.exists() && !dir.isDirectory() && !dir.mkdirs())
throw new Exception("创建文件夹" + fileTem + "错误,联系管理员!");
rst.FilePath = filePath;
rst.aPath = apath;
rst.TempPath = fileTem;
return rst;
}
/**
* 写入文件
*
* @param filePath
* 除了文件名剩下的路径
* @param apath
* 写入数据库的相对路径
* @param fileTem
* 临时文件目录
* @param imgthb
* 是否生成缩略图
* @param allowTypes
* null 允许所有文件
* @param maxSize
* 大小限制 k
* @return
* @throws Exception
*/
private static CJPALineData<Shw_physic_file> writefiles(String filePath, String apath, String fileTem, boolean imgthb, String filetitle,
String[] allowTypes, long maxSize) throws Exception {
long MAXFILESIZE = maxSize; // 允许的最大文件尺寸 2*1000M
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024); // 设置缓冲区
factory.setRepository(new File(fileTem)); // 文件临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAXFILESIZE);// 设置最大文件
upload.setProgressListener(new UpLoadFileExProgressListener());
CJPALineData<Shw_physic_file> rst = new CJPALineData<Shw_physic_file>(Shw_physic_file.class);
upload.setHeaderEncoding("UTF-8");
List<?> items = upload.parseRequest(CSContext.getRequest());
HashMap<String, String> parms = CSContext.getParms();
for (int i = 0; i < items.size(); i++) {
FileItem fi = (FileItem) items.get(i);
if (!fi.isFormField()) {// 如果是文件
String displayfname = fi.getName();// 数据库显示的文件名
String suffix = FileType.getSuffixByFilename(displayfname);
if (!validType(suffix, allowTypes)) {
throw new Exception("不许可的文件类型");
}
displayfname = new File(displayfname.trim()).getName();
String extfname = getExtention(displayfname);
Logsw.debug("上传文件:" + displayfname);
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
// String fname = un + "_" + Systemdate.getStrDateByFmt(new Date(), "hhmmss") + "_" + displayfname;
String fname = getNoReptFileName(extfname);
String fullfname = filePath + fname;
fi.write(new File(fullfname));
DecimalFormat df = new DecimalFormat("0.##");
Shw_physic_file pf = new Shw_physic_file();
pf.ppath.setValue(apath);
pf.pfname.setValue(fname);
pf.create_time.setAsDatetime(new Date());
pf.creator.setValue(un);
pf.displayfname.setValue((filetitle == null) ? displayfname : filetitle);
pf.filesize.setValue(df.format(fi.getSize() / (1024f)));// K
pf.extname.setValue(extfname);
pf.fsid.setAsInt(0);
pf.setJpaStat(CJPAStat.RSINSERT);
pf.save();
if (imgthb) {
createThemImg(pf, apath, displayfname, filetitle, fullfname);
}
rst.add(pf);
} else {
parms.put(fi.getFieldName(), fi.getString("UTF-8"));
}
}
// extname filesize filecreator filecreate_time
CSContext.removeParm("uploadfile");
return rst;
}
/**
* 将JPA某Blob longtext等类型字段值,字段值用Base64编码, 写入文件
*
* @param fdvalue
* 用来写入文件的字段内容 base64字符串
* @param fname
* 文件名 包含扩展文件名,不包含路径
* @return
* @throws Exception
*/
public static Shw_physic_file witrefileFromFieldValue(String fdvalue, String fname) throws Exception {
String apath = Systemdate.getStrDateNowYYMM();// 相对路径
String filePath = getfilepath(apath);
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
String dbfname = un + "_" + Systemdate.getStrDateByFmt(new Date(), "hhmmss") + "_" + fname;
String fullfname = filePath + dbfname;
OutputStream out = new FileOutputStream(fullfname);
CjpaUtil.generateImage(fdvalue, out);
out.flush();
out.close();
File file = new File(fullfname);
if (file.exists()) {
DecimalFormat df = new DecimalFormat("0.##");
Shw_physic_file pf = new Shw_physic_file();
pf.ppath.setValue(apath);
pf.pfname.setValue(dbfname);
pf.create_time.setAsDatetime(new Date());
pf.creator.setValue(un);
pf.displayfname.setValue(fname);
pf.filesize.setValue(df.format(file.length() / (1024f)));// K
pf.extname.setValue(getExtention(fname));
pf.fsid.setAsInt(0);
pf.setJpaStat(CJPAStat.RSINSERT);
pf.save();
return pf;
} else
throw new Exception("写入之后文件【" + fullfname + "】不存在!");
}
public static String getExtention(String fileName) {
if (fileName != null && fileName.length() > 0 && fileName.lastIndexOf(".") > -1) {
return fileName.substring(fileName.lastIndexOf("."));
}
return "";
}
private static void createThemImg(Shw_physic_file pf, String apath, String displayfname, String filetitle, String fullfname) {
try {
String tfilename = new ImageUtil().thumbnailImage(fullfname, 200, 200);
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
File f = new File(tfilename);
if (tfilename != null) {
Shw_physic_file pfe = new Shw_physic_file();
pfe.ppath.setValue(apath);
pfe.pfname.setValue(f.getName());
pfe.create_time.setAsDatetime(new Date());
pfe.creator.setValue(un);
pfe.displayfname.setValue((filetitle == null) ? displayfname : filetitle);
pfe.filesize.setValue("0");
pfe.extname.setValue(getExtention(displayfname));
pfe.fsid.setAsInt(0);
pfe.ppfid.setAsInt(pf.pfid.getAsIntDefault(0));
pfe.ptype.setAsInt(1);// 缩略图
pfe.save();
}
} catch (Exception e) {
try {
Logsw.error("生成缩略图错误", e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public static boolean isImage(Shw_physic_file pf) {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (file.exists())
return false;
}
try {
BufferedImage Image = ImageIO.read(file);
return (Image != null);
} catch (IOException e) {
return false;
}
}
public static void delAttFile(String pfid) throws Exception {
Shw_physic_file pf = new Shw_physic_file();
pf.findByID(pfid);
if (pf.isEmpty()) {
Logsw.debug("没有找到物理文件记录【" + pfid + "】");
return;
}
// 删除自关联文档 比如缩略图等
String sqlstr = "SELECT * FROM shw_physic_file f WHERE f.ppfid=" + pf.pfid.getValue();
CJPALineData<Shw_physic_file> phfs = new CJPALineData<Shw_physic_file>(Shw_physic_file.class);
phfs.findDataBySQL(sqlstr);
if (phfs.size() > 0) {
for (CJPABase jpa : phfs) {
delAttFile(((Shw_physic_file) jpa).pfid.getValue());
}
}
String fullname = getPhysicalFileName(pf);
File file = new File(fullname);
if (file.exists())
file.delete();
if (pf.isEmpty())
throw new Exception("没有找到物理文件记录!");
pf.delete();
}
public static void updateDisplayName(String pfid, String displayname) throws Exception {
CDBConnection con = DBPools.defaultPool().getCon("UpLoadFileEx.updateDisplayName");
try {
Shw_physic_file pf = new Shw_physic_file();
pf.findByID4Update(con, pfid, false);
if (pf.isEmpty()) {
throw new Exception("没有找到物理文件【" + pfid + "】记录!");
}
String sqlstr = "UPDATE shw_physic_file SET displayfname='" + displayname + "' WHERE ppfid=" + pf.pfid.getValue();
con.execsql(sqlstr);
pf.displayfname.setValue(displayname);
pf.save(con);
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
public static String getPhysicalFileName(String pfid) {
try {
Shw_physic_file pf = new Shw_physic_file();
pf.findByID(pfid);
return getPhysicalFileName(pf);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static String getPhysicalFileName(Shw_physic_file pf) {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
Logsw.debug("getPhysicalFileName fullname:" + fullname);
if (!(new File(fullname)).exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
}
return fullname;
}
/**
* 获取不重复文件名
* 如果有登录用户 则用登陆用户ID+_+UUID
*
* @param extfname
* 扩展文件名 .jpg || jpg
* @return
*/
public static String getNoReptFileName(String extfname) {
if (extfname == null)
extfname = "";
if (!extfname.isEmpty()) {
if (!extfname.substring(0, 1).equals("."))
extfname = "." + extfname;
}
String un = (CSContext.getUserIDNoErr() == null) ? "SYSTEM" : CSContext.getUserIDNoErr();
return un + "_" + CorUtil.getShotuuid() + extfname;
}
/**
* 是否存在的文件类型
*
* @param type
* //.png
* @param allowTypes
* //[".png", ".jpg", ".jpeg", ".gif", ".bmp"]
* @return
*/
private static boolean validType(String type, String[] allowTypes) {
if (allowTypes == null)
return true;
if (allowTypes.length == 0)
return true;
List<String> list = Arrays.asList(allowTypes);
return list.contains(type);
}
}
<file_sep>/src/com/hr/.svn/pristine/77/77b3b348771d26f84e09c18fa98678c20784265b.svn-base
package com.hr.perm.entity;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.hr.perm.ctr.CtrHr_quota_release;
@CEntity(controller = CtrHr_quota_release.class)
public class Hr_quota_release extends CJPA {
@CFieldinfo(fieldname = "qrlsid", iskey = true, notnull = true, caption = "发布单ID", datetype = Types.INTEGER)
public CField qrlsid; // 发布单ID
@CFieldinfo(fieldname = "orlscode", codeid = 51, notnull = true, caption = "发布单编码", datetype = Types.VARCHAR)
public CField orlscode; // 发布单编码
@CFieldinfo(fieldname = "quota_year", notnull = true, caption = "编制年度", datetype = Types.VARCHAR)
public CField quota_year; // 编制年度
@CFieldinfo(fieldname = "quota_moth", caption = "编制月份", datetype = Types.VARCHAR)
public CField quota_moth; // 编制月份
@CFieldinfo(fieldname = "idpath", caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", caption = "stat", datetype = Types.INTEGER)
public CField stat; // stat
@CFieldinfo(fieldname = "entid", caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "entname", caption = "entname", datetype = Types.VARCHAR)
public CField entname; // entname
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Hr_quota_releaseline.class, linkFields = { @LinkFieldItem(lfield = "qrlsid", mfield = "qrlsid") })
public CJPALineData<Hr_quota_releaseline> hr_quota_releaselines;
public Hr_quota_release() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/cjquery.js
/**
* Created by Administrator on 2014-09-28
* just for corsair server.
*/
//数据字典
function getBrowserInfo() {
var ua = navigator.userAgent.toLowerCase(),
rMsie = /(msie\s|trident.*rv:)([\w.]+)/,
rFirefox = /(firefox)\/([\w.]+)/,
rOpera = /(opera).+version\/([\w.]+)/,
rChrome = /(chrome)\/([\w.]+)/,
rSafari = /version\/([\w.]+).*(safari)/;
var match = rMsie.exec(ua);
if (match != null) {
return {browser: "IE", version: match[2] || "0"};
}
var match = rFirefox.exec(ua);
if (match != null) {
return {browser: match[1] || "", version: match[2] || "0"};
}
var match = rOpera.exec(ua);
if (match != null) {
return {browser: match[1] || "", version: match[2] || "0"};
}
var match = rChrome.exec(ua);
if (match != null) {
return {browser: match[1] || "", version: match[2] || "0"};
}
var match = rSafari.exec(ua);
if (match != null) {
return {browser: match[2] || "", version: match[1] || "0"};
}
if (match != null) {
return {browser: "", version: "0"};
}
}
var browinfo = getBrowserInfo();
//日期精度
var $Precision = {
piNone: 0, piYear: 1, piMonth: 2, piDay: 3, piHour: 4, piMinute: 5, piSecond: 6
};
//汇总类型
var $Aggregation = {
agNone: 0, agConst: 1, agSUM: 2, agCOUNT: 3, agAVG: 4, agMAX: 5, agMin: 6
};
//导出Excel列的数据类型
var $ECType = {
ectUnknown: 0, ectNumber: 1
};
//$.parser.auto = false;
var pc;
var $OnCorsairReady;
var comUrls;
//var islie8 = $.isLessIe8();
$(document).ready(function () {
try {
if ($urlparms && $urlparms.title) {
document.title = $urlparms.title;
}
} catch (e) {
//
}
var vfrmOptions = window.frmOptions;
if (vfrmOptions && vfrmOptions.extattrfilter) {
init_jpaattr({filter: vfrmOptions.extattrfilter});
}
if (comUrls) {
do_initdics({
comUrls: comUrls, onOK: function (delay) {
doinitdealy(delay);
}
});
} else {
doinitdealy(false);
}
});
function doinitdealy(delay) {
if (delay)
setTimeout(doinit, 500);
else
doinit();
}
//部分dic经常会变化的,可能需要及时刷新
function do_initdics(comOptions) {
var comUrls = comOptions.comUrls;
if (iswiect(comUrls) == 0)
if (comOptions.onOK) comOptions.onOK(true);
for (var i = 0; i < comUrls.length; i++) {
var comurl = comUrls[i];
if (comurl.iswie) {
var url = _serUrl + comurl.url;
$ajaxjsonget(url, function (jsondata, comurl) {
var edtor = {type: comurl.type, options: {}};
if (comurl.type == "combobox") {
edtor.options.valueField = comurl.valueField;
edtor.options.textField = comurl.textField;
}
if (comurl.type == "combotree") {
$C.tree.setTree1OpendOtherClosed(jsondata);//第一级开着 第二级后全关上
}
var strvalname = "comUrl_" + comurl.index;
window[strvalname] = comurl;
comurl.jsondata = jsondata;
edtor.options.data = comurl.jsondata;
comurl.editor = edtor;
comurl.formator = function (value, row) {
var curl = window[strvalname];
if (value == "get_com_data") {
return curl.jsondata;
}
if (value == "get_com_url") {
return curl;
}
// alert(comurl.index + ":" + value + ":" + JSON.stringify(jsondata));
if (curl.type == "combobox") {
for (var i = 0; i < curl.jsondata.length; i++) {
if (value == curl.jsondata[i][curl.valueField])
return curl.jsondata[i][curl.textField];
}
}
if (curl.type == "combotree") {
var txt = $getTreeTextById(curl.jsondata, value);
if (txt == undefined) txt = value;
return txt;
}
return value;
};
comurl.succ = true;
if (checkAllSuccess()) {
if (comOptions.onOK) comOptions.onOK(false);
}
}, function (err) {
$.messager.alert('错误', '初始化Grid Combobox错误:' + err.errmsg, 'error');
}, true, comurl);
}
}
function checkAllSuccess() {
for (var i = 0; i < comUrls.length; i++) {
if ((comUrls[i].iswie) && (!comUrls[i].succ))
return false;
}
return true;
}
function iswiect(comUrls) {
var rst = 0;
for (var i = 0; i < comUrls.length; i++) {
if (comUrls[i].iswie) rst++;
}
return rst;
}
}
var _intfunctions = [];
//注册页面初始化函数
function $RegInitfunc(func) {
_intfunctions.push(func);
}
var inited = false;
function doinit() {
inited = true;
if (pc) clearTimeout(pc);
var rst = execinitfunctions();
if ($OnCorsairReady) {
if (!$OnCorsairReady())
pc = setTimeout(closes, 1000);
} else
pc = setTimeout(closes, 1000);
}
//执行注册的初始化函数 所有函数都返回true,则执行函数返回true 否则返回false
function execinitfunctions() {
var rst = true;
for (var i = 0; i < _intfunctions.length; i++) {
rst = rst && _intfunctions[i]();
}
return rst;//
}
function closes() {
$("#loading").fadeOut("normal", function () {
$(this).remove();
});
}
$.c_parseOptions = function (obj) {
var s = $.trim(obj.attr("cjoptions"));
return $.c_parseOptionsStr(s);
};
$.c_parseOptionsStr = function (s) {
try {
if (s.substring(0, 1) != "{") {
s = "{" + s + "}";
}
return (new Function("return " + s))();
} catch (err) {
alert(err + ":" + s) // 可执行
}
};
$.fn.c_initDictionary = function () {
$(this).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.dicgpid != undefined) {
var obj = $(this);
$ajaxjsonget(_serUrl + "/web/dict/getdictvalues.co?dicid=" + co.dicgpid,
function (jsondata) {
obj.combobox({
data: jsondata,
valueField: 'dictvalue',
textField: 'language1'
});
}, function () {
obj.combobox({
data: {},
valueField: 'dictvalue',
textField: 'language1'
});
$.messager.alert("错误", "获取数据字典错误!", "error");
});
}
});
};
$.fn.c_clearData = function () {
$(this).find("input[cjoptions]").each(function (index, el) {
$(this).textbox('setValue', "");
});
};
function getElEditType(el) {
var tp = $(el).attr("type");
if (tp == "checkbox")
return 6;
var cls = $(el).attr("class");
if (cls.indexOf("easyui-datetimebox") >= 0) {
return 1;
} else if (cls.indexOf("easyui-textbox") >= 0) {
return 5;
}
}
$.fn.c_fromJsonData = function (jsondata) {
$(this).c_clearData();
$(this).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getElEditType(el);
var v = jsondata[co.fdname];
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL")) {
$(this).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(this).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
case 6:
{
if ((v == undefined) || (v == null) || (v == "NULL")) {
$(this).attr("checked", false);
} else {
$(this).attr("checked", (parseInt(v) == 1));
}
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(this).textbox('setValue', "");
else {
if (co.dicgpid) {
$(this).combobox('select', v);
} else
$(this).textbox('setValue', v);
}
break;
}
}
});
};
$.fn.c_setJsonDefaultValue = function (jsondata, isnew) {
var ctimes = ["createtime", "create_time"];
var utimes = ["updatetime", "update_time"];
var ctors = ["creator"];
var utors = ["updator"];
var ent = "entid";
var std = "stat";
var usb = "usable";
var vsb = "isvisible";
$(this).find("input[cjoptions]").each(function (index, el) {
var fdn = $.c_parseOptions($(this)).fdname;
if (isnew) {
if (ctimes.indexOf(fdn) >= 0) jsondata[fdn] = (new Date()).format("yyyy-MM-dd hh:mm:ss");
if (ctors.indexOf(fdn) >= 0) jsondata[fdn] = $C.UserInfo.username();
if (fdn == ent) jsondata[fdn] = $C.UserInfo.entid();
if (fdn == std) jsondata[fdn] = 1;
if (fdn == usb) jsondata[fdn] = 1;
if (fdn == vsb) jsondata[fdn] = 1;
}
else {
if (utimes.indexOf(fdn) >= 0) jsondata[fdn] = (new Date()).format("yyyy-MM-dd hh:mm:ss");
if (utors.indexOf(fdn) >= 0) jsondata[fdn] = $C.UserInfo.username();
}
});
};
$.fn.c_toJsonData = function (jsondata, isNew) {//不能新建 父亲窗口可能传递隐含值
$(this).find("input[cjoptions]").each(function (index, el) {
var et = getElEditType(el);
if (et == 6) {
jsondata[$.c_parseOptions($(this)).fdname] = ( $(this).attr("checked")) ? 1 : 2;
} else {
jsondata[$.c_parseOptions($(this)).fdname] = $(this).textbox("getValue");
}
});
if (!isNew)
$(this).c_setJsonDefaultValue(jsondata, false);
return jsondata;
};
/*
wdinfo:
isNew: false,
url: _serUrl + "/web/common/editorg.co",
jsonData: node,
onOK: infoWindowOK,
onCancel: infoWindowCancel,
otherData: {}
*/
$.fn.c_popInfoWindow = function (wdinfo) {
if ($(this).attr('class').indexOf("easyui-window") < 0)
throw new Error("非easyui-window窗口,不允许弹出!");
var iframs = $(this).find("iframe")[0];
var ifw = undefined;
if (iframs == undefined)
ifw = window;
else
ifw = iframs.contentWindow;
ifw.c$wdinfo = wdinfo;
if (ifw._showInitFormData) {
ifw.c$wdinfo.jsonData = ifw._showInitFormData(wdinfo);
}
$(this).window({
onOpen: ifw.onShowWindow
});
$(this).window('open');
};
function _showInitFormData(wdinfo) {
var oform = $("#" + wdinfo.formID);
if (oform[0] == undefined) {
throw new Error(wdinfo.formID + "对象不存在!");
return;
}
oform.c_clearData();
var jsondata = wdinfo.jsonData;
if (wdinfo.isNew) {
oform.c_setJsonDefaultValue(jsondata, true);
} else {
jsondata = wdinfo.jsonData;
}
oform.c_fromJsonData(jsondata);
return jsondata;
};
/*var wdinfoex = {
isNew: false,
jsonData: data,
onOK: procok,
afterGetData:procgetdata(jsondata),
onCancel: proccancel,
onShow: onshow,
otherData: {}
}*/
//弹出窗体从json获取数据 并显示出来
$.fn.c_popInfo = function (wdinfoex) {
var iwobj = $(this);
var jsondata = wdinfoex.jsonData;
if ($(this).attr('class').indexOf("easyui-window") < 0)
throw new Error("非easyui-window窗口,不允许弹出!");
$(this).find(".easyui-tabs").each(function (index, el) {
$(this).tabs("select", 0);
});
clearInputData();
if (wdinfoex.isNew)
$(this).c_setJsonDefaultValue(jsondata, true);
setTimeout(setdata, 500);
function setdata() {
setData2Input();
setData2Grid();
}
//设置按钮事件
var bts = $(this).find("a[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
el.onclick = function () {
acceptAllGrid();
//从界面获取数据
var jdata = iwobj.c_toJsonData(jsondata, wdinfoex.isNew);
//获取列表数据
//需要重新load grid 数据吗? 可能不需要!
if (wdinfoex.afterGetData) {
wdinfoex.afterGetData(jsondata);
}
if ((wdinfoex.onOK) && (wdinfoex.onOK(jdata)))
iwobj.window('close');
};
}
if (co.caction == "act_cancel") {
el.onclick = function () {
if (wdinfoex.onCancel) {
var errmsg = wdinfoex.onCancel();
if (errmsg)alert(errmsg);
}
iwobj.window('close');
}
}
});
$(this).window({onOpen: wdinfoex.onShow});
$(this).window('open');
function clearInputData() {
iwobj.find("input[cjoptions]").each(function (index, el) {
var tp = $(this).attr("type");
if (tp == "checkbox")
$(this).attr("checked", false);
else
$(this).textbox('setValue', "");
});
}
function setData2Input() {
iwobj.find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
//alert(3);
var et = getElEditType(el);
//alert(4);
//alert(et);
var v = jsondata[co.fdname];
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL")) {
$(this).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(this).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
case 6:
{
if ((v == undefined) || (v == null) || (v == "NULL")) {
$(this).attr("checked", false);
} else {
$(this).attr("checked", (parseInt(v) == 1));
}
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(this).textbox('setValue', "");
else {
if (co.dicgpid) {
$(this).combobox('select', v);
} else
$(this).textbox('setValue', v);
}
break;
}
}
});
}
function setData2Grid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = jsondata[id];
if ($(this).datagrid) {
if (tbdata != undefined) {
$(this).datagrid({data: tbdata});
}
}
});
}
function acceptAllGrid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = jsondata[id];
if ((tbdata) && ($(this).datagrid)) {
$(this).datagrid("acceptChanges");
}
});
}
};
$.fn.c_popselectList = function (geturl, onItemClick, alladd) {
var iwobj = $(this);
if ($(this).attr('class').indexOf("easyui-window") < 0)
throw new Error("非easyui-window窗口,不允许弹出!");
var ulo = iwobj.find("ul");
if (alladd) {
iwobj.window({tools: "#pw_list_select_toolbar"});
$("#pw_list_select_toolbar_btnew").click(function () {
$.messager.prompt('提示信息', '请输入模板名称:', function (r) {
if (r) {
if (r.indexOf(".") == -1)
r = r + ".frx";
else
r.substr(r.indexOf(".") + 1) + ".frx";
var fi = {isnew: true, fname: r};
iwobj.window("close");
if (onItemClick)
onItemClick(fi);
}
});
});
}
iwobj.window("open");
$ajaxjsonget(geturl, function (jsdata) {
var its = "";
ulo.html("");
for (var i = 0; i < jsdata.length; i++) {
var fi = jsdata[i];
var item = $(" <li><span>" + fi.fname + "</span></li>").appendTo(ulo);
item.click(fi, function (event) {
if (onItemClick)
onItemClick(event.data);
iwobj.window("close");
});
}
});
};
////////////////////////////////////new///////////////////////////
function $showModalDialog(poptions) {
function getUnixTimestamp() {
var date = new Date();
var humanDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
return humanDate.getTime() / 1000 - 8 * 60 * 60;
}
var bgObjid = "cwinbg" + getUnixTimestamp();//div
var wdid = "cwin" + getUnixTimestamp();//窗体ID
this.getWindowID = function () {
return wdid;
};
var bgObj = $("<div></div>");
bgObj.attr("id", bgObjid);
var wdObj = $("<div></div>");
wdObj.attr("id", wdid);
wdObj.addClass("easyui-window");
wdObj.attr("title", poptions.title);
wdObj.attr("data-options", poptions.woptions);
wdObj.attr("style", poptions.style);
var layoutobj = $("<div class='easyui-layout' data-options='fit:true,border:false' style='padding: 0px;'></div>");
var layoutcenter = $("<div data-options=\"region:'center',border:false\" style=\"padding:0px;margin: 0px auto;overflow: hidden\">");
var ifrmObj = $("<iframe frameborder=0 style='width: 100%;height: 100%' scrolling='no'>不支持的iframe的浏览器</iframe>");
//ifrmObj.attr("src", poptions.url);
ifrmObj.appendTo(layoutcenter);
var layoutft = $("<div data-options=\"region:'south',border:false\" style=\"text-align:right;padding: 5px;background-color: #EBF2FF;height: auto\">");
var btokObj = $("<a class='easyui-linkbutton'>确定</a>");
btokObj.attr("data-options", "iconCls:'icon-ok'");
btokObj.attr("style", "width:80px");
btokObj.appendTo(layoutft);
var btcancelObj = $("<a class='easyui-linkbutton'>取消</a>");
btcancelObj.attr("data-options", "iconCls:'icon-cancel'");
btcancelObj.attr("style", "width:80px");
btcancelObj.appendTo(layoutft);
layoutcenter.appendTo(layoutobj);
layoutft.appendTo(layoutobj);
layoutobj.appendTo(wdObj);
wdObj.appendTo(bgObj);
bgObj.appendTo("body");
$.parser.parse(bgObj);
var onOKCallBack = undefined, onCancelCallBack = undefined;
this.doOkClick = doclick;
function doclick() {
var iwd = ifrmObj[0].contentWindow;
if (iwd.OnOKModalDialog) {
var rst = iwd.OnOKModalDialog();
if (rst != undefined) {
if (onOKCallBack) {
if (onOKCallBack(rst)) wdObj.window("close");
} else
wdObj.window("close");
}
} else
wdObj.window("close");
}
this.doCancelClick = doCancel;
function doCancel() {
if (onCancelCallBack) onCancelCallBack();
wdObj.window("close");
}
btokObj.click(doclick);
btcancelObj.click(doCancel);
this.show = function (parms, onOK, onCancel) {
onOKCallBack = onOK;
onCancelCallBack = onCancel;
ifrmObj.attr("src", "");
ifrmObj.attr("src", poptions.url + "?parms=" + encodeURIComponent(JSON.stringify(parms))) + "&".concat(Math.random());
wdObj.window("open");
//var iwd = ifrmObj[0].contentWindow;
//if (iwd) {
// iwd.sender = this;
// if (iwd.OnShowModalDialog)
// iwd.OnShowModalDialog(parms);
// }
};
this.close = function () {
wdObj.window("close");
};
}
var curthname = undefined;
setEaysuiTheme();
function setEaysuiTheme() {
var twd = window.top;
var cth = twd.curthname;
if (!cth) {
cth = "default";
twd.curthname = cth;
}
$("link[rel='stylesheet']").each(function () {
var herf = $(this).attr("href");
var ts = "easyui/themes/";
var eidx = herf.indexOf("/easyui.css");
var bidx = herf.indexOf(ts);
if ((bidx > 0) && (eidx > 0)) {
bidx = bidx + ts.length;
var nherf = herf.substr(0, bidx) + cth + "/easyui.css";
$(this).attr("href", nherf);
}
});
$("iframe").each(function () {
var ifr = $(this)[0];
if (ifr) {
var wd = ifr.contentWindow;
if (wd && (wd.setEaysuiTheme)) {
wd.setEaysuiTheme(cth);
}
}
});
}
function $setFindTextByRow(rec, inputo, findeditable) {
//alert(JSON.stringify(rec));
if (findeditable == undefined)
findeditable = false;
if (rec.cjoptions) {
var clsname = rec.cjoptions.easyui_class;
if (!clsname)alert(JSON.stringify(rec.cjoptions) + "没有设置easyui_class");
var funcname = getEasuiFuncNameByCls(clsname);
inputo[funcname](rec.cjoptions);
} else {
if (rec.findtype) {
if (rec.findtype == "date") {
inputo.datebox({
formatter: $dateformattostrrYYYY_MM_DD,
editable: findeditable,
parser: $date4str
});
} else if (rec.findtype == "datetime") {
inputo.datetimebox({
formatter: $dateformattostr,
editable: findeditable,
parser: $date4str
});
} else
inputo.textbox({});
} else {
if (rec.formatter) {
var comurl = rec.formatter("get_com_url");
if (comurl.type == "combobox") {
inputo.combobox({
valueField: comurl.valueField,
textField: comurl.textField,
editable: findeditable,
data: eval('comUrl_' + comurl.index).jsondata
});
} else {
if (rec.formatter == $fieldDateFormatorYYYY_MM_DD) {
inputo.datebox({
formatter: $dateformattostrrYYYY_MM_DD,
editable: findeditable,
parser: $date4str
});
} else if (rec.formatter == $fieldDateFormatorYYYY_MM) {
inputo.datebox({
formatter: $dateformattostrrYYYY_MM,
editable: findeditable,
parser: $date4str
});
$parserDatebox2YearMonth(inputo);
} else if (rec.formatter == $fieldDateFormator) {
inputo.datetimebox({
formatter: $dateformattostr,
editable: findeditable,
parser: $date4str
});
} else if (rec.formatter == $fieldDateFormatorYYYY_MM_DD_HH_MM) {
inputo.datetimebox({
formatter: $dateformattostrrYYYY_MM_DD_HH_MM,
editable: findeditable,
showSeconds: false,
parser: $date4str
});
} else
inputo.textbox({});
}
} else {
inputo.textbox({});
}
}
}
}
var $$demoptions = {
filter: "",
JPAClass: ""
};
function init_jpaattr(options) {
var $tdht = "<td cjoptions=\"fdname:'{{fdname}}'\">{{uscaption}}</td>"
+ "<td><input cjoptions=\"{{options}}\" {{iptattrs}}/></td>";
var filter = options.filter;
if (!filter) {
alert("方法【init_jpaattr】参数【filter】不能为空");
return;
}
var JPAClass = options.JPAClass;
if (!JPAClass) {//试着从窗体配置获取参数
if (frmOptions) {
JPAClass = frmOptions.JPAClass;
} else {
alert("方法【init_jpaattr】参数【JPAClass】不能为空");
return;
}
}
initui();
function initui() {
var url = _serUrl + "/web/common/getJPAAttrsByCls.co?jpaclassname=" + JPAClass;
$ajaxjsonget(url, function (jsdata) {
var colnum = jsdata.colct;
colnum = parseInt(colnum);
if (isNaN(colnum))colnum = 2;
var rows = jsdata.shwjpaattrlines;
var ht = "";
var cct = 0;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (parseInt(row.usable) == 1) {
if (!$isEmpty(row.datasourse)) {
var ds = $.c_parseOptionsStr(row.datasourse);
var cu = {iswie: true};
cu.index = ds.ix;
cu.type = ds.tp;
cu.url = ds.url;
cu.valueField = ds.vf;
cu.textField = ds.tf;
if (comUrls && (comUrls instanceof Array)) {
comUrls.push(cu);
}
}
var rht = $tdht;
if (cct == 0)
rht = "<tr>" + rht;
if (cct + 1 >= colnum) {
rht = rht + "</tr>";
cct == 0;
} else
cct++;
rht = rht.replace(new RegExp("{{fdname}}", "g"), row.fdname);
if (!row.fdcaption)row.fdcaption = "";
rht = rht.replace(new RegExp("{{uscaption}}", "g"), row.uscaption);
var options = row.inputoption;
if ($isEmpty(options)) {
options = "easyui_class:'easyui-textbox',fdname:'" + row.fdname + "'";
}
rht = rht.replace(new RegExp("{{options}}", "g"), options);
var iptattrs = "style='height:20px;width: 120px'";
rht = rht.replace(new RegExp("{{iptattrs}}", "g"), iptattrs);
ht += rht;
}
}
if (!$isEmpty(ht)) {
if (right(ht, 5) != "</tr>")
ht = ht + "</tr>";
ht = "<table>" + ht + "</table>";
//console.error(ht);
$(filter).html(ht);
} else {
$(filter).html("");
}
}, function (err) {
alert(err.errmsg);
}, false);
}
function right(mainStr, lngLen) {
if (mainStr.length - lngLen >= 0 && mainStr.length >= 0 && mainStr.length - lngLen <= mainStr.length) {
return mainStr.substring(mainStr.length - lngLen, mainStr.length)
}
else {
return null
}
}
}
<file_sep>/WebContent/webapp/js/hrms/dlhrsary.js
/**
* Created by Administrator on 2018/12/8.
*/
//查询表单薪资变动明细
function showsalarydetail(tp, id,callback) {
var url = _serUrl + "/web/hr/sa/get_salary_chgblill.co?tp=" + tp + "&id=" + id;
$ajaxjsonget(url, function (jsdata) {
console.log(JSON.stringify(jsdata));
if (parseInt(jsdata.accessed) == 2) {//没有权限
$("#salary_div").hide();
return;
}
$("#salary_div").show();
var chgbill = jsdata.chgbill;
selected_salary_structure = jsdata.newstruc;
var mdata = mainline.getMainData();
mdata.scatype = chgbill.scatype;
mdata.stype = chgbill.stype;
mdata.oldstru_id = chgbill.oldstru_id;
mdata.oldstru_name = chgbill.oldstru_name;
mdata.oldchecklev = chgbill.oldchecklev;
mdata.oldattendtype = chgbill.oldattendtype;
mdata.oldcalsalarytype = chgbill.oldcalsalarytype;
mdata.oldposition_salary = chgbill.oldposition_salary; // 调薪前职位工资
mdata.oldbase_salary = chgbill.oldbase_salary; // 调薪前基本工资
mdata.oldtech_salary = chgbill.oldtech_salary; // 调薪前技能工资
mdata.oldachi_salary = chgbill.oldachi_salary; // 调薪前绩效工资
mdata.oldotwage = chgbill.oldotwage; // 调薪前固定加班工资
mdata.oldtech_allowance = chgbill.oldtech_allowance; // 调薪前技术津贴
mdata.oldparttimesubs = chgbill.oldparttimesubs; // 调薪前兼职津贴
mdata.oldpostsubs = chgbill.oldpostsubs; // 调薪前岗位津贴
mdata.oldavg_salary = chgbill.oldavg_salary; // 调薪前平均工资
mdata.newstru_id = chgbill.newstru_id; // 调薪后工资结构ID
mdata.newstru_name = chgbill.newstru_name; // 调薪后工资结构名
mdata.newchecklev = chgbill.newchecklev; // 调薪后绩效考核层级
mdata.newattendtype = chgbill.newattendtype; // 调薪后出勤类别
mdata.newcalsalarytype = chgbill.newcalsalarytype; // 调薪后计薪方式
mdata.newposition_salary = chgbill.newposition_salary; // 调薪后职位工资
mdata.newbase_salary = chgbill.newbase_salary; // 调薪后基本工资
mdata.newtech_salary = chgbill.newtech_salary; // 调薪后技能工资
mdata.newachi_salary = chgbill.newachi_salary; // 调薪后绩效工资
mdata.newotwage = chgbill.newotwage; // 调薪后固定加班工资
mdata.newtech_allowance = chgbill.newtech_allowance; // 调薪后技术津贴
mdata.newparttimesubs = chgbill.newparttimesubs; // 调薪后兼职津贴
mdata.newpostsubs = chgbill.newpostsubs; // 调薪后岗位津贴
mdata.sacrage = chgbill.sacrage; // 调薪幅度
mdata.chgdate = chgbill.chgdate; // 调薪日期
mdata.chgreason = chgbill.chgreason; // 调薪原因
mainline.setJson2Inputs();
if (callback)
callback(jsdata);
}, function (err) {
alert(JSON.stringify(err));
});
}
function getOldSaralyInfo(er_id, callback) {
var url = _serUrl + "/web/hr/sa/getCur_salary_chglg.co?er_id=" + er_id;
$ajaxjsonget(url, function (jsdata) {
if (parseInt(jsdata.accessed) == 2) {//没有权限
$("#salary_div").hide();
return;
}
$("#salary_div").show();
mainline.setisloadingdata(true);
mainline.setFieldValue('oldstru_id', jsdata.newstru_id);
mainline.setFieldValue('oldstru_name', jsdata.newstru_name);
mainline.setFieldValue('oldchecklev', jsdata.newchecklev);
mainline.setFieldValue('oldattendtype', jsdata.newattendtype);
mainline.setFieldValue('oldposition_salary',(isNaN(jsdata.newposition_salary))?0: parseFloat(jsdata.newposition_salary).toFixed(2));
mainline.setFieldValue('oldbase_salary',(isNaN(jsdata.newbase_salary))?0: parseFloat(jsdata.newbase_salary).toFixed(2));
mainline.setFieldValue('oldotwage',(isNaN(jsdata.newotwage))?0: parseFloat(jsdata.newotwage).toFixed(2));
mainline.setFieldValue('oldtech_salary',(isNaN(jsdata.newtech_salary))?0: parseFloat(jsdata.newtech_salary).toFixed(2));
mainline.setFieldValue('oldachi_salary',(isNaN(jsdata.newachi_salary))?0: parseFloat(jsdata.newachi_salary).toFixed(2));
mainline.setFieldValue('oldtech_allowance',(isNaN(jsdata.newtech_allowance))?0: parseFloat(jsdata.newtech_allowance).toFixed(2));
mainline.setFieldValue('oldparttimesubs',(isNaN(jsdata.newparttimesubs))?0: parseFloat(jsdata.newparttimesubs).toFixed(2));
mainline.setFieldValue('oldpostsubs',(isNaN(jsdata.newpostsubs))?0: parseFloat(jsdata.newpostsubs).toFixed(2));
mainline.setFieldValue('newstru_id', jsdata.newstru_id);
mainline.setFieldValue('newstru_name', jsdata.newstru_name);
mainline.setFieldValue('newchecklev', jsdata.newchecklev);
mainline.setFieldValue('newattendtype', jsdata.newattendtype);
mainline.setFieldValue('newposition_salary', parseFloat(jsdata.newposition_salary).toFixed(2));
mainline.setFieldValue('newbase_salary', parseFloat(jsdata.newbase_salary).toFixed(2));
mainline.setFieldValue('newotwage', parseFloat(jsdata.newotwage).toFixed(2));
mainline.setFieldValue('newtech_salary', parseFloat(jsdata.newtech_salary).toFixed(2));
mainline.setFieldValue('newachi_salary', parseFloat(jsdata.newachi_salary).toFixed(2));
mainline.setFieldValue('newtech_allowance',(isNaN(jsdata.newtech_allowance))?0: parseFloat(jsdata.newtech_allowance).toFixed(2));
mainline.setFieldValue('newparttimesubs', (isNaN(jsdata.newparttimesubs))?0: parseFloat(jsdata.newparttimesubs).toFixed(2));
mainline.setFieldValue('newpostsubs',(isNaN(jsdata.newpostsubs))?0: parseFloat(jsdata.newpostsubs).toFixed(2));
mainline.setisloadingdata(false);
if (callback)
callback(jsdata);
}, function (err) {
alert(JSON.stringify(err));
});
}
function $RndNum(n) {
var rnd = "";
for (var i = 0; i < n; i++)
rnd += Math.floor(Math.random() * 10);
return rnd;
}<file_sep>/src/com/corsair/server/test/Test.java
package com.corsair.server.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPoolParms;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.VclZip;
import com.corsair.server.genco.CODevloper;
import com.corsair.server.generic.Shwposition;
import com.corsair.server.generic.Shwrole;
import com.corsair.server.generic.Shwuserparmsconst;
import com.corsair.server.util.Base64;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DesSwEx;
import com.corsair.server.util.MatrixUtil;
import com.corsair.server.weixin.WXMsgSend;
import com.corsair.server.weixin.WXUtil;
public class Test {
private static ReadWriteLock rwl = new ReentrantReadWriteLock();
private static List<String> ls = new ArrayList<String>();
private static Lock lock = new ReentrantLock();
final static char[] digits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' };
private static String sctstr = "var a=1;b=2;" +
"function add(a,b){" +
"return a+b;" +
"}" +
"function cf(a,b){" +
"return a*b" +
"}";
private static void f1(boolean a) {
a = !a;
}
private static void f2(Boolean a) {
a = !a;
}
private static boolean hasKey(List<HashMap<String, String>> list, String key) {
for (HashMap<String, String> item : list) {
if (item.containsKey(key))
return true;
}
return false;
}
public static List<String> testlist = new ArrayList<String>();
public static void main(String[] args) throws Exception {
// Date actd = Systemdate.getDateByStr("2015-11-01");
// Calendar cale = Calendar.getInstance();
// cale.setTime(actd);
// cale.set(Calendar.DAY_OF_MONTH,
// cale.getActualMaximum(Calendar.DAY_OF_MONTH));
// Date actded = cale.getTime();
//
// System.out.println(Systemdate.getStrDateyyyy_mm_dd(actded));
// System.out.println(CorUtil.isNumeric("123.21"));
// System.out.println(CorUtil.isNumeric("123"));
// String mxs = "http://www.icefall.com.cn?fdsafdsafdsa=fdsafdsa";
// File f = new File("c:\\a.jpg");
// MatrixUtil.toQrcodeFile(mxs, f, 800, 800, "jpg");
// int a = 3280340;
// System.out.println(a);
// String s = numericToString(a, 16);
// System.out.println(s);
// System.out.println(stringToNumeric(s, 16));
// for (int i = 0; i < 5; i++) {
// Thread t = newFunctionT1();
// t.setName("ThreadA" + i);
// t.start();
// //System.out.println("Thread start:" + t.getName());
// }
//
// for (int i = 0; i < 5; i++) {
// Thread t = newFunctionT2();
// t.setName("ThreadB" + i);
// t.start();
// //System.out.println("Thread start:" + t.getName());
// }
// for (int i = 0; i < 5; i++) {
// Thread t = newUpdateT();
// t.setName("UT" + i);
// t.start();
// // System.out.println("Thread start:" + t.getName());
// }
//
// for (int i = 0; i < 100; i++) {
// Thread t = newReadT();
// t.setName("RT" + i);
// t.start();
// }
// System.out.println(WXUtil.getWXDatetime());
// String[] fileName =
// getFileName("D:\\MyWorks2\\zy\\webservice\\tomcat71\\webapps\\csm\\webapp\\js\\easyui\\themes\\icons\\filetype\\32");
// for (String name : fileName) {
// String an = name.substring(0, name.indexOf("."));
//
// String s = ".icon-file-" + an + "32 {\n"
// + "background: url('icons/filetype/32/" + name +
// "') no-repeat left center;\n"
// + "}";
// System.out.println(s);
// }
// readf();
// System.out.println(getShortHex(200) + getShortHex(147) +
// getShortHex(70) + getShortHex(192) + getShortHex(74) +
// getShortHex(80));
// 线程锁测试
// ThreadCallSourse tcs = new ThreadCallSourse();
// for (int i = 0; i < 10; i++) {
// (new Thread(new TestThreadRunable(tcs, i))).start();
// (new Thread(new TestThreadRunable2(tcs, i))).start();
// }
// String msg = null;
// String rst = dotest1(msg);
// System.out.println("rst:" + rst);
// System.out.println("msg:" + msg);
// TestClass1 c1 = new TestClass1();
// TestClass1 c2 = new TestClass1();
// System.out.println(c1.getnewid());
// System.out.println(c2.getnewid());
// String pstr = "003";
// String cstr = "004002";
// System.out.println(cstr.substring(pstr.length(), cstr.length()));
// String funcname = "aaa.bb.cc.dd.fffffff";
// String classname = funcname.substring(0, funcname.lastIndexOf("."));
// String mname = funcname.substring(funcname.lastIndexOf(".") + 1);
// System.out.println(classname + "|" + mname);
// String s1="111222333";
// System.out.println(s1.substring(0, 12));
// String[] allfields = { "orgid", "orgname", "code", "superid", "extorgname", "manager", "orgtype", "idpath", "stat", "creator",
// "createtime", "updator", "updatetime", "attribute1" };
// System.out.println(strs2str(allfields));
// System.out.println(rightSubstr("1", 2));
// Class2 c2 = new Class2();
// c2.function1();
// String ss = "http://www.163.com/webapp/aaa.html";
// System.out.println(ss.substring(0, ss.lastIndexOf("/")+1));
// Date resdate = new Date();
// String sdb = Systemdate.getStrDateByFmt(resdate, "yyyy-MM-01");
// String sde = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(resdate, 1), "yyyy-MM-01");
// System.out.println(sdb + " " + sde);
// float days = (float) 4 / 8;// 按每天8小时计算
// System.out.println(1);
// System.out.println(Float.valueOf("1.0"));
// CDBPool pool = getpool();
// CDBConnection con = pool.getCon(null);
// CJPALineData<Shwuserparmsconst> pcs = new CJPALineData<Shwuserparmsconst>(Shwuserparmsconst.class);
// pcs.findDataBySQL(con, "select * from shwuserparmsconst", false, false);
//
// String sqlstr = "SELECT * FROM `a_init_user1225`";
// List<HashMap<String, String>> ius = pool.openSql2List(sqlstr);
// for (HashMap<String, String> iu : ius) {
// String userid = iu.get("userid").toString();
// String username = iu.get("username").toString();
// for (CJPABase jpa : pcs) {
// Shwuserparmsconst pc = (Shwuserparmsconst) jpa;
// sqlstr = "INSERT INTO shwuserparms(cstparmid, userid, parmvalue) VALUES ('" + pc.cstparmid.getValue() + "', '" + userid + "', '"
// + pc.defaultvalue.getValue() + "')";
// pool.execsql(sqlstr);
// }
// }
// System.out.println("OK");
// System.out.println(Math.round(Float.valueOf("4.0")));
// List<String> delfs = new ArrayList<String>();
// delfs.add("aaaa");
// delfs.add("bbb");
// delfs.add("ccc");
// String[] as = new String[delfs.size()];
// delfs.toArray(as);
// for(String s:as){
// System.out.println(s);
// }
// System.out.println(511 >> 8);
// System.out.println(511 - ((511 >> 8) << 8));
// int[] as = getLEndLong(23, 2);
// for (int a : as)
// System.out.println(Integer.toHexString(a));
// String synid="20170322224313266732";
// synid = synid.substring(2, synid.length());
// System.out.println(synid);
// Random random = new Random();
// for (int i = 0; i < 4; i++)
// System.out.println(random.nextInt(100));
// JSONObject jo = new JSONObject();
// jo.put("rst", "OK");
// System.out.println(jo.toString());
// String v="412,";
// System.out.println(v.substring(0, v.length()-1));
// String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
// System.out.println(code);
// for (int i = 1; i <= 31; i++) {
// String d = "00" + i;
// d = d.substring(d.length() - 2, d.length());
// System.out.println(d);
// }
// jpatest();
// long a = 1000 * 60 * 60*24 ;
// String sd1 = "2017-07-03 12:12:12";
// String sd2 = "2017-07-03 12:12:12";
//
// long rst1 = Systemdate.getDateByStr(sd1).getTime() / a;
// long rst2 = Systemdate.getDateByStr(sd2).getTime() / a;
//
// System.out.println(rst1 + ":" + rst2);
// String str="1234567890";
// System.out.println(str.substring(1,str.length()-1));
// System.out.println(str.substring(1,str.length()));
// Date t = Systemdate.getDateByStr("20180415121843", "yyyyMMddHHmmss");
// System.out.println(Systemdate.getStrDate(t));//2018-04-15 12:18:43
// System.out.println(new Date().getTime());
// JSONObject j1 = new JSONObject();
// j1.put("a", "11111111");
// j1.put("b", "33333333");
// JSONObject j2 = new JSONObject();
// j2.put("b", "222222222");
// j2.putAll(j1);
// System.out.println(j2.toString());
// float allothours = 4f;
// float mu = 3.5f;
// float fhs = (allothours - allothours % mu);
// System.out.println(fhs);
// String md5str ="username=系统管理员&noncestr=lFdNxnt2RAtBO2I0Uqz2l3SvyXJgMsb5×tr=20180611164735&password=<PASSWORD>";
// md5str = DesSwEx.MD5(md5str);
// System.out.println(md5str);
// System.out.println(Boolean.valueOf("TRUE1"));
// WXMsgSend.MergeConent(null, "fdsafdsafdsa{{{{parame1}},fdsa{{parame2}},fdsa{{parame4}}");
// System.out.println("1234567890".subSequence(0, 2));
// System.out.println(new Date().getTime());
// System.out.println(ConstsSw.EncryUserPassword("<PASSWORD>"));
// System.out.println(ConstsSw.DESryUserPassword("<PASSWORD>"));
// String s1 = "1,2,3,4,5,";
// String s2 = "1,3,4,";
// System.out.print(s1.substring(0, s2.length()));// 1,2,3,
System.out.println("hellow word");
}
private static void jpatest() throws Exception {
CDBPool pool = getpool();
String sqlstr = "select * from atable_test";
System.out.println(new CODevloper().createJPAClass(pool, "Atable_test", sqlstr));
}
// 获取长整形小端数组
// 负数无效
public static int[] getLEndLong(long l) {
List<Integer> lis = new ArrayList<Integer>();
while (l > 0) {
long lt = l >> 8;
int f = (int) (l - (lt << 8));
lis.add(f);
l = lt;
}
int[] rst = new int[lis.size()];
for (int i = 0; i < rst.length; i++)
rst[i] = lis.get(i);
return rst;
}
// 限制位数 超过截取 不足不0 错误
public static int[] getLEndLong(long l, int bts) {
int[] les = getLEndLong(l);
int[] rst = new int[bts];
int s = les.length;
int k = 0;
for (int i = 0; i < bts; i++) {
rst[i] = (i < s) ? les[i] : 0;
}
return rst;
}
// Object o = iu.get("position");
// if (o != null) {
// String userid = iu.get("userid").toString();
// String ps = o.toString();
// if (!ps.isEmpty()) {
// String[] pps = ps.split(",");
// for (String pp : pps) {
// String positionid = getopid(ops, pp);
// if (positionid == null) {
// System.out.println(pp + ",找不到岗位ID");
// }
// sqlstr = "INSERT INTO shwpositionuser(positionid, userid) VALUES (" + positionid + ", " + userid + ")";
// pool.execsql(sqlstr);
// }
// }
// }
private static String getorgid(CDBPool pool, String employee_code) throws Exception {
String sqlstr = "SELECT orgid FROM `hr_employee` WHERE `employee_code`='" + employee_code + "'";
List<HashMap<String, String>> oids = pool.openSql2List(sqlstr);
if (oids.size() <= 0)
return null;
return oids.get(0).get("orgid").toString();
}
private static String getroid(CJPALineData<Shwrole> ops, String rolename) {
for (CJPABase jpa : ops) {
Shwrole op = (Shwrole) jpa;
if (op.rolename.getValue().equalsIgnoreCase(rolename)) {
return op.roleid.getValue();
}
}
return null;
}
private static String getopid(CJPALineData<Shwposition> ops, String positiondesc) {
for (CJPABase jpa : ops) {
Shwposition op = (Shwposition) jpa;
if (op.positiondesc.getValue().equalsIgnoreCase(positiondesc)) {
return op.positionid.getValue();
}
}
return null;
}
private static CDBPool getpool() {
DBPoolParms pm = new DBPoolParms();
pm.dirver = "com.mysql.jdbc.Driver";
pm.url = "jdbc:mysql://127.0.0.1:13306/dlhr?characterEncoding=utf-8&autoReconnect=true&useSSL=true";
pm.schema = "dlhr";
pm.user = "root";
pm.password = "<PASSWORD>";
pm.minsession = 5;
pm.maxsession = 10;
pm.isdefault = true;
CDBPool pool = new CDBPool(pm);
return pool;
}
private static String rightSubstr(String s, int l) {
return s.substring(s.length() - l, s.length());
}
private static String strs2str(String[] fds) {
String rst = "";
for (String fd : fds) {
rst = rst + fd + ",";
}
if (!rst.isEmpty())
rst = rst.substring(0, rst.length() - 1);
return rst;
}
public static String dotest1(String msg) {
msg = "11111";
return "22222";
}
public static String getShortHex(long value) {
String s = Long.toHexString(value).toUpperCase();
if (s.length() < 2)
s = "0" + s;
return s;
}
public static void readf() {
try {
// read file content from file
StringBuffer sb = new StringBuffer("");
FileReader reader = new FileReader("d://filetype.txt");
BufferedReader br = new BufferedReader(reader);
String str = null;
while ((str = br.readLine()) != null) {
int idx = str.indexOf(":");
System.out.println(str.substring(0, idx));
System.out.println(str.substring(idx + 1));
}
br.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String[] getFileName(String path) {
File file = new File(path);
String[] fileName = file.list();
return fileName;
}
private static final void printIp() {
}
public static String numericToString(int i, int system) {
long num = 0;
if (i < 0) {
num = ((long) 2 * 0x7fffffff) + i + 2;
} else {
num = i;
}
char[] buf = new char[32];
int charPos = 32;
while ((num / system) > 0) {
buf[--charPos] = digits[(int) (num % system)];
num /= system;
}
buf[--charPos] = digits[(int) (num % system)];
return new String(buf, charPos, (32 - charPos));
}
public static int stringToNumeric(String s, int system) {
char[] buf = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
long num = 0;
for (int i = 0; i < buf.length; i++) {
for (int j = 0; j < digits.length; j++) {
if (digits[j] == buf[i]) {
num += j * Math.pow(system, buf.length - i - 1);
break;
}
}
}
return (int) num;
}
private static Thread newFunctionT1() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Test.funciton1();
}
});
return t;
}
private static Thread newFunctionT2() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Test.funciton2();
}
});
return t;
}
private static void funciton1() {
Test.lock.lock();
try {
String n = Thread.currentThread().getName();
System.out.println(n + "进入funciton1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(n + "退出funciton1");
} finally {
Test.lock.unlock();
}
}
private static void funciton2() {
Test.lock.lock();
try {
String n = Thread.currentThread().getName();
System.out.println(n + "进入funciton2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(n + "退出funciton2");
} finally {
Test.lock.unlock();
}
}
// ///////////////////////////////////////
// ///////////////////////////////////////
// ///////////////////////////////////////
// ///////////////////////////////////////
private static Thread newUpdateT() {
Thread Tupdate = new Thread(new Runnable() {
@Override
public void run() {
rwl.writeLock().lock();// 取到写锁
try {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!ls.contains(i)) {
ls.add(String.valueOf(i));
}
System.out.println(Thread.currentThread().getName() + "写入");
}
} finally {
rwl.writeLock().unlock();// 释放写锁
}
}
});
return Tupdate;
}
private static Thread newReadT() {
Thread Tupdate = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (!ls.contains(i)) {
int idx = ls.indexOf(i);
if (idx >= 0) {
String s = ls.get(idx);
System.out.println(Thread.currentThread().getName() + "读取:" + s + ";sum:" + ls.size());
} else
System.out.println(Thread.currentThread().getName() + "读取NULL;sum:" + ls.size());
} else
System.out.println(Thread.currentThread().getName() + "读取NULL;sum:" + ls.size());
}
}
});
return Tupdate;
}
public static String read(String fileName, String encoding) {
StringBuffer fileContent = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), encoding));
String line = null;
while ((line = br.readLine()) != null) {
fileContent.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileContent.toString();
}
}
<file_sep>/src/com/corsair/server/ctrl/OnChangeOrgInfoListener.java
package com.corsair.server.ctrl;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.generic.Shworg;
import net.sf.json.JSONObject;
/**
* 机构信息变动监听器
*
* @author Administrator
*
*/
public abstract class OnChangeOrgInfoListener {
public abstract void OnOrgChg(CDBConnection con, JSONObject jorg, JSONObject jporg) throws Exception;
public abstract void OnOrgData2Org(CDBConnection con, Shworg sorg, JSONObject dorg_s) throws Exception;
}
<file_sep>/src/com/corsair/cjpa/JPAControllerBase.java
package com.corsair.cjpa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.corsair.cjpa.CJPABase.JPAAction;
import com.corsair.cjpa.util.CPoint;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.PraperedSql;
/**
* 控制器基类
*
* @author Administrator
*
*/
public class JPAControllerBase {
public enum ArraiveType {
atCreate, atSubmit, atReject
};
public String OngetNewCode(CJPABase jpa, int codeid) {
return null;
}
/**
* 保存前
*
* @param jpa里面有值
* ,还没检测数据完整性,没生成ID CODE 设置默认值
* @param con
* @param selfLink
* @throws Exception
*/
public void BeforeSave(CJPABase jpa, CDBConnection con, boolean selfLink) throws Exception {
}
/**
* 保存中
*
* @param jpa
* 完成完整性检测、生成ID、CODE、设置完默认值、生成SQL语句;还未保存到数据库,JPA状态未变
* @param con
* @param sqllist
* @param selfLink
* @throws Exception
*/
public void OnSave(CJPABase jpa, CDBConnection con, ArrayList<PraperedSql> sqllist, boolean selfLink) throws Exception {
}
/**
* 完成保存
*
* @param jpa
* 已经实例化到数据库,JPA变为 RSLOAD4DB 状态
* @param con
* @param selfLink
*/
public void AfterSave(CJPABase jpa, CDBConnection con, boolean selfLink) throws Exception {
}
/**
* 删除前 貌似列表JPA被干掉时候无法监控到
*
* @param jpa还未保存到数据库
* ,JPA状态未变
* @param con
* @param selfLink
* @throws Exception
*/
public void OnDelete(CJPABase jpa, CDBConnection con, boolean selfLink) throws Exception {
}
/**
* 监控JPA 持久化 插入、更新、删除
* JPA通过ID删除 貌似无法监控到自关联数据删除
* 保存中,已经生成SQL语句,重新给JPA赋值也没卵用了
*
* @param jpa
* @param con
* @param act
* @throws Exception
*/
public void OnJAPAction(CJPABase jpa, CDBConnection con, JPAAction act) throws Exception {
}
/**
* 打印到Excel
* 用于从数据库获取数据
*
* @param jpa
* @param mdfname
* @return
*/
public List<HashMap<String, String>> OnPrintDBData2Excel(CJPABase jpa, String mdfname) {
return null;
}
/**
* 打印某一个字段到某一个CELL事件,返回false 将不执行默认打印
*
* @param jpa
* @param mdfname
* @param fdname
* @param cell
* @return
*/
public String OnPrintField2Excel(CJPABase jpa, String modelkey, String fdname, String value, Cell cell) {
return null;
}
/**
* 向Excel写入一条数据后
*
* @param jpa
* @param mdfname
* @param sheet
* @param cellfrom
* col == x row ==y
* @param cellto
*/
public void AfterPrintItem2Excel(CJPABase jpa, String modelkey, Workbook workbook, Sheet sheet, CPoint cellfrom, CPoint cellto) {
}
}
<file_sep>/src/com/hr/salary/ctr/CtrHr_salary_techsub_cancel.java
package com.hr.salary.ctr;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.salary.entity.Hr_salary_chglg;
import com.hr.salary.entity.Hr_salary_techsub_cancel;
import com.hr.salary.entity.Hr_salary_techsub_line;
public class CtrHr_salary_techsub_cancel extends JPAController {
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf,
boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if(isFilished){
doCancelTechSub(jpa,con);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf,
Shwwfproc proc, Shwwfproc nxtproc, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
if(isFilished){
doCancelTechSub(jpa,con);
}
}
private void doCancelTechSub(CJPA jpa, CDBConnection con) throws Exception{
Hr_salary_techsub_cancel tsc=(Hr_salary_techsub_cancel)jpa;
float subsidyarm = tsc.ntechsub.getAsFloatDefault(0);
if (subsidyarm == 0)
return;
subsidyarm = subsidyarm * -1;
Hr_salary_chglg scold = CtrSalaryCommon.getCur_salary_chglg(tsc.er_id.getValue());// 获取现在薪资情况
Hr_salary_chglg sc = new Hr_salary_chglg();
sc.er_id.setValue(tsc.er_id.getValue());
sc.scatype.setValue(8);// 1 入职定薪、2调动核薪、3 转正调薪、4 年度调薪、5 特殊调薪 6调动转正 7 兼职8津贴
sc.stype.setValue(10); // 来源类别 1 历史数据、2 实习登记、3 入职表单、4 调动表单、5 入职转正、6 调动转正、7个人特殊调薪 8兼职、9批量特殊调薪、10技术津贴....
sc.sid.setValue(tsc.tsc_id.getValue()); // 来源ID
sc.scode.setValue(tsc.tsc_code.getValue()); // 来源单号
sc.oldstru_id.setValue(scold.newstru_id.getValue()); // 调薪前工资结构ID
sc.oldstru_name.setValue(scold.newstru_name.getValue()); // 调薪前工资结构名
sc.oldchecklev.setValue(scold.newchecklev.getValue());// 调薪前绩效考核层级
sc.oldattendtype.setValue(scold.newattendtype.getValue()); // 调薪前出勤类别
sc.oldcalsalarytype.setValue(scold.newcalsalarytype.getValue()); // 调薪前计薪方式
sc.oldposition_salary.setValue(scold.newposition_salary.getValue()); // 调薪前职位工资
sc.oldbase_salary.setValue(scold.newbase_salary.getValue()); // 调薪前基本工资
sc.oldtech_salary.setValue(scold.newtech_salary.getValue()); // 调薪前技能工资
sc.oldachi_salary.setValue(scold.newachi_salary.getValue()); // 调薪前绩效工资
sc.oldotwage.setValue(scold.newotwage.getValue()); // 调薪前固定加班工资
sc.oldtech_allowance.setValue(scold.newtech_allowance.getValue()); // 调薪前技术津贴
sc.oldparttimesubs.setValue(scold.newparttimesubs.getValue()); // 调薪前兼职津贴
sc.oldpostsubs.setValue(scold.newpostsubs.getValue()); // 调薪前岗位津贴
sc.oldavg_salary.setValue(0); // 调薪前平均工资
sc.newstru_id.setValue(scold.newstru_id.getValue()); // 调薪后工资结构ID
sc.newstru_name.setValue(scold.newstru_name.getValue()); // 调薪后工资结构名
sc.newchecklev.setValue(scold.newchecklev.getValue());// 调薪后绩效考核层级
sc.newattendtype.setValue(scold.newattendtype.getValue()); // 调薪后出勤类别
sc.newcalsalarytype.setValue(scold.newcalsalarytype.getValue()); // 调薪后计薪方式
sc.newposition_salary.setValue(scold.newposition_salary.getAsFloatDefault(0)); // 调薪后职位工资
sc.newbase_salary.setValue(scold.newbase_salary.getAsFloatDefault(0)); // 调薪后基本工资
sc.newtech_salary.setValue(scold.newtech_salary.getAsFloatDefault(0)); // 调薪后技能工资
sc.newachi_salary.setValue(scold.newachi_salary.getAsFloatDefault(0)); // 调薪后绩效工资
sc.newotwage.setValue(scold.newotwage.getAsFloatDefault(0)); // 调薪后固定加班工资
sc.newparttimesubs.setValue(scold.newparttimesubs.getAsFloatDefault(0)); // 调薪后兼职津贴
float newtech_allowance = scold.newtech_allowance.getAsFloatDefault(0) + subsidyarm;
if (newtech_allowance < 0)
newtech_allowance = 0;
sc.newtech_allowance.setValue(newtech_allowance); // 调薪后技术津贴
sc.newpostsubs.setValue(scold.newpostsubs.getAsFloatDefault(0)); // 调薪后岗位津贴
sc.sacrage.setValue(subsidyarm); // 调薪幅度
sc.chgdate.setValue(tsc.canceldate.getValue()); // 调薪日期
sc.chgreason.setValue("技术津贴中止审批通过调薪"); // 调薪原因
sc.save(con);
String sqlstr="SELECT tsl.* FROM `hr_salary_techsub` ts,`hr_salary_techsub_line` tsl "+
"WHERE tsl.ts_id=ts.ts_id AND ts.stat=9 AND tsl.isend=2 and er_id="+tsc.er_id.getValue()+
" and tsl_id="+tsc.tsl_id.getValue();
Hr_salary_techsub_line tsl=new Hr_salary_techsub_line();
tsl.findBySQL(sqlstr);
if(!tsl.isEmpty()){
tsl.isend.setAsInt(1);
tsl.save(con);
}
}
}
<file_sep>/src/com/hr/.svn/pristine/19/19cecd246674f7e43860f43008176b19b941517c.svn-base
package com.hr.attd.co;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.attd.ctr.CtrHrkq_overtime;
import com.hr.attd.entity.Hrkq_overtime;
import com.hr.attd.entity.Hrkq_overtime_hour;
import com.hr.attd.entity.Hrkq_overtime_line;
import com.hr.attd.entity.Hrkq_overtime_qual;
import com.hr.attd.entity.Hrkq_overtime_qual_line;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
@ACO(coname = "web.hrkq.overtime")
public class COHrkq_overtime {
@ACOAction(eventname = "findOverTimeHours", Authentication = true, ispublic = false, notes = "查询加班时间段")
public String findOverTimeHours() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String otl_id = CorUtil.hashMap2Str(parms, "otl_id", "需要参数otl_id");
Hrkq_overtime_hour oth = new Hrkq_overtime_hour();
String sqlstr = "SELECT * FROM hrkq_overtime_hour WHERE otl_id= " + otl_id;
return oth.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "getOverTimeTotal", Authentication = true, ispublic = false, notes = "查询加班汇总信息")
public String getOverTimeTotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String[] notnull = {};
String ps = parms.get("parms");
if (ps == null) {
throw new Exception("需要选择筛选条件");
}
List<JSONParm> jps = CJSON.getParms(ps);
String orgcode = CorUtil.getJSONParmValue(jps, "orgcode1", "需要参数【机构编码】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【统计年月】");
Date begin_date = Systemdate.getDateByStr(yearmonth + "-01");
Date end_date = Systemdate.dateMonthAdd(begin_date, 1);
String bdate = Systemdate.getStrDateyyyy_mm_dd(begin_date);
String edate = Systemdate.getStrDateyyyy_mm_dd(end_date);
Shworg org = new Shworg();
String sqlstr1 = "select * from shworg where usable=1 and code = '" + orgcode + "'";
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("名称为【" + orgcode + "】的机构不存在");
String sqlstr = "select '" + yearmonth + "' yearmonth,tb.* from (select em.orgid, em.orgcode, if(em.hwc_namezl='OO',2,1) isoffjob,"
+ " em.orgname, em.er_id, em.employee_code, em.employee_name, "
+ " em.lv_id, em.lv_num, em.ospid, em.sp_name, otl.dealtype, em.idpath, " // otl.bgtime, otl.edtime,
+ " sum(otl.othours) othours, SUM( "
+ " CASE "
+ " WHEN ot.over_type = 1 and otltype IN(1,2) "
+ " THEN otl.othours "
+ " ELSE 0 "
+ " END "
+ " ) othour1, SUM( "
+ " CASE "
+ " WHEN ot.over_type = 2 and otltype IN(1,2) "
+ " THEN otl.othours "
+ " ELSE 0 "
+ " END "
+ " ) othour2, SUM( "
+ " CASE "
+ " WHEN ot.over_type = 3 and otltype IN(1,2) "
+ " THEN otl.othours "
+ " ELSE 0 "
+ " END "
+ " ) othour3, SUM( "
+ " CASE "
+ " WHEN otltype IN(3,4,5) "
+ " THEN otl.othours "
+ " ELSE 0 "
+ " END "
+ " ) othour4, SUM( "
+ " CASE "
+ " WHEN otl.frst=2 "
+ " THEN 1 "
+ " ELSE 0 "
+ " END "
+ " ) cdnums, SUM( "
+ " CASE "
+ " WHEN otl.trst=3 "
+ " THEN 1 "
+ " ELSE 0 "
+ " END "
+ " ) ztnums,( "
+ " CASE "
+ " WHEN ot.over_type = 1 "
+ " THEN ot.otrate "
+ " ELSE 0 "
+ " END "
+ " ) otrate1, ( "
+ " CASE "
+ " WHEN ot.over_type = 2 "
+ " THEN ot.otrate "
+ " ELSE 0 "
+ " END "
+ " ) otrate2, ( "
+ " CASE "
+ " WHEN ot.over_type = 3 "
+ " THEN ot.otrate "
+ " ELSE 0 "
+ " END "
+ " ) otrate3 "
+ " FROM hr_employee em,hrkq_overtime_list otl LEFT JOIN hrkq_overtime ot ON ot.ot_id = otl.ot_id "
+ " where otl.er_id = em.er_id "
+ " AND em.idpath like '" + org.idpath.getValue() + "%'";
sqlstr = sqlstr + " and otl.edtime>='" + bdate + "'";
sqlstr = sqlstr + " and otl.edtime<='" + edate + "'";
sqlstr = sqlstr + " group by otl.er_id,otl.dealtype) tb where 1=1 ";
String[] ignParms = { "yearmonth", "orgcode1" };// 忽略的查询条件
JSONObject rst = new CReport(sqlstr, notnull).findReport2JSON_O(ignParms);
JSONArray rows = rst.getJSONArray("rows");
getOverTimeTotalExinfo(rows, bdate, edate);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(rows, scols);
return null;
}
}
private void getOverTimeTotalExinfo(JSONArray rows, String bdate, String edate) throws Exception {
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
String er_id = row.getString("er_id");
if (row.has("dealtype") && (row.getInt("dealtype") == 2)) {
String sqlstr = "SELECT IFNULL(permonlimit,0) permonlimit FROM hrkq_overtime_qual q,`hrkq_overtime_qual_line`l "
+ " WHERE q.`oq_id`=l.oq_id AND q.`stat`=9 AND l.`breaked`=2 AND l.er_id=" + er_id
+ " AND q.`begin_date`<'" + edate + "' AND q.`end_date`>'" + bdate + "' "
+ " ORDER BY q.`apply_date` DESC LIMIT 1";
List<HashMap<String, String>> mps = DBPools.defaultPool().openSql2List(sqlstr);
double permonlimit = 0;
if (mps.size() > 0) {
permonlimit = Double.valueOf(mps.get(0).get("permonlimit").toString());
}
row.put("permonlimit", permonlimit);
double othours = row.getDouble("othours");
double ccothours = othours - permonlimit;
if (ccothours < 0)
ccothours = 0;
row.put("ccothours", ccothours);
double vvothours = othours - ccothours;
row.put("vvothours", vvothours);
}
}
}
@ACOAction(eventname = "checkOverTime", Authentication = true, ispublic = false, notes = "检查加班时间合法性")
public String checkOverTime() throws Exception {
Hrkq_overtime ot = new Hrkq_overtime();
ot.fromjson(CSContext.getPostdata());
if (ot.stat.getAsIntDefault(0) >= 2) {
return "{\"rst\":\"OK\"}";
}
if ((ot.isoffjob.getAsIntDefault(0) == 2) || (ot.dealtype.getAsIntDefault(0) == 1))// 非脱产或调休不控制
return "{\"rst\":\"OK\"}";
for (CJPABase jt : ot.hrkq_overtime_lines) {
Hrkq_overtime_line otl = (Hrkq_overtime_line) jt;
CtrHrkq_overtime.check(ot, otl);
}
return "{\"rst\":\"OK\"}";
}
@ACOAction(eventname = "qualimpexcel", Authentication = true, ispublic = false, notes = "加班资格从表Excel")
public String qualimpexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
HashMap<String, String> parms = CSContext.getParms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String lv_num = CorUtil.hashMap2Str(parms, "emplev", "需要参数emplev");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
String rst = null;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, orgid, lv_num);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
return rst;
}
private String parserExcelFile(Shw_physic_file pf, String orgid, String lv_num) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, orgid, lv_num);
}
private String parserExcelSheet(Sheet aSheet, String orgid, String lv_num) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "";
}
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
JSONArray rst = new JSONArray();
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
// System.out.println("employee_code:" + employee_code);
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
Hr_employee emp = new Hr_employee();
String sqlstr = "SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "' and idpath like '" + org.idpath.getValue() + "%'";
int lvn = Integer.valueOf(lv_num);
if (lvn == 1) {
sqlstr = sqlstr + " and lv_num>=3 and lv_num<4 ";
}
if (lvn == 2) {
sqlstr = sqlstr + " and lv_num>=4 ";
}
emp.findBySQL(sqlstr);
if (emp.isEmpty())
throw new Exception("限定机构及职级条件下,工号【" + employee_code + "】的人事资料不存在");
JSONObject jo = emp.toJsonObj();
jo.put("remark", v.get("remark"));
rst.add(jo);
}
return rst.toString();
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "overtimeimpexcel", Authentication = true, ispublic = false, notes = "加班从表孙表导入Excel")
public String overtimeimpexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
HashMap<String, String> parms = CSContext.getParms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String lv_num = CorUtil.hashMap2Str(parms, "emplev", "需要参数emplev");
String isoffjob = CorUtil.hashMap2Str(parms, "isoffjob", "需要参数isoffjob");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
String rst = null;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFileOverTime(p, orgid, lv_num, isoffjob);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
return rst;
}
private String parserExcelFileOverTime(Shw_physic_file pf, String orgid, String lv_num, String isoffjob) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheetOvertime(aSheet, orgid, lv_num, isoffjob);
}
private String parserExcelSheetOvertime(Sheet aSheet, String orgid, String lv_num, String isoffjob) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "";
}
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
List<CExcelField> efds = initExcelFieldsOvertime();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 1);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 1);
JSONArray rst = new JSONArray();
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
// System.out.println("employee_code:" + employee_code);
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
Hr_employee emp = new Hr_employee();
String sqlstr = "SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "' and idpath like '" + org.idpath.getValue() + "%'";
int lvn = Integer.valueOf(lv_num);
if (lvn == 1) {
sqlstr = sqlstr + " and lv_num>=3 and lv_num<4 and hg_name not like 'M%'";
}
if (lvn == 2) {
sqlstr = sqlstr + " and lv_num>=4";
}
int ifo = Integer.valueOf(isoffjob);
if (ifo == 1)
sqlstr = sqlstr + " and emnature='脱产'";
if (ifo == 2)
sqlstr = sqlstr + " and emnature='非脱产'";
emp.findBySQL(sqlstr);
if (emp.isEmpty())
throw new Exception("限定机构、职级及职位性质条件下,工号【" + employee_code + "】的人事资料不存在");
Date bd = Systemdate.getDateByStr(v.get("begin_date"));
Date ed = Systemdate.getDateByStr(v.get("end_date"));
if (ed.getTime() <= bd.getTime())
throw new Exception("工号为【" + employee_code + "】的加班时段,截止时间小于开始时间");
JSONObject jo = emp.toJsonObj();
jo.put("begin_date", Systemdate.getStrDateByFmt(bd, "yyyy-MM-dd HH:mm"));
jo.put("end_date", Systemdate.getStrDateByFmt(ed, "yyyy-MM-dd HH:mm"));
jo.put("needchedksb", ("是".equalsIgnoreCase(v.get("needchedksb"))) ? 1 : 2);
jo.put("needchedkxb", ("是".equalsIgnoreCase(v.get("needchedkxb"))) ? 1 : 2);
rst.add(jo);
}
return rst.toString();
}
private List<CExcelField> initExcelFieldsOvertime() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("开始时间", "begin_date", true));
efields.add(new CExcelField("结束时间", "end_date", true));
efields.add(new CExcelField("上班打卡", "needchedksb", true));
efields.add(new CExcelField("下班打卡", "needchedkxb", true));
return efields;
}
@ACOAction(eventname = "find", Authentication = true, ispublic = true, notes = "加班申请替换通用查询")
public String find() throws Exception {
String sqlstr = "select * from hrkq_overtime where 1=1 ";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String[] ignParms = { "employee_code" };// 忽略的查询条件
Hrkq_overtime ho = new Hrkq_overtime();
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
// sqlstr = sqlstr + " and ot_id=" + id;
ho.findByID(id);
return ho.tojson();
} else {
String parms = urlparms.get("parms");
List<JSONParm> jps = CJSON.getParms(parms);
JSONParm ecp = CorUtil.getJSONParm(jps, "employee_code");
if (ecp != null)
sqlstr = sqlstr + "AND EXISTS(SELECT 1 FROM hrkq_overtime_line WHERE hrkq_overtime.ot_id=hrkq_overtime_line.ot_id "
+ "AND hrkq_overtime_line.employee_code='" + ecp.getParmvalue() + "')";
String where = CSearchForm.getCommonSearchWhere(urlparms, ho);
if ((where != null) && (!where.isEmpty()))
sqlstr = sqlstr + where;
//sqlstr = sqlstr + " order by ot_id desc";
return new CReport(sqlstr," createtime desc ", null).findReport(ignParms);
}
}
@ACOAction(eventname = "findqual", Authentication = true, ispublic = true, notes = "加班资格替换通用查询")
public String findqual() throws Exception {
String sqlstr = "select * from hrkq_overtime_qual where 1=1 ";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String[] ignParms = { "employee_code" };// 忽略的查询条件
Hrkq_overtime_qual ho = new Hrkq_overtime_qual();
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
// sqlstr = sqlstr + " and ot_id=" + id;
ho.findByID(id);
return ho.tojson();
} else {
String parms = urlparms.get("parms");
List<JSONParm> jps = CJSON.getParms(parms);
JSONParm ecp = CorUtil.getJSONParm(jps, "employee_code");
if (ecp != null)
sqlstr = sqlstr + "AND EXISTS(SELECT 1 FROM hrkq_overtime_qual_line WHERE hrkq_overtime_qual.oq_id=hrkq_overtime_qual_line.oq_id "
+ "AND hrkq_overtime_qual_line.employee_code='" + ecp.getParmvalue() + "')";
String where = CSearchForm.getCommonSearchWhere(urlparms, ho);
if ((where != null) && (!where.isEmpty()))
sqlstr = sqlstr + where;
//sqlstr = sqlstr + " order by createtime desc";
return new CReport(sqlstr," createtime desc ", null).findReport(ignParms);
}
}
@ACOAction(eventname = "qualbatchimpexcel", Authentication = true, ispublic = false, notes = "加班资格批量Excel")
public String qualbatchimpexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelQBFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelQBFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserQBExcelSheet(aSheet, batchno);
}
private int parserQBExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
String lguserid = CSContext.getUserID();
String lgusername = CSContext.getUserName();
String lguserdsname = CSContext.getUserDisplayname();
String widpath = CSContext.getIdpathwhere();
Date nowdate = new Date();
List<CExcelField> efds = initQBExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hrkq_overtime_qual oq = new Hrkq_overtime_qual();
Hrkq_overtime_qual_line oql = new Hrkq_overtime_qual_line();
Hr_employee emp = new Hr_employee();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
// System.out.println("employee_code:" + employee_code);
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
String sqlstr = "SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'" + widpath;
emp.clear();
emp.findBySQL(sqlstr);
if (emp.isEmpty())
throw new Exception("权限范围内,工号【" + employee_code + "】的人事资料不存在");
oq.clear();
oq.hrkq_overtime_qual_lines.clear();
oql.clear();
oq.er_id.setValue(lguserid); // 申请人档案ID
oq.employee_code.setValue(lgusername); // 申请人工号
oq.employee_name.setValue(lguserdsname); // 申请人姓名
oq.orgid.setValue(emp.orgid.getValue()); // 部门ID
oq.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
oq.orgname.setValue(emp.orgname.getValue()); // 部门名称
oq.apply_date.setAsDatetime(nowdate); // 申请日期
oq.over_type.setValue(getover_type(dictemp, employee_code, v.get("over_type"))); // 申请加班类型
oq.begin_date.setValue(v.get("begin_date")); // 申请加班开始时间
oq.end_date.setValue(v.get("end_date")); // 申请加班结束时间
oq.dealtype.setValue("2"); // 加班处理
// oq.employee_type.setValue(value); // 加班人员类型
oq.permonlimit.setValue(v.get("permonlimit")); // 月度加班上限时数
oq.appreason.setValue(v.get("appreason")); // 申请原因
oq.remark.setValue(v.get("remark")); // 备注
oq.stat.setValue("1"); // 表单状态
oq.idpath.setValue(emp.idpath.getValue()); // idpath
oq.entid.setValue("1"); // entid
oq.creator.setValue(lguserdsname); // 创建人
oq.createtime.setAsDatetime(nowdate); // 创建时间
oq.emplev.setValue("0"); // 人事层级
oq.orghrlev.setValue("0"); // 机构人事层级
// //////
oql.breaked.setValue("2"); // 已终止
oql.er_id.setValue(emp.er_id.getValue()); // 员工档案ID
oql.employee_code.setValue(emp.employee_code.getValue()); // 工号
oql.employee_name.setValue(emp.employee_name.getValue()); // 姓名
oql.orgid.setValue(emp.orgid.getValue()); // 部门ID
oql.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
oql.orgname.setValue(emp.orgname.getValue()); // 部门名称
oql.lv_id.setValue(emp.lv_id.getValue()); // 职级ID
oql.lv_num.setValue(emp.lv_num.getValue()); // 职级
oql.ospid.setValue(emp.ospid.getValue()); // 职位ID
oql.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
oql.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
oql.orghrlev.setValue("0"); // 机构人事层级
oql.emplev.setValue("0"); // 人事层级
oql.remark.setValue("批量导入" + batchno); // 备注
oq.hrkq_overtime_qual_lines.add(oql);
oq.save(con);
oq.wfcreate(null, con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private String getover_type(DictionaryTemp dictemp, String employee_code, String over_type) throws Exception {
String[] ots = over_type.split(",");
String rst = "";
for (String ot : ots) {
if ((ot != null) && (!ot.isEmpty())) {
String otid = dictemp.getVbCE("923", ot, false, "工号【" + employee_code + "】加班类型【" + ot + "】不存在");
rst = rst + otid + ",";
}
}
if (rst.isEmpty())
throw new Exception("工号【" + employee_code + "】加班类型不能为空");
else
rst = rst.substring(0, rst.length() - 1);
return rst;
}
private List<CExcelField> initQBExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("月上限(H)", "permonlimit", true));
efields.add(new CExcelField("加班处理", "dealtype", true));
efields.add(new CExcelField("加班类型", "over_type", true));
efields.add(new CExcelField("开始日期", "begin_date", true));
efields.add(new CExcelField("截止日期", "end_date", true));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
}
<file_sep>/src/com/hr/perm/entity/Hr_traindisp_batchline.java
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_traindisp_batchline extends CJPA {
@CFieldinfo(fieldname="tdipbl_id",iskey=true,notnull=true,caption="分配行ID",datetype=Types.INTEGER)
public CField tdipbl_id; //分配行ID
@CFieldinfo(fieldname="tdipb_id",notnull=true,caption="分配ID",datetype=Types.INTEGER)
public CField tdipb_id; //分配ID
@CFieldinfo(fieldname="er_id",notnull=true,caption="人事档案ID",datetype=Types.INTEGER)
public CField er_id; //人事档案ID
@CFieldinfo(fieldname="employee_code",notnull=true,caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname="sex",notnull=true,caption="性别",datetype=Types.INTEGER)
public CField sex; //性别
@CFieldinfo(fieldname="id_number",notnull=true,caption="身份证号",datetype=Types.VARCHAR)
public CField id_number; //身份证号
@CFieldinfo(fieldname="employee_name",notnull=true,caption="姓名",datetype=Types.VARCHAR)
public CField employee_name; //姓名
@CFieldinfo(fieldname="degree",caption="学历",datetype=Types.INTEGER)
public CField degree; //学历
@CFieldinfo(fieldname="jxdatetry",notnull=true,caption="见习到期日期",datetype=Types.TIMESTAMP)
public CField jxdatetry; //见习到期日期
@CFieldinfo(fieldname="orgid",notnull=true,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="ospid",notnull=true,caption="职位ID",datetype=Types.INTEGER)
public CField ospid; //职位ID
@CFieldinfo(fieldname="ospcode",notnull=true,caption="职位编码",datetype=Types.VARCHAR)
public CField ospcode; //职位编码
@CFieldinfo(fieldname="sp_name",notnull=true,caption="职位名称",datetype=Types.VARCHAR)
public CField sp_name; //职位名称
@CFieldinfo(fieldname="hg_name",caption="职等",datetype=Types.VARCHAR)
public CField hg_name; //职等
@CFieldinfo(fieldname="lv_num",caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="norgid",caption="拟用人部门ID",datetype=Types.INTEGER)
public CField norgid; //拟用人部门ID
@CFieldinfo(fieldname="norgname",caption="拟用人部门名称",datetype=Types.VARCHAR)
public CField norgname; //拟用人部门名称
@CFieldinfo(fieldname="nospid",caption="拟职位ID",datetype=Types.INTEGER)
public CField nospid; //拟职位ID
@CFieldinfo(fieldname="nsp_name",caption="拟职位名称",datetype=Types.VARCHAR)
public CField nsp_name; //拟职位名称
@CFieldinfo(fieldname="nhg_name",caption="职等",datetype=Types.VARCHAR)
public CField nhg_name; //职等
@CFieldinfo(fieldname="nlv_num",caption="职级",datetype=Types.DECIMAL)
public CField nlv_num; //职级
@CFieldinfo(fieldname="exam_title",caption="考试课题",datetype=Types.VARCHAR)
public CField exam_title; //考试课题
@CFieldinfo(fieldname="exam_time",caption="考试时间",datetype=Types.TIMESTAMP)
public CField exam_time; //考试时间
@CFieldinfo(fieldname="wfresult",caption="评审结果1 通过 2 没通过",datetype=Types.INTEGER)
public CField wfresult; //评审结果1 通过 2 没通过
@CFieldinfo(fieldname ="oldchecklev",precision=2,scale=0,caption="调薪前绩效考核层级",datetype=Types.INTEGER)
public CField oldchecklev; //调薪前绩效考核层级
@CFieldinfo(fieldname ="oldattendtype",precision=32,scale=0,caption="调薪前出勤类别",datetype=Types.VARCHAR)
public CField oldattendtype; //调薪前出勤类别
@CFieldinfo(fieldname ="newchecklev",precision=2,scale=0,caption="调薪后绩效考核层级",datetype=Types.INTEGER)
public CField newchecklev; //调薪后绩效考核层级
@CFieldinfo(fieldname ="newattendtype",precision=32,scale=0,caption="调薪后出勤类别",defvalue="0",datetype=Types.VARCHAR)
public CField newattendtype; //调薪后出勤类别
@CFieldinfo(fieldname ="oldstru_id",precision=10,scale=0,caption="转正前工资结构ID",datetype=Types.INTEGER)
public CField oldstru_id; //转正前工资结构ID
@CFieldinfo(fieldname ="oldstru_name",precision=32,scale=0,caption="转正前工资结构名",datetype=Types.VARCHAR)
public CField oldstru_name; //转正前工资结构名
@CFieldinfo(fieldname ="oldposition_salary",precision=10,scale=2,caption="转正前职位工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldposition_salary; //转正前职位工资
@CFieldinfo(fieldname ="oldbase_salary",precision=10,scale=2,caption="转正前基本工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldbase_salary; //转正前基本工资
@CFieldinfo(fieldname ="oldtech_salary",precision=10,scale=2,caption="转正前技能工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldtech_salary; //转正前技能工资
@CFieldinfo(fieldname ="oldachi_salary",precision=10,scale=2,caption="转正前绩效工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldachi_salary; //转正前绩效工资
@CFieldinfo(fieldname ="oldotwage",precision=10,scale=2,caption="转正前固定加班工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldotwage; //转正前固定加班工资
@CFieldinfo(fieldname ="oldtech_allowance",precision=10,scale=2,caption="转正前技术津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldtech_allowance; //转正前技术津贴
@CFieldinfo(fieldname ="oldpostsubs",precision=10,scale=2,caption="转正前岗位津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField oldpostsubs; //转正前岗位津贴
@CFieldinfo(fieldname ="newstru_id",precision=10,scale=0,caption="转正后工资结构ID",datetype=Types.INTEGER)
public CField newstru_id; //转正后工资结构ID
@CFieldinfo(fieldname ="newstru_name",precision=32,scale=0,caption="转正后工资结构名",datetype=Types.VARCHAR)
public CField newstru_name; //转正后工资结构名
@CFieldinfo(fieldname ="newposition_salary",precision=10,scale=2,caption="转正后职位工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newposition_salary; //转正后职位工资
@CFieldinfo(fieldname ="newbase_salary",precision=10,scale=2,caption="转正后基本工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newbase_salary; //转正后基本工资
@CFieldinfo(fieldname ="newtech_salary",precision=10,scale=2,caption="转正后技能工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newtech_salary; //转正后技能工资
@CFieldinfo(fieldname ="newachi_salary",precision=10,scale=2,caption="转正后绩效工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newachi_salary; //转正后绩效工资
@CFieldinfo(fieldname ="newotwage",precision=10,scale=2,caption="转正后固定加班工资",defvalue="0.00",datetype=Types.DECIMAL)
public CField newotwage; //转正后固定加班工资
@CFieldinfo(fieldname ="newtech_allowance",precision=10,scale=2,caption="转正后技术津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField newtech_allowance; //转正后技术津贴
@CFieldinfo(fieldname ="newpostsubs",precision=10,scale=2,caption="转正后岗位津贴",defvalue="0.00",datetype=Types.DECIMAL)
public CField newpostsubs; //转正后岗位津贴
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
// 自关联数据定义
public Hr_traindisp_batchline() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/test.js
function aa() {
var userdata=111;
$ajaxjsonpost(url, {}, function () {
userdata
}, function () {
}, false, userdata, true);
}
function bb() {
var userdata=2222;
$ajaxjsonpost(url, {}, function () {
}, function () {
}, false, {}, true);
}<file_sep>/src/com/hr/.svn/pristine/eb/eb0bc79f78835a54626597f7361f880c1bda2aab.svn-base
package com.hr.perm.co;
import java.util.HashMap;
import java.util.List;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CorUtil;
import com.hr.perm.entity.Hr_employee;
@ACO(coname = "web.hr.interface")
public class COInterface {
private int maxct = 1000;
@ACOAction(eventname = "ifOrg", Authentication = true, notes = "机构列表通用接口")
public String ifOrg() throws Exception {
String[] allfields = { "orgid", "orgname", "code", "superid", "extorgname", "manager", "orgtype", "idpath", "stat", "creator",
"createtime", "updator", "updatetime", "attribute1" };
HashMap<String, String> urlparms = CSContext.getParms();
String parms = CorUtil.hashMap2Str(urlparms, "parms");
String fields = urlparms.get("fields");
int page = Integer.valueOf(CorUtil.hashMap2Str(urlparms, "page", "需要参数page"));
int rows = Integer.valueOf(CorUtil.hashMap2Str(urlparms, "rows", "需要参数rows"));
if (rows > maxct)
throw new Exception("单页数据不超过【" + maxct + "】条");
List<JSONParm> jps = CJSON.getParms(parms);
Shworg org = new Shworg();
String where = CjpaUtil.buildFindSqlByJsonParms(org, jps);
where = where + CSContext.getIdpathwhere();
String sqlstr = "select " + getfields(allfields, fields)
+ " from "
+ " shworg where 1=1 " + where;
return org.pool.opensql2json(sqlstr, page, rows);
}
@ACOAction(eventname = "ifEmp", Authentication = true, notes = "人事档案通用接口")
public String ifEmp() throws Exception {
String[] allfields = { "er_id", "employee_code", "id_number", "employee_name", "birthday", "sex", "hiredday", "degree", "married", "nationality",
"nativeplace", "address", "nation", "empstatid", "pldcp", "major", "registertype", "registeraddress", "health", "medicalhistory", "bloodtype",
"urgencycontact", "telphone", "speciality", "orgid", "orgcode", "orgname", "lv_num", "hg_code", "hg_name", "ospcode", "sp_name", "iskey",
"hwc_namezq", "hwc_namezz", "dorm_bed", "pay_way", "note", "creator", "createtime", "updator", "updatetime" };
HashMap<String, String> urlparms = CSContext.getParms();
String parms = CorUtil.hashMap2Str(urlparms, "parms");
String fields = urlparms.get("fields");
int page = Integer.valueOf(CorUtil.hashMap2Str(urlparms, "page", "需要参数page"));
int rows = Integer.valueOf(CorUtil.hashMap2Str(urlparms, "rows", "需要参数rows"));
if (rows > maxct)
throw new Exception("单页数据不超过【" + maxct + "】条");
List<JSONParm> jps = CJSON.getParms(parms);
Hr_employee emp = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(emp, jps);
where = where + CSContext.getIdpathwhere();
String sqlstr = "SELECT " + getfields(allfields, fields)
+ " FROM hr_employee where 1=1" + where;
return emp.pool.opensql2json(sqlstr, page, rows);
}
private String getfields(String[] allfields, String rfields) {
if ((rfields == null) || (rfields.isEmpty()))
return strs2str(allfields);
String[] rfds = rfields.split(",");
String rst = "";
if (rfds.length == 0)
return strs2str(allfields);
for (String rfd : rfds) {
if (isStrInStrs(allfields, rfd))
rst = rst + rfd + ",";
}
if (!rst.isEmpty())
rst = rst.substring(0, rst.length() - 1);
else
return strs2str(allfields);
return rst;
}
private boolean isStrInStrs(String[] fds, String fd) {
if ((fd == null) || (fd.isEmpty()))
return false;
for (String afd : fds) {
if (fd.equalsIgnoreCase(afd))
return true;
}
return false;
}
private String strs2str(String[] fds) {
String rst = "";
for (String fd : fds) {
rst = rst + fd + ",";
}
if (!rst.isEmpty())
rst = rst.substring(0, rst.length() - 1);
return rst;
}
}
<file_sep>/src/com/corsair/server/test/Class1.java
package com.corsair.server.test;
public class Class1 {
public void function1() {
System.out.println("Class1 function1");
}
}
<file_sep>/WebContent/webapp/js/common/mainlineNew.js
var mainline = undefined;
var frmOptions = undefined;
$.parser.auto = false;
$(document).ready(function () {
// if (window._menu) {
// if (frmOptions && (!mainline))
mainline = new TMainLine(frmOptions);
//$.parser.onComplete = function () {
// mainline.initInterFace();//初始化界面
//}
// }
}
);
var TEditType = {etEdit: 1, etSubmit: 2, etView: 3, etFind: 4};
var TFrmType = {ftMainLine: 1, ftSimple: 2};
var TButtons = {
btNew: {
disable: function () {
$("#id_bt_new").linkbutton("disable")
},
enable: function () {
$("#id_bt_new").linkbutton("enable")
}
},
btCopy: {
disable: function () {
$("#id_bt_copy").linkbutton("disable")
},
enable: function () {
$("#id_bt_copy").linkbutton("enable")
}
},
btSave: {
disable: function () {
$("#id_bt_save").linkbutton("disable")
},
enable: function () {
$("#id_bt_save").linkbutton("enable")
}
},
btSubmit: {
disable: function () {
$("#id_bt_submit").linkbutton("disable")
},
enable: function () {
$("#id_bt_submit").linkbutton("enable")
}
},
btFind: {
disable: function () {
$("#id_bt_find").linkbutton("disable")
},
enable: function () {
$("#id_bt_find").linkbutton("enable")
}
},
// btDeatil: {
// disable: function () {
// $("#id_bt_detail").linkbutton("disable")
// },
// enable: function () {
// $("#id_bt_detail").linkbutton("enable")
// }
// },
btReload: {
disable: function () {
$("#id_bt_reload").linkbutton("disable")
},
enable: function () {
$("#id_bt_reload").linkbutton("enable")
}
},
btDel: {
disable: function () {
$("#id_bt_del").linkbutton("disable")
},
enable: function () {
$("#id_bt_del").linkbutton("enable")
}
},
btAtt: {
disable: function () {
$("#id_bt_att").linkbutton("disable")
},
enable: function () {
$("#id_bt_att").linkbutton("enable")
}
},
btPrint: {
disable: function () {
$("#id_bt_print").linkbutton("disable")
},
enable: function () {
$("#id_bt_print").linkbutton("enable")
}
},
btExpt: {
disable: function () {
$("#id_bt_expt").linkbutton("disable")
},
enable: function () {
$("#id_bt_expt").linkbutton("enable")
}
},
btExit: {
disable: function () {
$("#id_bt_exit").linkbutton("disable")
},
enable: function () {
$("#id_bt_exit").linkbutton("enable")
}
},
btDelAtt: {
disable: function () {
$("#id_bt_delatt").linkbutton("disable")
},
enable: function () {
$("#id_bt_delatt").linkbutton("enable")
}
},
btDownloadAtt: {
disable: function () {
$("#id_bt_downloadatt").linkbutton("disable")
},
enable: function () {
$("#id_bt_downloadatt").linkbutton("enable")
}
},
setClick: function (onClick) {
$("#id_bt_new").linkbutton({onClick: function () {
onClick($C.action.New);
}});
$("#id_bt_copy").linkbutton({onClick: function () {
onClick($C.action.Copy);
}});
$("#id_bt_save").linkbutton({onClick: function () {
onClick($C.action.Save);
}});
$("#id_bt_submit").linkbutton({onClick: function () {
onClick($C.action.Submit);
}});
$("#id_bt_find").linkbutton({onClick: function () {
onClick($C.action.Find);
}});
// $("#id_bt_detail").linkbutton({onClick: function () {
// onClick($C.action.Detail);
// }});
$("#id_bt_reload").linkbutton({onClick: function () {
onClick($C.action.Reload);
}});
$("#id_bt_del").linkbutton({onClick: function () {
onClick($C.action.Del);
}});
$("#id_bt_print").linkbutton({onClick: function () {
onClick($C.action.Print);
}});
$("#id_bt_expt").linkbutton({onClick: function () {
onClick($C.action.Export);
}});
$("#id_bt_exit").linkbutton({onClick: function () {
onClick($C.action.Exit);
}});
$("#id_bt_att").linkbutton({onClick: function () {
onClick($C.action.Upload);
}});
$("#id_bt_delatt").linkbutton({onClick: function () {
onClick($C.action.DelAtt);
//alert("asd");
//deleteattfile()
}});
$("#id_bt_downloadatt").linkbutton({onClick: function () {
onClick($C.action.Download);
//rightClickDownload();
}});
}
};
function TMainLine(aFrmOptions) {
var frmOptions = aFrmOptions;
if (!aFrmOptions) {
$.messager.alert('错误', '没有设置frmOptions变量!', 'error');
return;
}
var copyFind_pw = undefined;//复制单据的选择弹出窗体
var curMainData = undefined;//当前数据JSON对象
var isloadingdata = false; //是否正在加载数据
var els_readonly = []; //初始化时 保存界面上所有只读 输入框
var added_grid_ids = [];//其它添加的grid的id数字
var isnew = false;//是否新建状态
var lineToolBar = [
{
text: '添加行',
iconCls: 'icon-add1',
handler: function () {
if (frmOptions.onAddLine)
frmOptions.onAddLine(append)
else
$C.grid.append(frmOptions.gdLinesName, {}, true)
function append(rowdata) {
$C.grid.append(frmOptions.gdLinesName, rowdata, true);
}
}
},
"-",
{
text: '删除行',
iconCls: 'icon-remove',
handler: function () {
var rowdata = $("#" + frmOptions.gdLinesName).datagrid("getSelected");
if (!rowdata) {
$.messager.alert('错误', '没有选择的数据!', 'error');
return;
}
if (frmOptions.onRemoveLine) {
if (frmOptions.onRemoveLine(rowdata)) {
$C.grid.remove(frmOptions.gdLinesName);
}
} else {
$C.grid.remove(frmOptions.gdLinesName);
}
}
}
];//明细行工具栏
readOptions(aFrmOptions);//检查参数,并初始化默认参数
var edittype = initEditType();//根据菜单获得单据编辑类型
function doinitInterFace() {
if (frmOptions.gdCbxUrls)
$C.grid.initComFormaters({comUrls: frmOptions.gdCbxUrls, onOK: function () {
addLineGrid();
}});
else
addLineGrid();
}
doinitInterFace()
function addLineGrid() {
if (frmOptions.frmType == TFrmType.ftMainLine) {
$("#detail_main_layout_id").css("height", frmOptions.lineHeight + "px");
var s = "<div title='明细数据'><table id='" + frmOptions.gdLinesName + "' style='position:relative;'></table></div>";
$(s).appendTo("#detail_main_tabs_id");//添加了html元素 会自动渲染,但是需要延时
}
setTimeout(initUI, 500);
}
function initUI() {
$("#main_tabs_id").tabs("select", 1);
$("#main_tabs_id").tabs("select", 0);
var gdLinesName = frmOptions.gdLinesName;
var allowWF = frmOptions.allowWF;
var allowAtt = frmOptions.allowAtt;
var frmtype = frmOptions.frmType;
$("#" + gdLinesName).datagrid({singleSelect: true, rownumbers: true, fit: true, onClickRow: function (index, row) {
$C.grid.accept(gdLinesName);
}, onDblClickRow: function (index, row) {
if (edittype == TEditType.etEdit)
$C.grid.edit(gdLinesName);
},
border: false,
columns: [frmOptions.gdLinesColumns()]
});
if ((edittype == TEditType.etSubmit) || (edittype == TEditType.etView)) {
$("#" + gdLinesName).datagrid({toolbar: undefined});
} else {
$("#" + gdLinesName).datagrid({toolbar: lineToolBar});
}
TButtons.setClick(OnBtClick);//设置按钮事件
initBts();//设置按钮enable
initMainTabs();//设置主页
initInput();//设置输入框
initGrids();//设置Grid
function initBts() {
setBtsDisable();
TButtons.btFind.enable();
TButtons.btExpt.enable();
TButtons.btExit.enable();
//TButtons.btDeatil.enable();
TButtons.btReload.enable();
TButtons.btPrint.enable();
if (edittype == TEditType.etEdit) {
TButtons.btNew.enable();
TButtons.btSave.enable();
TButtons.btDel.enable();
TButtons.btSubmit.enable();
TButtons.btCopy.enable();
if (allowWF) {
TButtons.btSubmit.enable();
}
if (allowAtt) {
TButtons.btAtt.enable();
TButtons.btDelAtt.enable();
TButtons.btDownloadAtt.enable();
}
}
if (edittype == TEditType.etSubmit) {
TButtons.btSave.enable();
if (allowWF) {
}
if (allowAtt) {
// TButtons.btAtt.enable();
// TButtons.btDelAtt.enable();
TButtons.btDownloadAtt.enable();
}
}
if (edittype == TEditType.etView) {
if (allowWF) {
}
if (allowAtt) {
// TButtons.btAtt.enable();
TButtons.btDownloadAtt.enable();
}
}
if (frmOptions.onSetButtonts) {
frmOptions.onSetButtonts();
}
}
function initMainTabs() {
if (!allowWF) {
$("#main_tabs_id").tabs("close", "流程");
}
if (!allowAtt) {
$("#main_tabs_id").tabs("close", "附件");
}
if (frmtype == TFrmType.ftSimple)
$("#main_tab_common_layout_id").layout("remove", "south");
}
function initInput() {
getInputReadOnlys();
$("#main_tabs_id").find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.dicgpid != undefined) {
var obj = $(this);
$ajaxjsonget(_serUrl + "/web/dict/getdictvalues.co?dicid=" + co.dicgpid,
function (jsondata) {
if (frmOptions.onInitInputComboboxDict) {
frmOptions.onInitInputComboboxDict(co, jsondata);
}
obj.combobox({
data: jsondata,
valueField: 'dictvalue',
textField: 'language1'
});
}, function () {
obj.combobox({
data: {},
valueField: 'dictvalue',
textField: 'language1'
});
$.messager.alert("错误", "获取数据字典错误!", "error");
}, false);
}
if (co.required) {
var tv = getInputLabel("#main_tabs_id", co.fdname);//$(this).parent().prev();
if (tv)
tv.html(tv.html() + "(<span style='color: red'>*</span>)");
// else
// alert(co.fdname);
}
if ((co.readonly) || (edittype == TEditType.etSubmit) || (edittype == TEditType.etView)) {
setInputReadOnly($(this), true);
}
});
}
function initGrids() {
$("#dg_att_id").datagrid({
border: false,
columns: [
[
{field: 'displayfname', title: '附件名', width: 200},
{field: 'extname', title: '扩展名', width: 100},
{field: 'filesize', title: '大小', width: 100},
{field: 'filevision', title: '版本', width: 100},
{field: 'filecreator', title: '所有者', width: 100},
{field: 'filecreate_time', title: '创建时间', width: 150}
]
],
onDblClickRow: onAttGrigDBClick,
onRowContextMenu: onRowRightClick
});
if (!frmOptions.gdListColumns) {
$.messager.alert('错误', '没有设置列表页字段!', 'error');
}
$("#dg_datalist_id").datagrid({
border: false,
onDblClickRow: onListDbClick,
columns: [frmOptions.gdListColumns()]
});
inipageins("#dg_datalist_id");
if (frmOptions.afterEditGrid) {
$("#dg_att_id").datagrid({
onAfterEdit: function (index, row, changes) {
frmOptions.afterEditGrid("#dg_att_id", index, row, changes);
}
});
$("#dg_datalist_id").datagrid({onAfterEdit: function (index, row, changes) {
frmOptions.afterEditGrid("#dg_datalist_id", index, row, changes);
}});
if (frmOptions.gdLinesColumns) {
$("#" + gdLinesName).datagrid({onAfterEdit: function (index, row, changes) {
frmOptions.afterEditGrid("#" + gdLinesName, index, row, changes);
}});
}
}
}
}
function setBtsDisable() {
for (var i in TButtons) {
if (TButtons[i].disable)
TButtons[i].disable();
}
}
function OnBtClick(act) {
switch (act) {
case $C.action.Find:
find();
break;
case $C.action.New:
donew();
break;
case $C.action.Copy:
docopy();
break;
case $C.action.Save:
dosave();
break;
case $C.action.Del:
dodel();
break;
case $C.action.Submit:
dosubmit();
break;
case $C.action.Print:
doprint();
break;
case $C.action.Exit:
if (frmOptions.onExit)
frmOptions.onExit();
break;
case $C.action.Upload:
doupload();
break;
case $C.action.Download:
rightClickDownload();
break;
case $C.action.DelAtt:
deleteattfile();
break;
}
}
function clearViewData() {
if (frmtype == TFrmType.ftMainLine) {
var grids = (gdLinesName) ? added_grid_ids.concat([gdLinesName]) : added_grid_ids;
JSONBandingFrm.clearMainData("#main_tabs_id", grids);
} else
JSONBandingFrm.clearMainData("#main_tabs_id", []);
}
//// new
function donew() {
reSetInputReadOnly();
isnew = true;
clearViewData();
curMainData = {};
$("#main_tabs_id").c_setJsonDefaultValue(curMainData, true);
if (frmOptions.onNew)
frmOptions.onNew(curMainData);
showDetail();
return true;
}
////copy
function docopy() {
if (!copyFind_pw) {
var copyFind_pw_options = {
id: "copyFind_pw",
enableIdpath: true,
JPAClass: frmOptions.JPAClass, //对应后台JPAClass名
gdListColumns: frmOptions.gdListColumns(),
selfLine: false,
edittype: TEditType.etFind,
onResult: function (rows) {
if (rows.length > 0) {
var jpa = rows[0];
//jpaclass id clearfields
var parms = {};
parms.jpaclass = frmOptions.JPAClass;
parms.id = jpa[frmOptions.JPAIdField];
if (frmOptions.onCopy) {
frmOptions.onCopy(parms);
}
$ajaxjsonpost($C.cos.commonCopy, JSON.stringify(parms), function (jsdata) {
$("#dg_datalist_id").datagrid("appendRow", jsdata);
var id = jsdata[frmOptions.JPAIdField];
if ((!id) || (id.length == 0)) {
alert("列表数据没发现ID值");
return;
}
findDetail(id);
}, function (msg) {
$.messager.alert('错误', '复制错误:' + msg, 'error');
});
}
}
};
copyFind_pw = new TSearchForm(copyFind_pw_options);
}
copyFind_pw.show();
}
//save
function dosave() {
curMainData = getMainData();
if (!JSONBandingFrm.checkNotNull("#main_tabs_id", curMainData)) return false;
//////save
var surl = ((frmOptions.saveUrl) && (frmOptions.saveUrl.length > 0)) ? frmOptions.saveUrl : $C.cos.commonsave;
var postData = {jpaclass: frmOptions.JPAClass, lines: true, jpadata: curMainData};
if (frmOptions.onSave) {
if (!frmOptions.onSave(postData)) return false;
}
$ajaxjsonpost(surl, JSON.stringify(postData), function (jdata) {
curMainData = jdata;
if (isnew) {
$("#dg_datalist_id").datagrid("appendRow", jdata);
}
showDetail();
}, function (msg) {
$.messager.alert('错误', '保存数据错误:' + msg, 'error');
});
}
function dodel() {
curMainData = getMainData();
var id = (curMainData[frmOptions.JPAIdField]);
if ((!id) || (id.length == 0)) {
$.messager.alert('错误', '未保存的或空数据,不需要删除!', 'error');
return;
}
$.messager.confirm('确认', '确认删除当前记录?', function (r) {
if (r) {
var surl = ((frmOptions.delUrl) && (frmOptions.delUrl.length > 0)) ? frmOptions.delUrl : $C.cos.commondelete;
surl = surl + "?jpaclass=" + frmOptions.JPAClass + "&id=" + id;
$ajaxjsonget(surl, function (jdata) {
if (jdata.result == "OK") {
$C.grid.removeByField("#dg_datalist_id", id, frmOptions.JPAIdField);
donew();//成功删除后,清除界面,恢复新建状态
} else {
$.messager.alert('错误', '删除失败:' + jdata.result, 'error');
}
}, function (msg) {
$.messager.alert('错误', '删除失败:' + msg, 'error');
});
}
});
}
var pw_SearchWT = undefined;
function dosubmit() {
curMainData = getMainData();
var jpaid = (curMainData[frmOptions.JPAIdField]);
if ((!jpaid) || (jpaid.length == 0)) {
$.messager.alert('错误', '未保存的或空数据,不能提交!', 'error');
return;
}
$.messager.confirm('确认', '确认提交当前单据?', function (r) {
if (r) {
var pwOption = {
id: "pws_selectWFTem",
JPAClass: "com.corsair.server.wordflow.Shwwftemp", //对应后台JPAClass名
gdListColumns: [
{field: 'wftempname', title: '流程名称', width: 150}
],
singleSelect: true,
autoFind: true, singleAutoReturn: true, notFindAutoReturn: true,
edittype: TEditType.etView,
enableIdpath: false,
beforeFind: function (parms) {
parms.url = _serUrl + "/web/common/findWfTemps.co";
parms.jpaclass = frmOptions.JPAClass;
parms.id = jpaid;
return true;
},
onResult: function (rows) {
var wftempid = (rows.length == 0) ? undefined : rows[0].wftempid;
var parms = {jpaclass: frmOptions.JPAClass, jpaid: jpaid};
if (wftempid)
parms.wftempid = wftempid;
$ajaxjsonpost($C.cos.commoncreateWF, JSON.stringify(parms), function (jsdata) {
curMainData = jsdata;
showDetail();
}, function (msg) {
$.messager.alert('错误', '提交单据错误:' + msg.errmsg, 'error');
});
}
};
if (pw_SearchWT) {
pw_SearchWT.TSearchForm(pwOption);
} else {
pw_SearchWT = new TSearchForm(pwOption);
}
pw_SearchWT.show();
}
});
}
////find begin
this.find_window_ok_click = function () {
$C.grid.accept("dg_find_window_parms_id");
var parms = $("#dg_find_window_parms_id").datagrid("getData").rows;
do_find(parms);
}
function find() {
var peditor = {
type: 'combobox',
options: {
valueField: 'field', textField: 'title', data: frmOptions.gdListColumns()
}
};
var pft = function (value, row) {
var dt = frmOptions.gdListColumns;
for (var i = 0; i < dt.length; i++) {
var r = dt[i];
if (value == r.field) {
return r.title;
}
}
return value;
};
var redtor = {
type: 'combobox',
options: {
valueField: 'id', textField: 'value',
data: [
{id: 'like', value: 'like'},
{id: '=', value: '='},
{id: '>', value: '>'},
{id: '<', value: '<'}
]}
};
$("#dg_find_window_parms_id").datagrid({columns: [
[
{field: 'parmname', title: '参数名', width: 100, editor: peditor, formatter: pft},
{field: 'reloper', title: '运算关系', width: 60, editor: redtor},
{field: 'parmvalue', title: '参数值', width: 100, editor: 'text'}
]
]});
$C.grid.clearData('dg_find_window_parms_id');
$C.grid.append('dg_find_window_parms_id', {}, true);
$("#find_window_id").window("open");
}
function inipageins(gdfilter) {
var gd = $(gdfilter);
gd.datagrid({
// pageNumber: 1,
pagination: true,
rownumbers: true,
pageList: [10, 50, 100, 300]
});
var p = gd.datagrid('getPager');
p.pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '共{total}条数据'
});
}
function do_find(parms) {
for (var i = parms.length - 1; i >= 0; i--) {
if ((!parms[i].parmname) || (parms[i].parmname.length == 0)) {
parms.splice(i, 1);
}
}
var url = $C.cos.commonfind + "?type=list&chgidpath=true&edittype=" + edittype + "&jpaclass=" + frmOptions.JPAClass;
if (parms.length > 0)
url = url + "&parms=" + JSON.stringify(parms);
//console.error(url);
var gd = $("#dg_datalist_id");
var p = gd.datagrid("getPager");
setOnListselectPage(url);
var option = p.pagination("options");
do_getdata(url, option.pageNumber, option.pageSize);
}
function setOnListselectPage(url) {
var gd = $("#dg_datalist_id");
var p = gd.datagrid("getPager");
p.pagination({
onSelectPage: function (pageNumber, pageSize) {
do_getdata(url, pageNumber, pageSize);
}
});
}
function do_getdata(url, page, pageSize) {
$ajaxjsonget(url + "&page=" + page + "&rows=" + pageSize, function (jsdata) {
$C.grid.clearData("dg_datalist_id");
$("#dg_datalist_id").datagrid({pageNumber: page, pageSize: pageSize});
setOnListselectPage(url);
$("#dg_datalist_id").datagrid("loadData", jsdata);
$("#main_tabs_id").tabs("select", 1);
$("#find_window_id").window("close");
}, function () {
//console.error("查询错误");
});
}
function onListDbClick(index, row) {
if (!frmOptions.JPAIdField) {
alert("没有设置JPA ID字段名");
return;
}
var id = row[frmOptions.JPAIdField];
if ((!id) || (id.length == 0)) {
alert("列表数据没发现ID值");
return;
}
findDetail(id);
}
function onRowRightClick(e, rowIndex, rowData) {
e.preventDefault();
$('#ContextMenu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
this.findDetail = findDetail;
function findDetail(id) {
curMainData = {};
var url = $C.cos.commonfind + "?type=byid&chgidpath=true&id=" + id + "&jpaclass=" + frmOptions.JPAClass;
$ajaxjsonget(url, function (jsdata) {
isnew = false;
curMainData = jsdata;
showDetail();
}, function () {
alert("查询数据错误");
});
}
this.showDetail = showDetail;
function showDetail() {
isloadingdata = true;
//先改界面显示 再写入值,否则会消失,应该是bug
if ((!$isEmpty(curMainData.stat)) && (parseInt(curMainData.stat) > 1)) {
setAllInputReadOnly(true);
showWFinfo();//如果有流程 根据流程刷新可以编辑的输入框
} else {
$("#main_tab_wf_id").html("");
$("#main_tabs_id").tabs("select", "常规");
}
setJson2Inputs();
setJson2Grids();
isloadingdata = false;
}
function showWFinfo() {
if (!$isEmpty(curMainData.wfid)) {
$("#main_tabs_id").tabs("select", "流程");
var src = _serUrl + "/webapp/common/shwwf.html?wfid=" + curMainData.wfid;
var wfifrm = "<iframe scrolling='no' frameborder='0' src='" + src + "' style='width: 100%;height: 98%'></iframe>";
$("#main_tab_wf_id").html(wfifrm);
//$("#main_tabs_id").tabs("select", "常规");
} else {
$("#main_tabs_id").tabs("select", "常规");
$("#main_tab_wf_id").html("");
}
}
this.setJson2Inputs = setJson2Inputs;
function setJson2Inputs() {
return JSONBandingFrm.fromJsonData("#maindata_id", curMainData)
}
this.setJson2Grids = setJson2Grids;
function setJson2Grids() {
var frmtype = frmOptions.frmType;
var gdLinesName = frmOptions.gdLinesName;
if (frmtype == TFrmType.ftMainLine) {
if (curMainData[gdLinesName]) {
$("#" + gdLinesName).datagrid("loadData", curMainData[gdLinesName]);
}
else $C.grid.clearData(gdLinesName);
}
if ((curMainData.shw_attachs) && (curMainData.shw_attachs.length > 0) && (curMainData.shw_attachs[0].shw_attach_lines)) {
$("#dg_att_id").datagrid("loadData", curMainData.shw_attachs[0].shw_attach_lines);
} else {
$C.grid.clearData("dg_att_id");
}
}
function doprint() {
curMainData = getMainData();
var jpaid = (curMainData[frmOptions.JPAIdField]);
if ((!jpaid) || (jpaid.length == 0)) {
$.messager.alert('错误', '未保存的或空数据,不能提交!', 'error');
return;
}
var url = _serUrl + "/web/common/findModels.co?jpaclass=" + frmOptions.JPAClass;
$("#pw_list_select").c_popselectList(url, function (fi) {
if (fi) {
var url = $C.cos.commondowloadExcelByModel + "?jpaclass=" + frmOptions.JPAClass + "&modfilename=" + fi.fname
+ "&jpaid=" + getid();
window.open(url);
}
});
}
//find end
///upload att
function doupload() {
curMainData = getMainData();
var id = (curMainData[frmOptions.JPAIdField]);
if ((!id) || (id.length == 0)) {
$.messager.alert('错误', '未保存的或空数据,不允许上传附件!', 'error');
return;
}
if (curMainData.shw_attachs == undefined) {
$.messager.alert('错误', 'JPA没有设置附件属性,不允许上传附件!', 'error');
return;
}
var wd = $("#pw_uploadfile iframe");
wd.attr("src", _serUrl + "/webapp/templet/default/uploadfile.html?action=" + $C.cos.commonUpLoadFile);
window.setTimeout(function () {
wd[0].contentWindow._callback = function (rst) {
var Shw_attach = ((curMainData.shw_attachs) && (curMainData.shw_attachs.length > 0)) ? curMainData.shw_attachs[0] : {};
if (!Shw_attach.shw_attach_lines) {
Shw_attach.shw_attach_lines = [];
}
try {
var pfs = eval(rst);
for (var i = 0; i < pfs.length; i++) {
pf = pfs[i];
Shw_attach.shw_attach_lines.push({pfid: pf.pfid, fdrid: 0, displayfname: pf.displayfname, extname: pf.extname, filesize: pf.filesize});
}
curMainData.shw_attachs = [Shw_attach];
dosave();//上传附件后 需要保存对象
$("#pw_uploadfile").window("close");
} catch (e) {
if (rst.indexOf("Request Entity Too Large") > -1) {
$.messager.alert('上传文件错误', "文件超大", 'error');
} else {
$.messager.alert('上传文件错误', rst, 'error');
}
}
};
}, 500);
$("#pw_uploadfile").window("open");
}
function onAttGrigDBClick(index, row) {
var furl = $C.cos.downattfile() + "?pfid=" + row.pfid;
window.open(furl);
}
////类函数
function readOptions(aFrmOptions) {
frmOptions.frmType = (aFrmOptions.frmType) ? aFrmOptions.frmType : TFrmType.ftMainLine;
frmOptions.allowWF = (aFrmOptions.allowWF != undefined) ? aFrmOptions.allowWF : true;
frmOptions.allowAtt = (aFrmOptions.allowAtt != undefined) ? aFrmOptions.allowAtt : true;
frmOptions.gdLinesName = (aFrmOptions.gdLinesName) ? aFrmOptions.gdLinesName : new Date().format("hhmmss") + "_id";
frmOptions.lineHeight = ( aFrmOptions.lineHeight) ? aFrmOptions.lineHeight : 200;
}
function initEditType() {
var menu = window._menu;
var edittype = undefined;
if (menu) {
if (parseInt(menu.frmedttype) == 1)
edittype = TEditType.etEdit;
else if (parseInt(menu.frmedttype) == 2)
edittype = TEditType.etSubmit;
else if (parseInt(menu.frmedttype) == 3)
edittype = TEditType.etView;
else
edittype = TEditType.etView;
}
else
edittype = TEditType.etEdit;
return edittype;
}
this.setReadOnly = function (fdname, readonly) {
var v = undefined;
var ipt = undefined;
$("#maindata_id").find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getInputType(el);
if (co.fdname == fdname) {
ipt = $(this);
v = $(this).textbox("getValue");
return false;
}
});
setInputReadOnly(ipt, readonly);
$setInputValue("#maindata_id", fdname, v);
}
function setInputReadOnly(input, readonly) {
//alert(input.next().find("input:first").parent().html());
var tp = getInputType(input[0]);
if (tp == 1)
input.datetimebox({readonly: readonly});
if (tp == 2)
input.combobox({readonly: readonly});
if (tp == 5)
input.textbox({readonly: readonly});
if (readonly) {
input.next().find("input:first").css("background-color", "#E8EEFA");
} else {
input.next().find("input:first").css("background-color", "#FFFFFF");
}
}
function setAllInputReadOnly(readonly) {
$("#maindata_id").find("input[cjoptions]").each(function (index, el) {
setInputReadOnly($(this), readonly);
});
}
function getInputReadOnlys() {
els_readonly = [];
$("#maindata_id").find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.readonly) {
els_readonly.push($(this)[0]);
}
});
// console.error(JSON.stringify(els_readonly));
}
function reSetInputReadOnly() {
$("#main_tabs_id").find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if ((co.readonly) || (edittype == TEditType.etSubmit) || (edittype == TEditType.etView)) {
setInputReadOnly($(this), true);
} else
setInputReadOnly($(this), false);
});
}
this.getFieldValue = function (fdname) {
var v = $getInputValue("#maindata_id", fdname);
if (v)
return v;
else
return curMainData[fdname];
}
this.setFieldValue = function (fdname, value) {
curMainData[fdname] = value;
$setInputValue("#maindata_id", fdname, value);
}
//////类方法
this.getMainData = getMainData;
function getMainData() {
curMainData = JSONBandingFrm.toJsonData("#main_tabs_id", curMainData, isnew);
if ((frmtype == TFrmType.ftMainLine) && gdLinesName) {
var lines = $("#" + gdLinesName).datagrid("getRows");
curMainData[gdLinesName] = lines;
}
return curMainData;
}
this.getid = getid;
function getid() {
return curMainData[frmOptions.JPAIdField];
}
this.isnew = function () {
return isnew;
}
this.lineToolBar = function () {
return lineToolBar;
};
this.getEditType = function () {
return edittype;
}
this.setEditType = function (value) {
edittype = value;
}
}
var JSONBandingFrm = new function () {
this.clearMainData = function (sfilter, grids) {
this.clearFrmData(sfilter);
for (var i = 0; i < grids.length; i++) {
$C.grid.clearData(grids[i]);
}
}
this.clearFrmData = function (sfilter) {
$(sfilter).find("input[cjoptions]").each(function (index, el) {
$(this).textbox('setValue', "");
});
}
this.fromJsonData = function (sfilter, jsondata) {
$(sfilter).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getInputType(el);
var v = jsondata[co.fdname];
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL") || (v == "")) {
$(this).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(this).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(this).textbox('setValue', "")
else {
if (co.dicgpid) {
$(this).combobox('select', v);
} else
$(this).textbox('setValue', v);
}
break;
}
}
});
return true;
}
this.toJsonData = function (sfilter, jsondata, isnew) {
$(sfilter).find("input[cjoptions]").each(function (index, el) {
jsondata[$.c_parseOptions($(this)).fdname] = $(this).textbox("getValue");
});
//line datas
if (!isnew)
$(sfilter).c_setJsonDefaultValue(jsondata, false);
return jsondata;
}
this.checkNotNull = function (sfilter, jsondata) {
var msg = "";
$(sfilter).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getInputType(el);
var v = jsondata[co.fdname];
if ((co.required) && ((v == null) || (!v) || (v == ""))) {
msg = msg + "<" + getInputLabel(sfilter, co.fdname).html() + "><br/>";
}
});
if (msg == "") return true
else {
$.messager.alert('错误', msg + '不允许为空!', 'error');
return false;
}
}
}
function $setInputValue(sfilter, fdname, value) {
$(sfilter).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.fdname == fdname) {
var et = getInputType(el);
var v = value;
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL") || (v == "")) {
$(this).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(this).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(this).textbox('setValue', "")
else {
if (co.dicgpid) {
$(this).combobox('select', v);
} else
$(this).textbox('setValue', v);
}
break;
}
}
}
});
}
function TSearchForm(sfrmOptions) {
var inited = false;
var id = sfrmOptions.id;
if ((!id) || (id.length < 0)) {
$.messager.alert('错误', '没有设置id变量!', 'error');
return undefined;
}
var istree, htmlTempt, idField, treeField, singleSelect, enableIdpath, autoFind, singleAutoReturn, notFindAutoReturn, edittype, showTitle, orderStr;
function readOptions() {
istree = (sfrmOptions.isTree == undefined) ? false : sfrmOptions.isTree;
htmlTempt = (sfrmOptions.htmlTempt) ? sfrmOptions.htmlTempt : "../templet/default/search_grid.html";
idField = (sfrmOptions.idField) ? sfrmOptions.idField : undefined;
treeField = (sfrmOptions.treeField) ? sfrmOptions.treeField : undefined;
singleSelect = (sfrmOptions.singleSelect == undefined) ? true : sfrmOptions.singleSelect;
enableIdpath = (sfrmOptions.enableIdpath == undefined) ? true : sfrmOptions.enableIdpath;
autoFind = (sfrmOptions.autoFind == undefined) ? false : sfrmOptions.autoFind;
singleAutoReturn = (sfrmOptions.singleAutoReturn == undefined) ? false : sfrmOptions.singleAutoReturn;
notFindAutoReturn = (sfrmOptions.notFindAutoReturn == undefined) ? false : sfrmOptions.notFindAutoReturn;
edittype = (sfrmOptions.edittype == undefined) ? TEditType.etFind : sfrmOptions.edittype;
showTitle = (sfrmOptions.showTitle == undefined) ? true : sfrmOptions.showTitle;
orderStr = (sfrmOptions.orderStr == undefined) ? "" : sfrmOptions.orderStr;
}
readOptions();
var valuehtml = undefined;
this.tag = 0;
initPopFrm();
this.TSearchForm = function (NsfrmOptions) {
sfrmOptions = $.extend(sfrmOptions, NsfrmOptions);
readOptions();
}
function initPopFrm() {
$.ajax({
url: htmlTempt,
type: 'get',
dataType: 'text',
cache: false,
async: true,
contentType: "text/HTML; charset=utf-8",
success: function (data) {
//alert(data);
if ($("#pop_search_divs").length == 0)
$("<div id='pop_search_divs'></div>").appendTo("body");
data = data.replace("$pwid$", "'" + id + "'");
var pw = $(data).appendTo("#pop_search_divs");
valuehtml = getInputByField("value").parent().html();
$("#" + id).find(".easyui-linkbutton[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_search") {
$(this).click(function () {
OnFindClick();
});
} else if (co.caction == "act_ok") {
$(this).click(function () {
OnOKClick();
});
} else if (co.caction == "act_select") {
$(this).click(function () {
OnSelectClick();
});
} else if (co.caction == "act_cancel") {
$(this).click(function () {
$("#" + id).window("close");
});
}
});
$.parser.parse(pw.parent());///////////////////////刷新整个界面??
var listgrid = $("#" + id).find("table[cjoptions]");
var multiRow = (sfrmOptions.multiRow == undefined) ? false : sfrmOptions.multiRow;
listgrid.datagrid({border: false,
singleSelect: !multiRow,
singleSelect: singleSelect,
onDblClickRow: onListDbClick,
columns: [sfrmOptions.gdListColumns]});
if (istree) {
}
var item = getInputByField("item");
if (!item) {
$.messager.alert('错误', '没有找到item录入框!', 'error');
return;
}
item.combobox({
data: sfrmOptions.gdListColumns,
valueField: 'field',
textField: 'title',
onSelect: onItemSelect
});
if (!showTitle) {
$("#" + id).find(".easyui-layout").each(function (index, el) {
if (index == 1) {
$(this).layout("remove", "north");
}
});
}
//show();
inited = true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$.messager.alert('错误', '获取Search模板文件错误!', 'error');
}
});
}
this.show = show;
function show(clear) {
if (!inited) {
setTimeout(function () {
show(clear);
}, 100);
} else doshow(clear);
}
function doshow(clear) {
if (clear) {
var listgrid = $("#" + id).find("table[cjoptions]");
var multiRow = (sfrmOptions.multiRow == undefined) ? false : sfrmOptions.multiRow;
$C.grid.clearData(listgrid);
listgrid.datagrid({singleSelect: !multiRow});
}
if (autoFind) {
OnFindClick();
}
$("#" + id).window("open");
}
function getInputByField(fdname) {
var inpt = undefined;
$("#" + id).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getInputType(el);
if (co.fdname == fdname) {
inpt = $(this);
return;
}
});
return inpt;
}
function onListDbClick() {
OnOKClick();
}
function getFdItemdataByvalue(value) {
if (!value) return undefined;
var cdata = getInputByField("item").combobox("getData");
for (var i = 0; i < cdata.length; i++) {
var idata = cdata[i];
if (idata["field"] == value)
return idata;
}
}
function onItemSelect(row) {
var p = getInputByField("value").parent();
p.html(valuehtml);
$.parser.parse(p);
var v = getInputByField("value");
if (row.formatter) {
var comurl = row.formatter("get_com_url");
if (comurl) {
v.combobox({
data: comurl.data,
valueField: comurl.valueField,
textField: comurl.textField
});
} else {
//isdate?
}
} else {
// v.textbox("setValue", "");
}
}
function OnFindClick() {
if (showTitle) {
var fd = getInputByField("item").textbox("getValue");
var v = getInputByField("value").textbox("getValue");
var parms = (fd && v) ? [
{ parmname: fd, reloper: "like", parmvalue: v}
] : [];
} else
var parms = [];
if (sfrmOptions.extParms)
parms = parms.concat(sfrmOptions.extParms);
var fdparms = {url: $C.cos.commonfind, type: "list", enableIdpath: enableIdpath, edittype: edittype, jpaclass: sfrmOptions.JPAClass, parms: parms};
if (!$isEmpty(orderStr))
fdparms.order = orderStr;
var selfLine = (sfrmOptions.selfLine == undefined) ? true : sfrmOptions.selfLine;
sfrmOptions.selfLine = selfLine;
if (sfrmOptions.beforeFind) {
if (!sfrmOptions.beforeFind(fdparms))
return;
}
var url = fdparms.url + "?";
for (var parm in fdparms) {
if (typeof(fdparms[parm]) == "function")
continue;
if ((parm != "url") && (fdparms[parm] != undefined))
if (parm == "parms")
url = url + "&parms=" + JSON.stringify(fdparms[parm]);
else
url = url + "&" + parm + "=" + fdparms[parm];
}
// alert(url);
/* var url = fdparms.url + "?type=" + fdparms.type + "&selfline=" + selfLine + "&enableIdpath=" + enableIdpath + "&edittype=" + fdparms.edittype + "&jpaclass=" + fdparms.jpaclass;
if (fdparms.order) {
url = url + "&order=" + fdparms.order;
}
if (fdparms.parms.length > 0)
url = url + "&parms=" + JSON.stringify(fdparms.parms);*/
//console.error(url);
$ajaxjsonget(url, function (jsdata) {
if (((jsdata.length == 1) && singleAutoReturn) || ((jsdata.length == 0) && notFindAutoReturn)) {
if (sfrmOptions.onResult)
sfrmOptions.onResult(jsdata);
$("#" + id).window("close");
return;
}
var listgrid = $("#" + id).find("table[cjoptions]");
$C.grid.clearData(listgrid);
listgrid.datagrid("loadData", jsdata);
}, function () {
//console.error("查询错误");
});
}
function OnOKClick() {
var listgrid = $("#" + id).find("table[cjoptions]");
var rows = listgrid.datagrid('getSelections');
if (rows.length == 0) {
$.messager.alert('错误', '没有选择数据!', 'error');
} else {
if (sfrmOptions.onResult) {
sfrmOptions.onResult(rows);
}
$("#" + id).window("close");
}
}
function OnSelectClick() {
var listgrid = $("#" + id).find("table[cjoptions]");
var rows = listgrid.datagrid('getSelections');
if (rows.length == 0) {
listgrid.datagrid("selectAll");
} else {
listgrid.datagrid("unselectAll");
}
}
//alert(2);
}
function $getInputValue(sfilter, fdname) {
var v = undefined;
$(sfilter).find("input[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
var et = getInputType(el);
if (co.fdname == fdname) {
v = $(this).textbox("getValue");
return false;
}
});
return v;
}
function getInputLabel(sfilter, fdname) {
var lb = undefined;
$(sfilter).find("td[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.fdname == fdname) {
lb = $(this);
return false;
}
});
return lb;
}
function getInputType(el) {
var cls = $(el).attr("class");
if (cls.indexOf("easyui-datetimebox") >= 0) {
return 1;
} else if (cls.indexOf("easyui-combobox") >= 0) {
return 2;//combobox
} else if (cls.indexOf("easyui-textbox") >= 0) {
return 5;
}
}<file_sep>/src/com/corsair/cjpa/CJPALoad.java
package com.corsair.cjpa;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import com.corsair.cjpa.util.CJPASqlUtil;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.CDBConnection.DBType;
import com.corsair.dbpool.util.CPoolSQLUtil;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
/**
* JPA加载数据实现
*
* @author Administrator
*
*/
public abstract class CJPALoad extends CJPAJSON {
public CJPALoad() throws Exception {
}
public CJPALoad(String sqlstr) throws Exception {
this();
findBySQL(sqlstr);
}
/**
* 查询并锁定对象
*
* @param con
* @throws Exception
*/
public void findByID4Update(CDBConnection con) throws Exception {
CField idfd = this.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA【" + this.getClass().getSimpleName() + "】数据没发现ID字段");
}
findByID4Update(con, idfd.getValue(), true);
}
/**
* 查询并锁定对象
*
* @param con
* @param id
* @param selflink
* @throws Exception
*/
public void findByID4Update(CDBConnection con, String id, boolean selflink) throws Exception {
CField idfd = this.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA【" + this.getClass().getSimpleName() + "】数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + tablename + " where " + sqlfdname + "=" + sqlvalue + " for update";
findBySQL4Update(con, sqlstr, selflink);
}
/**
* 查询并锁定对象
*
* @param con
* @param sqlstr
* @param selflink
* @throws Exception
*/
public void findBySQL4Update(CDBConnection con, String sqlstr, boolean selflink) throws Exception {
try {
clear();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.con.createStatement();
long time = System.currentTimeMillis();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(con, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
if (!rs.next()) {
return;
}
load4DataSet(con, rs, selflink, true);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
throw new Exception("根据SQL载入数据错误:" + e.getMessage() + sqlstr);
}
}
// 查询并锁定对象 end
/**
* 根据ID查询
*
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findByID(boolean selflink) throws Exception {
CField idfd = this.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA【" + this.getClass().getSimpleName() + "】数据没发现ID字段");
}
findByID(idfd.getValue(), selflink);
return (CJPABase) this;
}
/**
* 根据ID查询
*
* @param id
* @return
* @throws Exception
*/
public CJPABase findByID(String id) throws Exception {
findByID(id, true);
return (CJPABase) this;
}
/**
* 根据ID查询
*
* @param con
* @param id
* @return
* @throws Exception
*/
public CJPABase findByID(CDBConnection con, String id) throws Exception {
findByID(con, id, true);
return (CJPABase) this;
}
/**
* 根据ID查询
*
* @param con
* @param id
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findByID(CDBConnection con, String id, boolean selflink) throws Exception {
CField idfd = this.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA【" + this.getClass().getSimpleName() + "】数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + tablename + " where " + sqlfdname + "=" + sqlvalue;
findBySQL(con, sqlstr, selflink);
return (CJPABase) this;
}
/**
* 根据ID查询
*
* @param id
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findByID(String id, boolean selflink) throws Exception {
if (pool == null) {
throw new Exception("JPA通过sql载入数据前,必须初始化连接池pool");
}
CDBConnection con = pool.getCon(this);
try {
findByID(con, id, selflink);
} catch (Exception e) {
throw e;
} finally {
con.close();
}
return (CJPABase) this;
}
/**
* 根据SQL查询
*
* @param psql
* @return
* @throws Exception
*/
public CJPABase findByPSQL(PraperedSql psql) throws Exception {
return findByPSQL(psql, true);
}
/**
* 根据SQL查询
*
* @param psql
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findByPSQL(PraperedSql psql, boolean selflink) throws Exception {
if (pool == null) {
throw new Exception("JPA通过sql载入数据前,必须初始化连接池pool");
}
CDBConnection con = pool.getCon(this);
try {
findByPSQL(con, psql, selflink);
return (CJPABase) this;
} catch (Exception e) {
throw new Exception("根据SQL载入数据错误:" + e.getMessage() + psql.getSqlstr());
} finally {
con.close();
}
}
/**
* 根据SQL查询
*
* @param con
* @param psql
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findByPSQL(CDBConnection con, PraperedSql psql, boolean selflink) throws Exception {
clear();
String sqlstr = psql.getSqlstr();
if (con.getDBType() == DBType.mysql)
sqlstr = sqlstr + " limit 1";
if (con.getDBType() == DBType.oracle)
// sqlstr = sqlstr + " and rownum<=1";
sqlstr = "select * from (" + sqlstr + ") where rownum<=1";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = con.con.prepareStatement(sqlstr);
for (int i = 0; i < psql.getParms().size(); i++) {
PraperedValue pv = psql.getParms().get(i);
CPoolSQLUtil.setSqlPValue(pstmt, i + 1, pv);
}
long time = System.currentTimeMillis();
rs = pstmt.executeQuery();
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(con, "【执行SQL:" + psql.getSqlstr() + ";耗时:" + (et - time) + "】");
}
if (!rs.next()) {
return (CJPABase) this;
}
load4DataSet(con, rs, selflink, false);
return (CJPABase) this;
} finally {
DBPools.safeCloseS_R(pstmt, rs);
}
}
/**
* 根据SQL查询
*
* @param sqlstr
* @return
* @throws Exception
*/
public CJPABase findBySQL(String sqlstr) throws Exception {
findBySQL(sqlstr, true);
return (CJPABase) this;
}
/**
* 根据SQL查询
*
* @param selflink
* @return
* @throws Exception
*/
public CJPABase findBySQL(boolean selflink) throws Exception {
String sqlstr = "select * from " + this.tablename + " where 1=1 " + SqlWhere;
findBySQL(sqlstr, selflink);
return (CJPABase) this;
}
/**
* 根据SQL查询
*
* @param con
* @param sqlstr
* @param selflink 是否查询行表
* @return
* @throws Exception
*/
public CJPABase findBySQL(CDBConnection con, String sqlstr, boolean selflink) throws Exception {
clear();
if (con.getDBType() == DBType.mysql)
sqlstr = sqlstr + " limit 1";
if (con.getDBType() == DBType.oracle)
// sqlstr = sqlstr + " and rownum<=1";
sqlstr = "select * from (" + sqlstr + ") where rownum<=1";
Logsw.debug("执行查询:" + sqlstr);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.con.createStatement();
long time = System.currentTimeMillis();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(con, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
if (!rs.next()) {
return (CJPABase) this;
}
load4DataSet(con, rs, selflink, false);
return (CJPABase) this;
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
}
/**
* 根据SQL查询
*
* @param sqlstr
* @param selflink 是否查询行表
* @return
* @throws Exception
*/
public CJPABase findBySQL(String sqlstr, boolean selflink) throws Exception {
if (pool == null) {
throw new Exception("JPA通过sql载入数据前,必须初始化连接池pool");
}
CDBConnection con = pool.getCon(this);
try {
return findBySQL(con, sqlstr, selflink);
} catch (Exception e) {
throw new Exception("根据SQL载入数据错误:" + e.getMessage() + sqlstr);
} finally {
con.close();
}
}
/**
* 从数据集加载
*
* @param con
* @param rs
* @param selflink
* @param update
* @return
* @throws Exception
*/
public boolean load4DataSet(CDBConnection con, ResultSet rs, boolean selflink, boolean update) throws Exception {
try {
ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集的定义结构
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
CField fd = cfieldNoCase(rsmd.getColumnName(i));
if (fd == null) {
continue;
}
fd.setFieldtype(rsmd.getColumnType(i));
fd.setSize(rsmd.getColumnDisplaySize(i));
String value = CjpaUtil.getShowvalue(con.getDBType(), rs, i, fd.getFieldtype());
fd.setValue(value);
fd.setChanged(false);
}
} catch (Exception e) {
throw new Exception("CJAP从ResultSet载入数据错误:" + e.getMessage());
}
if (selflink) {
for (CJPALineData<CJPABase> ld : cJPALileDatas) {
ld.loadDataByOwner(con, true, true, update);
}
}
setAllJpaStat(CJPAStat.RSLOAD4DB);
return true;
}
}
<file_sep>/src/com/hr/perm/co/COHr_employee.java
package com.hr.perm.co;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_attach_line;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CFileUtiil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.attd.ctr.CtrHrkq_leave_blance;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.base.ctr.CtrHr_systemparms;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.ctr.CtrHrEmployeeUtil;
import com.hr.perm.ctr.CtrHrPerm;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_cretl;
import com.hr.perm.entity.Hr_employee_family;
import com.hr.perm.entity.Hr_employee_leanexp;
import com.hr.perm.entity.Hr_employee_linked;
import com.hr.perm.entity.Hr_employee_nreward;
import com.hr.perm.entity.Hr_employee_relation;
import com.hr.perm.entity.Hr_employee_reward;
import com.hr.perm.entity.Hr_employee_trainexp;
import com.hr.perm.entity.Hr_employee_work;
import com.hr.perm.entity.Hr_leavejob;
import com.hr.util.HRUtil;
import com.hr.util.TimerTaskHRZM;
@ACO(coname = "web.hr.employee")
public class COHr_employee {
@ACOAction(eventname = "findEmployeeByid", Authentication = true, notes = "根据员工ID查找员工资料,权限范围内")
public String findEmployeeByid() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
int tp = Integer.valueOf(CorUtil.hashMap2Str(parms, "tp", "需要参数tp"));// tp:1
// 扩展
// 2
// 基础资料
String serid = CorUtil.hashMap2Str(parms, "er_id");
if (serid == null)
serid = CorUtil.hashMap2Str(parms, "id");
if (serid == null)
throw new Exception("需要参数er_id");
int er_id = Integer.valueOf(serid);
String sqlstr = "SELECT *,TIMESTAMPDIFF(YEAR, birthday, CURDATE()) age FROM hr_employee WHERE er_id=? "
+ CSContext.getIdpathwhere();
PraperedSql psql = new PraperedSql();
psql.setSqlstr(sqlstr);
psql.getParms().add(new PraperedValue(1, er_id));
JSONArray jrmps = DBPools.defaultPool().opensql2json_O(psql);
if (jrmps.size() == 0)
throw new Exception("权限范围内没找到该用户资料!");
int age = jrmps.getJSONObject(0).getInt("age");
if (tp == 1) {
Hr_employee_linked el = new Hr_employee_linked();
el.findByPSQL(psql);
if (el.isEmpty())
throw new Exception("权限范围内没找到该用户资料!");
JSONObject rst = el.toJsonObj();
rst.put("age", age);
return rst.toString();
} else if (tp == 2) {
Hr_employee e = new Hr_employee();
e.findByPSQL(psql);
if (e.isEmpty())
throw new Exception("权限范围内没找到该用户资料!");
JSONObject rst = e.toJsonObj();
rst.put("age", age);
return rst.toString();
} else
throw new Exception("tp参数错误");
}
@ACOAction(eventname = "findEmployeeinfo4Edit", Authentication = true, notes = "根据员工ID查找员工资料,权限范围内")
public String findEmployeeinfo4Edit() throws Exception {
// String sqlstr = "SELECT
// e.*,l.ljtype2,l.ljtype1,l.ljreason,TIMESTAMPDIFF(YEAR, e.birthday,
// CURDATE()) age "
// + "FROM hr_employee e LEFT JOIN hr_leavejob l ON e.er_id=l.er_id AND
// l.`stat`=9 and l.iscanced<>1 ";
String sqlstr = "SELECT * FROM "
+ "(SELECT e.*,l.ljtype2,l.ljtype1,l.ljreason,TIMESTAMPDIFF(YEAR, e.birthday, CURDATE()) age "
+ " FROM hr_employee e LEFT JOIN hr_leavejob l ON e.er_id=l.er_id AND l.`stat`=9 AND l.iscanced<>1) tb "
+ "WHERE 1=1 ";
if (!HRUtil.hasRoles("2")) {// 不是招募中心人员 只能看没有离职的 或 离职类型不是招募中心自理的
sqlstr = sqlstr + " AND ((ljtype1 is NULL) OR (ljtype1<>8)) ";
}
JSONObject rst = new CReport(sqlstr, " createtime desc ", null).findReport2JSON_O();
JSONArray rows = rst.getJSONArray("rows");
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
String erid = row.getString("er_id");
Date hiredday = Systemdate.getDateByStr(row.getString("hiredday"));
// row.put("workym", CtrHrkq_leave_blance.getworkym(hiredday, new
// Date()));// 工龄
String yearmonth = CtrHrkq_leave_blance.getworkymString(hiredday, new Date());
if(yearmonth.equals("0")){
row.put("workym", "0年0月");// 工龄
}else{
String nian = yearmonth.substring(0, yearmonth.indexOf("."));
String yue = yearmonth.substring(yearmonth.indexOf(".") + 1);
row.put("workym", nian + "年" + yue + "月");// 工龄
}
}
// 判斷前端是否有返回參數,無則是查詢,有則是導出
HashMap<String, String> parms = CSContext.get_pjdataparms();
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(rows, scols);
return null;
}
}
@ACOAction(eventname = "findEmpnameByCode", Authentication = true, notes = "根据工号查姓名")
public String findEmpnameByCode() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String employee_code = CorUtil.hashMap2Str(parms, "employee_code", "需要参数employee_code");
String sqlstr = "select employee_name from hr_employee where employee_code='" + employee_code + "'";
Hr_employee emp = new Hr_employee();
List<HashMap<String, String>> ns = emp.pool.openSql2List(sqlstr);
if (ns.size() == 0)
throw new Exception("工号为【" + employee_code + "】的人事资料不存在");
JSONObject rst = new JSONObject();
rst.put("employee_name", ns.get(0).get("employee_name"));
return rst.toString();
}
@ACOAction(eventname = "findOrgOptionByLoginUser", Authentication = true, notes = "获取权限范围内机构岗位非批量")
public String findOrgOptionByLoginUser() throws Exception {
HashMap<String, String> urlparms = CSContext.getParms();
String parms = urlparms.get("parms");
String sqlstr = "select * from hr_orgposition where usable=1 ";
String order = " ORDER BY orgid ASC ";
String smax = urlparms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
List<JSONParm> jps = CJSON.getParms(parms);
Hr_orgposition hsp = new Hr_orgposition();
String where = CjpaUtil.buildFindSqlByJsonParms(hsp, jps);
sqlstr = sqlstr + CSContext.getIdpathwhere() + where + order + " limit 0," + max;
return hsp.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "getepsts", Authentication = true, ispublic = true, notes = "获取状态")
public String getEmpkoyeeStats() throws Exception {
String sqlstr = "select * from hr_employeestat where usable=1 order by statvalue";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "findEmployeeTrancer", Authentication = true, ispublic = false, notes = "查询权限范围内允许调动的员工资料")
public String findEmployeeTrancer() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
int tp = Integer.valueOf(CorUtil.hashMap2Str(parms, "tp", "需要参数tp"));// 1单调
// 2批调
// 3混合
String eparms = parms.get("parms");
List<JSONParm> jps = CJSON.getParms(eparms);
// if (jps.size() == 0)
// throw new Exception("需要查询参数");
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
// System.out.println("where:" + where);
String sqlstr = "select * from hr_employee where usable=1 and empstatid in(SELECT statvalue FROM hr_employeestat WHERE allowtransfer=1) ";
if (tp == 1) {// OO类允许单独调动 主要是升职调动时候
} else if (tp == 2) {
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
sqlstr = sqlstr + " and ospid IN (SELECT ospid FROM hr_orgposition WHERE hwc_idzl IN("
+ "SELECT parmvalue FROM hr_systemparms WHERE usable=1 AND parmcode='BATCH_QUATA_CLASS')) "
+ " and orgid in(select orgid from shworg where idpath like '" + org.idpath.getValue() + "%')";
} else if (tp == 3) {// 混合调动
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
sqlstr = sqlstr + " and orgid=" + org.orgid.getValue();
} else
throw new Exception("tp参数允许值为1,2,3");
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
sqlstr = sqlstr + " and employee_code='" + CSContext.getUserName() + "' ";
}
sqlstr = sqlstr + CSContext.getIdpathwhere() + where + " limit 0," + max;
return he.pool.opensql2json(sqlstr);
// JSONArray ems = he.pool.opensql2json_O(sqlstr);
// for (int i = 0; i < ems.size(); i++) {
// JSONObject em = ems.getJSONObject(i);
// em.put("extorgname",
// COShwUser.getOrgNamepath(em.getString("orgid")));
// }
// return ems.toString();
}
@ACOAction(eventname = "findEmployeeByIDCard", Authentication = true, ispublic = false, notes = "入职按身份证查找重入")
public String findEmployeeByIDCard() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String id_number = CorUtil.hashMap2Str(parms, "id_number", "id_number参数不能为空");
// 黑名单
// if (CtrHrEmployeeUtil.isInBlackList(id_number))
// throw new Exception("身份证为【" + id_number + "】的员工标记为【黑名单】");
// 有在职的
Hr_employee he = CtrHrEmployeeUtil.getIDNumberIsFrmal(id_number);
if (!he.isEmpty()) {
throw new Exception("员工资料在职,不允许重新入职");
}
// 查找最后离职
String sqlstr = "SELECT * FROM hr_employee WHERE empstatid=12 AND id_number ='" + id_number
+ "' ORDER BY hiredday DESC";
he.findBySQL(sqlstr);
if (he.isEmpty())
throw new Exception("只有【离职】状态的员工允许重新入职");
return he.tojson();
}
@ACOAction(eventname = "findEmployeebackByIDCard", Authentication = true, ispublic = false, notes = "查找黑名单")
public String findEmployeebackByIDCard() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String id_number = CorUtil.hashMap2Str(parms, "id_number", "id_number参数不能为空");
// 黑名单
if (CtrHrEmployeeUtil.isInBlackList(id_number))
throw new Exception("身份证为【" + id_number + "】的员工标记为【黑名单】,请先解封");
Hr_employee he = CtrHrEmployeeUtil.getIDNumberIsFrmal(id_number);
if (!he.isEmpty()) {
throw new Exception("员工资料在职,不允许重新入职");
}
JSONObject rst = new JSONObject();
rst.put("rst", "OK");
return rst.toString();
}
@ACOAction(eventname = "getUserInfo", Authentication = true, ispublic = false, notes = "根据用户名获取用户信息")
public String getUserInfo() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String employee_code = CorUtil.hashMap2Str(parms, "employee_code", "employee_code参数不能为空");
String sqlstr = "select * from shwuser where username='" + employee_code + "'";
Shwuser user = new Shwuser();
user.findBySQL(sqlstr, false);
if (user.isEmpty())
throw new Exception("没有登录名为【" + employee_code + "】的系统用户");
String[] fields = { "userid", "username", "displayname" };
return user.tojsonsimple(fields);
}
/**
* includelv 包含离职的
*
* @return
* @throws Exception
*/
@ACOAction(eventname = "findEmoloyeeList", Authentication = true, ispublic = false, notes = "根据登录权限查询员工资料")
public String findEmoloyeeList() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
String spcetype = parms.get("spcetype");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String orgid = parms.get("orgid");
if ((orgid != null) && (!orgid.isEmpty())) {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("没发现ID为【" + orgid + "】的机构");
where = where + " and idpath like '" + org.idpath.getValue() + "%'";
}
if ((spcetype != null) && (Integer.valueOf(spcetype) == 1)) {
where = where + " and employee_code='" + CSContext.getUserName() + "'";
}
String strincludelv = parms.get("includelv");
boolean includelv = (strincludelv == null) ? false : Boolean.valueOf(strincludelv);
String llvdate = parms.get("llvdate");// 最晚离职日期
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
String sqlstr = "select * from hr_employee where usable=1";
if ((llvdate != null) && (!llvdate.isEmpty())) {
sqlstr = sqlstr + " and ( empstatid<=10 || ljdate<'" + llvdate + "') ";
} else {
if (!includelv)
sqlstr = sqlstr + " and empstatid<=10 ";
}
sqlstr = sqlstr + CSContext.getIdpathwhere() + where + " limit 0," + max;
return he.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findEmoloyeeListAll", Authentication = true, ispublic = false, notes = "查询所有员工资料")
public String findEmoloyeeListAll() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String orgid = parms.get("orgid");
if ((orgid != null) && (!orgid.isEmpty())) {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("没发现ID为【" + orgid + "】的机构");
where = where + " and idpath like '" + org.idpath.getValue() + "%'";
}
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
String sqlstr = "select * from hr_employee where usable=1 and empstatid<=10 " + where + " limit 0," + max;
return he.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findStateEmoloyeeList", Authentication = true, ispublic = false, notes = "查询特定类型员工资料")
public String findStateEmoloyeeList() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String empstatid = CorUtil.hashMap2Str(parms, "empstatid", "需要参数empstatid");
String sqlstr = "select * from hr_employee where usable=1 and empstatid=" + empstatid;
return CSearchForm.doExec2JSON(sqlstr);
}
@ACOAction(eventname = "findEmoloyee4BlackDel", Authentication = true, ispublic = false, notes = "查询特定类型员工资料")
public String findEmoloyee4BlackDel() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String empstatid = CorUtil.hashMap2Str(parms, "empstatid", "需要参数empstatid");
String sqlstr = "select * from hr_employee where usable=1 and empstatid=" + empstatid;
return new CReport(sqlstr, null).findReport2JSON_O(null, true, "").toString();
}
@ACOAction(eventname = "findEmpkoyeeByid", Authentication = true, ispublic = false, notes = "查询员工详细资料")
public String findEmpkoyeeByid() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_linked eml = new Hr_employee_linked();
eml.findByID(er_id);
if (eml.isEmpty())
throw new Exception("没有发现id为【" + er_id + "】的员工资料");
return eml.tojson();
}
// @ACOAction(eventname = "findEmpkoyeeLevedByid", Authentication = true,
// ispublic = false, notes = "查询离职员工详细资料")
// public String findEmpkoyeeLevedByid() throws Exception {
// HashMap<String, String> parms = CSContext.getParms();
// String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
//
// Hr_employee_linked eml = new Hr_employee_linked();
// String sqlstr = "select * from hr_employee_leved where er_id=" + er_id;
// eml.findBySQL(sqlstr);
// if (eml.isEmpty())
// throw new Exception("没有发现id为【" + er_id + "】的 离职员工资料");
// return eml.tojson();
// }
@ACOAction(eventname = "removeEmoloyePic", Authentication = true, notes = "")
public String removeEmoloyePic() throws Exception {
String avatar_id1 = CorUtil.hashMap2Str(CSContext.getParms(), "avatar_id1");
String avatar_id2 = CorUtil.hashMap2Str(CSContext.getParms(), "avatar_id2");
String er_id = CorUtil.hashMap2Str(CSContext.getParms(), "er_id");
if ((avatar_id1 == null) && (avatar_id2 == null)) {
throw new Exception("avatar_id1 avatar_id2参数不能都为空");
}
Hr_employee he = new Hr_employee();
if (er_id != null) {
he.findByID(er_id, false);
if (he.isEmpty())
throw new Exception("没有找到ID为【" + er_id + "】的员工资料");
}
if (avatar_id1 != null) {
UpLoadFileEx.delAttFile(avatar_id1);
if (!he.isEmpty()) {
he.avatar_id1.setValue(null);
he.save();
}
}
if (avatar_id2 != null) {
UpLoadFileEx.delAttFile(avatar_id2);
if (!he.isEmpty()) {
he.avatar_id2.setValue(null);
he.save();
}
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "uploadEmployeePic", Authentication = true, notes = "")
public String uploadEmployeePic() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String er_id = CorUtil.hashMap2Str(CSContext.getParms(), "er_id", "需要参数er_id");
Hr_employee he = new Hr_employee();
he.findByID(er_id, false);
if (he.isEmpty())
throw new Exception("没有找到ID为【" + er_id + "】的员工资料");
if (!he.avatar_id2.isEmpty()) {
UpLoadFileEx.delAttFile(he.avatar_id2.getValue());
}
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
if (!UpLoadFileEx.isImage(p)) {
UpLoadFileEx.delAttFile(he.avatar_id2.getValue());
throw new Exception("不是图片格式!");
}
if (p.filesize.getAsFloat() > (1024 * 5)) {
UpLoadFileEx.delAttFile(he.avatar_id2.getValue());
throw new Exception("图片不能超过5M!");
}
// BufferedImage Image = ImageIO.read(new File(name));
he.avatar_id2.setValue(p.pfid.getValue());
he.save(false);
// 添加图片引用
return "{\"avatar_id\":\"" + p.pfid.getValue() + "\"}";
} else
throw new Exception("没有图片文件");
}
@ACOAction(eventname = "getEmployeeFamilay", Authentication = true, notes = "获取员工家庭关系")
public String getEmployeeFamilay() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_family hef = new Hr_employee_family();
String sqlstr = "select * from hr_employee_family where er_id=" + er_id + " order by empf_id";
return hef.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeFamilay", Authentication = true, notes = "获取员工家庭关系")
public String delEmployeeFamilay() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String empf_id = CorUtil.hashMap2Str(parms, "empf_id", "需要参数empf_id");
Hr_employee_family hef = new Hr_employee_family();
hef.findByID(empf_id);
if (hef.isEmpty())
throw new Exception("没有找到ID为【" + empf_id + "】的家庭关系资料");
hef.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeFamilay", Authentication = true, notes = "获取员工家庭关系")
public String saveEmployeeFamilay() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_family hef = new Hr_employee_family();
hef.fromjson(jsondata);
if (isnew) {
hef.setJpaStat(CJPAStat.RSINSERT);
} else {
hef.setJpaStat(CJPAStat.RSUPDATED);
}
hef.save();
return hef.tojson();
}
@ACOAction(eventname = "getEmployeeLeanExp", Authentication = true, notes = "获取员工教育经历")
public String getEmployeeLeanExp() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_leanexp hele = new Hr_employee_leanexp();
String sqlstr = "select * from hr_employee_leanexp where er_id=" + er_id + " order by emple_id";
return hele.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeLeanExp", Authentication = true, notes = "删除员工教育经历")
public String delEmployeeLeanExp() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String emple_id = CorUtil.hashMap2Str(parms, "emple_id", "需要参数emple_id");
Hr_employee_leanexp hele = new Hr_employee_leanexp();
hele.findByID(emple_id);
if (hele.isEmpty())
throw new Exception("没有找到ID为【" + emple_id + "】的教育经历资料");
hele.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeLeanExp", Authentication = true, notes = "保存员工教育经历")
public String saveEmployeeLeanExp() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_leanexp hele = new Hr_employee_leanexp();
hele.fromjson(jsondata);
if (isnew) {
hele.setJpaStat(CJPAStat.RSINSERT);
} else {
hele.setJpaStat(CJPAStat.RSUPDATED);
}
hele.save();
return hele.tojson();
}
@ACOAction(eventname = "getEmployeeWork", Authentication = true, notes = "获取员工工作经历")
public String getEmployeeWork() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_work hew = new Hr_employee_work();
String sqlstr = "select * from hr_employee_work where er_id=" + er_id + " order by empl_id";
return hew.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeWork", Authentication = true, notes = "删除员工工作经历")
public String delEmployeeWork() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String empl_id = CorUtil.hashMap2Str(parms, "empl_id", "需要参数empl_id");
Hr_employee_work hew = new Hr_employee_work();
hew.findByID(empl_id);
if (hew.isEmpty())
throw new Exception("没有找到ID为【" + empl_id + "】的工作经历资料");
hew.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeWork", Authentication = true, notes = "保存员工工作经历")
public String saveEmployeeWork() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_work hew = new Hr_employee_work();
hew.fromjson(jsondata);
if (isnew) {
hew.setJpaStat(CJPAStat.RSINSERT);
} else {
hew.setJpaStat(CJPAStat.RSUPDATED);
}
hew.save();
return hew.tojson();
}
@ACOAction(eventname = "getEmployeeTrainExp", Authentication = true, notes = "获取员工培训经历")
public String getEmployeeTrainExp() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_trainexp hete = new Hr_employee_trainexp();
String sqlstr = "select * from hr_employee_trainexp where er_id=" + er_id + " order by tranexp_id";
return hete.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeTrainExp", Authentication = true, notes = "删除员工培训经历")
public String delEmployeeTrainExp() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String tranexp_id = CorUtil.hashMap2Str(parms, "tranexp_id", "需要参数tranexp_id");
Hr_employee_trainexp hete = new Hr_employee_trainexp();
hete.findByID(tranexp_id);
if (hete.isEmpty())
throw new Exception("没有找到ID为【" + tranexp_id + "】的培训经历资料");
hete.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeTrainExp", Authentication = true, notes = "保存员工培训经历")
public String saveEmployeeTrainExp() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_trainexp hete = new Hr_employee_trainexp();
hete.fromjson(jsondata);
if (isnew) {
hete.setJpaStat(CJPAStat.RSINSERT);
} else {
hete.setJpaStat(CJPAStat.RSUPDATED);
}
hete.save();
return hete.tojson();
}
@ACOAction(eventname = "getEmployeeRelation", Authentication = true, notes = "获取员工关联关系")
public String getEmployeeRelation() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_relation her = new Hr_employee_relation();
String sqlstr = "select * from hr_employee_relation where er_id=" + er_id + " order by empr_id";
return her.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeRelation", Authentication = true, notes = "删除员工关联关系")
public String delEmployeeRelation() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String empr_id = CorUtil.hashMap2Str(parms, "empr_id", "需要参数empr_id");
Hr_employee_relation her = new Hr_employee_relation();
her.findByID(empr_id);
if (her.isEmpty())
throw new Exception("没有找到ID为【" + empr_id + "】的关联关系资料");
her.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeRelation", Authentication = true, notes = "保存员工关联关系")
public String saveEmployeeRelation() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_relation her = new Hr_employee_relation();
her.fromjson(jsondata);
if (isnew) {
her.setJpaStat(CJPAStat.RSINSERT);
} else {
her.setJpaStat(CJPAStat.RSUPDATED);
}
her.save();
return her.tojson();
}
@ACOAction(eventname = "getEmployeeCretl", Authentication = true, notes = "获取员工证书资料")
public String getEmployeeCretl() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_cretl hec = new Hr_employee_cretl();
String sqlstr = "select * from hr_employee_cretl where er_id=" + er_id + " order by cert_id";
return hec.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeCretl", Authentication = true, notes = "删除员工证书资料")
public String delEmployeeCretl() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String cert_id = CorUtil.hashMap2Str(parms, "cert_id", "需要参数cert_id");
Hr_employee_cretl hec = new Hr_employee_cretl();
hec.findByID(cert_id);
if (hec.isEmpty())
throw new Exception("没有找到ID为【" + cert_id + "】的证书资料");
hec.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeCretl", Authentication = true, notes = "保存员工证书资料")
public String saveEmployeeCretl() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_cretl hec = new Hr_employee_cretl();
hec.fromjson(jsondata);
if (isnew) {
hec.setJpaStat(CJPAStat.RSINSERT);
} else {
hec.setJpaStat(CJPAStat.RSUPDATED);
}
hec.save();
return hec.tojson();
}
@ACOAction(eventname = "uploadEmployeeCretlPic", Authentication = true, notes = "上传证件图片")
public String uploadEmployeeCretlPic() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String cert_id = CorUtil.hashMap2Str(CSContext.getParms(), "cert_id", "需要参数cert_id");
Hr_employee_cretl hec = new Hr_employee_cretl();
hec.findByID(cert_id, false);
if (hec.isEmpty())
throw new Exception("没有找到ID为【" + cert_id + "】的证件资料");
if (!hec.picture_id.isEmpty()) {
UpLoadFileEx.delAttFile(hec.picture_id.getValue());
}
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
hec.picture_id.setValue(p.pfid.getValue());
hec.save(false);
// 添加图片引用
return "{\"picture_id\":\"" + p.pfid.getValue() + "\"}";
} else
throw new Exception("没有图片文件");
}
@ACOAction(eventname = "getEmployeeReward", Authentication = true, notes = "获取员工激励记录")
public String getEmployeeReward() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_reward her = new Hr_employee_reward();
String sqlstr = "select * from hr_employee_reward where er_id=" + er_id + " order by emprw_id";
return her.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeReward", Authentication = true, notes = "删除员工激励记录")
public String delEmployeeReward() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String emprw_id = CorUtil.hashMap2Str(parms, "emprw_id", "需要参数emprw_id");
Hr_employee_reward her = new Hr_employee_reward();
her.findByID(emprw_id);
if (her.isEmpty())
throw new Exception("没有找到ID为【" + emprw_id + "】的激励记录");
her.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeReward", Authentication = true, notes = "保存员工激励记录")
public String saveEmployeeReward() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_reward her = new Hr_employee_reward();
her.fromjson(jsondata);
if (isnew) {
her.setJpaStat(CJPAStat.RSINSERT);
} else {
her.setJpaStat(CJPAStat.RSUPDATED);
}
her.save();
return her.tojson();
}
@ACOAction(eventname = "getEmployeeNReward", Authentication = true, notes = "获取员工负激励记录")
public String getEmployeeNReward() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_employee_nreward henr = new Hr_employee_nreward();
String sqlstr = "select * from hr_employee_nreward where er_id=" + er_id + " order by nemprw_id";
return henr.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "delEmployeeNReward", Authentication = true, notes = "删除员工负激励记录")
public String delEmployeeNReward() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String nemprw_id = CorUtil.hashMap2Str(parms, "nemprw_id", "需要参数nemprw_id");
Hr_employee_nreward henr = new Hr_employee_nreward();
henr.findByID(nemprw_id);
if (henr.isEmpty())
throw new Exception("没有找到ID为【" + nemprw_id + "】的负激励记录");
henr.delete();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "saveEmployeeNReward", Authentication = true, notes = "保存员工负激励记录")
public String saveEmployeeNReward() throws Exception {
JSONObject rootNode = JSONObject.fromObject(CSContext.getPostdata());
boolean isnew = rootNode.getBoolean("isnew");
String jsondata = rootNode.getString("jsondata");
Hr_employee_nreward henr = new Hr_employee_nreward();
henr.fromjson(jsondata);
if (isnew) {
henr.setJpaStat(CJPAStat.RSINSERT);
} else {
henr.setJpaStat(CJPAStat.RSUPDATED);
}
henr.save();
return henr.tojson();
}
@ACOAction(eventname = "findLVEmoloyeeList", Authentication = true, ispublic = false, notes = "根据登录权限查询可离职员工资料")
public String findLVEmoloyeeList() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
String orgid = parms.get("orgid");
List<JSONParm> jps = CJSON.getParms(eparms);
// if (jps.size() == 0)
// throw new Exception("需要查询参数");
Hr_employee he = new Hr_employee();
int mengtag = Integer.valueOf(CorUtil.hashMap2Str(parms, "mengtag", "需要参数mengtag"));
String sdfdname = null;
if (mengtag == 1)
sdfdname = "allowlv";
else if (mengtag == 2)
sdfdname = "allowsxlv";
else
throw new Exception("参数【mengtag】只允许为1、2");
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
String sqlstr = "SELECT * FROM hr_employee WHERE 1=1 ";
if (orgid != null) {
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在!");
sqlstr = sqlstr
+ "AND EXISTS (SELECT 1 FROM shworg WHERE shworg.usable=1 AND hr_employee.orgid=shworg.orgid AND shworg.idpath LIKE '"
+ org.idpath.getValue() + "%')";
// sqlstr = sqlstr + " and orgid in (select orgid from shworg where
// idpath like
// '" + org.idpath.getValue() + "%')";
}
// sqlstr = sqlstr + " and empstatid IN( " + " SELECT statvalue FROM
// hr_employeestat WHERE " + sdfdname + "=1 " + ") ";
sqlstr = sqlstr
+ "AND EXISTS (SELECT 1 FROM hr_employeestat WHERE hr_employee.empstatid=hr_employeestat.statvalue AND hr_employeestat."+sdfdname+"=1)";
sqlstr = sqlstr + " AND usable=1 " + CSContext.getIdpathwhere() + where + " limit 0," + max;
return he.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findOrgHrlev", Authentication = true, ispublic = true, notes = "获取机构人事级别")
public String findOrgHrlev() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "orgid参数不能为空");
int hrlev = HRUtil.getOrgHrLev(orgid);
return "{\"hrlev\":\"" + hrlev + "\"}";
}
@ACOAction(eventname = "reSetOPNameIDPath", Authentication = true, ispublic = true, notes = "设置机构职位信息")
public String reSetOPNameIDPath() throws Exception {
CJPALineData<Hr_orgposition> ops = new CJPALineData<Hr_orgposition>(Hr_orgposition.class);
String sqlstr = "select * from Hr_orgposition ";
ops.findDataBySQL(sqlstr);
Shworg o = new Shworg();
for (CJPABase jpa : ops) {
Hr_orgposition e = (Hr_orgposition) jpa;
o.findByID(e.orgid.getValue());
if (!o.isEmpty()) {
e.orgname.setValue(COShwUser.getOrgNamepath(o.orgid.getValue()));
e.orgcode.setValue(o.code.getValue());
e.idpath.setValue(o.idpath.getValue());
e.save();
}
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "reSetEmpOrgNameIDPath", Authentication = true, ispublic = true, notes = "设置人事机构信息")
public String reSetEmpOrgNameIDPath() throws Exception {
CJPALineData<Hr_employee> emps = new CJPALineData<Hr_employee>(Hr_employee.class);
String sqlstr = "select * from hr_employee ";
emps.findDataBySQL(sqlstr);
Shworg o = new Shworg();
for (CJPABase jpa : emps) {
Hr_employee e = (Hr_employee) jpa;
o.findByID(e.orgid.getValue());
if (!o.isEmpty()) {
e.orgname.setValue(COShwUser.getOrgNamepath(o.orgid.getValue()));
e.orgcode.setValue(o.code.getValue());
e.idpath.setValue(o.idpath.getValue());
e.save();
}
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "reSetEmpOSPInfo", Authentication = true, ispublic = true, notes = "设置人事职位信息")
public String reSetEmpOSPInfo() throws Exception {
CJPALineData<Hr_employee> emps = new CJPALineData<Hr_employee>(Hr_employee.class);
String sqlstr = "select * from hr_employee ";
emps.findDataBySQL(sqlstr);
Hr_orgposition osp = new Hr_orgposition();
Shworg o = new Shworg();
for (CJPABase jpa : emps) {
Hr_employee e = (Hr_employee) jpa;
osp.findByID(e.ospid.getValue());
o.findByID(e.orgid.getValue());
if (!osp.isEmpty()) {
e.lv_id.setValue(osp.lv_id.getValue());
e.lv_num.setValue(osp.lv_num.getValue());
e.hg_id.setValue(osp.hg_id.getValue());
e.hg_code.setValue(osp.hg_code.getValue());
e.hg_name.setValue(osp.hg_name.getValue());
e.ospcode.setValue(osp.ospcode.getValue());
e.sp_name.setValue(osp.sp_name.getValue());
e.iskey.setValue(osp.iskey.getValue());
e.hwc_namezq.setValue(osp.hwc_namezq.getValue());
e.hwc_namezz.setValue(osp.hwc_namezz.getValue());
e.save();
}
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "getEmployee_cret_attach", Authentication = true, ispublic = false, notes = "getEmployee_cret_attach")
public String getEmployee_cret_attach() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String id = CorUtil.hashMap2Str(parms, "id", "id参数不能为空");
Hr_employee_cretl ec = new Hr_employee_cretl();
ec.findByID(id);
if (ec.isEmpty())
throw new Exception("ID为【" + id + "】的证件不存在");
Shw_attach att = new Shw_attach();
att.findByID(ec.attid.getValue());
return att.tojson();
}
/**
* 文件名
* 工号+证件名.*
*
* @return
* @throws Exception
*/
@ACOAction(eventname = "impattrs", Authentication = true, ispublic = false, notes = "批量导入附件")
public String impattrs() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (!HRUtil.hasRoles("87")) {// 没有权限,直接删除上传的文件
dellallfile(pfs);
throw new Exception("需要证件管理员权限");
}
int rst = 0;
Hr_employee emp = new Hr_employee();
CDBConnection con = DBPools.defaultPool().getCon(this);
con.startTrans();
try {
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
String displayfname = pf.displayfname.getValue();
Integer spidx = displayfname.indexOf("+");
String empcode = displayfname.substring(0, spidx);
String dname = displayfname.substring(spidx + 1, displayfname.length());
emp.clear();
String sqlstr = "SELECT * FROM hr_employee WHERE employee_code='" + empcode + "'";
emp.findBySQL(con, sqlstr, true);
if (emp.isEmpty())
throw new Exception("工号【" + empcode + "】不存在");
CJPALineData<Shw_attach> shw_attachs = emp.shw_attachs;
Shw_attach att = null;
if (shw_attachs.size() == 0) {
att = new Shw_attach();
shw_attachs.add(att);
} else {
att = (Shw_attach) shw_attachs.get(0);
}
Shw_attach_line al = new Shw_attach_line();
al.pfid.setValue(pf.pfid.getValue()); // 物理文件ID
al.fdrid.setValue(0); // 文件夹ID 单据的附件 本属性为0
al.displayfname.setValue(dname); // 显示的名称
al.extname.setValue(pf.extname.getValue()); // 扩展文件名
al.filesize.setValue(pf.filesize.getValue()); // 文件大小
al.filevision.setValue(pf.filevision.getValue()); // 文件版本
al.filecreator.setValue(pf.creator.getValue()); // 所有者
al.filecreate_time.setAsDatetime(new Date()); // 创建时间
att.shw_attach_lines.add(al);
emp.save(con);
rst++;
// UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
con.submit();
} catch (Exception e) {
con.rollback();
dellallfile(pfs);
throw e;
} finally {
con.close();
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private void dellallfile(CJPALineData<Shw_physic_file> pfs) throws Exception {
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
@ACOAction(eventname = "expcerts", Authentication = true, ispublic = false, notes = "批量导出附件")
public String expcerts() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String erids = CorUtil.hashMap2Str(parms, "erids", "需要参数erids");
String sqlstr = "SELECT p.*,al.displayfname fname,e.employee_code FROM hr_employee e,shw_attach_line al,shw_physic_file p " +
"WHERE e.attid=al.attid AND al.pfid=p.pfid " +
"AND e.er_id IN(" + erids + ")";
List<JSONObject> files = new ArrayList<JSONObject>();
JSONArray pfs1 = DBPools.defaultPool().opensql2json_O(sqlstr);
for (int i = 0; i < pfs1.size(); i++) {
files.add(pfs1.getJSONObject(i));
}
sqlstr = "SELECT p.*,al.displayfname fname,e.employee_code FROM hr_employee e,hr_employee_cretl c,shw_attach_line al,shw_physic_file p "
+ " WHERE e.er_id=c.er_id AND al.attid=c.attid AND p.pfid=al.pfid"
+ " AND e.er_id IN(" + erids + ")";
JSONArray pfs2 = DBPools.defaultPool().opensql2json_O(sqlstr);
for (int i = 0; i < pfs2.size(); i++) {
files.add(pfs2.getJSONObject(i));
}
if (files.size() == 0)
throw new Exception("没有附件");
createTempFile(files);
return null;
}
private void createTempFile(List<JSONObject> files) throws Exception {
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
String fsep = System.getProperty("file.separator");
String rootfstr = ConstsSw.geAppParmStr("UDFilePath") + "temp" + fsep + un
+ "_" + Systemdate.getStrDateByFmt(new Date(), "hhmmss") + fsep;
File file = new File(rootfstr);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
for (int i = 0; i < files.size(); i++) {
JSONObject pf = files.get(i);
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fsep + pf.getString("ppath") + fsep + pf.getString("pfname");
if (!(new File(fullname)).exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fsep + pf.getString("ppath") + fsep + pf.getString("pfname");
if (!(new File(fullname)).exists())
throw new Exception("文件" + fullname + "不存在!");
}
String fname = pf.getString("fname");
fname = fname.replace("\\", fsep);
fname = fname.replace("/", fsep);
String[] sz = fname.split(fsep);
fname = sz[sz.length - 1];
String strtem = pf.getString("employee_code") + "-" + fname;
String nfname = rootfstr + fsep + strtem;
file = new File(nfname);
if ((file.exists()) && (file.isFile())) {
if (!file.delete())
throw new Exception("删除文件错误【" + nfname + "】");
}
RandomAccessFile outfile = new RandomAccessFile(nfname, "rw");
forTransfer(new RandomAccessFile(fullname, "r"), outfile);
}
String rarfname = ConstsSw.geAppParmStr("UDFilePath") + "temp" + fsep + "下载文件.zip";
file = new File(rarfname);
if ((file.exists()) && (file.isFile())) {
if (!file.delete())
throw new Exception("删除文件错误【" + rarfname + "】");
}
CFileUtiil.zipFold(rarfname, rootfstr);
HttpServletResponse rsp = CSContext.getResponse();
rsp.setContentType(getContentType(rarfname));
rsp.setHeader("content-disposition", "attachment; filename=" + new String(("下载文件.zip").getBytes("GB2312"), "ISO_8859_1"));
OutputStream os = rsp.getOutputStream();
FileInputStream fis = new FileInputStream(rarfname);
try {
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
fis.close();
os.flush();
os.close();
}
File f = new File(rootfstr);
CFileUtiil.delete(f);
f = new File(rarfname);
CFileUtiil.delete(f);
}
private static String getContentType(String pathToFile) {
Path path = Paths.get(pathToFile);
try {
return Files.probeContentType(path);
} catch (IOException e) {
return "application/text";
}
}
private static void forTransfer(RandomAccessFile f1, RandomAccessFile f2) throws Exception {
final int len = 20971520;
int curPosition = 0;
FileChannel inC = f1.getChannel();
FileChannel outC = f2.getChannel();
while (true) {
if (inC.position() == inC.size()) {
inC.close();
outC.close();
break;
}
if ((inC.size() - inC.position()) < len)
curPosition = (int) (inC.size() - inC.position());
else
curPosition = len;
inC.transferTo(inC.position(), curPosition, outC);
inC.position(inC.position() + curPosition);
}
}
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "入职导入Excel")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new
// HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
String idpathwhere = CSContext.getIdpathwhere();
String entid = CSContext.getCurEntID();
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 1);// 解析title
// 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 1);
Hr_employee emp = new Hr_employee();
Hr_leavejob lv = new Hr_leavejob();
Hr_orgposition osp = new Hr_orgposition();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
int ct = values.size();
int curidx = 0;
for (Map<String, String> v : values) {
Logsw.debug("人事资料导入【" + (curidx++) + "/" + ct + "】");
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
boolean undup = (Integer.valueOf(HrkqUtil.getParmValueErr("IMPORT_EMP_DUP")) == 1);// 批量导入人事资料重复时处理规则
// 1
// 禁止重复
// 2
// 重复更新
if (undup) {
if (!emp.isEmpty())
throw new Exception("工号【" + employee_code + "】的人事资料已经存在");
}
String sqlstr = "select * from hr_leavejob where employee_code = '" + employee_code + "'";
lv.findBySQL(sqlstr, false);
if (!lv.isEmpty())
throw new Exception("已经存在员工【" + employee_code + "】的离职表单,无法重新导入");
lv.clear();
String ospcode = v.get("ospcode");
if ((ospcode == null) || (ospcode.isEmpty()))
throw new Exception("【" + v.get("employee_name") + "】机构职位编码不能为空");
sqlstr = "SELECT * FROM hr_orgposition WHERE ospcode='" + ospcode + "' ";
// if (!CSContext.isAdminNoErr())
sqlstr = sqlstr + " " + idpathwhere;
osp.clear();
osp.findBySQL(sqlstr, false);
if (osp.isEmpty())
throw new Exception("工号【" + employee_code + "】的机构职位编码【" + ospcode + "】不存在或权限范围内不存在");
String id_number = v.get("id_number");
if ((id_number == null) || (id_number.isEmpty()))
throw new Exception("【" + v.get("employee_name") + "】身份证不能为空");
if (undup)// 1 禁止重复 2 重复更新
emp.clear();
boolean lvjob = false;
if ("离职".equalsIgnoreCase(v.get("empstatid"))) {
lvjob = true;
emp.empstatid.setValue("4");
} else if ("正式".equals(v.get("empstatid")))
emp.empstatid.setValue("4");
else
throw new Exception("【" + v.get("employee_name") + "】只能导入人事状态为【正式、离职】的人事资料");
emp.card_number.setValue(v.get("card_number"));
emp.employee_code.setValue(employee_code);
emp.employee_name.setValue(v.get("employee_name"));
emp.usedname.setValue(v.get("usedname"));
emp.english_name.setValue(v.get("english_name"));
emp.pldcp.setValue(dictemp.getVbCE("495", v.get("pldcp"), true,
"工号【" + employee_code + "】政治面貌【" + v.get("pldcp") + "】不存在"));
emp.bwday.setValue(v.get("bwday"));
emp.health.setValue(v.get("health"));
emp.bloodtype.setValue(dictemp.getVbCE("697", v.get("bloodtype"), true,
"工号【" + employee_code + "】血型【" + v.get("bloodtype") + "】不存在"));
emp.medicalhistory.setValue(v.get("medicalhistory"));
emp.nation.setValue(dictemp.getVbCE("797", v.get("nation"), false,
"工号【" + employee_code + "】民族【" + v.get("nation") + "】不存在"));
emp.nationality.setValue(v.get("nationality"));
emp.talentstype.setValue(v.get("talentstype"));
emp.married.setValue(dictemp.getVbCE("714", v.get("married"), false,
"工号【" + employee_code + "】婚姻状况【" + v.get("married") + "】不存在"));
emp.email.setValue(v.get("email"));
emp.nativeplace.setValue(v.get("nativeplace"));
emp.address.setValue(v.get("address"));
emp.registertype.setValue(dictemp.getVbCE("702", v.get("registertype"), true,
"工号【" + employee_code + "】户籍类型【" + v.get("registertype") + "】不存在"));
emp.registeraddress.setValue(v.get("registeraddress"));
emp.sscurty_addr.setValue(v.get("sscurty_addr"));
emp.sscurty_startdate.setValue(v.get("sscurty_startdate"));
emp.shoesize.setValue(v.get("shoesize"));
emp.pants_code.setValue(v.get("pants_code"));
emp.coat_code.setValue(v.get("coat_code"));
emp.pay_way.setValue(v.get("pay_way"));
emp.schedtype.setValue(v.get("schedtype"));
emp.speciality.setValue(v.get("speciality"));
emp.entrysourcr.setValue(dictemp.getValueByCation("741", v.get("entrysourcr")));//
emp.advisercode.setValue(v.get("advisercode"));
emp.advisername.setValue(v.get("advisername"));
emp.adviserphone.setValue(v.get("adviserphone"));
emp.juridical.setValue(v.get("juridical"));
emp.transorg.setValue(v.get("transorg"));
emp.transextime.setValue(v.get("transextime"));
emp.dispunit.setValue(dictemp.getVbCE("1322", v.get("dispunit"), false,
"工号【" + employee_code + "】的派遣机构【" + v.get("dispunit") + "】不存在"));
emp.dispeextime.setValue(v.get("dispeextime"));
emp.note.setValue(v.get("note"));
emp.sex.setValue(dictemp.getVbCE("81", v.get("sex"), false,
"工号【" + employee_code + "】性别【" + v.get("sex") + "】不存在"));
emp.degree.setValue(dictemp.getVbCE("84", v.get("degree"), false,
"工号【" + employee_code + "】学历【" + v.get("degree") + "】不存在"));
emp.degreetype.setValue(dictemp.getVbCE("1495", v.get("degreetype"), false,
"工号【" + employee_code + "】学历类型【" + v.get("degreetype") + "】不存在"));
emp.degreecheck.setValue(dictemp.getVbCE("1507", v.get("degreecheck"), false,
"工号【" + employee_code + "】学历验证【" + v.get("degreecheck") + "】不存在"));
emp.introducer.setValue(v.get("introducer"));
emp.guarantor.setValue(v.get("guarantor"));
emp.eovertype.setValue(dictemp.getVbCE("1394", v.get("eovertype"), true,
"工号【" + employee_code + "】加班类别【" + v.get("eovertype") + "】不存在"));
emp.major.setValue(v.get("major"));
emp.birthday.setValue(v.get("birthday"));
emp.id_number.setValue(v.get("id_number"));
emp.registeraddress.setValue(v.get("registeraddress"));
emp.sign_org.setValue(v.get("sign_org"));
emp.sign_date.setValue(v.get("sign_date"));
emp.expired_date.setValue(v.get("expired_date"));
emp.hiredday.setValue(v.get("hiredday"));
emp.telphone.setValue(v.get("telphone"));
emp.urgencycontact.setValue(v.get("urgencycontact"));
emp.cellphone.setValue(v.get("cellphone"));
emp.dorm_bed.setValue(v.get("dorm_bed"));
emp.orgid.setValue(osp.orgid.getValue()); // 部门ID
emp.orgcode.setValue(osp.orgcode.getValue()); // 部门编码
emp.orgname.setValue(osp.orgname.getValue()); // 部门名称
emp.hwc_namezl.setValue(osp.hwc_namezl.getValue()); // 职类
emp.lv_id.setValue(osp.lv_id.getValue()); // 职级ID
emp.lv_num.setValue(osp.lv_num.getValue()); // 职级
emp.hg_id.setValue(osp.hg_id.getValue()); // 职等ID
emp.hg_code.setValue(osp.hg_code.getValue()); // 职等编码
emp.hg_name.setValue(osp.hg_name.getValue()); // 职等名称
emp.ospid.setValue(osp.ospid.getValue()); // 职位ID
if(osp.isoffjob.getValue().equals("1")){
emp.emnature.setValue("脱产");
}else {
emp.emnature.setValue("非脱产");
}
emp.ospcode.setValue(osp.ospcode.getValue()); // 职位编码
emp.sp_name.setValue(osp.sp_name.getValue()); // 职位名称
emp.iskey.setValue(osp.iskey.getValue()); // 关键岗位
emp.hwc_namezq.setValue(osp.hwc_namezq.getValue()); // 职群
emp.hwc_namezz.setValue(osp.hwc_namezz.getValue()); // 职种
emp.rectcode.setValue(v.get("rectcode")); // 招聘人工号
emp.rectname.setValue(v.get("rectname")); // 招聘人
// System.out.println("atdtype:" + v.get("atdtype"));
emp.atdtype.setValue(dictemp.getVbCE("1399", v.get("atdtype"), false,
"工号【" + employee_code + "】出勤类别【" + v.get("atdtype") + "】不存在"));
emp.noclock.setValue(dictemp.getVbCE("5", v.get("noclock"), false,
"工号【" + employee_code + "】免打考勤卡【" + v.get("noclock") + "】不存在"));
emp.usable.setAsInt(1); // 有效
emp.idpath.setValue(osp.idpath.getValue());
emp.property2.setValue("批量导入,批号:" + batchno);
emp.entid.setValue(entid);
emp.save(con, false);
if (lvjob) {// 离职表单
String[] asfds = { "orgid", "orgcode", "orgname", "er_id", "er_code", "employee_code", "sex",
"id_number", "employee_name", "degree", "birthday", "registeraddress", "hiredday", "lv_id",
"lv_num", "hg_id", "hg_code", "hg_name", "ospid", "ospcode", "sp_name", "hwc_namezl",
"idpath" };
lv.assignfieldOnlyValue(emp, asfds);
lv.ljtype.setAsInt(2); // 实习生或员工离职 1 实习生 2 员工
lv.ljappdate.setValue(v.get("ljappdate")); // 申请离职日期
lv.ljdate.setValue(v.get("ljappdate")); // 离职日期
lv.worktime.setValue(v.get("worktime")); // 司龄
lv.ljtype1.setValue(dictemp.getVbCE("782", v.get("ljtype1"), false,
"工号【" + employee_code + "】离职类别【" + v.get("ljtype1") + "】不存在")); // 离职类别
lv.ljtype2.setValue(dictemp.getVbCE("1045", v.get("ljtype2"), false,
"工号【" + employee_code + "】离职类型【" + v.get("ljtype2") + "】不存在")); // 离职类型
lv.ljreason.setValue(dictemp.getVbCE("1049", v.get("ljreason"), false,
"工号【" + employee_code + "】离职原因【" + v.get("ljreason") + "】不存在")); // 离职原因
lv.iscpst.setValue(dictemp.getValueByCation("5", v.get("iscpst"), "2")); // 是否补偿
lv.cpstarm.setValue(v.get("cpstarm")); // 补偿金额
lv.iscpt.setValue(dictemp.getValueByCation("5", v.get("iscpt"), "2")); // 是否投诉
lv.isabrt.setValue(dictemp.getValueByCation("5", v.get("isabrt"), "2")); // 是否仲裁
lv.islawsuit.setValue(dictemp.getValueByCation("5", v.get("islawsuit"), "2")); // 是否诉讼
lv.isblacklist.setValue(dictemp.getValueByCation("5", v.get("isblacklist"), "2")); // 是否加入黑名单
boolean addb = (lv.isblacklist.getAsInt() == 1);
// System.out.println("工号【" + employee_code + "】加封类型【" +
// v.get("addtype") + "】");
// System.out.println("工号【" + employee_code + "】加封类别【" +
// v.get("addtype1") + "】");
lv.addtype.setValue(dictemp.getVbCE("1071", v.get("addtype"), !addb,
"工号【" + employee_code + "】加封类型【" + v.get("addtype") + "】不存在")); // 加封类型
lv.addtype1.setValue(dictemp.getVbCE("1074", v.get("addtype1"), !addb,
"工号【" + employee_code + "】加封类别【" + v.get("addtype1") + "】不存在")); // 加封类别
lv.blackreason.setValue(v.get("blackreason")); // 加入黑名单原因
lv.iscanced.setValue("2"); // 已撤销
lv.pempstatid.setValue(emp.empstatid.getValue()); // 离职前状态
lv.remark.setValue("自动导入离职表单"); // 备注
lv.attribute2.setValue("批量导入,批号:" + batchno);
lv.entid.setValue(entid);
lv.save(con);
lv.wfcreate(null, con);// 提交离职表单
}
}
// throw new Exception("不给通过");
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("卡号", "card_number", false));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("学历类型", "degreetype", true));
efields.add(new CExcelField("学历验证", "degreecheck", true));
efields.add(new CExcelField("介绍人工号", "guarantor", false));
efields.add(new CExcelField("介绍人", "introducer", false));
efields.add(new CExcelField("加班类别", "eovertype", false));
efields.add(new CExcelField("曾用名", "usedname", false));
efields.add(new CExcelField("英文名", "english_name", false));
efields.add(new CExcelField("人事状态", "empstatid", true));
efields.add(new CExcelField("政治面貌", "pldcp", false));
efields.add(new CExcelField("参加工作时间", "bwday", false));
efields.add(new CExcelField("健康情况", "health", false));
efields.add(new CExcelField("血型", "bloodtype", false));
efields.add(new CExcelField("过往病史", "medicalhistory", false));
efields.add(new CExcelField("民族", "nation", false));
efields.add(new CExcelField("国籍", "nationality", false));
efields.add(new CExcelField("人才类型", "talentstype", false));
efields.add(new CExcelField("婚姻状况", "married", false));
efields.add(new CExcelField("邮箱", "email", false));
efields.add(new CExcelField("籍贯", "nativeplace", false));
efields.add(new CExcelField("现住址", "address", false));
efields.add(new CExcelField("户籍类型", "registertype", false));
efields.add(new CExcelField("户籍住址", "registeraddress", false));
efields.add(new CExcelField("社保购买地", "sscurty_addr", false));
efields.add(new CExcelField("社保开始时间", "sscurty_startdate", false));
efields.add(new CExcelField("鞋码", "shoesize", false));
efields.add(new CExcelField("裤码", "pants_code", false));
efields.add(new CExcelField("上衣码", "coat_code", false));
efields.add(new CExcelField("计薪方式", "pay_way", false));
efields.add(new CExcelField("默认班制", "schedtype", false));
efields.add(new CExcelField("招聘人工号", "rectcode", false));
efields.add(new CExcelField("招聘人", "rectname", false));
efields.add(new CExcelField("兴趣特长", "speciality", false));
efields.add(new CExcelField("备注", "note", false));
efields.add(new CExcelField("性别", "sex", true));
efields.add(new CExcelField("学历", "degree", false));
efields.add(new CExcelField("专业", "major", false));
efields.add(new CExcelField("出生日期", "birthday", true));
efields.add(new CExcelField("身份证/护照号码", "id_number", true));
// efields.add(new CExcelField("身份证地址", "registeraddress", true));
efields.add(new CExcelField("发证机关", "sign_org", true));
efields.add(new CExcelField("签发日期", "sign_date", true));
efields.add(new CExcelField("签发到期", "expired_date", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("机构职位编码", "ospcode", true));
efields.add(new CExcelField("联系电话", "telphone", false));
efields.add(new CExcelField("紧急联系人", "urgencycontact", false));
efields.add(new CExcelField("紧急联系人电话", "cellphone", false));
efields.add(new CExcelField("宿舍床位", "dorm_bed", false));
efields.add(new CExcelField("离职日期", "ljappdate", false));
efields.add(new CExcelField("离职类型", "ljtype2", false));
efields.add(new CExcelField("司龄", "worktime", false));
efields.add(new CExcelField("离职类别", "ljtype1", false));
efields.add(new CExcelField("离职原因", "ljreason", false));
efields.add(new CExcelField("是否补偿", "iscpst", false));
efields.add(new CExcelField("补偿金额", "cpstarm", false));
efields.add(new CExcelField("劳动投诉", "iscpt", false));
efields.add(new CExcelField("申请仲裁", "isabrt", false));
efields.add(new CExcelField("申请诉讼", "islawsuit", false));
efields.add(new CExcelField("加入黑名单", "isblacklist", false));
efields.add(new CExcelField("加封类型", "addtype", false));
efields.add(new CExcelField("加封类别", "addtype1", false));
efields.add(new CExcelField("加封原因", "blackreason", false));
efields.add(new CExcelField("人员来源", "entrysourcr", true));
efields.add(new CExcelField("派遣机构", "dispunit", true));
efields.add(new CExcelField("派遣期限", "dispeextime", true));
efields.add(new CExcelField("输送机构", "transorg", true));
efields.add(new CExcelField("输送期限", "transextime", true));
efields.add(new CExcelField("指导老师工号", "advisercode", true));
efields.add(new CExcelField("指导老师姓名", "advisername", true));
efields.add(new CExcelField("指导老师电话", "adviserphone", true));
efields.add(new CExcelField("法人单位", "juridical", true));
efields.add(new CExcelField("出勤类别", "atdtype", true));
efields.add(new CExcelField("免考勤打卡", "noclock", true));
return efields;
}
@ACOAction(eventname = "getrewardlist", Authentication = true, ispublic = true, notes = "获取奖惩信息")
public String getrewardlist() throws Exception {
String sqlstr = "SELECT e.employee_code,e.employee_name,e.orgname,e.sp_name,e.hg_name,e.lv_num,e.idpath,r.* "
+ " FROM hr_employee e,hr_employee_reward r " + " WHERE e.er_id=r.er_id ";
if (CtrHr_systemparms.getIntValue("ALLFJL") != 1)// 不允许负激励
sqlstr = sqlstr + " and rwnature=1 ";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
sqlstr = sqlstr + " and emprw_id=" + id;
}
return new CReport(sqlstr, "rewardtime desc ", null).findReport();
}
@ACOAction(eventname = "imprewardlistexcel", Authentication = true, ispublic = false, notes = "奖惩导入Excel")
public String imprewardlistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_rwd(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_rwd(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new
// HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_rwd(aSheet, batchno);
}
private int parserExcelSheet_rwd(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
String idpathwhere = CSContext.getIdpathwhere();
List<CExcelField> efds = initExcelFields_rwd();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title
// 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Hr_employee_reward er = new Hr_employee_reward();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
String sqlstr = "SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "' " + idpathwhere;
emp.findBySQL(sqlstr);
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在或不在权限范围内");
er.clear();
er.er_id.setValue(emp.er_id.getValue());
er.rewardtime.setValue(v.get("rewardtime"));
er.rreason.setValue(v.get("rreason")); // 激励事由
er.rwtype.setValue(dictemp.getVbCE("870", v.get("rwtype"), false,
"工号【" + employee_code + "】激励类型【" + v.get("rwtype") + "】不存在")); // 激励类型
er.rwnature.setValue(dictemp.getVbCE("711", v.get("rwnature"), false,
"工号【" + employee_code + "】激励性质【" + v.get("rwnature") + "】不存在"));// 激励性质
er.rwscore.setValue(v.get("rwscore")); // 激励绩效系数
er.rwfile.setValue(v.get("rwfile")); // 激励支持文件
er.rwnote.setValue(v.get("rwnote")); // 激励情况描述
er.rwfilenum.setValue(v.get("rwfilenum")); // 激励文件字号
er.remark.setValue(v.get("remark")); // 备注
int rwnature = er.rwnature.getAsInt(0);
float rwscore = er.rwscore.getAsFloat(0);
if (rwnature == 1 && rwscore < 0) {
throw new Exception("正激励绩效系数不能为负数");
}
if (rwnature == 2 && rwscore > 0) {
throw new Exception("负激励绩效系数不能为正数");
}
float lv_num = emp.lv_num.getAsFloat(0);
float rwamount = ((lv_num < 4) ? 2000 : 500) * rwscore;
er.rwamount.setValue(rwamount); // 激励金额//v.get("rwamount")
er.save(con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields_rwd() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("激励性质", "rwnature", true));
efields.add(new CExcelField("激励类型", "rwtype", true));
efields.add(new CExcelField("激励金额", "rwamount", false));
efields.add(new CExcelField("激励绩效系数", "rwscore", false));
efields.add(new CExcelField("激励情况描述", "rwnote", false));
efields.add(new CExcelField("激励支持文件", "rwfile", false));
efields.add(new CExcelField("激励文件字号", "rwfilenum", false));
efields.add(new CExcelField("激励生效日期", "rewardtime", false));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
@ACOAction(eventname = "impphotoexcel", Authentication = true, ispublic = false, notes = "相片同步Excel")
public String impphotoexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_photo(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_photo(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new
// HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_photo(aSheet, batchno);
}
private int parserExcelSheet_photo(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_photo();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 1);// 解析title
// 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 1);
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
if (TimerTaskHRZM.syncempphoto(employee_code))
rst++;
}
return rst;
} catch (Exception e) {
throw e;
}
}
private List<CExcelField> initExcelFields_photo() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
return efields;
}
// @ACOAction(eventname = "find", Authentication = true, ispublic = false,
// notes = "人事资料查询")
// public String find() {
// String sqlstr = "";
//
// }
@ACOAction(eventname = "putmonthemployee", Authentication = true, ispublic = true, notes = "人事信息月结")
public String putmonthemployee() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String ym = CorUtil.hashMap2Str(parms, "ym", "需要参数ym");// yyyy-mm 年月
JSONObject rst = new JSONObject();
rst.put("result", CtrHrPerm.putmonthemployee(ym));
return rst.toString();
}
@ACOAction(eventname = "findEmployeeAdvtech", Authentication = true, ispublic = true, notes = "高技人事信息")
public String findEmployeeAdvtech() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String sqlwhere = urlparms.get("sqlwhere");
if ("list".equalsIgnoreCase(type)) {
String sqlstr = "SELECT e.* FROM hr_employee e,hr_orgposition op"
+ " WHERE e.ospid=op.ospid AND op.isadvtech=1 AND e.empstatid>0 AND e.empstatid<10";
return new CReport(sqlstr, null).findReport();
}
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
Hr_employee emp = new Hr_employee();
emp.findByID(id);
return emp.toString();
}
return null;
}
@ACOAction(eventname = "findHrClass", Authentication = true, ispublic = true, notes = "职类列表")
public String findHrClass() throws Exception {
String sqlstr = "select * from hr_wclass where type_id=1 and usable=1";
return DBPools.defaultPool().opensql2json(sqlstr);
}
}
<file_sep>/src/com/hr/.svn/pristine/39/39380e3345206531335d5ae3bd9765eee76dc199.svn-base
package com.hr.perm.entity;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
@CEntity()
public class Hr_quota_chglog extends CJPA {
@CFieldinfo(fieldname = "qchgid", iskey = true, notnull = true, caption = "id", datetype = Types.INTEGER)
public CField qchgid; // id
@CFieldinfo(fieldname = "ospid", notnull = true, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "机构ID", datetype = Types.INTEGER)
public CField orgid; // 机构ID
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "机构名称", datetype = Types.VARCHAR)
public CField orgname; // 机构名称
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "机构编码", datetype = Types.VARCHAR)
public CField orgcode; // 机构编码
@CFieldinfo(fieldname = "sourceid", notnull = true, caption = "原单ID", datetype = Types.INTEGER)
public CField sourceid; // 原单ID
@CFieldinfo(fieldname = "sourcelineid", notnull = true, caption = "原单行ID", datetype = Types.INTEGER)
public CField sourcelineid; // 原单行ID
@CFieldinfo(fieldname = "sourcecode", notnull = true, caption = "原单编码", datetype = Types.VARCHAR)
public CField sourcecode; // 原单编码
@CFieldinfo(fieldname = "sourcetype", notnull = true, caption = "原单类型", datetype = Types.INTEGER)
public CField sourcetype; // 原单类型1 编制发布 2 编制调整 3 编制申请 4调动单 5批量调动单 6入职单
@CFieldinfo(fieldname = "oldquota", caption = "原编制", datetype = Types.INTEGER)
public CField oldquota; // 原编制
@CFieldinfo(fieldname = "newquota", caption = "新编制", datetype = Types.INTEGER)
public CField newquota; // 新编制
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_quota_chglog() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/61/612031c71f1d1bca00bcef5c3f892d003267ba60.svn-base
package com.hr.inface.entity;
/**
* 招募系统接口实体
*
* @author shangwen
*
*/
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(dbpool = "oldtxmssql", tablename = "HRMS.dbo.view_TxZlEmployee_zp")
public class View_TxZlEmployee_zp extends CJPA {
@CFieldinfo(fieldname = "id", notnull = true, precision = 10, scale = 0, caption = "id", datetype = Types.INTEGER)
public CField id; // 员工id
@CFieldinfo(fieldname = "dept", precision = 24, scale = 0, caption = "dept", datetype = Types.VARCHAR)
public CField dept; // orgcode组织
@CFieldinfo(fieldname = "code", notnull = true, precision = 12, scale = 0, caption = "code", datetype = Types.CHAR)
public CField code; // 工号employee_code
@CFieldinfo(fieldname = "name", precision = 100, scale = 0, caption = "name", datetype = Types.VARCHAR)
public CField name; // 姓名employee_name
@CFieldinfo(fieldname = "sex", notnull = true, precision = 10, scale = 0, caption = "sex", datetype = Types.INTEGER)
public CField sex; // CASE WHEN z.sex=0 THEN 2 ELSE 1 END AS sex,--性别
@CFieldinfo(fieldname = "borndate", notnull = true, precision = 23, scale = 3, caption = "borndate", datetype = Types.TIMESTAMP)
public CField borndate; // ,--出生日期birthday
@CFieldinfo(fieldname = "g_sg", notnull = true, precision = 10, scale = 0, caption = "g_sg", datetype = Types.VARCHAR)
public CField g_sg; // --身高g_sg
@CFieldinfo(fieldname = "hrcode", precision = 50, scale = 0, caption = "hrcode", datetype = Types.NVARCHAR)
public CField hrcode; // 民族nation
@CFieldinfo(fieldname = "hunyin", notnull = true, precision = 10, scale = 0, caption = "hunyin", datetype = Types.INTEGER)
public CField hunyin; // z.hunyin='01' THEN 1 WHEN z.hunyin='02' THEN 2 WHEN z.hunyin='03' THEN 3 ELSE 2 END AS hunyin,--婚姻married
@CFieldinfo(fieldname = "jxfs", notnull = true, precision = 4, scale = 0, caption = "jxfs", datetype = Types.VARCHAR)
public CField jxfs; // WHEN z.Jxfs='01' THEN '计时' WHEN z.Jxfs='02' THEN '月薪' WHEN z.Jxfs='03' THEN '计件' WHEN z.Jxfs='04' THEN '日薪' ELSE '计时' END AS jxfs
// ,--计薪方式pay_way
@CFieldinfo(fieldname = "ifdaka", notnull = true, precision = 10, scale = 0, caption = "ifdaka", datetype = Types.INTEGER)
public CField ifdaka; // WHEN z.ifDaKa=1 THEN 2 ELSE 1 END AS ifdaka ,--免考勤打卡noclock
@CFieldinfo(fieldname = "g_ygjg", notnull = true, precision = 1, scale = 0, caption = "g_ygjg", datetype = Types.VARCHAR)
public CField g_ygjg; // z.g_ygjg='本市户籍' THEN '1' WHEN z.g_ygjg='外市农村户籍' THEN '3' z.g_ygjg='外市城镇户籍' THEN '4' ELSE '3' END AS g_ygjg ,--户籍类型registertype
@CFieldinfo(fieldname = "jiguan", notnull = true, precision = 100, scale = 0, caption = "jiguan", datetype = Types.VARCHAR)
public CField jiguan; // 籍贯nativeplace
@CFieldinfo(fieldname = "g_sfzf", notnull = true, precision = 50, scale = 0, caption = "g_sfzf", datetype = Types.VARCHAR)
public CField g_sfzf; // 身份证发证机构sign_org
@CFieldinfo(fieldname = "g_jtzz", notnull = true, precision = 80, scale = 0, caption = "g_jtzz", datetype = Types.VARCHAR)
public CField g_jtzz; // 家庭住址address,身份证地址registeraddress
@CFieldinfo(fieldname = "G_Dqzz", notnull = true, precision = 100, scale = 0, caption = "G_Dqzz", datetype = Types.VARCHAR)
public CField G_Dqzz; // G_Dqzz 当前住址address
@CFieldinfo(fieldname = "G_rzfs", notnull = true, precision = 30, scale = 0, caption = "G_rzfs", datetype = Types.VARCHAR)
public CField G_rzfs; // G_rzfs人员来源
@CFieldinfo(fieldname = "G_jblb", notnull = true, precision = 30, scale = 0, caption = "G_jblb", datetype = Types.VARCHAR)
public CField G_jblb; // G_jblb加班类别
@CFieldinfo(fieldname = "sfz", notnull = true, precision = 18, scale = 0, caption = "sfz", datetype = Types.CHAR)
public CField sfz; // 身份证号码id_number
@CFieldinfo(fieldname = "g_qfrq", precision = 23, scale = 3, caption = "g_qfrq", datetype = Types.TIMESTAMP)
public CField g_qfrq; // 签发日期sign_date
@CFieldinfo(fieldname = "g_sxq", precision = 23, scale = 3, caption = "g_sxq", datetype = Types.TIMESTAMP)
public CField g_sxq; // 签发到期expired_date
@CFieldinfo(fieldname = "zhiji", precision = 6, scale = 0, caption = "zhiji", datetype = Types.CHAR)
public CField zhiji; // --职级
@CFieldinfo(fieldname = "xueli", notnull = true, precision = 10, scale = 0, caption = "xueli", datetype = Types.INTEGER)
public CField xueli; // --学历degree
@CFieldinfo(fieldname = "g_zy", notnull = true, precision = 50, scale = 0, caption = "g_zy", datetype = Types.VARCHAR)
public CField g_zy; // 专业major
@CFieldinfo(fieldname = "G_cqlb", precision = 60, scale = 0, caption = "G_cqlb", datetype = Types.VARCHAR)
public CField G_cqlb; // 出勤类别atdtype
@CFieldinfo(fieldname = "isoffjob", notnull = true, precision = 10, scale = 0, caption = "isoffjob", datetype = Types.INTEGER)
public CField isoffjob; // z.cy=1 THEN 1 ELSE 0 END AS isoffjob,--脱产非脱产
@CFieldinfo(fieldname = "typeName", precision = 6, scale = 0, caption = "typeName", datetype = Types.VARCHAR)
public CField typeName; // when z.cy=1 then '脱产' when z.cy=0 then '非脱产' end typeName,--脱产
@CFieldinfo(fieldname = "g_lxdh", precision = 50, scale = 0, caption = "g_lxdh", datetype = Types.VARCHAR)
public CField g_lxdh; // 联系电话telphone
@CFieldinfo(fieldname = "g_jjllr", notnull = true, precision = 30, scale = 0, caption = "g_jjllr", datetype = Types.VARCHAR)
public CField g_jjllr; // 紧急联系人urgencycontact
@CFieldinfo(fieldname = "g_jjlldh", notnull = true, precision = 30, scale = 0, caption = "g_jjlldh", datetype = Types.VARCHAR)
public CField g_jjlldh; // 紧急联系电话cellphone
@CFieldinfo(fieldname = "ospcode", precision = 255, scale = 0, caption = "ospcode", datetype = Types.NVARCHAR)
public CField ospcode; // --职务编码
@CFieldinfo(fieldname = "zhiwu", precision = 255, scale = 0, caption = "zhiwu", datetype = Types.NVARCHAR)
public CField zhiwu; // --同鑫职务编码
@CFieldinfo(fieldname = "yuZhiWu", precision = 50, scale = 0, caption = "yuZhiWu", datetype = Types.CHAR)
public CField yuZhiWu; // -职务名称
@CFieldinfo(fieldname = "pydate", notnull = true, precision = 23, scale = 3, caption = "pydate", datetype = Types.TIMESTAMP)
public CField pydate; // 入职时间hiredday
@CFieldinfo(fieldname = "state", notnull = true, precision = 3, scale = 0, caption = "state", datetype = Types.TINYINT)
public CField state; // 员工在职状态
@CFieldinfo(fieldname = "roomBed", notnull = true, precision = 16, scale = 0, caption = "roomBed", datetype = Types.VARCHAR)
public CField roomBed; // 住宿床位号dorm_bed
@CFieldinfo(fieldname = "g_pqjg", notnull = true, precision = 10, scale = 0, caption = "g_pqjg", datetype = Types.INTEGER)
public CField g_pqjg; // z.g_pqjg='新宝' then 1 when z.g_pqjg='锐旗(新宝自招)' then 2 when z.g_pqjg='同烜(新宝自招)' then 3 when z.g_pqjg='同烜输送' then 4 when
// z.g_pqjg='特思德(新宝自招)' then 5 when z.g_pqjg='志高公司' then 6
// when z.g_pqjg='电机派遣' then 7 else 1 end as g_pqjg ,--派遣机构dispunit
@CFieldinfo(fieldname = "G_ZPRY", precision = 10, scale = 0, caption = "G_ZPRY", datetype = Types.VARCHAR)
public CField G_ZPRY; // 招聘员工号
@CFieldinfo(fieldname = "G_ZPRYXM", precision = 20, scale = 0, caption = "G_ZPRYXM", datetype = Types.VARCHAR)
public CField G_ZPRYXM; // 招聘员姓名
@CFieldinfo(fieldname = "G_lsgjg", notnull = true, precision = 20, scale = 0, caption = "G_lsgjg", datetype = Types.VARCHAR)
public CField G_lsgjg; // 输送机构transorg
@CFieldinfo(fieldname = "G_lwhz", notnull = true, precision = 23, scale = 3, caption = "G_lwhz", datetype = Types.TIMESTAMP)
public CField G_lwhz; // 输送期限transextime
@CFieldinfo(fieldname = "jdate", precision = 23, scale = 3, caption = "jdate", datetype = Types.TIMESTAMP)
public CField jdate; // 最后操作时间
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public View_TxZlEmployee_zp() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/26/268f09d54ff2844ab91ba47d805c332391929d5a.svn-base
package com.hr.asset.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "销假补发工资表", tablename = "Hrkq_holidayapp_backpay")
public class Hrkq_holidayapp_backpay extends CJPA {
@CFieldinfo(fieldname = "habpid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "补发ID", datetype = Types.INTEGER)
public CField habpid; // 补发ID
@CFieldinfo(fieldname = "habpym", notnull = true, precision = 6, scale = 0, caption = "补发月度yyyy-mm", datetype = Types.VARCHAR)
public CField habpym; // 补发月度yyyy-mm
@CFieldinfo(fieldname = "hapym", notnull = true, precision = 6, scale = 0, caption = "发薪月度", datetype = Types.VARCHAR)
public CField hapym; // 发薪月度 这个月补发之前的 几个月度的工资
@CFieldinfo(fieldname = "hacid", notnull = true, precision = 10, scale = 0, caption = "销假ID", datetype = Types.INTEGER)
public CField hacid; // 销假ID
@CFieldinfo(fieldname = "haccode", notnull = true, precision = 16, scale = 0, caption = "销假编码", datetype = Types.VARCHAR)
public CField haccode; // 销假编码
@CFieldinfo(fieldname = "haid", notnull = true, precision = 10, scale = 0, caption = "申请ID", datetype = Types.INTEGER)
public CField haid; // 申请ID
@CFieldinfo(fieldname = "hacode", notnull = true, precision = 16, scale = 0, caption = "请假编码", datetype = Types.VARCHAR)
public CField hacode; // 请假编码
@CFieldinfo(fieldname = "er_id", notnull = true, precision = 10, scale = 0, caption = "人事ID", datetype = Types.INTEGER)
public CField er_id; // 人事ID
@CFieldinfo(fieldname = "employee_code", notnull = true, precision = 16, scale = 0, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "employee_name", notnull = true, precision = 64, scale = 0, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "orgid", notnull = true, precision = 10, scale = 0, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, precision = 16, scale = 0, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, precision = 128, scale = 0, caption = "部门", datetype = Types.VARCHAR)
public CField orgname; // 部门
@CFieldinfo(fieldname = "ospid", notnull = true, precision = 20, scale = 0, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, precision = 16, scale = 0, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, precision = 128, scale = 0, caption = "职位", datetype = Types.VARCHAR)
public CField sp_name; // 职位
@CFieldinfo(fieldname = "lv_num", notnull = true, precision = 4, scale = 1, caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "hdaystrue", precision = 4, scale = 1, caption = "实际请假天数", datetype = Types.DECIMAL)
public CField hdaystrue; // 实际请假天数
@CFieldinfo(fieldname = "timebg", notnull = true, precision = 19, scale = 0, caption = "请假时间开始 yyyy-MM-dd hh:mm", datetype = Types.TIMESTAMP)
public CField timebg; // 请假时间开始 yyyy-MM-dd hh:mm
@CFieldinfo(fieldname = "timeed", notnull = true, precision = 19, scale = 0, caption = "请假时间截止 yyyy-MM-dd hh:mm", datetype = Types.TIMESTAMP)
public CField timeed; // 请假时间截止 yyyy-MM-dd hh:mm
@CFieldinfo(fieldname = "remark", precision = 512, scale = 0, caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "attid", precision = 20, scale = 0, caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "idpath", notnull = true, precision = 256, scale = 0, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, precision = 5, scale = 0, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", precision = 32, scale = 0, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", precision = 19, scale = 0, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", precision = 32, scale = 0, caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", precision = 19, scale = 0, caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attr1", precision = 32, scale = 0, caption = "备用字段1", datetype = Types.VARCHAR)
public CField attr1; // 备用字段1
@CFieldinfo(fieldname = "attr2", precision = 32, scale = 0, caption = "备用字段2", datetype = Types.VARCHAR)
public CField attr2; // 备用字段2
@CFieldinfo(fieldname = "attr3", precision = 32, scale = 0, caption = "备用字段3", datetype = Types.VARCHAR)
public CField attr3; // 备用字段3
@CFieldinfo(fieldname = "attr4", precision = 32, scale = 0, caption = "备用字段4", datetype = Types.VARCHAR)
public CField attr4; // 备用字段4
@CFieldinfo(fieldname = "attr5", precision = 32, scale = 0, caption = "备用字段5", datetype = Types.VARCHAR)
public CField attr5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_holidayapp_backpay() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/perm/co/COHr_employee_transfer.java
package com.hr.perm.co;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CJPASqlUtil;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.base.entity.Hr_orgposition;
import com.hr.inface.entity.WageSysTohr;
import com.hr.perm.ctr.CtrHr_employee_transfer;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_transfer;
import com.hr.salary.ctr.CtrSalaryCommon;
import com.hr.util.HRUtil;
@ACO(coname = "web.hr.employeetransfer")
public class COHr_employee_transfer {
@ACOAction(eventname = "findOrgPostions", Authentication = true, ispublic = false, notes = "查询机构职位")
public String findOrgPostions() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String sqlwhere = parms.get("sqlwhere");
sqlwhere = (sqlwhere == null) ? "" : sqlwhere;
String disidpwstr = parms.get("disidpw");
boolean disidpw = (disidpwstr == null) ? false : Boolean.valueOf(disidpwstr);
String sqlstr = "select * from hr_orgposition where usable=1 ";
if (!sqlwhere.isEmpty())
sqlstr = sqlstr + " and " + sqlwhere;
if (disidpw) {
return (new CReport(sqlstr, null)).findReport(null, null);
} else {
return (new CReport(sqlstr, null)).findReport();
}
}
@ACOAction(eventname = "findTransferlist", Authentication = true, ispublic = false, notes = "查询调动单")
public String findTransferlist() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee_transfer ht = new Hr_employee_transfer();
String where = CjpaUtil.buildFindSqlByJsonParms(new Hr_employee_transfer(), jps);
String idpw = CSContext.getIdpathwhere().replace("idpath", "shworg.idpath");
String sqlstr = "SELECT * FROM hr_employee_transfer WHERE 1=1 ";
where = where + " and (EXISTS (SELECT 1 FROM shworg WHERE hr_employee_transfer.neworgid=shworg.orgid " + idpw + ") "
+ "or EXISTS (SELECT 1 FROM shworg WHERE hr_employee_transfer.odorgid=shworg.orgid " + idpw + ")"
+ ") ";
if (!HRUtil.hasRoles("71")) {// 薪酬管理员
sqlstr = sqlstr + " and employee_code='" + CSContext.getUserName() + "' ";
}
sqlstr = sqlstr + where;
String[] ignParms = {};
return new CReport(sqlstr, "createtime desc", null).findReport(ignParms, null);
// JSONArray ems = ht.pool.opensql2json_O(sqlstr);
// // for (int i = 0; i < ems.size(); i++) {
// // JSONObject em = ems.getJSONObject(i);
// // em.put("extorgname",
// // COShwUser.getOrgNamepath(em.getString("orgid")));
// // }
// return ems.toString();
}
@ACOAction(eventname = "isneedsarryqcode", Authentication = true, ispublic = false, notes = "是否需要工资额度必填")
public String isneedsarryqcode() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String odospid = CorUtil.hashMap2Str(parms, "odospid", "需要参数odospid");
String newospid = CorUtil.hashMap2Str(parms, "newospid", "需要参数newospid");
int tranftype3 = Integer.valueOf(CorUtil.hashMap2Str(parms, "tranftype3", "需要参数tranftype3"));// 内部
int bt = CtrHr_employee_transfer.isneedsarryqcode(odospid, newospid, tranftype3);
JSONObject rst = new JSONObject();
rst.put("salary_qcnotnull", bt);
return rst.toString();
}
@ACOAction(eventname = "findTransfer", Authentication = true, ispublic = false, notes = "替换通用查询")
public String findTransfer() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String jpaclass = CorUtil.hashMap2Str(urlparms, "jpaclass", "需要参数jpaclass");
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String disidpath = urlparms.get("disidpath");
boolean disi = (disidpath != null) ? Boolean.valueOf(disidpath) : false;
disi = disi || (ConstsSw.getSysParmIntDefault("ALLCLIENTCHGIDPATH", 2) == 2);
String sqlwhere = urlparms.get("sqlwhere");
String selflines = urlparms.get("selfline");
boolean selfline = (selflines != null) ? Boolean.valueOf(selflines) : true;
if ("list".equalsIgnoreCase(type) || "tree".equalsIgnoreCase(type)) {
selfline = false;
String parms = urlparms.get("parms");
String edittps = CorUtil.hashMap2Str(urlparms, "edittps", "需要参数edittps");
String activeprocname = urlparms.get("activeprocname");
HashMap<String, String> edts = CJSON.Json2HashMap(edittps);
String smax = urlparms.get("max");
String order = urlparms.get("order");
String spage = urlparms.get("page");
String srows = urlparms.get("rows");
boolean needpage = false;// 是否需要分页
int page = 0, rows = 0;
if (spage == null) {
if (smax == null) {
needpage = false;
} else {
needpage = true;
page = 1;
rows = Integer.valueOf(smax);
}
} else {
needpage = true;
page = Integer.valueOf(spage);
rows = (srows == null) ? 300 : Integer.valueOf(srows);
}
CJPALineData<CJPABase> jpas = CjpaUtil.newJPALinedatas(jpaclass);
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
List<JSONParm> jps = CJSON.getParms(parms);
String where = CjpaUtil.buildFindSqlByJsonParms(jpa, jps);
String idpw = CSContext.getIdpathwhere().replace("idpath", "shworg.idpath");
if ((sqlwhere != null) && (sqlwhere.length() > 0))
where = where + " and " + sqlwhere + " ";
where = where + " and ((EXISTS (SELECT 1 FROM shworg WHERE hr_employee_transfer.odorgid=shworg.orgid " + idpw + ")) "
+ " OR "
+ " (EXISTS (SELECT 1 FROM shworg WHERE hr_employee_transfer.neworgid=shworg.orgid " + idpw + "))) ";
if (jpa.getPublicControllerBase() != null) {
String w = ((JPAController) jpa.getPublicControllerBase()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null)
where = where + " " + w;
}
if (jpa.getController() != null) {
String w = ((JPAController) jpa.getController()).OnCCoFindBuildWhere(jpa, urlparms);
if (w != null)
where = where + " " + w;
}
// edittps:{"isedit":true,"issubmit":true,"isview":true,"isupdate":false,"isfind":true}
if (jpa.cfieldbycfieldname("stat") != null) {
String sqlstat = "";
if (Obj2Bl(edts.get("isedit")))
sqlstat = sqlstat + " (stat=1) or";
if (Obj2Bl(edts.get("issubmit"))) {
sqlstat = sqlstat + " (stat>1 and stat<9) or";
// 去掉 在流程中、当前节点为数据保护节点 且 当前 登录用户不在 当前节点
}
if (Obj2Bl(edts.get("isview"))) // 查询所有单据 包含作废的
sqlstat = sqlstat + " ( 1=1 ) or";
if (Obj2Bl(edts.get("isupdate")) || Obj2Bl(edts.get("isfind")))
sqlstat = sqlstat + " (stat=9) or";
if (sqlstat.length() > 0) {
sqlstat = sqlstat.substring(1, sqlstat.length() - 2);
where = where + " and (" + sqlstat + ")";
}
}
if ((activeprocname != null) && (!activeprocname.isEmpty())) {
String idfd = jpa.getIDField().getFieldname();
String ew = "SELECT " + idfd + " FROM " + jpa.tablename + " t,shwwf wf,shwwfproc wfp"
+ " WHERE t.stat>1 AND t.stat<9 AND t.wfid=wf.wfid AND wf.wfid=wfp.wfid "
+ " AND wfp.stat=2 AND wfp.procname='" + activeprocname + "'";
ew = " and " + idfd + " in (" + ew + ")";
where = where + ew;
}
String sqltr = null;
String textfield = urlparms.get("textfield");
// String pidfd = null;
// if ("tree".equalsIgnoreCase(type))
// pidfd = CorUtil.hashMap2Str(urlparms, "parentid", "需要参数parentid");
//
// if (("tree".equalsIgnoreCase(type)) && (textfield != null) && (textfield.length() > 0)) {
// String idfd = jpa.getIDField().getFieldname();
// sqltr = "select " + idfd + " as id," + textfield +
// " as text," + idfd + "," + textfield + "," + pidfd
// + ",a.* from " + jpa.tablename + " a where 1=1 " + where;
// } else
sqltr = "select * from " + jpa.tablename + " where 1=1 " + where;
sqltr = sqltr + " order by tranfcmpdate desc,appdate desc";
// if ((order != null) && (!order.isEmpty())) {
// sqltr = sqltr + " order by " + order;
// } else
// sqltr = sqltr + " order by " + jpa.getIDFieldName() + " desc ";
if (jpa.getPublicControllerBase() != null) {
String rst = ((JPAController) jpa.getPublicControllerBase()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null)
return rst;
}
if (jpa.getController() != null) {
String rst = ((JPAController) jpa.getController()).OnCCoFindList((Class<CJPA>) jpa.getClass(), jps, edts, disi, selfline);
if (rst != null)
return rst;
}
if ("list".equalsIgnoreCase(type)) {
String scols = urlparms.get("cols");
if (scols != null) {
String[] ignParms = new String[] {};
new CReport(sqltr, null).export2excel(ignParms, scols, null);
return null;
} else {
if (!needpage) {
JSONArray js = jpa.pool.opensql2json_O(sqltr);
// JSONArray js = DBPools.poolByName("dlhrmycatread").opensql2json_O(sqltr);
if (jpa.getController() != null) {
String rst = ((JPAController) jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), js, 0, 0);
if (rst != null)
return rst;
}
return js.toString();
} else {
// JSONObject jo = DBPools.poolByName("dlhrmycatread").opensql2json_O(sqltr, page, rows);
JSONObject jo = jpa.pool.opensql2json_O(sqltr, page, rows);
if (jpa.getController() != null) {
String rst = ((JPAController) jpa.getController()).AfterCOFindList((Class<CJPA>) jpa.getClass(), jo, page, rows);
if (rst != null)
return rst;
}
return jo.toString();
}
}
}
// if ("tree".equalsIgnoreCase(type)) {
// return jpa.pool.opensql2jsontree(sqltr, jpa.getIDField().getFieldname(), pidfd, false);
// }
}
// //by id
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
if (jpa.getPublicControllerBase() != null) {
String rst = ((JPAController) jpa.getPublicControllerBase()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null)
return rst;
}
if (jpa.getController() != null) {
String rst = ((JPAController) jpa.getController()).OnCCoFindByID((Class<CJPA>) jpa.getClass(), id);
if (rst != null)
return rst;
}
CField idfd = jpa.getIDField();
if (idfd == null) {
throw new Exception("根据ID查询JPA<" + jpa.getClass().getSimpleName() + ">数据没发现ID字段");
}
String sqlfdname = CJPASqlUtil.getSqlField(jpa.pool.getDbtype(), idfd.getFieldname());
String sqlvalue = CJPASqlUtil.getSqlValue(jpa.pool.getDbtype(), idfd.getFieldtype(), id);
String sqlstr = "select * from " + jpa.tablename + " where " + sqlfdname + "=" + sqlvalue;
// if ((chgi) && (userIsInside())) {
// sqlstr = sqlstr + " and idpath like '1,%'";
// } else if (dfi && (jpa.cfield("idpath") != null))
// sqlstr = sqlstr + CSContext.getIdpathwhere();
jpa.findBySQL(sqlstr, selfline);
if (jpa.isEmpty())
return "{}";
else
return jpa.tojson();
}
return "";
}
private static boolean Obj2Bl(Object o) {
if (o == null)
return false;
return Boolean.valueOf(o.toString());
}
public static boolean hasaccrole37() throws Exception {
String userid = CSContext.getUserID();
Shwuser user = new Shwuser();
user.findByID(userid, false);
if (user.isEmpty())
throw new Exception("获取当前登录用户错误!");
if (user.usertype.getAsIntDefault(0) != 1) {// 不是管理员
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM shwroleuser where roleid=37 AND userid=" + userid; // 调动维护人员
return (Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr).get(0).get("ct")) > 0);
} else
return true;
}
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "导入Excel")
public String impexcel() throws Exception {
// 权限检查
if (!hasaccrole37())
throw new Exception("当前登录用户无此权限");
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Hr_orgposition osp = new Hr_orgposition();
Hr_employee_transfer tr = new Hr_employee_transfer();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
osp.clear();
osp.findBySQL("SELECT * FROM hr_orgposition WHERE ospcode='" + v.get("newospcode") + "'", false);
if (osp.isEmpty())
throw new Exception("工号【" + employee_code + "】的机构职位编码【" + v.get("newospcode") + "】不存在");
if (osp.usable.getAsIntDefault(0) == 2)
throw new Exception("工号【" + employee_code + "】的机构职位编码【" + v.get("newospcode") + "】不可用");
tr.clear();
tr.er_id.setValue(emp.er_id.getValue()); // 人事ID
tr.employee_code.setValue(emp.employee_code.getValue()); // 工号
tr.id_number.setValue(emp.id_number.getValue()); // 身份证号
tr.employee_name.setValue(emp.employee_name.getValue()); // 姓名
tr.mnemonic_code.setValue(emp.mnemonic_code.getValue()); // 助记码
tr.email.setValue(emp.email.getValue()); // 邮箱/微信
tr.empstatid.setValue(emp.empstatid.getValue()); // 人员状态
tr.telphone.setValue(emp.telphone.getValue()); // 电话
tr.tranfcmpdate.setValue(v.get("tranfcmpdate")); // 调动时间
tr.hiredday.setValue(emp.hiredday.getValue()); // 聘用日期
tr.degree.setValue(emp.degree.getValue()); // 学历
tr.tranflev.setValue(dictemp.getVbCE("1215", v.get("tranflev"), false, "工号【" + employee_code + "】调动层级【" + v.get("tranflev") + "】不存在")); // 调动层级
tr.tranftype1.setValue(dictemp.getVbCE("719", v.get("tranftype1"), false, "工号【" + employee_code + "】调动类别【" + v.get("tranftype1") + "】不存在")); // 调动类别
// 1晋升调动
// 2降职调动
// 3同职种平级调动
// 4跨职种平级调动
tr.tranftype2.setValue(dictemp.getVbCE("724", v.get("tranftype2"), false, "工号【" + employee_code + "】调动性质【" + v.get("tranftype2") + "】不存在")); // 调动性质
// 1公司安排
// 2个人申请
// 3梦职场调动
String tranftype3 = dictemp.getVbCE("729", v.get("tranftype3"), false, "工号【" + employee_code + "】调动范围【" + v.get("tranftype3") + "】不存在"); // 4内部招聘
// System.out.println("tranftype3:" + tranftype3);
tr.tranftype3.setValue(tranftype3); // 调动范围// 1内部调用// 2// 跨单位// 3// 跨模块/制造群
// System.out.println(tr.toString());
tr.tranfreason.setValue(v.get("tranfreason")); // 调动原因
tr.probation.setValue(v.get("probation")); // 考察期
tr.probationdate.setValue(v.get("probationdate")); // 考察到期日期
tr.ispromotioned.setValue("2"); // 已转正
tr.odorgid.setValue(emp.orgid.getValue()); // 调动前部门ID
tr.odorgcode.setValue(emp.orgcode.getValue()); // 调动前部门编码
tr.odorgname.setValue(emp.orgname.getValue()); // 调动前部门名称
tr.odorghrlev.setValue("0"); // 调调动前部门人事层级
tr.odlv_id.setValue(emp.lv_id.getValue()); // 调动前职级ID
tr.odlv_num.setValue(emp.lv_num.getValue()); // 调动前职级
tr.odhg_id.setValue(emp.hg_id.getValue()); // 调动前职等ID
tr.odhg_code.setValue(emp.hg_code.getValue()); // 调动前职等编码
tr.odhg_name.setValue(emp.hg_name.getValue()); // 调动前职等名称
tr.odospid.setValue(emp.ospid.getValue()); // 调动前职位ID
tr.odospcode.setValue(emp.ospcode.getValue()); // 调动前职位编码
tr.odsp_name.setValue(emp.sp_name.getValue()); // 调动前职位名称
tr.oldemnature.setValue(emp.emnature.getValue());// 调动前职位性质
tr.odattendtype.setValue(emp.atdtype.getValue()); // 调动前出勤类别
tr.oldcalsalarytype.setValue(emp.pay_way.getValue()); // 调动前计薪方式
tr.oldhwc_namezl.setValue(emp.hwc_namezl.getValue()); // 调动前职类
tr.oldposition_salary.setValue("0"); // 调动前职位工资
tr.oldbase_salary.setValue("0"); // 调动前基本工资
tr.oldtech_salary.setValue("0"); // 调动前技能工资
tr.oldachi_salary.setValue("0"); // 调动前技能工资
tr.oldtech_allowance.setValue("0"); // 调动前技术津贴
tr.oldavg_salary.setValue("0"); // 调动前平均工资
tr.neworgid.setValue(osp.orgid.getValue()); // 调动后部门ID
tr.neworgcode.setValue(osp.orgcode.getValue()); // 调动后部门编码
tr.neworgname.setValue(osp.orgname.getValue()); // 调动后部门名称
tr.neworghrlev.setValue("0"); // 调动后部门人事层级
tr.newlv_id.setValue(osp.lv_id.getValue()); // 调动后职级ID
tr.newlv_num.setValue(osp.lv_num.getValue()); // 调动后职级
tr.newhg_id.setValue(osp.hg_id.getValue()); // 调动后职等ID
tr.newhg_code.setValue(osp.hg_code.getValue()); // 调动后职等编码
tr.newhg_name.setValue(osp.hg_name.getValue()); // 调动后职等名称
tr.newospid.setValue(osp.ospid.getValue()); // 调动后职位ID
tr.newospcode.setValue(osp.ospcode.getValue()); // 调动后职位编码
tr.newsp_name.setValue(osp.sp_name.getValue()); // 调动后职位名称
String newemnature = (osp.isoffjob.getAsIntDefault(0) == 1) ? "脱产" : "非脱产";
tr.newemnature.setValue(newemnature);// 调动后职位性质
tr.newattendtype.setValue(emp.atdtype.getValue()); // 调动后出勤类别
tr.newcalsalarytype.setValue(emp.pay_way.getValue()); // 调动后计薪方式
tr.newhwc_namezl.setValue(osp.hwc_namezl.getValue()); // 调动后职类
tr.newposition_salary.setValue("0"); // 调动前职位工资
tr.newbase_salary.setValue("0"); // 调动后基本工资
tr.newtech_salary.setValue("0"); // 调动后技能工资
tr.newachi_salary.setValue("0"); // 调动后技能工资
tr.newtech_allowance.setValue("0"); // 调动后技术津贴
tr.newavg_salary.setValue("0"); // 调动后平均工资
tr.salary_quotacode.setValue("0"); // 可用工资额度证明编号
tr.salary_quota_stand.setValue("0"); // 标准工资额度
tr.salary_quota_canuse.setValue("0"); // 可用工资额度
tr.salary_quota_used.setValue("0"); // 己用工资额度
tr.salary_quota_blance.setValue("0"); // 可用工资余额
tr.salary_quota_appy.setValue("0"); // 申请工资额度
tr.salary_quota_ovsp.setValue("0"); // 超额度审批
tr.salarydate.setValue(null); // 核薪生效日期
tr.istp.setValue(dictemp.getVbCE("5", v.get("istp"), false, "工号【" + employee_code + "】是否词汇【" + v.get("istp") + "】不存在")); // 是否特批
tr.tranamt.setValue(v.get("tranamt")); // 调拨金额
tr.remark.setValue(v.get("remark")); // 备注
tr.quota_over.setValue("2"); // 是否超编
tr.quota_over_rst.setValue("2"); // 超编审批结果 1 允许增加编制调动 ps是否自动生成编制调整单 2 超编调动 3 不允许调动
tr.isdreamposition.setValue("2"); // 是否梦职场调入
tr.isdreamemploye.setValue("2"); // 是否梦职场储备员工
tr.tranftype4.setValue(dictemp.getVbCE("1189", v.get("tranftype4"), false, "工号【" + employee_code + "】调动类型【" + v.get("tranftype4") + "】不存在")); // 调动类型
// 1M类调动
// 2 高技调动
//3梦职场调动
// 4其他调动
tr.isexistsrl.setValue("2"); // 关联关系 有关联关系 无关联关系
tr.rlmgms.setValue("1"); // 管控措施 不需管控 终止调动 申请豁免
tr.ismangerl.setValue("2"); // 是否构成需要管控的管理关系类别
tr.isapprlhm.setValue(null); // 是否申请关联关系豁免
tr.isapprlhmsp.setValue(null); // 关联关系豁免申请是否得到审批
tr.quotastand.setValue(osp.quota.getValue()); // 标准配置人数
tr.quotasj.setValue("0"); // 实际配置人数
tr.quotacq.setValue("0"); // 超缺编人数(正数表示超编、负数表示缺编)
tr.isallowdrmin.setValue(null); // 是否同意特批调动至梦职场职位
tr.idpath.setValue(emp.idpath.getValue()); // idpath
tr.attribute1.setAsInt(2);// 批量导入的单据
tr.save(con);
tr.wfcreate(null, con);
// throw new Exception("1111");
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("调动范围", "tranftype3", true));
efields.add(new CExcelField("调动层级", "tranflev", true));
efields.add(new CExcelField("调动性质", "tranftype2", true));
efields.add(new CExcelField("调动类型", "tranftype4", true));
efields.add(new CExcelField("调动类别", "tranftype1", true));
efields.add(new CExcelField("考察期", "probation", true));
efields.add(new CExcelField("调动生效日期", "tranfcmpdate", true));
efields.add(new CExcelField("待转正日期", "probationdate", true));
efields.add(new CExcelField("调动后机构职位编码", "newospcode", true));
efields.add(new CExcelField("是否特批", "istp", true));
efields.add(new CExcelField("调拨金额", "tranamt", true));
efields.add(new CExcelField("调动原因", "tranfreason", false));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
@ACOAction(eventname = "imphisexcel", Authentication = true, ispublic = false, notes = "历史导入Excel")
public String imphisexcel() throws Exception {
// 权限检查
if (!hasaccrole37())
throw new Exception("当前登录用户无此权限");
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserHisExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserHisExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserHisExcelSheet(aSheet, batchno);
}
private int parserHisExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initHisExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Hr_orgposition oldosp = new Hr_orgposition();
Hr_orgposition newosp = new Hr_orgposition();
Hr_employee_transfer tr = new Hr_employee_transfer();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
oldosp.clear();
oldosp.findBySQL("SELECT * FROM hr_orgposition WHERE ospcode='" + v.get("odospcode") + "'", false);
if (oldosp.isEmpty())
throw new Exception("工号【" + employee_code + "】的调动前机构职位编码【" + v.get("odospcode") + "】不存在");
newosp.clear();
newosp.findBySQL("SELECT * FROM hr_orgposition WHERE ospcode='" + v.get("newospcode") + "'", false);
if (newosp.isEmpty())
throw new Exception("工号【" + employee_code + "】的调动后机构职位编码【" + v.get("newospcode") + "】不存在");
// if (newosp.usable.getAsIntDefault(0) == 2) 19.3.21 历史记录 职位不可用也没关系
// throw new Exception("工号【" + employee_code + "】的调动后机构职位编码【" + v.get("newospcode") + "】不可用");
tr.clear();
tr.er_id.setValue(emp.er_id.getValue()); // 人事ID
tr.employee_code.setValue(emp.employee_code.getValue()); // 工号
tr.id_number.setValue(emp.id_number.getValue()); // 身份证号
tr.employee_name.setValue(emp.employee_name.getValue()); // 姓名
tr.mnemonic_code.setValue(emp.mnemonic_code.getValue()); // 助记码
tr.email.setValue(emp.email.getValue()); // 邮箱/微信
tr.empstatid.setValue(emp.empstatid.getValue()); // 人员状态
tr.telphone.setValue(emp.telphone.getValue()); // 电话
tr.tranfcmpdate.setValue(v.get("tranfcmpdate")); // 调动时间
tr.hiredday.setValue(emp.hiredday.getValue()); // 聘用日期
tr.degree.setValue(emp.degree.getValue()); // 学历
tr.tranflev.setValue(dictemp.getVbCE("1215", v.get("tranflev"), true, "工号【" + employee_code + "】调动层级【" + v.get("tranflev") + "】不存在")); // 调动层级
tr.tranftype1.setValue(dictemp.getVbCE("719", v.get("tranftype1"), true, "工号【" + employee_code + "】调动类别【" + v.get("tranftype1") + "】不存在")); // 调动类别
// 1晋升调动
// 2降职调动
// 3同职种平级调动
// 4跨职种平级调动
tr.tranftype2.setValue(dictemp.getVbCE("724", v.get("tranftype2"), true, "工号【" + employee_code + "】调动性质【" + v.get("tranftype2") + "】不存在")); // 调动性质
// 1公司安排
// 2个人申请
// 3梦职场调动
// 4内部招聘
tr.tranftype3.setValue(dictemp.getVbCE("729", v.get("tranftype3"), true, "工号【" + employee_code + "】调动范围【" + v.get("tranftype3") + "】不存在")); // 调动范围
// 1内部调用
// 2
// 跨单位
// 3
// 跨模块/制造群
tr.tranfreason.setValue(v.get("tranfreason")); // 调动原因
tr.probation.setValue(v.get("probation")); // 考察期
tr.probationdate.setValue(v.get("probationdate")); // 考察到期日期
tr.ispromotioned.setValue("1"); // 已转正
tr.odorgid.setValue(oldosp.orgid.getValue()); // 调动前部门ID
tr.odorgcode.setValue(oldosp.orgcode.getValue()); // 调动前部门编码
tr.odorgname.setValue(oldosp.orgname.getValue()); // 调动前部门名称
tr.odorghrlev.setValue("0"); // 调调动前部门人事层级
tr.odlv_id.setValue(oldosp.lv_id.getValue()); // 调动前职级ID
tr.odlv_num.setValue(oldosp.lv_num.getValue()); // 调动前职级
tr.odhg_id.setValue(oldosp.hg_id.getValue()); // 调动前职等ID
tr.odhg_code.setValue(oldosp.hg_code.getValue()); // 调动前职等编码
tr.odhg_name.setValue(oldosp.hg_name.getValue()); // 调动前职等名称
tr.odospid.setValue(oldosp.ospid.getValue()); // 调动前职位ID
tr.odospcode.setValue(oldosp.ospcode.getValue()); // 调动前职位编码
tr.odsp_name.setValue(oldosp.sp_name.getValue()); // 调动前职位名称
tr.oldemnature.setValue(emp.emnature.getValue());// 调动前职位性质
tr.odattendtype.setValue(emp.atdtype.getValue()); // 调动前出勤类别
tr.oldcalsalarytype.setValue("0"); // 调动前计薪方式
tr.oldhwc_namezl.setValue(oldosp.hwc_namezl.getValue()); // 调动前职类
tr.oldposition_salary.setValue("0"); // 调动前职位工资
tr.oldbase_salary.setValue("0"); // 调动前基本工资
tr.oldtech_salary.setValue("0"); // 调动前技能工资
tr.oldachi_salary.setValue("0"); // 调动前技能工资
tr.oldtech_allowance.setValue("0"); // 调动前技术津贴
tr.oldavg_salary.setValue("0"); // 调动前平均工资
tr.neworgid.setValue(newosp.orgid.getValue()); // 调动后部门ID
tr.neworgcode.setValue(newosp.orgcode.getValue()); // 调动后部门编码
tr.neworgname.setValue(newosp.orgname.getValue()); // 调动后部门名称
tr.neworghrlev.setValue("0"); // 调动后部门人事层级
tr.newlv_id.setValue(newosp.lv_id.getValue()); // 调动后职级ID
tr.newlv_num.setValue(newosp.lv_num.getValue()); // 调动后职级
tr.newhg_id.setValue(newosp.hg_id.getValue()); // 调动后职等ID
tr.newhg_code.setValue(newosp.hg_code.getValue()); // 调动后职等编码
tr.newhg_name.setValue(newosp.hg_name.getValue()); // 调动后职等名称
tr.newospid.setValue(newosp.ospid.getValue()); // 调动后职位ID
tr.newospcode.setValue(newosp.ospcode.getValue()); // 调动后职位编码
tr.newsp_name.setValue(newosp.sp_name.getValue()); // 调动后职位名称
String newemnature = (newosp.isoffjob.getAsIntDefault(0) == 1) ? "脱产" : "非脱产";
tr.newemnature.setValue(newemnature);// 调动后职位性质
tr.newattendtype.setValue("0"); // 19.3.21 取消 调动后出勤类别 dictemp.getVbCE("1399", v.get("newattendtype"), true, "工号【" + employee_code + "】调动后出勤类别【" + v.get("newattendtype") + "】不存在")
tr.newcalsalarytype.setValue("0"); // 调动后计薪方式
tr.newhwc_namezl.setValue(newosp.hwc_idzl.getValue()); // 调动后职类
tr.newposition_salary.setValue("0"); // 调动前职位工资
tr.newbase_salary.setValue("0"); // 调动后基本工资
tr.newtech_salary.setValue("0"); // 调动后技能工资
tr.newachi_salary.setValue("0"); // 调动后技能工资
tr.newtech_allowance.setValue("0"); // 调动后技术津贴
tr.newavg_salary.setValue("0"); // 调动后平均工资
tr.salary_quotacode.setValue("0"); // 可用工资额度证明编号
tr.salary_quota_stand.setValue("0"); // 标准工资额度
tr.salary_quota_canuse.setValue("0"); // 可用工资额度
tr.salary_quota_used.setValue("0"); // 己用工资额度
tr.salary_quota_blance.setValue("0"); // 可用工资余额
tr.salary_quota_appy.setValue("0"); // 申请工资额度
tr.salary_quota_ovsp.setValue("0"); // 超额度审批
tr.salarydate.setValue(null); // 核薪生效日期
tr.istp.setValue(dictemp.getVbCE("5", v.get("istp"), true, "工号【" + employee_code + "】是否词汇【" + v.get("istp") + "】不存在")); // 是否特批
tr.tranamt.setValue(v.get("tranamt")); // 调拨金额
tr.remark.setValue(v.get("remark")); // 备注
tr.quota_over.setValue("2"); // 是否超编
tr.quota_over_rst.setValue("2"); // 超编审批结果 1 允许增加编制调动 ps是否自动生成编制调整单 2 超编调动 3 不允许调动
tr.isdreamposition.setValue("2"); // 是否梦职场调入
tr.isdreamemploye.setValue("2"); // 是否梦职场储备员工
tr.tranftype4.setValue(dictemp.getVbCE("1189", v.get("tranftype4"), true, "工号【" + employee_code + "】调动类型【" + v.get("tranftype4") + "】不存在")); // 调动类型
// 4其他调动
tr.isexistsrl.setValue("2"); // 关联关系 有关联关系 无关联关系
tr.rlmgms.setValue("1"); // 管控措施 不需管控 终止调动 申请豁免
tr.ismangerl.setValue("2"); // 是否构成需要管控的管理关系类别
tr.isapprlhm.setValue(null); // 是否申请关联关系豁免
tr.isapprlhmsp.setValue(null); // 关联关系豁免申请是否得到审批
tr.quotastand.setValue("0"); // 标准配置人数
tr.quotasj.setValue("0"); // 实际配置人数
tr.quotacq.setValue("0"); // 超缺编人数(正数表示超编、负数表示缺编)
tr.isallowdrmin.setValue(null); // 是否同意特批调动至梦职场职位
tr.idpath.setValue(emp.idpath.getValue()); // idpath
tr.stat.setAsInt(9);
tr.attribute3.setValue(batchno);
tr.save(con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initHisExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("调动范围", "tranftype3", true));
efields.add(new CExcelField("调动层级", "tranflev", true));
efields.add(new CExcelField("调动性质", "tranftype2", true));
efields.add(new CExcelField("调动类型", "tranftype4", true));
efields.add(new CExcelField("调动类别", "tranftype1", true));
efields.add(new CExcelField("考察期", "probation", true));
efields.add(new CExcelField("调动生效日期", "tranfcmpdate", true));
efields.add(new CExcelField("待转正日期", "probationdate", true));
efields.add(new CExcelField("调动前机构职位编码", "odospcode", true));
efields.add(new CExcelField("调动后机构职位编码", "newospcode", true));
efields.add(new CExcelField("调动后出勤类别", "newattendtype", false));
efields.add(new CExcelField("是否特批", "istp", true));
efields.add(new CExcelField("调拨金额", "tranamt", true));
efields.add(new CExcelField("调动原因", "tranfreason", false));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
@ACOAction(eventname = "findWageSysTohr", Authentication = true, ispublic = false, notes = "工资额度查询")
public String findWageSysTohr() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String salary_quotacode = CorUtil.hashMap2Str(parms, "salary_quotacode", "需要参数salary_quotacode");
//String type = CorUtil.hashMap2Str(parms, "type", "需要参数type");
String employee_code = CorUtil.hashMap2Str(parms, "employee_code", "需要参数employee_code");
// WageSysTohr wst = new WageSysTohr();
// String sqlstr = "select * from dbo.wageSysTohr where DocNo='" + salary_quotacode + "' and Status='完成'";
// wst.findBySQL(sqlstr);
// if (wst.isEmpty())
// throw new Exception("编码为【" + salary_quotacode + "】的额度不存在");
// System.out.println("wst:" + wst.toString());
// return wst.tojson();
return CtrSalaryCommon.getWageSys(salary_quotacode,employee_code).toString();
}
}
<file_sep>/src/com/hr/attd/co/COHrkq_business_trip_batch.java
/**
*
*/
package com.hr.attd.co;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.perm.entity.Hr_employee;
import com.hr.attd.entity.Hrkq_business_trip_batchline;
/**
* @ClassName:COHrkq_business_trip_batch
* @Description:TODO
* @author David
* @date 2019年12月5日 下午3:11:46
*/
@ACO(coname = "web.hrkq.businesstripbatch")
public class COHrkq_business_trip_batch {
@ACOAction(eventname = "impexcel", Authentication = true, notes = "从excel导入出差人员信息")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
//String orgid = CorUtil.hashMap2Str(CSContext.getParms(), "orgid", "需要参数orgid");
String orgid="";
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
String rst = parserExcelFile(p, orgid);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
return rst;
} else
return "[]";
}
private String parserExcelFile(Shw_physic_file pf, String orgid) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fullname));
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
HSSFSheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, orgid);
}
private String parserExcelSheet(HSSFSheet aSheet, String orgid) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "[]";
}
int empcol = -1;
int tripreasoncol = -1;
int triptypecol = -1;
int destincol = -1;
int begindatecol = -1;
int enddatecol = -1;
int isagentcol = -1;
HSSFRow aRow = aSheet.getRow(0);
for (int col = 0; col <= aRow.getLastCellNum(); col++) {
HSSFCell aCell = aRow.getCell(col);
String celltext = CExcelUtil.getCellValue(aCell);
if ((celltext == null) || (celltext.isEmpty()))
continue;
if ("工号".equals(celltext.trim())) {
empcol = col;
}
if ("流程代理".equals(celltext.trim())) {
isagentcol = col;
}
if ("出差事由".equals(celltext.trim())) {
tripreasoncol = col;
}
if ("出差类型".equals(celltext.trim())) {
triptypecol = col;
}
if ("出差地点".equals(celltext.trim())) {
destincol = col;
}
if ("出差开始时间".equals(celltext.trim())) {
begindatecol = col;
}
if ("出差结束时间".equals(celltext.trim())) {
enddatecol = col;
}
}
if ((empcol == -1) || (triptypecol == -1) || (destincol == -1)|| (begindatecol == -1)|| (enddatecol == -1)) {
throw new Exception("没找到【工号】【出差类型】【出差地点】【出差开始时间】或【出差结束时间】列");
}
//boolean ctrl = (Integer.valueOf(HrkqUtil.getParmValueErr("TRANSFERBATCH_CTROL")) == 1);
//boolean hasr37 = Hrkq_business_trip_batch..hasaccrole37();
CJPALineData<Hrkq_business_trip_batchline> rls = new CJPALineData<Hrkq_business_trip_batchline>(Hrkq_business_trip_batchline.class);
Hr_employee emp = new Hr_employee();
for (int row = 1; row <= aSheet.getLastRowNum(); row++) {
aRow = aSheet.getRow(row);
if (null != aRow) {
HSSFCell aCell = aRow.getCell(empcol);
String employee_code = CExcelUtil.getCellValue(aCell);
if (employee_code == null)
continue;
emp.findBySQL("select * from hr_employee where employee_code='" + employee_code + "'", false);
if (emp.isEmpty())
throw new Exception("没有找到工号为【" + employee_code + "】的员工资料");
aCell = aRow.getCell(tripreasoncol);
String tripreason = CExcelUtil.getCellValue(aCell);
if ((tripreason == null) || (tripreason.isEmpty()))
tripreason = null;
aCell = aRow.getCell(triptypecol);
String triptype = CExcelUtil.getCellValue(aCell);
aCell = aRow.getCell(isagentcol);
String isagent = CExcelUtil.getCellValue(aCell);
aCell = aRow.getCell(destincol);
String destin = CExcelUtil.getCellValue(aCell);
aCell = aRow.getCell(begindatecol);
String begindate = CExcelUtil.getCellValue(aCell);
aCell = aRow.getCell(enddatecol);
String enddate = CExcelUtil.getCellValue(aCell);
Hrkq_business_trip_batchline etb = new Hrkq_business_trip_batchline();
etb.er_id.setValue(emp.er_id.getValue()); // 人事ID
etb.employee_code.setValue(emp.employee_code.getValue()); // 工号
etb.employee_name.setValue(emp.employee_name.getValue()); // 姓名
etb.orgid.setValue(emp.orgid.getValue()); // 部门ID
etb.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
etb.orgname.setValue(emp.orgname.getValue()); // 部门名称
etb.lv_id.setValue(emp.lv_id.getValue()); // 职级ID
etb.lv_num.setValue(emp.lv_num.getValue()); // 职级
etb.ospid.setValue(emp.ospid.getValue()); // 职位ID
etb.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
etb.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
etb.trip_type.setValue("国内出差".equals(triptype)?1:2); // 出差类型
etb.destination.setValue(destin); // 出差目的地
etb.begin_date.setValue(begindate); // 出差开始日期
etb.end_date.setValue(enddate); // 出差结束日期
etb.tripreason.setValue(tripreason); // 出差事由
etb.iswfagent.setValue("是".equals(isagent)?1:2); // 是否代理
//etb.is_agent.setValue(1); // 是否代理
rls.add(etb);
}
}
return rls.tojson();
}
}
<file_sep>/src/com/corsair/server/weixin/entity/Shwwxappparmdefault.java
package com.corsair.server.weixin.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwwxappparmdefault extends CJPA {
@CFieldinfo(fieldname = "pdid", precision = 20, scale = 0, caption = "pdid", datetype = Types.INTEGER)
public CField pdid; // pdid
@CFieldinfo(fieldname = "parmname", precision = 50, scale = 0, caption = "parmname", datetype = Types.VARCHAR)
public CField parmname; // parmname
@CFieldinfo(fieldname = "parmvalue", precision = 50, scale = 0, caption = "parmvalue", datetype = Types.VARCHAR)
public CField parmvalue; // parmvalue
@CFieldinfo(fieldname = "acaption", precision = 100, scale = 0, caption = "acaption", datetype = Types.VARCHAR)
public CField acaption; // acaption
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwwxappparmdefault() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/eai/EAIController.java
//EAI 控制器
package com.corsair.server.eai;
import java.io.File;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.eai.CEAIParamBase.EAITYPE;
import com.corsair.server.eai.CEAIParamBase.TRANASTYPE;
public class EAIController {
private List<CEAIParam> eaips = new ArrayList<CEAIParam>();
private List<CEAIThread> eaits = new ArrayList<CEAIThread>();
public EAIController() {
try {
System.out.println("------------初始化 EAI-------------");
initEaiPs();
System.out.println("检测EAI");
checkEaisType();
initThreads();
System.out.println("启动EAI线程");
startAllthread();
System.out.println("------------初始化 EAI-------------");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// //初始化所有XML文件
private void initEaiPs() throws Exception {
String dirname = ConstsSw.eaiXMLFilePath;
File file = new File(dirname);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
String fname = files[i].getName();
if (getExtensionName(fname).equalsIgnoreCase("xml")) {
System.out.println("载入EAI配置文件" + fname);
fname = dirname + fname;
CEAIParam cep = new CEAIParam(fname);
CEAIParam cep2 = findEAIPByName(cep.getName());
if (cep2 != null) {
throw new Exception("命名为<" + cep.getName() + ">的EAI重名,请重新修改配置文件");
}
eaips.add(cep);
}
}
}
}
// /////检查所有eai关联性
// /////作为其它EAI的子EAI,其 eaitype 必须为 ParEAI:非轮询,由级联EAI触发
// /////所有EAI不允许同名
// /////所有子EAI只允许一个主EAI指向它
private void checkEaisType() throws Exception {
for (CEAIParam cep : eaips) {
if (!cep.isEnable()) {
System.out.println("EAI:" + cep.getName() + "已经禁用,跳过检查...");
continue;
}
for (CChildEAIParm ccep : cep.getChildeais()) {
CEAIParam ceaip = findEAIPByName(ccep.getCldEaiName());// 找到
// 从EAI
// 参数对象
if ((ceaip == null) || (!ceaip.isEnable())) {
throw new Exception("检查EAI失败<" + cep.getName() + ">的关联EAI<" + ccep.getCldEaiName() + ">不存在或已禁用!");
}
if (ceaip.getEaitype() != EAITYPE.ParEAI) {
throw new Exception("检查EAI失败<" + cep.getName() + ">的关联EAI<" + ccep.getCldEaiName() + ">的eaitype必须为ParEAI!");
}
ccep.setCdeaiparam(ceaip);
if (ceaip.getOwnerEaiParam() != null) {
throw new Exception("检查EAI失败<" + cep.getName() + ">的关联EAI<" + ccep.getCldEaiName() + ">被多个主EAI指定!");
}
ceaip.setOwnerEaiParam(cep);
if (ceaip.getTrans_type() != TRANASTYPE.none) {
throw new Exception("检查EAI失败,主EAI<" + ccep.getCldEaiName() + ">使用事务处理的时候,从EAI<" + ccep.getCldEaiName() + ">事务处理只允许为none类型!");
}
// 用 ceaip 的原表字段 初始化 ChildEAI 的 cfieldtype;
System.out.println("初始化ChileEAI 关联字段数据!");
initChileEAICfieldType(ceaip, ccep);
// //检查所有字段 如果发现类型为 -999 的 ,说明字段不存
}
}
}
private EAIMapField findLinkField(CChildEAIParm mainChildEAI, String cfieldname) {
for (EAIMapField lf : mainChildEAI.getLinkfields()) {
if (lf.getD_field().equalsIgnoreCase(cfieldname)) {
return lf;
}
}
return null;
}
private void initChileEAICfieldType(CEAIParam ceaip, CChildEAIParm mainChildEAI) throws Exception {
CDBConnection con = DBPools.poolByName(ceaip.getDbpool_target()).getCon(this);
if (con == null)
throw new Exception("获取数据库连接错误:" + ceaip.getDbpool_target());
try {
String sqlstr = "select * from " + ceaip.getS_tablename() + " where 0=1";
Statement stmt = con.con.createStatement();
// System.out.println(sqlstr);
ResultSet rs = stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集的定义结构
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String fdname = rsmd.getColumnLabel(i);
EAIMapField lf = findLinkField(mainChildEAI, fdname);
if (lf != null) {
lf.setD_fieldtype(rsmd.getColumnType(i));
}
}
} finally {
con.close();
}
}
private CEAIParam findEAIPByName(String name) {
for (CEAIParam eaip : eaips) {
if (eaip.getName().equalsIgnoreCase(name))
return eaip;
}
return null;
}
private void initThreads() throws Exception {
for (CEAIParam eaip : eaips) {
if ((eaip.isEnable()) && (eaip.getEaitype() != EAITYPE.ParEAI)) {
System.out.println("创建EAI线程:" + eaip.getName());
CEAIThread eait = new CEAIThread(eaip);
eaits.add(eait);
}
}
}
private void startAllthread() {
for (CEAIThread eait : eaits) {
eait.start();
}
}
public String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
public List<CEAIThread> getEaits() {
return eaits;
}
public void setEaits(List<CEAIThread> eaits) {
this.eaits = eaits;
}
public List<CEAIParam> getEaips() {
return eaips;
}
public void setEaips(List<CEAIParam> eaips) {
this.eaips = eaips;
}
}
<file_sep>/src/com/hr/.svn/pristine/c6/c6dd5acf9c0da4908604892545fb5d2fcddd0d35.svn-base
package com.hr.perm.co;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.server.base.CSContext;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CorUtil;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_linked;
import com.hr.perm.entity.Hr_train_reg;
import com.hr.perm.entity.Hr_train_regex;
@ACO(coname = "web.hr.trainreg")
public class COHr_train_reg {
private static String sctfields = "t.treg_id,t.treg_code,t.er_id,t.employee_code,t.regtype,t.regdate,t.enddatetrain,t.enddatetry,t.jxdatetry,"
+ " t.isfrainflish,t.ospid,t.lv_num,t.norgid,t.norgname,t.nospid,t.nsp_name,t.nlv_num,t.remark,t.wfid,t.stat,t.idpath,t.creator,t.createtime,t.rectname,"
+ " t.updator,t.updatetime,t.attribute1,t.attribute2,t.attribute3,t.attribute4,t.attribute5,e.nationality,e.bwday,"
+ " e.id_number, e.card_number,e.employee_name, e.mnemonic_code, e.english_name, e.avatar_id1,e.avatar_id2,e.birthday, e.sex, e.hiredday,"
+ " e.degree, e.married,e.nativeid, e.nativeplace,e.address, e.nation, e.email, e.empstatid, e.modify, e.usedname,e.pldcp, e.major,"
+ " e.registertype, e.registeraddress, e.health,e.medicalhistory, e.bloodtype, e.height, e.importway, e.importor,e.cellphone,"
+ " e.urgencycontact, e.telphone, e.introducer, e.guarantor,e.skill,"
+ " e.skillfullanguage, e.speciality, e.welfare, e.talentstype,e.orgid, e.orgcode, e.orgname, e.lv_id, "
+ " e.hg_id,e.hg_code, e.hg_name, e.ospcode, e.sp_name, e.usable,e.sscurty_addr, e.sscurty_startdate,"
+ " e.iskey,e.hwc_namezq,e.hwc_namezz,e.degreecheck,e.degreetype,e.idtype,e.sign_date,e.expired_date,"
+ " e.sign_org,e.entrysourcr,e.dispunit,e.juridical,e.atdtype,e.noclock,e.kqdate_start,"
+ " t.newstru_id,t.newstru_name,t.newposition_salary,t.newbase_salary,t.newtech_salary,t.newachi_salary,t.newotwage,t.newtech_allowance,t.newpostsubs,"
+ " t.newchecklev,t.newattendtype,e.shoesize, e.pants_code,e.coat_code, e.dorm_bed, e.pay_way, e.schedtype, e.note, t.attid,e.emnature";
@ACOAction(eventname = "save", Authentication = true, notes = "保存实习登记单据")
public String save() throws Exception {
Hr_employee_linked emp = new Hr_employee_linked();
Hr_train_reg treg = new Hr_train_reg();
String psd = CSContext.getPostdata();
JSONObject oj = JSONObject.fromObject(psd);
Object oerid = oj.get("er_id");
String[] disFlds = null;
if ((oerid != null) && (!oerid.toString().isEmpty())) {
emp.findByID(oerid.toString());
if (emp.isEmpty()) {
throw new Exception("没有找到ID为【" + oerid.toString() + "】的员工档案 ");
}
disFlds = new String[] { "idpath", "creator", "createtime", "updator", "updatetime" };
} else {
disFlds = new String[] {};
}
String[] flds = emp.getFieldNames(disFlds);
emp.fromjson(psd, flds);
emp.empstatid.setAsInt(6);// 待入职
// checkIDNumber(emp);// 检查是否有重复身份证号码 检查在职的
// 检查岗位年龄
treg.fromjson(psd);
CDBConnection con = emp.pool.getCon(this);
con.startTrans();
try {
emp.save(con);
treg.er_id.setValue(emp.er_id.getValue());
treg.employee_code.setValue(emp.employee_code.getValue());
treg.er_id.setValue(emp.er_id.getValue());
treg.save(con);
con.submit();
return findbyid(treg.treg_id.getValue());
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private void checkIDNumber(Hr_employee_linked emp) throws Exception {
if (!emp.er_id.isEmpty())
return;// 已经保存的资料无需判断
String idnumber = emp.id_number.getValue();
String sqlstr = "select count(*) ct from hr_employee where id_number='" + idnumber + "'";
if (Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct")) != 0)
throw new Exception("身份证号码【" + idnumber + "】重复!");
}
@ACOAction(eventname = "find", Authentication = true, notes = "查询实习登记单据")
public String find() throws Exception {
HashMap<String, String> urlparms = CSContext.getParms();
String type = CorUtil.hashMap2Str(urlparms, "type", "需要参数type");
String sqlwhere = urlparms.get("sqlwhere");
if ("list".equalsIgnoreCase(type) || "tree".equalsIgnoreCase(type)) {
String parms = urlparms.get("parms");
String edittps = CorUtil.hashMap2Str(urlparms, "edittps", "需要参数edittps");
String activeprocname = urlparms.get("activeprocname");
HashMap<String, String> edts = CJSON.Json2HashMap(edittps);
String smax = urlparms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
String order = urlparms.get("order");
String spage = urlparms.get("page");
String srows = urlparms.get("rows");
int page = (spage == null) ? 1 : Integer.valueOf(spage);
int rows = (srows == null) ? 300 : Integer.valueOf(srows);
CJPALineData<Hr_train_regex> jpas = new CJPALineData<Hr_train_regex>(Hr_train_regex.class);
Hr_train_reg enty = new Hr_train_reg();
List<JSONParm> jps = CJSON.getParms(parms);
String where = CjpaUtil.buildFindSqlByJsonParms(new Hr_train_regex(), jps);
// if (dfi && chgi && (userIsInside()) && (jpa.cfield("idpath") !=
// null)) {
// where = where + " and idpath like '1,%'";
// } else if (dfi && )
if (enty.cfield("idpath") != null)
where = where + CSContext.getIdpathwhere();
if ((sqlwhere != null) && (sqlwhere.length() > 0))
where = where + " and " + sqlwhere + " ";
// edittps:{"isedit":true,"issubmit":true,"isview":true,"isupdate":false,"isfind":true}
if (enty.cfieldbycfieldname("stat") != null) {
String sqlstat = "";
if (Obj2Bl(edts.get("isedit")))
sqlstat = sqlstat + " (stat=1) or";
if (Obj2Bl(edts.get("issubmit"))) {
sqlstat = sqlstat + " (stat>1 and stat<9) or";
// 去掉 在流程中、当前节点为数据保护节点 且 当前 登录用户不在 当前节点
}
if (Obj2Bl(edts.get("isview")))
sqlstat = sqlstat + " (stat<=9) or";
if (Obj2Bl(edts.get("isupdate")) || Obj2Bl(edts.get("isfind")))
sqlstat = sqlstat + " (stat=9) or";
if (sqlstat.length() > 0) {
sqlstat = sqlstat.substring(1, sqlstat.length() - 2);
where = where + " and (" + sqlstat + ")";
}
}
if ((activeprocname != null) && (!activeprocname.isEmpty())) {
String idfd = enty.getIDField().getFieldname();
String ew = "SELECT " + idfd + " FROM " + enty.tablename + " t,shwwf wf,shwwfproc wfp"
+ " WHERE t.stat>1 AND t.stat<9 AND t.wfid=wf.wfid AND wf.wfid=wfp.wfid "
+ " AND wfp.stat=2 AND wfp.procname='" + activeprocname + "'";
ew = " and " + idfd + " in (" + ew + ")";
where = where + ew;
}
String sqltr = null;
String textfield = urlparms.get("textfield");
sqltr = "select * from (SELECT " + sctfields + " FROM hr_train_reg t,hr_employee e WHERE t.er_id=e.er_id) tb where 1=1 " + where;
if ((order != null) && (!order.isEmpty())) {
sqltr = sqltr + " order by " + order;
} else
sqltr = sqltr + " order by " + enty.getIDFieldName() + " desc ";
if ("list".equalsIgnoreCase(type)) {
if ((spage == null) || (srows == null)) {
jpas.findDataBySQL(sqltr, false, false, 1, max, true);
return jpas.tojson();
} else {
jpas.findDataBySQL(sqltr, false, false, page, rows, true);
return jpas.tojsonpage();
}
}
}
// //by id
if ("byid".equalsIgnoreCase(type)) {
String id = CorUtil.hashMap2Str(urlparms, "id", "需要参数id");
return findbyid(id);
}
return null;
}
private boolean Obj2Bl(Object o) {
if (o == null)
return false;
return Boolean.valueOf(o.toString());
}
private String findbyid(String treg_id) throws Exception {
String sqlstr = "SELECT " + sctfields + " FROM hr_train_reg t,hr_employee e WHERE t.er_id=e.er_id AND t.treg_id=" + treg_id;
Hr_train_reg treg = new Hr_train_reg();
JSONArray os = treg.pool.opensql2json_O(sqlstr);
if (os.size() == 0)
throw new Exception("没有找到ID为【" + treg_id + "】的实习登记表单");
JSONObject o = os.getJSONObject(0);
String er_id = o.getString("er_id");
o.put("hr_employee_works", treg.pool.opensql2json_O("select * from hr_employee_work where er_id=" + er_id));
o.put("hr_employee_rewards", treg.pool.opensql2json_O("select * from hr_employee_reward where er_id=" + er_id));
// o.put("hr_employee_relations", treg.pool.opensql2json_O("select * from hr_employee_relation where er_id=" + er_id));
o.put("hr_employee_phexas", treg.pool.opensql2json_O("select * from hr_employee_phexa where er_id=" + er_id));
o.put("hr_employee_leanexps", treg.pool.opensql2json_O("select * from hr_employee_leanexp where er_id=" + er_id));
o.put("hr_employee_familys", treg.pool.opensql2json_O("select * from hr_employee_family where er_id=" + er_id));
o.put("hr_employee_cretls", treg.pool.opensql2json_O("select * from hr_employee_cretl where er_id=" + er_id));
o.put("hr_employee_trainexps", treg.pool.opensql2json_O("select * from hr_employee_trainexp where er_id=" + er_id));
return o.toString();
}
@ACOAction(eventname = "del", Authentication = true, notes = "删除入职单据")
public String del() throws Exception {
String id = CSContext.getParms().get("id");
if ((id == null) || id.isEmpty())
throw new Exception("需要id参数");
Hr_train_reg reg = new Hr_train_reg();
CDBConnection con = reg.pool.getCon(this);
con.startTrans();
try {
reg.findByID4Update(con, id, false);
if (reg.stat.getAsInt() > 1)
throw new Exception("非制单状态,不允许删除");
Hr_employee_linked el = new Hr_employee_linked();
reg.delete(con, id, true);
el.delete(con, reg.er_id.getValue(), true);
con.submit();
return "{\"result\":\"OK\"}";
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "findSXEmoloyeeList", Authentication = true, ispublic = false, notes = "根据登录权限查询实习生资料")
public String findSXEmoloyeeList() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
String empstatid = CorUtil.hashMap2Str(parms, "empstatid", "需要参数empstatid");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String sqlstr = "select * from (SELECT " + sctfields + " FROM hr_train_reg t,hr_employee e WHERE t.er_id=e.er_id and e.empstatid="
+ empstatid + ") tb where 1=1 " + CSContext.getIdpathwhere() + where;
return he.pool.opensql2json(sqlstr);
// JSONArray ems = he.pool.opensql2json_O(sqlstr);
// for (int i = 0; i < ems.size(); i++) {
// JSONObject em = ems.getJSONObject(i);
// em.put("extorgname", COShwUser.getOrgNamepath(em.getString("orgid")));
// }
// return ems.toString();
}
}
<file_sep>/src/com/corsair/server/util/FilePath.java
package com.corsair.server.util;
public class FilePath {
public String FilePath = null; // 文件存储路径 c:\aa\aaa\
public String aPath = null;// 相对路径 bbbb
public String TempPath = null;// c:\aa\temp\
}
<file_sep>/src/com/hr/insurance/entity/Hr_ins_prebuyins.java
package com.hr.insurance.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption="预生成购保单明细表")
public class Hr_ins_prebuyins extends CJPA {
@CFieldinfo(fieldname="pbi_id",iskey=true,notnull=true,precision=20,scale=0,caption="ID",datetype=Types.INTEGER)
public CField pbi_id; //ID
@CFieldinfo(fieldname="er_id",precision=10,scale=0,caption="档案ID",datetype=Types.INTEGER)
public CField er_id; //档案ID
@CFieldinfo(fieldname="employee_code",precision=16,scale=0,caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname="employee_name",precision=64,scale=0,caption="员工姓名",datetype=Types.VARCHAR)
public CField employee_name; //员工姓名
@CFieldinfo(fieldname="orgid",notnull=true,precision=10,scale=0,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,precision=16,scale=0,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,precision=128,scale=0,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="ospid",precision=20,scale=0,caption="职位ID",datetype=Types.INTEGER)
public CField ospid; //职位ID
@CFieldinfo(fieldname="ospcode",precision=16,scale=0,caption="职位编码",datetype=Types.VARCHAR)
public CField ospcode; //职位编码
@CFieldinfo(fieldname="sp_name",precision=128,scale=0,caption="职位名称",datetype=Types.VARCHAR)
public CField sp_name; //职位名称
@CFieldinfo(fieldname="lv_id",precision=10,scale=0,caption="职级ID",datetype=Types.INTEGER)
public CField lv_id; //职级ID
@CFieldinfo(fieldname="lv_num",precision=4,scale=1,caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="sex",precision=1,scale=0,caption="性别",datetype=Types.INTEGER)
public CField sex; //性别
@CFieldinfo(fieldname="hiredday",precision=19,scale=0,caption="入职日期",datetype=Types.TIMESTAMP)
public CField hiredday; //入职日期
@CFieldinfo(fieldname="birthday",notnull=true,precision=19,scale=0,caption="出生日期",datetype=Types.TIMESTAMP)
public CField birthday; //出生日期
@CFieldinfo(fieldname="tranfcmpdate",precision=19,scale=0,caption="调动生效日期",datetype=Types.TIMESTAMP)
public CField tranfcmpdate; //调动生效日期
@CFieldinfo(fieldname="dobuyinsdate",precision=19,scale=0,caption="购保日期",datetype=Types.TIMESTAMP)
public CField dobuyinsdate; //购保日期
@CFieldinfo(fieldname="isbuyins",precision=2,scale=0,caption="是否已购保",defvalue="2",datetype=Types.INTEGER)
public CField isbuyins; //是否已购保
@CFieldinfo(fieldname="sourceid",precision=10,scale=0,caption="来源单ID",datetype=Types.INTEGER)
public CField sourceid; //来源单ID
@CFieldinfo(fieldname="sourcecode",precision=16,scale=0,caption="来源单编码",datetype=Types.VARCHAR)
public CField sourcecode; //来源单编码
@CFieldinfo(fieldname="buyins_id",precision=10,scale=0,caption="保险购买ID",datetype=Types.INTEGER)
public CField buyins_id; //保险购买ID
@CFieldinfo(fieldname="buyins_code",precision=16,scale=0,caption="保险购买编码",datetype=Types.VARCHAR)
public CField buyins_code; //保险购买编码
@CFieldinfo(fieldname="remark",precision=512,scale=0,caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname = "registertype", caption = "户籍类型", datetype = Types.INTEGER)
public CField registertype; // 户籍类型
@CFieldinfo(fieldname="idpath",notnull=true,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="prebuytype",precision=2,scale=0,caption="预生成类型",datetype=Types.INTEGER)
public CField prebuytype; //预生成类型
@CFieldinfo(fieldname="degree",precision=2,scale=0,caption="学历",datetype=Types.INTEGER)
public CField degree; //学历
@CFieldinfo(fieldname="nativeplace",precision=128,scale=0,caption="籍贯",datetype=Types.VARCHAR)
public CField nativeplace; //籍贯
@CFieldinfo(fieldname="id_number",precision=20,scale=0,caption="身份证号",datetype=Types.VARCHAR)
public CField id_number; //身份证号
@CFieldinfo(fieldname="registeraddress",precision=256,scale=0,caption="户籍住址",datetype=Types.VARCHAR)
public CField registeraddress; //户籍住址
@CFieldinfo(fieldname="telphone",precision=64,scale=0,caption="联系电话",datetype=Types.VARCHAR)
public CField telphone; //联系电话
@CFieldinfo(fieldname="transorg",precision=64,scale=0,caption="输送机构",datetype=Types.VARCHAR)
public CField transorg; //输送机构
@CFieldinfo(fieldname="dispunit",precision=64,scale=0,caption="派遣机构",datetype=Types.VARCHAR)
public CField dispunit; //派遣机构
@CFieldinfo(fieldname="age",precision=16,scale=0,caption="年龄",datetype=Types.VARCHAR)
public CField age; //年龄
@CFieldinfo(fieldname="creator",notnull=true,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname="createtime",notnull=true,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="updator",caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname="updatetime",caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_ins_prebuyins() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/otherjs/easuiextends.js
$.extend($.fn.datagrid.defaults.editors, {
datetimebox_disableseconnds: {// datetimebox就是你要自定义editor的名称
init: function (container, options) {
var input = $('<input class="easyuidatetimebox">').appendTo(container);
return input.datetimebox({
showSeconds: false
});
},
getValue: function (target) {
var val = $(target).parent().find('input.textbox-value').val();
return val;
},
setValue: function (target, value) {
$(target).datetimebox("setValue", value);
},
resize: function (target, width) {
var input = $(target);
if ($.boxModel == true) {
input.width(width - (input.outerWidth() - input.width()));
} else {
input.width(width);
}
}
}
});
<file_sep>/WebContent/webapp/js/common/easyui-extend-rcm.js
(function ($) {
/**
* jQuery EasyUI 1.4 --- 功能扩展
*
* Copyright (c) 2009-2015 RCM
*
* 新增 validatebox 校验规则
*
*/
$.extend($.fn.validatebox.defaults.rules, {
idcard: {
validator: function (value, param) {
//return idCardNoUtil.checkIdCardNo(value);
return true;
},
message: '请输入正确的身份证号码'
},
checkNum: {
validator: function (value, param) {
return /^([0-9]+)$/.test(value);
},
message: '请输入整数'
},
checkFloat: {
validator: function (value, param) {
return /^[+|-]?([0-9]+\.[0-9]+)|[0-9]+$/.test(value);
},
message: '请输入合法数字'
},
checkFloatMinMax: {
validator: function (value, param) {
if (!(/^[+|-]?([0-9]+\.[0-9]+)|[0-9]+$/.test(value)))
return false;
var num = parseFloat(value);
return ((num >= param[0]) && (num <= param[1]));
},
message: '请输入合法数字'
}
});
})(jQuery); <file_sep>/src/com/hr/.svn/pristine/11/11b44e60d4ffbacf7bacc23f131ff34b294bc8d2.svn-base
package com.hr.perm.ctr;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shworg;
import com.corsair.server.wordflow.Shwwfprocuser;
import com.hr.perm.entity.Hr_employee_transfer;
import com.hr.perm.entity.Hr_entry;
import com.hr.perm.entity.Hr_entry_prob;
public class WfProcProcoption {
// 调出
public void afterFindTranUser(CJPA jpa, CJPALineData<Shwwfprocuser> procusers) throws Exception {
Hr_employee_transfer tr = (Hr_employee_transfer) jpa;
if (isqunOrg(tr.odorgid.getValue())) {// 是群机构
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isqunUser(pu)) {// 不是群审批用户
iter.remove();
}
}
}
}
// 检查编制
public void beforeSubmitCheckQuota(CJPA jpa) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
if (ep.quota_over.getAsInt() == 1) {// 超编
if (ep.quota_over_rst.isEmpty())
throw new Exception("超编的调动需要评审超编处理方式");
}
}
// 调入
public void afterFindTrantoUser(CJPA jpa, CJPALineData<Shwwfprocuser> procusers) throws Exception {
Hr_employee_transfer tr = (Hr_employee_transfer) jpa;
if (isqunOrg(tr.neworgid.getValue())) {// 是群机构
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isqunUser(pu)) {// 不是群审批用户
iter.remove();
}
}
}
}
// 是否制造群下面的机构
private boolean isqunOrg(String orgid) throws Exception {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty()) {
throw new Exception("ID为【" + orgid + "】的机构不存在");
}
if (org.idpath.isEmpty())
return false;
String idps = org.idpath.getValue();
idps = idps.substring(0, idps.length() - 1);
String sqlstr = "select * from shworg where orgid in(" + idps + ")";
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(sqlstr, true, false);
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (o.orgtype.getAsIntDefault(0) == 4) {
return true;
}
}
return false;
}
// 是否工厂下面的机构
private boolean isGCOrg(String orgid) throws Exception {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty()) {
throw new Exception("ID为【" + orgid + "】的机构不存在");
}
if (org.idpath.isEmpty())
return false;
String idps = org.idpath.getValue();
idps = idps.substring(0, idps.length() - 1);
String sqlstr = "select * from shworg where orgid in(" + idps + ")";
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(sqlstr, true, false);
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (o.orgtype.getAsIntDefault(0) == 6) {
return true;
}
}
return false;
}
// 是否是制造群下面的用户
private boolean isqunUser(Shwwfprocuser pu) throws Exception {
String sqlstr = "SELECT o.* FROM shworguser ou,shworg o WHERE ou.orgid=o.orgid AND ou.userid=" + pu.userid.getValue();
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(sqlstr, true, false);
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (isqunOrg(o.orgid.getValue()))
return true;
}
return false;
}
// 是否是工厂下面的用户
private boolean isGCUser(Shwwfprocuser pu) throws Exception {
String sqlstr = "SELECT o.* FROM shworguser ou,shworg o WHERE ou.orgid=o.orgid AND ou.userid=" + pu.userid.getValue();
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(sqlstr, true, false);
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (isGCOrg(o.orgid.getValue()))
return true;
}
return false;
}
public void afterFindEntryUser1(CJPA jpa, CJPALineData<Shwwfprocuser> procusers) throws Exception {
Hr_entry et = (Hr_entry) jpa;
if (isqunOrg(et.orgid.getValue())) {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isqunUser(pu)) {// 不是群审批用户
iter.remove();
}
}
return;
}
}
public void afterFindEntryUser2(CJPA jpa, CJPALineData<Shwwfprocuser> procusers) throws Exception {
Hr_entry et = (Hr_entry) jpa;
if (isGCOrg(et.orgid.getValue())) {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isGCUser(pu)) {// 不是工厂审批用户
iter.remove();
}
}
return;
} else if (isqunOrg(et.orgid.getValue())) {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isqunUser(pu)) {// 不是群审批用户
iter.remove();
}
}
return;
}
}
public void afterFindEntryProbUser1(CJPA jpa, CJPALineData<Shwwfprocuser> procusers) throws Exception {
Hr_entry_prob et = (Hr_entry_prob) jpa;
if (isGCOrg(et.orgid.getValue())) {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isGCUser(pu)) {// 不是工厂审批用户
iter.remove();
}
}
return;
} else if (isqunOrg(et.orgid.getValue())) {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (!isqunUser(pu)) {// 不是群审批用户
iter.remove();
}
}
return;
} else {
java.util.Iterator<CJPABase> iter = procusers.iterator();
while (iter.hasNext()) {
Shwwfprocuser pu = (Shwwfprocuser) iter.next();
if (isqunUser(pu) || (isGCUser(pu))) {// 是群或工厂
iter.remove();
}
}
return;
}
}
// [{"acttion":"create","stage":"after","funcname":"com.hr.perm.ctr.WfProcProcoption.afterFindEntryUser","prams":"jpa,procusers"}]
}
<file_sep>/src/com/corsair/server/generic/Shworg_acthis.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shworg_acthis extends CJPA {
@CFieldinfo(fieldname = "orgactid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField orgactid; // ID
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "orgid", datetype = Types.INTEGER)
public CField orgid; // orgid
@CFieldinfo(fieldname = "acttype", notnull = true, caption = "沿革类型 1 成立 2 合并 3 被合并 4 调整级别 5 注销", datetype = Types.INTEGER)
public CField acttype; // 沿革类型 1 成立 2 合并 3 被合并 4 调整级别 5 注销
@CFieldinfo(fieldname = "acttime", caption = "处理时间", datetype = Types.TIMESTAMP)
public CField acttime; // 处理时间
@CFieldinfo(fieldname = "actcommit", notnull = true, caption = "备注", datetype = Types.VARCHAR)
public CField actcommit; // 备注
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shworg_acthis() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/canteen/entity/Hr_canteen_guest_line.java
package com.hr.canteen.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_canteen_guest_line extends CJPA {
@CFieldinfo(fieldname="ctgl_id",iskey=true,notnull=true,caption="客餐申请明细ID",datetype=Types.INTEGER)
public CField ctgl_id; //客餐申请明细ID
@CFieldinfo(fieldname="ctg_id",notnull=true,caption="客餐申请ID",datetype=Types.INTEGER)
public CField ctg_id; //客餐申请ID
@CFieldinfo(fieldname="num",caption="用餐人数",datetype=Types.INTEGER)
public CField num; //用餐人数
@CFieldinfo(fieldname="guestname",caption="姓名",datetype=Types.VARCHAR)
public CField guestname; //姓名
@CFieldinfo(fieldname="sex",caption="性别",datetype=Types.INTEGER)
public CField sex; //性别
@CFieldinfo(fieldname="guestorg",caption="单位",datetype=Types.VARCHAR)
public CField guestorg; //单位
@CFieldinfo(fieldname="classtype",caption="餐类",datetype=Types.INTEGER)
public CField classtype; //餐类
@CFieldinfo(fieldname="mealstand",caption="餐标",datetype=Types.DECIMAL)
public CField mealstand; //餐标
@CFieldinfo(fieldname="mealbg_date",caption="用餐开始时间",datetype=Types.VARCHAR)
public CField mealbg_date; //用餐开始时间
@CFieldinfo(fieldname="mealed_date",caption="用餐截止时间",datetype=Types.VARCHAR)
public CField mealed_date; //用餐截止时间
@CFieldinfo(fieldname="ctmc_id",caption="餐标ID",datetype=Types.INTEGER)
public CField ctmc_id; //餐标ID
@CFieldinfo(fieldname="mc_id",caption="餐类ID",datetype=Types.INTEGER)
public CField mc_id; //餐类ID
@CFieldinfo(fieldname="mc_name",caption="餐类名称",datetype=Types.VARCHAR)
public CField mc_name; //餐类名称
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_canteen_guest_line() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/8d/8db10d9adefafa2a739ed941cfa08c44850882f7.svn-base
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrkq_wkoffsourse extends CJPA {
@CFieldinfo(fieldname = "wolsid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField wolsid; // ID
@CFieldinfo(fieldname = "woid", notnull = true, caption = "主ID", datetype = Types.INTEGER)
public CField woid; // 主ID
@CFieldinfo(fieldname = "lbid", notnull = false, caption = "可休流水ID", datetype = Types.INTEGER)
public CField lbid; // 可休流水ID
@CFieldinfo(fieldname = "lbname", notnull = true, caption = "标题", datetype = Types.VARCHAR)
public CField lbname; // 标题
@CFieldinfo(fieldname = "stype", notnull = true, caption = "源类型 1 年假 2 加班 3 值班 4出差", datetype = Types.INTEGER)
public CField stype; // 源类型 1 年假 2 加班 3 值班 4出差
@CFieldinfo(fieldname = "sccode", caption = "源编码/年假的年份", datetype = Types.VARCHAR)
public CField sccode; // 源编码/年假的年份
@CFieldinfo(fieldname = "bgtime", caption = "开始时间", datetype = Types.TIMESTAMP)
public CField bgtime; // 开始时间
@CFieldinfo(fieldname = "edtime", caption = "截止时间", datetype = Types.TIMESTAMP)
public CField edtime; // 截止时间
@CFieldinfo(fieldname = "alllbtime", notnull = true, caption = "可调休时间小时", datetype = Types.INTEGER)
public CField alllbtime; // 可调休时间小时
@CFieldinfo(fieldname = "usedlbtime", notnull = true, caption = "已调休时间小时", datetype = Types.INTEGER)
public CField usedlbtime; // 已调休时间小时
@CFieldinfo(fieldname = "wotime", notnull = true, caption = "本次调休时间", datetype = Types.INTEGER)
public CField wotime; // 本次调休时间
@CFieldinfo(fieldname = "valdate", caption = "有效期", datetype = Types.TIMESTAMP)
public CField valdate; // 有效期
@CFieldinfo(fieldname = "note", caption = "可调休备注", datetype = Types.VARCHAR)
public CField note; // 可调休备注
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_wkoffsourse() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/ef/ef77712d562f7af16f6578cfc4a1ef02c2b5a986.svn-base
package com.hr.insurance.co;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.Login;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.insurance.entity.Hr_ins_buyins;
import com.hr.insurance.entity.Hr_ins_buyins_line;
import com.hr.insurance.entity.Hr_ins_buyinsurance;
import com.hr.insurance.entity.Hr_ins_cancel;
import com.hr.insurance.entity.Hr_ins_insurancetype;
import com.hr.insurance.entity.Hr_ins_insurancetype_line;
import com.hr.insurance.entity.Hr_ins_prebuyins;
import com.hr.perm.entity.Hr_empconbatch_line;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_contract;
import com.hr.perm.entity.Hr_leavejob;
import com.hr.util.HRUtil;
@ACO(coname = "web.hrins.insurance")
public class COHr_ins_insurance {
@ACOAction(eventname = "findbuyinsmonth", Authentication = true, notes = "获取月参保明细")
public String findbuyinsmonth() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpbuyday = CjpaUtil.getParm(jps, "buydday");
if (jpbuyday == null)
throw new Exception("需要参数【buydday】");
String orgcode = jporgcode.getParmvalue();
String reloper = jporgcode.getReloper();
String dqdate = jpbuyday.getParmvalue();
// String emplcode="";
// if(jpempcode!=null){
// emplcode= jpcosttime.getParmvalue();
// }
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
// String sqlstr = "SELECT * FROM hr_ins_buyinsurance buy WHERE buy.stat=9 ";
String[] notnull = {};
// String sqlstr =
// "SELECT buy.insbuy_code,buy.buydday as buyday,buy.payment,buy.tselfpay,buy.tcompay,buy.remark as tremark,buy.stat,buy.ins_type AS instype,buy.insname,buyl.* "+
// "FROM hr_ins_buyins buy,hr_ins_buyins_line buyl WHERE buy.stat=9 AND buyl.insbuy_id=buy.insbuy_id ";
String sqlstr = "SELECT * FROM hr_ins_buyinsurance buy WHERE buy.stat=9 AND buy.idpath ";
if (reloper.equals("<>")) {
sqlstr = sqlstr + " not ";
}
sqlstr = sqlstr + " LIKE '" + org.idpath.getValue() + "%' and buy.buydday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' and buy.buydday<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'";
String[] ignParms = { "buydday", "orgcode" };// 忽略的查询条件
JSONObject jo = new CReport(sqlstr, null).findReport2JSON_O(ignParms);
JSONArray rts = jo.getJSONArray("rows");
int rst = rts.size();
for (int i = 0; i < rst; i++) {
JSONObject row = rts.getJSONObject(i);
if (row.isEmpty())
continue;
Hr_employee emp = new Hr_employee();
emp.findByID(row.getString("er_id"));
if (emp.isEmpty())
continue;
// if(emp.empstatid.getAsInt()>11){
/*
* Hr_leavejob lj=new Hr_leavejob();
* lj.findBySQL("SELECT * FROM hr_leavejob WHERE stat=9 AND er_id="+row.getString("er_id")+" ORDER BY ljdate DESC");
* if(!lj.isEmpty()){
* row.put("ljdate", lj.ljdate.getValue());
* }else{
* row.put("ljdate", "");
* }
*/
row.put("ljdate", emp.ljdate.getValue());
Date firstdate = Systemdate.getFirstAndLastOfMonth(Systemdate.getDateByStr(Systemdate.getStrDate())).date1;
String fd = Systemdate.getStrDateyyyy_mm_dd(firstdate);
Hr_ins_cancel cc = new Hr_ins_cancel();
cc.findBySQL("SELECT * FROM hr_ins_cancel WHERE stat=9 AND er_id=" + row.getString("er_id") + " ORDER BY canceldate DESC");
if (!cc.isEmpty()) {
String buyid = row.getString("buyins_id");
// System.out.println(buyid+"---"+cc.insbuy_id.getValue());
if (cc.insbuy_id.getValue().equals(buyid)) {
row.put("canceldate", cc.canceldate.getValue());
} else {
row.put("canceldate", "");
}
} else {
row.put("canceldate", "");
}
// }
}
String scols = urlparms.get("cols");
if (scols == null) {
return jo.toString();
} else {
(new CReport()).export2excel(rts, scols);
return null;
}
}
@ACOAction(eventname = "findcancelinsmonth", Authentication = true, notes = "获取月退保明细")
public String findcancelinsmonth() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpcancelday = CjpaUtil.getParm(jps, "canceldate");
if (jpcancelday == null)
throw new Exception("需要参数【canceldate】");
String orgcode = jporgcode.getParmvalue();
String dqdate = jpcancelday.getParmvalue();
String reloper = jporgcode.getReloper();
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
String[] notnull = {};
// String sqlstr =
// " SELECT cc.*,bi.payment,bi.tselfpay,bi.tcompay FROM hr_ins_cancel cc,hr_ins_buyins bi WHERE cc.stat=9 and bi.insbuy_id=cc.insbuy_id ";
String sqlstr = " SELECT cc.*,bi.buyins_code,bi.payment,bi.tselfpay,bi.tcompay FROM hr_ins_cancel cc,hr_ins_buyinsurance bi WHERE cc.stat=9 AND bi.buyins_id=cc.insbuy_id ";
sqlstr = sqlstr + " and cc.idpath ";
if (reloper.equals("<>")) {
sqlstr = sqlstr + " not ";
}
sqlstr = sqlstr + " like '%" + org.idpath.getValue() + "%' and cc.canceldate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' and cc.canceldate<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'";
String[] ignParms = { "canceldate", "orgcode" };// 忽略的查询条件
return new CReport(sqlstr, notnull).findReport(ignParms);
}
@ACOAction(eventname = "findtbljemp", Authentication = true, ispublic = true, notes = "查询退保的离职人员")
public String findtbljemp() throws Exception {
/*
* String sqlstr =
* "SELECT emp.pay_way,emp.empstatid,bi.insbuy_code,bi.buydday as buyday,bi.ins_type as instype,bi.insit_id,bi.insname,bi.insurance_number,bil.*,bi.idpath "
* +
* " FROM hr_employee emp, hr_ins_buyins bi,hr_ins_buyins_line bil "+
* "WHERE bi.stat=9 AND bil.insbuy_id=bi.insbuy_id AND emp.er_id=bil.er_id AND emp.empstatid>=12 ";
*/
String sqlstr = "SELECT emp.pay_way,emp.empstatid,bi.* FROM hr_employee emp, hr_ins_buyinsurance bi WHERE bi.stat=9 AND emp.er_id=bi.er_id AND emp.empstatid>=12 ";
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String parms = urlparms.get("parms");
List<JSONParm> jps = CJSON.getParms(parms);
Hr_employee ep = new Hr_employee();
String[] ignParms = { "employee_code", "orgname" };// 忽略的查询条件
JSONParm orgparm = CorUtil.getJSONParm(jps, "orgname");
if (orgparm != null)
sqlstr = sqlstr + " and emp.orgname like '%" + orgparm.getParmvalue() + "%' ";
JSONParm empcode = CorUtil.getJSONParm(jps, "employee_code");
if (empcode != null)
sqlstr = sqlstr + " AND emp.employee_code='" + empcode.getParmvalue() + "'";
String where = CSearchForm.getCommonSearchWhere(urlparms, ep);
if ((where != null) && (!where.isEmpty()))
sqlstr = sqlstr + where;
sqlstr = sqlstr + " order by bi.buydday desc";
JSONObject rst = new CReport(sqlstr, null).findReport2JSON_O(ignParms);
return rst.toString();
}
@ACOAction(eventname = "getljemployee", Authentication = true, ispublic = false, notes = "查询退保人员的离职单")
public String getljemployee() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_leavejob hrlj = new Hr_leavejob();
String sqlstr = " SELECT * FROM hr_leavejob lj WHERE lj.stat=9 AND lj.er_id="
+ er_id + " ORDER BY ljid DESC LIMIT 1";
return hrlj.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "getccempbuyins", Authentication = true, ispublic = false, notes = "查询退保人员的购保单单")
public String getccempbuyins() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
Hr_ins_buyinsurance bi = new Hr_ins_buyinsurance();
String sqlstr = " SELECT * FROM hr_ins_buyinsurance WHERE stat=9 AND er_id="
+ er_id + " ORDER BY buydday DESC LIMIT 1";
return bi.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findinsmonthlist", Authentication = true, notes = "获取月购保统计")
public String findinsmonthlist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpbuyday = CjpaUtil.getParm(jps, "buydday");
if (jpbuyday == null)
throw new Exception("需要参数【buydday】");
String orgcode = jporgcode.getParmvalue();
String dqdate = jpbuyday.getParmvalue();
// String emplcode="";
// if(jpempcode!=null){
// emplcode= jpcosttime.getParmvalue();
// }
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
String[] ignParms = { "buydday", "orgcode" };// 忽略的查询条件
String[] notnull = {};
JSONArray dws = HRUtil.getOrgsByPid(org.orgid.getValue());
dws.add(0, org.toJsonObj());
dofindinsdetail(dws, bgdate, eddate);
/*
* String sqlstr = "SELECT bi.buydday AS buyday,bil.*,SUM(bil.selfpay) AS tsp,SUM(bil.compay) AS tcp,SUM(bil.lpayment) AS tpm,COUNT(*) AS tnum "+
* " FROM hr_ins_buyins bi,hr_ins_buyins_line bil WHERE bi.stat=9 AND bil.insbuy_id=bi.insbuy_id ";
*/
/*
* String sqlstr = "SELECT bi.*,SUM(bi.tselfpay) AS tsp,SUM(bi.tcompay) AS tcp,SUM(bi.payment) AS tpm,COUNT(*) AS tnum FROM hr_ins_buyinsurance bi WHERE bi.stat=9 ";
* sqlstr = sqlstr + " and bi.idpath like '%" + org.idpath.getValue() + "%' and bi.buydday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
* + "' and bi.buydday<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' GROUP BY bi.orgid";
* return new CReport(sqlstr, notnull).findReport(ignParms);
*/
String scols = urlparms.get("cols");
if (scols == null) {
return dws.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
@ACOAction(eventname = "PremiumCalculator", Authentication = true, notes = "保费计算器(计算已购保险在险种标准变更时的差额)")
public String PremiumCalculator() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpbuyday = CjpaUtil.getParm(jps, "buydday");
if (jpbuyday == null)
throw new Exception("需要参数【buydday】");
JSONParm jpoitname = CjpaUtil.getParm(jps, "oitname");
if (jpoitname == null)
throw new Exception("需要参数【oitname】");
JSONParm jpnitname = CjpaUtil.getParm(jps, "nitname");
if (jpnitname == null)
throw new Exception("需要参数【nitname】");
String orgcode = jporgcode.getParmvalue();
String dqdate = jpbuyday.getParmvalue();
String oldname = jpoitname.getParmvalue();
String newname = jpnitname.getParmvalue();
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
Hr_ins_insurancetype instype1 = new Hr_ins_insurancetype();
String sqlstr2 = " SELECT * FROM hr_ins_insurancetype WHERE insname='" + oldname + "'";
instype1.findBySQL(sqlstr2);
if (instype1.isEmpty())
throw new Exception("名称为【" + oldname + "】的险种不存在");
Hr_ins_insurancetype instype2 = new Hr_ins_insurancetype();
String sqlstr3 = " SELECT * FROM hr_ins_insurancetype WHERE insname='" + newname + "'";
instype2.findBySQL(sqlstr3);
if (instype2.isEmpty())
throw new Exception("名称为【" + newname + "】的险种不存在");
String[] notnull = {};
/*
* String sqlstr = " SELECT bi.insbuy_code,bi.buydday AS buyday,bi.insit_id AS oitid,"+
* "bi.insname AS oitname,bi.insurancebase as obase,bil.*,"+
* " it.insit_id AS nitid,it.insname AS nitname,it.insurancebase AS nbase,it.payment AS npayment,it.selfpay AS nsp,it.compay AS ncp, "+
* "(IFNULL(it.selfpay,0)-IFNULL(bil.selfpay,0)) AS spdiff,(IFNULL(it.compay,0)-IFNULL(bil.compay,0)) AS cpdiff,(IFNULL(it.payment,0)-IFNULL(bil.lpayment,0)) AS paydiff "
* +
* " FROM hr_ins_buyins bi,hr_ins_buyins_line bil,hr_ins_insurancetype it "+
*/
String sqlstr = " SELECT bi.buydday AS buyday,bi.insit_id AS oitid,bi.insname AS oitname,bi.insurancebase AS obase,bi.*, it.insit_id AS nitid,it.insname AS nitname," +
" it.insurancebase AS nbase,it.payment AS npayment,it.selfpay AS nsp,it.compay AS ncp, (IFNULL(it.selfpay,0)-IFNULL(bi.tselfpay,0)) AS spdiff," +
"(IFNULL(it.compay,0)-IFNULL(bi.tcompay,0)) AS cpdiff, (IFNULL(it.payment,0)-IFNULL(bi.payment,0)) AS paydiff FROM hr_ins_buyinsurance bi,hr_ins_insurancetype it " +
" WHERE bi.stat=9 AND bi.idpath LIKE '%" + org.idpath.getValue() + "%' " +
" AND bi.insit_id=" + instype1.insit_id.getAsInt() + " AND it.insit_id=" + instype2.insit_id.getAsInt() +
" AND bi.buydday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "'";
String[] ignParms = { "buydday", "orgcode", "oitname", "nitname" };// 忽略的查询条件
return new CReport(sqlstr, notnull).findReport(ignParms);
}
@ACOAction(eventname = "impinscancellistexcel", Authentication = true, ispublic = false, notes = "导入退保登记Excel")
public String impinscancellistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile_inscancel(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile_inscancel(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_inscancel(aSheet, batchno);
}
private int parserExcelSheet_inscancel(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_inscancel();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
// Hr_ins_buyins insbuy=new Hr_ins_buyins();
CJPALineData<Hr_ins_cancel> newccbiss = new CJPALineData<Hr_ins_cancel>(Hr_ins_cancel.class);
// CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
// con.startTrans();
int rst = 0;
// try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("退保单上的工号不能为空");
Hr_employee emp = new Hr_employee();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
/*
* if(emp.empstatid.getAsInt()!=12)
* throw new Exception("工号【" + employee_code + "】的员工不是离职状态");
*/
Date nowdate = Systemdate.getDateByStr(v.get("canceldate"));// 获取当前日期
Date bgdate = Systemdate.getFirstAndLastOfMonth(nowdate).date1;// 获取本月第一天日期
Date eddate = Systemdate.getFirstAndLastOfMonth(nowdate).date2;// 获取本月最后一天日期
Hr_ins_cancel oldcc = new Hr_ins_cancel();
oldcc.findBySQL(" SELECT * FROM `hr_ins_cancel` WHERE er_id=" + emp.er_id.getValue() + " AND canceldate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "' AND canceldate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'");
if (!oldcc.isEmpty()) {
// throw new Exception("工号【" + employee_code + "】本月已有退保单!");
continue;
}
Hr_leavejob lj = new Hr_leavejob();
lj.findBySQL("SELECT * FROM hr_leavejob WHERE stat=9 AND employee_code='" + employee_code + "'");
/*
* if (lj.isEmpty())
* throw new Exception("工号【" + employee_code + "】不存在离职记录");
*/
Hr_ins_buyinsurance insbuy = new Hr_ins_buyinsurance();
// insbuy.findBySQL("SELECT * FROM hr_ins_buyins bi,hr_ins_buyins_line bil WHERE bi.stat=9 AND bil.insbuy_id=bi.insbuy_id AND bil.employee_code='"
// + employee_code+"'" );
String instype = dictemp.getVbCE("1220", v.get("ins_type"), false, "员工【" + emp.employee_name.getValue() + "】保险类型【" + v.get("ins_type")
+ "】不存在");
// System.out.println("---------------"+instype);
insbuy.findBySQL("SELECT * FROM hr_ins_buyinsurance bi WHERE bi.stat=9 and ins_type=" + instype + " AND bi.employee_code='" + employee_code + "' order by buydday desc");
if (insbuy.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在购保信息!");
// continue;
Hr_ins_cancel inscc = new Hr_ins_cancel();
inscc.remark.setValue(v.get("remark")); // 备注
inscc.er_id.setValue(emp.er_id.getValue()); // 人事档案id
inscc.employee_code.setValue(emp.employee_code.getValue()); // 申请人工号
inscc.employee_name.setValue(emp.employee_name.getValue()); // 姓名
inscc.orgid.setValue(emp.orgid.getValue()); // 部门
inscc.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
inscc.orgname.setValue(emp.orgname.getValue()); // 部门名称
inscc.ospid.setValue(emp.ospid.getValue()); // 职位id
inscc.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
inscc.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
inscc.lv_id.setValue(emp.lv_id.getValue()); // 职级id
inscc.lv_num.setValue(emp.lv_num.getValue()); // 职级
inscc.degree.setValue(emp.degree.getValue()); // 学历
inscc.sex.setValue(emp.sex.getValue()); // 性别
inscc.birthday.setValue(emp.birthday.getValue()); // 出生日期
inscc.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
inscc.telphone.setValue(emp.telphone.getValue()); // 联系电话
inscc.id_number.setValue(emp.id_number.getValue()); // 身份证号
inscc.sign_org.setValue(emp.sign_org.getValue()); // 发证机构
inscc.sign_date.setValue(emp.sign_date.getValue()); // 有效日期
inscc.expired_date.setValue(emp.expired_date.getValue()); // 截止日期
inscc.nativeplace.setValue(emp.nativeplace.getValue()); // 籍贯
inscc.registertype.setValue(emp.registertype.getValue()); // 户籍类型
/*
* CJPALineData<Hr_ins_buyins_line> bils=insbuy.hr_ins_buyins_lines;
* Hr_ins_buyins_line bil=new Hr_ins_buyins_line();
* for (CJPABase jpa2 : bils) {
* Hr_ins_buyins_line temp=(Hr_ins_buyins_line)jpa2;
* if(employee_code.equals(temp.employee_code.getValue())){
* bil=temp;
* }
* }
*/
inscc.age.setValue(insbuy.age.getValue()); // 年龄
inscc.pay_type.setValue(emp.pay_way.getValue()); // 记薪方式
inscc.insurance_number.setValue(insbuy.insurance_number.getValue()); // 参保号
inscc.buydday.setValue(insbuy.buydday.getValue()); // 参保日期
inscc.ins_type.setValue(insbuy.ins_type.getValue()); // 保险类型
inscc.reg_type.setValue(insbuy.reg_type.getValue()); // 参保性质
inscc.insbuy_id.setValue(insbuy.buyins_id.getValue()); // 购保单id
inscc.insbuy_code.setValue(insbuy.buyins_code.getValue()); // 购保单编码
inscc.insit_id.setValue(insbuy.insit_id.getValue()); // 险种id
inscc.insname.setValue(insbuy.insname.getValue()); // 险种名称
if (!lj.isEmpty()) {
inscc.ljdate.setValue(lj.ljdate.getValue()); // 离职日期
inscc.ljtype2.setValue(lj.ljtype2.getValue()); // 离职类型
inscc.ljreason.setValue(lj.ljreason.getValue()); // 离职原因
}
inscc.canceldate.setValue(v.get("canceldate")); // 退保日期
inscc.cancelreason.setValue(v.get("cancelreason")); // 退保原因
inscc.stat.setAsInt(9);// 保存直接完成
// inscc.save(con);
newccbiss.add(inscc);
rst++;
}
if (newccbiss.size() > 0) {
System.out.println("====================导入购保单条数【" + newccbiss.size() + "】");
// System.out.println("+++++++++++++++++++++++++++"+listOfString.toString());
newccbiss.saveBatchSimple();// 高速存储
}
newccbiss.clear();
// con.submit();
return rst;
/*
* } catch (Exception e) {
* con.rollback();
* throw e;
* }
*/
}
private List<CExcelField> initExcelFields_inscancel() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("参保号", "insurance_number", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("性别", "sex", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("联系电话", "telphone", true));
efields.add(new CExcelField("参保日期", "reginsdate", true));
efields.add(new CExcelField("保险类型", "ins_type", true));
efields.add(new CExcelField("离职日期", "ljdate", true));
efields.add(new CExcelField("离职类型", "ljtype2", true));
efields.add(new CExcelField("离职原因", "ljreason", true));
efields.add(new CExcelField("退保日期", "canceldate", true));
efields.add(new CExcelField("退保原因", "cancelreason", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "findinscancelmonthlist", Authentication = true, notes = "月退保统计")
public String findinscancelmonthlist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpccday = CjpaUtil.getParm(jps, "canceldate");
if (jpccday == null)
throw new Exception("需要参数【canceldate】");
String orgcode = jporgcode.getParmvalue();
String dqdate = jpccday.getParmvalue();
// String emplcode="";
// if(jpempcode!=null){
// emplcode= jpcosttime.getParmvalue();
// }
String reloper = jporgcode.getReloper();
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
String[] ignParms = { "canceldate", "orgcode" };// 忽略的查询条件
String[] notnull = {};
String sqlstr = "SELECT cc.orgid,cc.orgname,'" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "' as canceldate, COUNT(*) AS tnum,SUM(bi.payment) AS tpayment,SUM(bi.tselfpay) AS tselfpay,SUM(bi.tcompay) AS tcompay " +
" FROM hr_ins_cancel cc,hr_ins_buyinsurance bi WHERE cc.stat=9 AND bi.buyins_id=cc.insbuy_id and cc.idpath ";
if (reloper.equals("<>")) {
sqlstr = sqlstr + " not ";
}
sqlstr = sqlstr + " like '%" + org.idpath.getValue() + "%' and cc.canceldate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' and cc.canceldate<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' GROUP BY cc.orgid,cc.orgname";
return new CReport(sqlstr, notnull).findReport(ignParms);
}
@ACOAction(eventname = "impbuyinslistexcel", Authentication = true, ispublic = false, notes = "导入购保登记明细Excel")
public String impbuyinslistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String orgid = CorUtil.hashMap2Str(CSContext.getParms(), "orgid", "需要参数orgid");
String insitid = CorUtil.hashMap2Str(CSContext.getParms(), "insit_id", "需要参数insit_id");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
String rst = parserExcelFile_buyins(p, orgid, insitid);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
return rst;
} else {
return "[]";
}
}
private String parserExcelFile_buyins(Shw_physic_file pf, String orgid, String insitid) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_buyins(aSheet, orgid, insitid);
}
private String parserExcelSheet_buyins(Sheet aSheet, String orgid, String insitid) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "[]";
}
List<CExcelField> efds = initExcelFields_buyins();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty()) {
throw new Exception("没找到ID为【" + orgid + "】的机构");
}
Hr_ins_insurancetype instype = new Hr_ins_insurancetype();
instype.findByID(insitid);
if (instype.isEmpty()) {
throw new Exception("没找到ID为【" + insitid + "】的保险资料");
}
Hr_employee emp = new Hr_employee();
CJPALineData<Hr_ins_buyins_line> bils = new CJPALineData<Hr_ins_buyins_line>(Hr_ins_buyins_line.class);
Shworg emporg = new Shworg();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("购保单上的工号不能为空");
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
emporg.clear();
emporg.findByID(emp.orgid.getValue());
if (emporg.isEmpty())
throw new Exception("没找到员工【" + emp.employee_name.getValue() + "】所属的ID为【" + emp.orgid.getValue() + "】的机构");
if (emporg.idpath.getValue().indexOf(org.idpath.getValue()) == -1) {
throw new Exception("员工【" + employee_code + "】不属于此机构");
}
Hr_ins_buyins_line buyinsline = new Hr_ins_buyins_line();
buyinsline.er_id.setValue(emp.er_id.getValue());
buyinsline.employee_code.setValue(emp.employee_code.getValue());
buyinsline.employee_name.setValue(emp.employee_name.getValue());
buyinsline.ospid.setValue(emp.ospid.getValue());
buyinsline.ospcode.setValue(emp.ospcode.getValue());
buyinsline.sp_name.setValue(emp.sp_name.getValue());
buyinsline.lv_id.setValue(emp.lv_id.getValue());
buyinsline.lv_num.setValue(emp.lv_num.getValue());
buyinsline.hiredday.setValue(emp.hiredday.getValue());
buyinsline.orgid.setValue(emp.orgid.getValue());
buyinsline.orgcode.setValue(emp.orgcode.getValue());
buyinsline.orgname.setValue(emp.orgname.getValue());
buyinsline.degree.setValue(emp.degree.getValue());
buyinsline.sex.setValue(emp.sex.getValue());
buyinsline.telphone.setValue(emp.telphone.getValue());
buyinsline.nativeplace.setValue(emp.nativeplace.getValue());
buyinsline.registertype.setValue(emp.registertype.getValue());
buyinsline.pay_type.setValue(emp.pay_way.getValue());
buyinsline.id_number.setValue(emp.id_number.getValue());
buyinsline.sign_org.setValue(emp.sign_org.getValue());
buyinsline.sign_date.setValue(emp.sign_date.getValue());
buyinsline.expired_date.setValue(emp.expired_date.getValue());
buyinsline.birthday.setValue(emp.birthday.getValue());
int age = getAgeByBirth(emp.birthday.getValue());
buyinsline.age.setAsInt(age);
buyinsline.sptype.setValue(emp.emnature.getValue());
int isnew = Integer.valueOf(dictemp.getVbCE("5", v.get("isnew"), false, "员工【" + emp.employee_name.getValue() + "】的是否新增【" + v.get("isnew")
+ "】不存在"));
int regtype = Integer.valueOf(dictemp.getVbCE("1234", v.get("reg_type"), false, "员工【" + emp.employee_name.getValue() + "】参保性质【" + v.get("reg_type")
+ "】不存在"));
buyinsline.isnew.setAsInt(isnew);
buyinsline.reg_type.setAsInt(regtype);
/*
* String nowtime ="";
* Calendar hday = Calendar.getInstance();
* Date hd=Systemdate.getDateByStr(emp.hiredday.getValue());
* hday.setTime(hd);
* int inday=hday.get(Calendar.DATE);
* if(inday<21){
* nowtime = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd");
* }else{
* Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd"));// 去除时分秒
* Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
* nowtime =Systemdate.getStrDateyyyy_mm_dd(eddate);
* }
*/
buyinsline.buydday.setValue(v.get("buydday"));
buyinsline.ins_type.setValue(instype.ins_type.getValue());
buyinsline.selfratio.setValue(instype.selfratio.getValue());
buyinsline.selfpay.setValue(instype.selfpay.getValue());
buyinsline.comratio.setValue(instype.comratio.getValue());
buyinsline.compay.setValue(instype.compay.getValue());
buyinsline.insurance_number.setValue(v.get("insurance_number"));
buyinsline.insurancebase.setValue(instype.insurancebase.getValue());
float sp = 0;
float cp = 0;
if (!("".equals(instype.selfpay.getValue()) || (instype.selfpay.getValue() == null))) {
sp = Float.parseFloat(instype.selfpay.getValue());
}
if (!("".equals(instype.compay.getValue()) || (instype.compay.getValue() == null))) {
cp = Float.parseFloat(instype.compay.getValue());
}
float lpm = sp + cp;
buyinsline.lpayment.setAsFloat(lpm);
buyinsline.remark.setValue(v.get("remark"));
bils.add(buyinsline);
}
return bils.tojson();
}
private List<CExcelField> initExcelFields_buyins() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("参保日期", "buydday", true));
efields.add(new CExcelField("参保号", "insurance_number", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("性别", "sex", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("联系电话", "telphone", true));
efields.add(new CExcelField("是否新增", "isnew", true));
efields.add(new CExcelField("参保性质", "reg_type", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
public static int getAgeByBirth(String birthday) {
int age = 0;
try {
Calendar now = Calendar.getInstance();
now.setTime(new Date());// 当前时间
Calendar birth = Calendar.getInstance();
Date bd = Systemdate.getDateByStr(birthday);
birth.setTime(bd);
if (birth.after(now)) {// 如果传入的时间,在当前时间的后面,返回0岁
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {// 兼容性更强,异常后返回数据
return 0;
}
}
@ACOAction(eventname = "impinstypelineexcel", Authentication = true, ispublic = false, notes = "导入险种设置明细Excel")
public String impinstypelineexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
String rst = parserExcelFile_instype(p);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
return rst;
} else {
return "[]";
}
}
private String parserExcelFile_instype(Shw_physic_file pf) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_instype(aSheet);
}
private String parserExcelSheet_instype(Sheet aSheet) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return "[]";
}
List<CExcelField> efds = initExcelFields_instype();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
CJPALineData<Hr_ins_insurancetype_line> itls = new CJPALineData<Hr_ins_insurancetype_line>(Hr_ins_insurancetype_line.class);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
DecimalFormat dec = new DecimalFormat("0.00");
for (Map<String, String> v : values) {
String lins = v.get("linsurance");
if ((lins == null) || (lins.isEmpty()))
throw new Exception("险种设置明细的保险名称不能为空");
String pb = v.get("paybase");
if ((pb == null) || (pb.isEmpty()))
throw new Exception("险种设置明细的缴费基数不能为空");
String lcr = v.get("lcomratio");
if ((lcr == null) || (lcr.isEmpty()))
throw new Exception("险种设置明细的单位缴费占比不能为空");
String lsr = v.get("lselfratio");
if ((lsr == null) || (lsr.isEmpty()))
throw new Exception("险种设置明细的个人缴费占比不能为空");
float cro = Float.parseFloat(lcr);
float sro = Float.parseFloat(lsr);
float paybase = Float.parseFloat(pb);
float cp = 0;
float sp = 0;
cp = (paybase * cro) / 100;
sp = (paybase * sro) / 100;
float lpm = cp + sp;
Hr_ins_insurancetype_line itline = new Hr_ins_insurancetype_line();
itline.paybase.setValue(dec.format(paybase));
itline.lpayment.setValue(dec.format(lpm));
itline.linsurance.setValue(lins);
itline.lselfratio.setValue(dec.format(sro));
itline.lselfpay.setValue(dec.format(sp));
itline.lcomratio.setValue(dec.format(cro));
itline.lcompay.setValue(dec.format(cp));
itline.remark.setValue(v.get("remark"));
itls.add(itline);
}
return itls.tojson();
}
private List<CExcelField> initExcelFields_instype() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("保险名称", "linsurance", true));
efields.add(new CExcelField("缴费基数", "paybase", true));
efields.add(new CExcelField("单位缴费占比", "lcomratio", true));
efields.add(new CExcelField("单位缴费金额", "lcompay", true));
efields.add(new CExcelField("个人缴费占比", "lselfratio", true));
efields.add(new CExcelField("个人缴费金额", "lselfpay", true));
efields.add(new CExcelField("缴纳总金额", "lpayment", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "findemployeeinslist", Authentication = true, notes = "员工社保汇总查询")
public String findemployeeinslist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
Date bgdate = new Date();
Date eddate = new Date();
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpmondate = CjpaUtil.getParm(jps, "monthdate");
if (jpmondate == null)
throw new Exception("需要参数【monthdate】");
String dqdate = jpmondate.getParmvalue();
bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
JSONParm jpbeginday = CjpaUtil.getParm(jps, "beginday");
if (jpbeginday != null) {
String beginday = jpbeginday.getParmvalue();
bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(beginday)));
}
JSONParm jpendday = CjpaUtil.getParm(jps, "endday");
if (jpendday != null) {
String endday = jpendday.getParmvalue();
eddate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(endday)));
}
String orgcode = jporgcode.getParmvalue();
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
String[] ignParms = { "canceldate", "orgcode" };// 忽略的查询条件
String[] notnull = {};
String sqlstr = " SELECT emp.*,bi.er_id AS biler_id,bi.buydday AS buydate,bi.buyins_code,bi.insurance_number,bi.insurancebase,bi.tselfpay AS lselfpay," +
"bi.tcompay AS lcompay,bi.payment AS lpayment,bi.sptype,bi.reg_type,bi.ins_type,bi.insname, " +
"cc.ljdate AS ljdate2,ljtype2,ljreason,canceldate,cancelreason " +
" FROM (SELECT * FROM hr_employee WHERE empstatid=4 AND idpath LIKE '" + org.idpath.getValue() + "%' ) emp " +
" LEFT JOIN (SELECT * FROM hr_ins_buyinsurance WHERE stat=9 AND buydday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) +
"' AND buydday<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "') bi ON (emp.er_id=bi.er_id ) " +
" LEFT JOIN (SELECT er_id,ljdate ,ljtype2,ljreason,canceldate,cancelreason FROM hr_ins_cancel WHERE stat=9) cc ON (emp.er_id=cc.er_id) ";
return new CReport(sqlstr, notnull).findReport(ignParms);
}
@ACOAction(eventname = "findemployeeinslistex", Authentication = true, notes = "员工社保汇总查询EX")
public String findemployeeinslistex() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
String orgcode = jporgcode.getParmvalue();
String reloper = jporgcode.getReloper();
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
JSONParm jpmondate = CjpaUtil.getParm(jps, "monthdate");
if (jpmondate == null)
throw new Exception("需要参数【monthdate】");
String dqdate = jpmondate.getParmvalue();
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
String bds = Systemdate.getStrDateyyyy_mm_dd(bgdate);
String eds = Systemdate.getStrDateyyyy_mm_dd(eddate);
String[] ignParms = { "canceldate", "orgcode", "monthdate", "beginday", "endday", "instype" };// 忽略的查询条件
String sqlstr = "SELECT * FROM hr_employee WHERE empstatid=4 AND idpath";
if (reloper.equals("<>")) {
sqlstr = sqlstr + " not ";
}
sqlstr = sqlstr + " LIKE '" + org.idpath.getValue() + "%'";
JSONObject jo = new CReport(sqlstr, null).findReport2JSON_O(ignParms);
JSONArray rts = jo.getJSONArray("rows");
Hr_ins_buyinsurance ibs = new Hr_ins_buyinsurance();
Hr_ins_cancel ibsc = new Hr_ins_cancel();
for (int i = 0; i < rts.size(); i++) {
JSONObject row = rts.getJSONObject(i);
String er_id = row.getString("er_id");
sqlstr = "SELECT * FROM hr_ins_buyinsurance WHERE er_id=" + er_id + " and stat=9 AND buydday >='" + bds + "' AND buydday<='" + eds + "'";
ibs.clear();
ibs.findBySQL(sqlstr, false);
if (!ibs.isEmpty()) {
row.put("buydate", ibs.buydday.getValue());
row.put("buyins_code", ibs.buyins_code.getValue());
row.put("insurance_number", ibs.insurance_number.getValue());
row.put("insurancebase", ibs.insurancebase.getValue());
row.put("lselfpay", ibs.tselfpay.getValue());
row.put("lcompay", ibs.tcompay.getValue());
row.put("lpayment", ibs.payment.getValue());
row.put("sptype", ibs.sptype.getValue());
row.put("reg_type", ibs.reg_type.getValue());
row.put("ins_type", ibs.ins_type.getValue());
row.put("insname", ibs.insname.getValue());
}
sqlstr = "select * from hr_ins_cancel where stat=9 and er_id=" + er_id;
ibsc.clear();
ibsc.findBySQL(sqlstr, false);
if (!ibsc.isEmpty()) {
row.put("ljdate2", ibsc.ljdate.getValue());
row.put("ljtype2", ibsc.ljtype2.getValue());
row.put("ljreason", ibsc.ljreason.getValue());
row.put("canceldate", ibsc.canceldate.getValue());
row.put("cancelreason", ibsc.cancelreason.getValue());
}
}
String scols = urlparms.get("cols");
if (scols == null) {
return jo.toString();
} else {
(new CReport()).export2excel(rts, scols);
return null;
}
}
@ACOAction(eventname = "dosumbitbuyinslist", Authentication = true, notes = "一键提交购保单")
public String dosumbitbuyinslist() throws Exception {
// CJPALineData<Hr_ins_buyins> bis= new CJPALineData<Hr_ins_buyins>(Hr_ins_buyins.class);
Date maxdate = Systemdate.getFirstAndLastOfMonth(new Date()).date2;// 当月最后一天的日期
CJPALineData<Hr_ins_buyinsurance> bis = new CJPALineData<Hr_ins_buyinsurance>(Hr_ins_buyinsurance.class);
// String sqlstr = "select * from hr_ins_buyins bi where bi.stat=1 ";
String sqlstr = "select * from hr_ins_buyinsurance bi where bi.stat=1 AND buydday<='" + Systemdate.getStrDateyyyy_mm_dd(maxdate) + "' ";
sqlstr = sqlstr + " order by bi.buyins_id desc";
bis.findDataBySQL(sqlstr, true, false);
// System.out.println("------------------"+bis.size());
// Hr_ins_buyins tempbi=new Hr_ins_buyins();
Hr_ins_buyinsurance tempbi = new Hr_ins_buyinsurance();
CDBConnection con = tempbi.pool.getCon(this);
con.startTrans();
try {
for (CJPABase jpa : bis) {
Hr_ins_buyinsurance bi = (Hr_ins_buyinsurance) jpa;
tempbi.clear();
tempbi.findByID(bi.buyins_id.getValue());
/*
* CJPALineData<Hr_ins_buyins_line> bils=tempbi.hr_ins_buyins_lines;
* if(bils.size()==0){
* continue;
* }
*/
// System.out.println("+++++++++++++++++++++++++++"+bils.size());
tempbi.wfcreate(null, con);
}
con.submit();
JSONObject rst = new JSONObject();
rst.put("rst", "ok");
return rst.toString();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "dosumbitcancelinslist", Authentication = true, notes = "一键提交退保单")
public String dosumbitcancelinslist() throws Exception {
CJPALineData<Hr_ins_cancel> ccs = new CJPALineData<Hr_ins_cancel>(Hr_ins_cancel.class);
String sqlstr = "select * from hr_ins_cancel cc where cc.stat=1 ";
sqlstr = sqlstr + " order by cc.inscc_id desc";
ccs.findDataBySQL(sqlstr, true, false);
// System.out.println("------------------"+ccs.size());
// int counts=0;
Hr_ins_cancel tempcc = new Hr_ins_cancel();
CDBConnection con = tempcc.pool.getCon(this);
con.startTrans();
try {
for (CJPABase jpa : ccs) {
Hr_ins_cancel cc = (Hr_ins_cancel) jpa;
tempcc.clear();
tempcc.findByID(cc.inscc_id.getValue());
if (tempcc.insbuy_id.isEmpty()) {
continue;
}
tempcc.wfcreate(null, con);
// counts++;
}
con.submit();
// System.out.println("++++++++++++++++"+counts);
JSONObject rst = new JSONObject();
rst.put("rst", "ok");
return rst.toString();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
@ACOAction(eventname = "impinsbuylistexcel", Authentication = true, ispublic = false, notes = "批量导入购保登记Excel")
public String impinsbuylistexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelSheet_buyinslist(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelSheet_buyinslist(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
Workbook workbook = WorkbookFactory.create(file);
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet_buyinslist(aSheet, batchno);
}
private int parserExcelSheet_buyinslist(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields_buyinslist();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_ins_insurancetype instype = new Hr_ins_insurancetype();
Hr_employee emp = new Hr_employee();
Hr_ins_buyinsurance buyins = new Hr_ins_buyinsurance();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
Shwuser admin = Login.getAdminUser();
String loginuser = CSContext.getUserName();
CDBConnection con = emp.pool.getCon(this);
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
throw new Exception("购保单上的工号不能为空");
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】不存在人事资料");
rst++;
/*
* emporg.clear();
* emporg.findByID(emp.orgid.getValue());
* if (emporg.isEmpty())
* throw new Exception("没找到员工【"+emp.employee_name.getValue()+"】所属的ID为【" + emp.orgid.getValue() + "】的机构");
* if (emporg.idpath.getValue().indexOf(org.idpath.getValue()) == -1) {
* throw new Exception("员工【" + employee_code + "】不属于此机构");
* }
*/
String insitcode = v.get("insit_code");
if ((insitcode == null) || (insitcode.isEmpty()))
throw new Exception("购保单上的保险编号不能为空");
instype.clear();
instype.findBySQL("SELECT * FROM hr_ins_insurancetype WHERE stat=9 and insit_code='" + insitcode + "'");
if (instype.isEmpty()) {
throw new Exception("没找到编号为【" + insitcode + "】的保险资料");
}
buyins.clear();
buyins.er_id.setValue(emp.er_id.getValue());
buyins.employee_code.setValue(emp.employee_code.getValue());
buyins.employee_name.setValue(emp.employee_name.getValue());
buyins.ospid.setValue(emp.ospid.getValue());
buyins.ospcode.setValue(emp.ospcode.getValue());
buyins.sp_name.setValue(emp.sp_name.getValue());
buyins.lv_id.setValue(emp.lv_id.getValue());
buyins.lv_num.setValue(emp.lv_num.getValue());
buyins.hiredday.setValue(emp.hiredday.getValue());
buyins.orgid.setValue(emp.orgid.getValue());
buyins.orgcode.setValue(emp.orgcode.getValue());
buyins.orgname.setValue(emp.orgname.getValue());
buyins.idpath.setValue(emp.idpath.getValue());
buyins.degree.setValue(emp.degree.getValue());
buyins.sex.setValue(emp.sex.getValue());
buyins.telphone.setValue(emp.telphone.getValue());
buyins.nativeplace.setValue(emp.nativeplace.getValue());
buyins.registertype.setValue(emp.registertype.getValue());
buyins.registeraddress.setValue(emp.registeraddress.getValue());
buyins.torgname.setValue(emp.transorg.getValue());
buyins.sorgname.setValue(emp.dispunit.getValue());
buyins.pay_type.setValue(emp.pay_way.getValue());
buyins.id_number.setValue(emp.id_number.getValue());
buyins.sign_org.setValue(emp.sign_org.getValue());
buyins.sign_date.setValue(emp.sign_date.getValue());
buyins.expired_date.setValue(emp.expired_date.getValue());
buyins.birthday.setValue(emp.birthday.getValue());
int age = getAgeByBirth(emp.birthday.getValue());
buyins.age.setAsInt(age);
buyins.sptype.setValue(emp.emnature.getValue());
int isnew = Integer.valueOf(dictemp.getVbCE("5", v.get("isnew"), false, "员工【" + emp.employee_name.getValue() + "】的是否新增【" + v.get("isnew")
+ "】不存在"));
int regtype = Integer.valueOf(dictemp.getVbCE("1234", v.get("reg_type"), false, "员工【" + emp.employee_name.getValue() + "】参保性质【" + v.get("reg_type")
+ "】不存在"));
buyins.isnew.setAsInt(isnew);
buyins.reg_type.setAsInt(regtype);
buyins.buydday.setValue(v.get("buydday"));
buyins.attribute1.setValue(v.get("attribute1"));
buyins.insit_id.setValue(instype.insit_id.getValue());
buyins.insit_code.setValue(instype.insit_code.getValue());
buyins.insname.setValue(instype.insname.getValue());
buyins.ins_type.setValue(instype.ins_type.getValue());
buyins.selfratio.setValue(instype.selfratio.getValue());
buyins.selfpay.setValue(instype.selfpay.getValue());
buyins.tselfpay.setValue(instype.selfpay.getValue());
buyins.comratio.setValue(instype.comratio.getValue());
buyins.compay.setValue(instype.compay.getValue());
buyins.tcompay.setValue(instype.compay.getValue());
buyins.insurance_number.setValue(v.get("insurance_number"));
buyins.insurancebase.setValue(instype.insurancebase.getValue());
buyins.payment.setValue(instype.payment.getValue());
buyins.remark.setValue(v.get("remark"));
buyins.creator.setValue(loginuser);
buyins.createtime.setValue(Systemdate.getStrDate());
buyins.save(con);
buyins.wfcreate(null, con, admin.userid.getValue(), "1", null);// 当前Session无登录验证,用任意管理员账号 提交表单(无流程)
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields_buyinslist() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("缴费年月", "buydday", true));
efields.add(new CExcelField("购保日期", "attribute1", true));
efields.add(new CExcelField("参保号", "insurance_number", true));
efields.add(new CExcelField("保险编号", "insit_code", true));
efields.add(new CExcelField("保险名称", "insname", true));
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("姓名", "employee_name", true));
efields.add(new CExcelField("部门", "orgname", true));
efields.add(new CExcelField("职位", "sp_name", true));
efields.add(new CExcelField("职级", "lv_num", true));
efields.add(new CExcelField("性别", "sex", true));
efields.add(new CExcelField("户籍类型", "registertype", true));
efields.add(new CExcelField("户籍住址", "registeraddress", true));
efields.add(new CExcelField("输送机构", "torgname", true));
efields.add(new CExcelField("入职日期", "hiredday", true));
efields.add(new CExcelField("联系电话", "telphone", true));
efields.add(new CExcelField("是否新增", "isnew", true));
efields.add(new CExcelField("参保性质", "reg_type", true));
efields.add(new CExcelField("备注", "remark", true));
return efields;
}
@ACOAction(eventname = "dotransferbuyinslist", Authentication = true, notes = "将主从表购保单数据导到单表购保单")
public String dotransferbuyinslist() throws Exception {
CJPALineData<Hr_ins_buyins> bis = new CJPALineData<Hr_ins_buyins>(Hr_ins_buyins.class);
CJPALineData<Hr_ins_buyinsurance> newbis = new CJPALineData<Hr_ins_buyinsurance>(Hr_ins_buyinsurance.class);
String sqlstr = "select * from hr_ins_buyins bi where 1=1 ";
bis.findDataBySQL(sqlstr, true, false);
Hr_ins_buyins tempbi = new Hr_ins_buyins();
// CDBConnection con = tempbi.pool.getCon(this);
// con.startTrans();
for (CJPABase jpa : bis) {
Hr_ins_buyins bi = (Hr_ins_buyins) jpa;
tempbi.clear();
tempbi.findByID(bi.insbuy_id.getValue());
CJPALineData<Hr_ins_buyins_line> bils = tempbi.hr_ins_buyins_lines;
for (CJPABase bijpa : bils) {
Hr_ins_buyins_line tempbil = (Hr_ins_buyins_line) bijpa;
Hr_employee emp = new Hr_employee();
emp.findByID(tempbil.er_id.getValue(), false);
Hr_ins_buyinsurance buyins = new Hr_ins_buyinsurance();
buyins.er_id.setValue(emp.er_id.getValue());
buyins.employee_code.setValue(emp.employee_code.getValue());
buyins.employee_name.setValue(emp.employee_name.getValue());
buyins.ospid.setValue(emp.ospid.getValue());
buyins.ospcode.setValue(emp.ospcode.getValue());
buyins.sp_name.setValue(emp.sp_name.getValue());
buyins.lv_id.setValue(emp.lv_id.getValue());
buyins.lv_num.setValue(emp.lv_num.getValue());
buyins.hiredday.setValue(emp.hiredday.getValue());
buyins.orgid.setValue(emp.orgid.getValue());
buyins.orgcode.setValue(emp.orgcode.getValue());
buyins.orgname.setValue(emp.orgname.getValue());
buyins.idpath.setValue(emp.idpath.getValue());
buyins.degree.setValue(emp.degree.getValue());
buyins.sex.setValue(emp.sex.getValue());
buyins.telphone.setValue(emp.telphone.getValue());
buyins.nativeplace.setValue(emp.nativeplace.getValue());
buyins.registertype.setValue(emp.registertype.getValue());
buyins.pay_type.setValue(emp.pay_way.getValue());
buyins.id_number.setValue(emp.id_number.getValue());
buyins.sign_org.setValue(emp.sign_org.getValue());
buyins.sign_date.setValue(emp.sign_date.getValue());
buyins.expired_date.setValue(emp.expired_date.getValue());
buyins.birthday.setValue(emp.birthday.getValue());
buyins.age.setValue(tempbil.age.getValue());
buyins.sptype.setValue(tempbil.sptype.getValue());
buyins.isnew.setValue(tempbil.isnew.getValue());
buyins.reg_type.setValue(tempbil.reg_type.getValue());
buyins.buydday.setValue(bi.buydday.getValue());
buyins.insit_id.setValue(bi.insit_id.getValue());
buyins.insit_code.setValue(bi.insit_code.getValue());
buyins.insname.setValue(bi.insname.getValue());
buyins.ins_type.setValue(bi.ins_type.getValue());
buyins.selfratio.setValue(bi.selfratio.getValue());
buyins.selfpay.setValue(bi.selfpay.getValue());
buyins.tselfpay.setValue(bi.selfpay.getValue());
buyins.comratio.setValue(bi.comratio.getValue());
buyins.compay.setValue(bi.compay.getValue());
buyins.tcompay.setValue(bi.compay.getValue());
buyins.insurance_number.setValue(bi.insurance_number.getValue());
buyins.insurancebase.setValue(bi.insurancebase.getValue());
buyins.payment.setValue(tempbil.lpayment.getValue());
buyins.remark.setValue(bi.remark.getValue());
newbis.add(buyins);
}
}
if (newbis.size() > 0) {
System.out.println("====================导入购保单条数【" + newbis.size() + "】");
// System.out.println("+++++++++++++++++++++++++++"+listOfString.toString());
newbis.saveBatchSimple();// 高速存储
}
newbis.clear();
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "findprebuyinslist", Authentication = true, notes = "获取当月预购保名单")
public String findprebuyinslist() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
// JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
String orgcode = jporgcode.getParmvalue();
String reloper = jporgcode.getReloper();
Date nowdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd());// 获取当前日期
Date bgdate = Systemdate.getFirstAndLastOfMonth(nowdate).date1;// 获取本月第一天日期
Date eddate = Systemdate.getFirstAndLastOfMonth(nowdate).date2;// 获取本月最后一天日期
String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr1);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
String[] notnull = {};
String sqlstr = " SELECT pbi.* FROM hr_ins_prebuyins pbi,hr_employee e WHERE pbi.isbuyins=2 AND pbi.dobuyinsdate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' AND pbi.dobuyinsdate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' and pbi.idpath ";
if (reloper.equals("<>")) {
sqlstr = sqlstr + " not ";
}
sqlstr = sqlstr + " like '" + org.idpath.getValue() +
"%' and pbi.er_id=e.er_id AND e.empstatid<12 order by pbi.dobuyinsdate ";
String[] ignParms = { "orgcode" };// 忽略的查询条件
return new CReport(sqlstr, notnull).findReport(ignParms, null);
}
private void dofindinsdetail(JSONArray datas, Date bgdate, Date eddate) throws Exception {
for (int i = 0; i < datas.size(); i++) {
// boolean includechld = (i != 0);
boolean includechld = true;
JSONObject dw = datas.getJSONObject(i);
String sqlstr = "SELECT bi.buydday,SUM(bi.tselfpay) AS tsp,SUM(bi.tcompay) AS tcp,SUM(bi.payment) AS tpm,COUNT(*) AS tnum " +
" FROM hr_ins_buyinsurance bi WHERE bi.stat=9 ";
sqlstr = sqlstr + " and bi.buydday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' and bi.buydday<'" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' ";
if (includechld) {
sqlstr = sqlstr + " and bi.idpath like '%" + dw.getString("idpath") + "%'";
} else {
sqlstr = sqlstr + " and bi.orgid=" + dw.getString("orgid");
}
sqlstr = sqlstr + " GROUP BY bi.buydday";
List<HashMap<String, String>> rsts = DBPools.defaultPool().openSql2List(sqlstr);
dw.put("tsp", rsts.get(0).get("tsp"));
dw.put("tcp", rsts.get(0).get("tcp"));
dw.put("tpm", rsts.get(0).get("tpm"));
dw.put("tnum", rsts.get(0).get("tnum"));
dw.put("buydday", rsts.get(0).get("buydday"));
}
}
@ACOAction(eventname = "findnotprebuyinslist", Authentication = true, notes = "获取当月未生成预购保名单")
public String findnotprebuyinslist() throws Exception {
/*
* HashMap<String, String> urlparms = CSContext.get_pjdataparms();
* List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
* JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
* // JSONParm jpempcode = CjpaUtil.getParm(jps, "employee_code");
* if (jporgcode == null)
* throw new Exception("需要参数【orgcode】");
* String orgcode = jporgcode.getParmvalue();
*/
Date nowdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd());// 获取当前日期
Date bgdate = Systemdate.getFirstAndLastOfMonth(nowdate).date1;// 获取本月第一天日期
Date eddate = Systemdate.getFirstAndLastOfMonth(nowdate).date2;// 获取本月最后一天日期
/*
* String sqlstr1 = "select * from shworg where code='" + orgcode + "'";
* Shworg org = new Shworg();
* org.findBySQL(sqlstr1);
* if (org.isEmpty())
* throw new Exception("编码为【" + orgcode + "】的机构不存在");
*/
String[] notnull = {};
String sqlstr = " SELECT * FROM `hr_employee` WHERE hiredday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' AND hiredday<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' AND empstatid<10 " +
" AND (lv_num<=6.3 OR registertype=1 OR registertype=2) AND er_id NOT IN " +
"(SELECT er_id FROM hr_ins_buyinsurance WHERE stat=9 AND '" + Systemdate.getStrDateyyyy_mm_dd(eddate) +
"'>=buydday AND '" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "'<=buydday) AND er_id NOT IN " +
"(SELECT er_id FROM hr_ins_prebuyins pbi WHERE isbuyins=2 AND pbi.dobuyinsdate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) +
"' AND pbi.dobuyinsdate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "') ORDER BY hiredday ";
String[] ignParms = { "orgcode" };// 忽略的查询条件
return new CReport(sqlstr, notnull).findReport(ignParms, null);
}
// @ACOAction(eventname = "dosetprebuyinslist", Authentication = true, notes = "未预购保名单插入预购保单")
private void dosetprebuyinslist(Date bgdate, Date eddate) throws Exception {
// Date nowdate= Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd());//获取当前日期
// Date bgdate = Systemdate.getFirstAndLastOfMonth(nowdate).date1;// 获取本月第一天日期
// Date eddate = Systemdate.getFirstAndLastOfMonth(nowdate).date2;// 获取本月最后一天日期
CJPALineData<Hr_employee> emps = new CJPALineData<Hr_employee>(Hr_employee.class);
String sqlstr = " SELECT * FROM `hr_employee` WHERE hiredday>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' AND hiredday<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "' AND empstatid<10 " +
" AND (lv_num<=6.3 OR registertype=1 OR registertype=2) AND er_id NOT IN " +
"(SELECT er_id FROM hr_ins_buyinsurance WHERE stat=9 AND '" + Systemdate.getStrDateyyyy_mm_dd(eddate) +
"'>=buydday AND '" + Systemdate.getStrDateyyyy_mm_dd(bgdate) + "'<=buydday) AND er_id NOT IN " +
"(SELECT er_id FROM hr_ins_prebuyins pbi WHERE isbuyins=2 AND pbi.dobuyinsdate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate) +
"' AND pbi.dobuyinsdate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "') ORDER BY hiredday ";
emps.findDataBySQL(sqlstr, true, false);
Hr_employee tempemp = new Hr_employee();
CDBConnection con = tempemp.pool.getCon(this);
con.startTrans();
try {
for (CJPABase jpa : emps) {
Hr_employee emp = (Hr_employee) jpa;
Hr_ins_prebuyins pbi = new Hr_ins_prebuyins();
pbi.er_id.setValue(emp.er_id.getValue());
pbi.employee_code.setValue(emp.employee_code.getValue());
pbi.employee_name.setValue(emp.employee_name.getValue());
pbi.ospid.setValue(emp.ospid.getValue());
pbi.ospcode.setValue(emp.ospcode.getValue());
pbi.sp_name.setValue(emp.sp_name.getValue());
pbi.lv_id.setValue(emp.lv_id.getValue());
pbi.lv_num.setValue(emp.lv_num.getValue());
pbi.hiredday.setValue(emp.hiredday.getValue());
pbi.orgid.setValue(emp.orgid.getValue());
pbi.orgcode.setValue(emp.orgcode.getValue());
pbi.orgname.setValue(emp.orgname.getValue());
pbi.sex.setValue(emp.sex.getValue());
pbi.birthday.setValue(emp.birthday.getValue());
pbi.registertype.setValue(emp.registertype.getValue());
pbi.idpath.setValue(emp.idpath.getValue());
pbi.degree.setValue(emp.degree.getValue());
pbi.nativeplace.setValue(emp.nativeplace.getValue());
pbi.id_number.setValue(emp.id_number.getValue());
pbi.registeraddress.setValue(emp.registeraddress.getValue());
pbi.telphone.setValue(emp.telphone.getValue());
pbi.transorg.setValue(emp.transorg.getValue());
pbi.dispunit.setValue(emp.dispunit.getValue());
int age = getAgeByBirth(emp.birthday.getValue());
pbi.age.setAsInt(age);
pbi.tranfcmpdate.setValue(emp.hiredday.getValue());
pbi.isbuyins.setAsInt(2);
Calendar hday = Calendar.getInstance();
Date hd = Systemdate.getDateByStr(emp.hiredday.getValue());
hday.setTime(hd);
String nowtime = "";
// Date ndate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd());
int inday = hday.get(Calendar.DATE);
if (inday <= 25) {
Date firstdate = Systemdate.getFirstAndLastOfMonth(hd).date1;
nowtime = Systemdate.getStrDateyyyy_mm_dd(firstdate);
} else {
Date lastdaydate = Systemdate.getFirstAndLastOfMonth(hd).date2;// 取最后一天的日期
Date nextdaydate = Systemdate.dateDayAdd(lastdaydate, 1);// 加一天获取下月一号的日期
nowtime = Systemdate.getStrDateyyyy_mm_dd(nextdaydate);
}
pbi.dobuyinsdate.setValue(nowtime);
pbi.save(con);
}
con.submit();
// JSONObject rst = new JSONObject();
// rst.put("rst", "ok");
// return rst.toString();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
}
<file_sep>/src/com/corsair/server/task/TaskScanWorkFlowPress.java
package com.corsair.server.task;
import java.util.Date;
import java.util.TimerTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPAWorkFlow2;
import com.corsair.server.cjpa.CWFNotify;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfprocuser;
public class TaskScanWorkFlowPress extends TimerTask {
@Override
public void run() {
Logsw.debug("TaskScanWorkFlowPress.run......");
int ljavm = 60 * 24;// token有效期 60分钟
int wpc = ConstsSw.getSysParmIntDefault("WFPressCycle", 0);
if (wpc == 0)
return;
try {
String sqlstr = "SELECT w.wfname,w.subject,u.* FROM shwwf w,shwwfproc p,shwwfprocuser u"
+ " WHERE w.wfid=p.wfid AND p.procid=u.procid"
+ " AND w.stat=1 AND p.stat=2 AND u.stat=1 AND (u.nextpresstime<NOW() OR u.nextpresstime IS NULL) "
+ " ORDER BY w.wfid,p.procid";
JSONArray pus = DBPools.defaultPool().opensql2json_O(sqlstr);
Shwwfprocuser pu = new Shwwfprocuser();
Shwwf wf = new Shwwf();
for (int i = 0; i < pus.size(); i++) {
JSONObject jpu = pus.getJSONObject(i);
try {
pu.clear();
pu.findByID(jpu.getString("wfprocuserid"), false);
wf.clear();
wf.findByID(jpu.getString("wfid"), false);
CWFNotify.wfPressNotify(CJPAWorkFlow2.getJPAByWF(wf), wf, jpu.getString("userid"), jpu.getString("wfprocuserid"));
Date nextpdate = Systemdate.dateDayAdd(new Date(), wpc);
pu.pressnum.setAsInt(pu.pressnum.getAsIntDefault(0) + 1);
pu.nextpresstime.setAsDatetime(nextpdate);
pu.save();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/com/hr/.svn/pristine/65/65665588f45d1c4854b162972522d842f4e63d23.svn-base
package com.hr.util;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.attd.entity.Hrkq_swcdlst;
import com.hr.inface.entity.TXkqView_Hrms;
public class TimerTaskHRSwcard extends TimerTask {
private static String autosynkqbgdate = "2017-07-01";
private static int syncrowno = 5000;
private static int pageonetime = 20;// 每次触发导入
@Override
public void run() {
Logsw.debug("同步考勤数据");
try {
for (int i = 0; i < pageonetime; i++) {
int synct = importdata4oldqkEx2();//
if (synct == 0) {
System.out.println("导入打卡数据提前结束【" + Systemdate.getStrDate() + "】" + i + "/" + pageonetime);
break;
} else
System.out.println("导入打卡数据【" + Systemdate.getStrDate() + "】" + i + "/" + pageonetime);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @return增量同步
* @throws Exception
*/
public static int importdata4oldqkEx2() throws Exception {
String sqlstr = "select max(synid) mx from hrkq_swcdlst";
Hrkq_swcdlst swte = new Hrkq_swcdlst();
List<HashMap<String, String>> sws = swte.pool.openSql2List(sqlstr);
long mx = ((sws.size() == 0) || (sws.get(0).get("mx") == null)) ? 0 : Long.valueOf(sws.get(0).get("mx"));
CJPALineData<TXkqView_Hrms> txcds = new CJPALineData<TXkqView_Hrms>(TXkqView_Hrms.class);
sqlstr = "SELECT TOP " + syncrowno + " * from view_Hrms_TXkq where KqId>" + mx
+ " and FDateTime>='" + autosynkqbgdate + "'";
sqlstr = sqlstr + " order by KqId";
txcds.findDataBySQL(sqlstr, true, false);
CJPALineData<Hrkq_swcdlst> kqsws = new CJPALineData<Hrkq_swcdlst>(Hrkq_swcdlst.class);
int rst = txcds.size();
for (CJPABase jpa : txcds) {
TXkqView_Hrms txcd = (TXkqView_Hrms) jpa;
Hrkq_swcdlst sw = new Hrkq_swcdlst();
sw.empno.setValue(txcd.Code.getValue().trim());// 工号
sw.card_number.setValue(txcd.CardNo.getValue().trim()); // 卡号
sw.skdate.setAsDatetime(txcd.FDateTime.getAsDatetime()); // yyyy-MM-dd hh:mm:ss
sw.sktype.setAsInt(1);// 1 刷卡 2 签卡
sw.synid.setValue(txcd.KqId.getValue()); // 旧ID 同步条件
sw.machineno.setValue(txcd.machno.getValue());
sw.machno1.setValue(txcd.machno1.getValue());
//sw.machno1.setValue("新宝");
kqsws.add(sw);
}
if (kqsws.size() > 0)
kqsws.saveBatchSimple();// 高速存储
return rst;
}
/**
* 同步该时间段一页数据到打卡记录表 时间段内增量
*
* @param ftime
* @param ttime
* @return 同步数据条数 条数为0 时候 表示该时间段数据同步完成
* @throws Exception
*/
private static int getTempdataPage(Date ftime, Date ttime, String empno) throws Exception {
String sft = Systemdate.getStrDateByFmt(ftime, "yyyy-MM-dd HH:mm:ss");
String stt = Systemdate.getStrDateByFmt(ttime, "yyyy-MM-dd HH:mm:ss");
String sqlstr = "select max(synid) mx from hrkq_swcdlst where skdate>='" + sft + "' AND skdate<'" + stt + "' and sktype=1 ";
if (empno != null)
sqlstr = sqlstr + " and empno='" + empno + "' ";
Hrkq_swcdlst swte = new Hrkq_swcdlst();
List<HashMap<String, String>> sws = swte.pool.openSql2List(sqlstr);
long mx = ((sws.size() == 0) || (sws.get(0).get("mx") == null)) ? 0 : Long.valueOf(sws.get(0).get("mx"));
CJPALineData<TXkqView_Hrms> txcds = new CJPALineData<TXkqView_Hrms>(TXkqView_Hrms.class);
sqlstr = "SELECT TOP " + syncrowno + " * from view_Hrms_TXkq where KqId>" + mx
+ " and FDateTime>='" + sft + "' and FDateTime<'" + stt + "'";
if (empno != null)
sqlstr = sqlstr + " and Code='" + empno + "'";
sqlstr = sqlstr + " order by KqId";
txcds.findDataBySQL(sqlstr, true, false);
CJPALineData<Hrkq_swcdlst> kqsws = new CJPALineData<Hrkq_swcdlst>(Hrkq_swcdlst.class);
int rst = txcds.size();
for (CJPABase jpa : txcds) {
TXkqView_Hrms txcd = (TXkqView_Hrms) jpa;
Hrkq_swcdlst sw = new Hrkq_swcdlst();
sw.empno.setValue(txcd.Code.getValue().trim());// 工号
sw.card_number.setValue(txcd.CardNo.getValue().trim()); // 卡号
sw.skdate.setAsDatetime(txcd.FDateTime.getAsDatetime()); // yyyy-MM-dd hh:mm:ss
sw.sktype.setAsInt(1);// 1 刷卡 2 签卡
sw.synid.setValue(txcd.KqId.getValue()); // 旧ID 同步条件
sw.machineno.setValue(txcd.machno.getValue()); // 机号
sw.machno1.setValue(txcd.machno1.getValue());
kqsws.add(sw);
}
if (kqsws.size() > 0)
kqsws.saveBatchSimple();// 高速存储
return rst;
}
/**
* 删除原始表该时间段数据; 同步原始表该时间段数据;
*
* @param ftime
* @param ttime
* @throws Exception
*/
public static void importdata4oldkq(Date ftime, Date ttime, String empno) throws Exception {
String sft = Systemdate.getStrDateByFmt(ftime, "yyyy-MM-dd HH:mm:ss");
String stt = Systemdate.getStrDateByFmt(ttime, "yyyy-MM-dd HH:mm:ss");
String sqlstr = null;
sqlstr = "DELETE FROM hrkq_swcdlst WHERE skdate>='" + sft + "' AND skdate<'" + stt + "' and sktype=1 ";
if ((empno != null) && (!empno.trim().isEmpty()))
sqlstr = sqlstr + " and empno='" + empno + "' ";
Hrkq_swcdlst swctem = new Hrkq_swcdlst();
swctem.pool.execsql(sqlstr);// 删除已经存在的数据
while (true) {
int synct = getTempdataPage(ftime, ttime, empno);
System.out.println("导入打卡数据【" + synct + "】条【" + Systemdate.getStrDate() + "】");
if (synct == 0)
break;
}
System.out.println("同步打卡数据,处理完毕" + Systemdate.getStrDate());
}
}
<file_sep>/src/com/corsair/server/generic/Shwrole.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwrole extends CJPA {
@CFieldinfo(fieldname = "roleid", iskey = true, notnull = true, datetype = Types.VARCHAR)
public CField roleid; // ID
@CFieldinfo(fieldname = "rolename", notnull = true, datetype = Types.VARCHAR)
public CField rolename; // 名称
@CFieldinfo(fieldname = "clas", datetype = Types.FLOAT)
public CField clas; //
@CFieldinfo(fieldname = "maxspace", datetype = Types.FLOAT)
public CField maxspace; // 空间限制
@CFieldinfo(fieldname = "note", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "maxemailspace", datetype = Types.FLOAT)
public CField maxemailspace; // 邮件空间
@CFieldinfo(fieldname = "fieldid", datetype = Types.FLOAT)
public CField fieldid; //
@CFieldinfo(fieldname = "maxattachsize", datetype = Types.FLOAT)
public CField maxattachsize; // 附件限制
@CFieldinfo(fieldname = "creator", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "updator", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updatetime", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "entid", datetype = Types.INTEGER)
public CField entid; // 组织
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwrole() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/common/cFindDlg.js
function TFindDialog(dlgOptions) {
var findFields = getFindColums(dlgOptions.findFields);
var findeditable = (dlgOptions.findeditable == undefined) ? false : dlgOptions.findeditable;
//if (!findFields) alert("TFindDialog构造函数未设置findFields");
if (dlgOptions.width == undefined)dlgOptions.width = 450;
if (dlgOptions.height == undefined)dlgOptions.height = 400;
var find_window = undefined;
var findline = $getHtmlFragment("#findline");
var dlgid = 'dlg' + $generateUUID();
initDlgUI();
var find_reloper_data = [
{id: 'like', value: '包含'},
{id: '=', value: '等于'},
{id: '>', value: '大于'},
{id: '>=', value: '大于等于'},
{id: '<', value: '小于'},
{id: '<=', value: '小于等于'},
{id: '<>', value: '不等于'},
{id: 'not like', value: '不包含'}
];
function initDlgUI() {
if ($("#common_divs_id").length <= 0) {
$("<div id='common_divs_id' style='display: none'></div>").appendTo("body");
}
find_window = $getHtmlFragment("#_find_window_id");
find_window = $(find_window).attr("id", dlgid).appendTo("#common_divs_id");
$.parser.parse("#common_divs_id");
find_window.window("resize", {
width: dlgOptions.width,
height: dlgOptions.height
});
find_window.keydown(onFindDlgKeydown);
find_window.find("a[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
el.onclick = function () {
onOKClick();
};
}
if (co.caction == "act_cancel") {
el.onclick = function () {
onCancelClick();
}
}
});
var cpanel = find_window.find(".easyui-layout").layout("panel", "center");
cpanel.panel({
tools: [
{
iconCls: 'icon-add1',
handler: function () {
find_window_add_click();
}
}
]
});
}
function onOKClick() {
var parms = getFindData();
if (dlgOptions.onOK) {
if (dlgOptions.onOK(parms))
find_window.window('close');
}
}
function onCancelClick() {
if (dlgOptions.onCancel) {
if (dlgOptions.onCancel()) {
find_window.window('close');
}
} else find_window.window('close');
}
function onFindDlgKeydown() {
//console.log(event.keyCode);
switch (event.keyCode) {
case 13://enter
onOKClick();
return false;
case 27://cancel
onCancelClick();
return false;
default:
break;
}
}
this.getDlgLayout = getDlgLayout;
function getDlgLayout() {
return find_window.find(".easyui-layout");
}
this.show = show;
function show() {
if (find_window.find("tbody tr").children().length == 0)
addNotNullParms();
if (find_window.find("tbody tr").children().length == 0)
find_window_add_click();
find_window.window("open");
}
this.close = close;
function close() {
find_window.window('close');
}
function addNotNullParms() {
for (var i = 0; i < findFields.length; i++) {
var fFd = findFields[i];
if (fFd.notnull) {
find_window_add_click(fFd.field);
}
}
}
function isNotNullField(field) {
for (var i = 0; i < findFields.length; i++) {
var fFd = findFields[i];
if (fFd.field == field) {
if (fFd.notnull) {
return fFd;
} else return undefined;
}
}
}
function checkNotNull(parms) {
for (var i = 0; i < parms.length; i++) {
var parm = parms[i];
var FD = isNotNullField(parm.parmname);
if (FD) {
if ($isEmpty(parm.parmvalue)) {
alert("参数【" + FD.title + "】不允许为空");
return false;
}
return true;
}
}
return true;
}
function find_window_add_click(field) {
var hml = findline;
var rowid = "row" + $generateUUID();
hml = hml.replace(new RegExp("{{rowid}}", "g"), rowid);
hml = hml.replace(new RegExp("{{parmnameData}}", "g"), "");
hml = hml.replace(new RegExp("{{reloperData}}", "g"), "valueField:'id',textField:'value'");
find_window.find(".dg_find_window_parms_id tbody").append(hml);
$.parser.parse("#" + rowid);
$("#" + rowid).find("input[fieldname]").each(function () {
var fdname = $(this).attr("fieldname");
if (fdname == "parmname") {
$(this).combobox({
valueField: 'field',
textField: 'title',
editable: findeditable,
data: findFields,
onSelect: onParmNameSelect
});
if (field) {
$(this).combobox("setValue", field);
$(this).combobox("readonly", true);
$(this).parent().append("(<span style='color: red'>*</span>)");
$(this).next().find("input:first").addClass("tabs-tool");
}
}
if (fdname == "reloper") {
$(this).combobox({
editable: findeditable,
data: find_reloper_data
});
$(this).combobox("setValue", "=");
}
});
if (field)
$("#" + rowid).find("a[fieldname='actiondel']").html("");
else
$("#" + rowid).find("a[fieldname='actiondel']").click(function (event) {
onFindRowDel(this);
});
}
function getFindColums(listGridColumns) {
if (!listGridColumns) return [];
var fcls = [];
for (var i = 0; i < listGridColumns.length; i++) {
var col = listGridColumns[i];
if (col) {
if ($.isArray(col)) {
for (var j = 0; j < col.length; j++) {
var coll = col[j];
if (coll && (coll.field) && (!col.notfind))
fcls.push(coll);
}
} else {
if (col.field && (!col.notfind))
fcls.push(col);
}
}
}
return fcls;
}
function onParmNameSelect(rec) {
var fieldinput = $(this);
fieldinput.attr("precision", rec.precision);
var tdreloper = fieldinput.parents("tr").find("td[tdtype='reloper']");
var htm = "<input type='text' fieldname='reloper' style='width:70px;height: 20px'>";
tdreloper.html(htm);
$.extend(rec.relOptions, {valueField: 'id', textField: 'value'});
var inputrel = tdreloper.find("input");
if (rec.relOptions) {
inputrel.combobox(rec.relOptions);
if (rec.relOptions.data.length > 0) {
inputrel.combobox("setValue", rec.relOptions.data[0].id);
}
} else {
inputrel.combobox({
valueField: 'id', textField: 'value',
editable: findeditable,
data: find_reloper_data
});
inputrel.combobox("setValue", "=");
}
var trparmvalue = $(this).parents("tr").find("td[tdtype='parmvalue']");
var htm = "<input type='text' fieldname='parmvalue' style='width:150px;height: 20px'>";
trparmvalue.html(htm);
var inputo = trparmvalue.find("input");
$setFindTextByRow(rec, inputo, findeditable);
}
function onFindRowDel(obj) {
$(obj).parents("tr").remove();
}
function getFindData() {
var data = [];
find_window.find("tbody tr").each(function () {
var row = {};
$(this).find("input[fieldname]").each(function () {
var objthis = $(this);
var fdname = objthis.attr("fieldname");
if (fdname == "parmname") {
row.parmname = objthis.combobox("getValue");
row.precision = objthis.attr("precision");
}
if (fdname == "reloper") {
row.reloper = objthis.combobox("getValue");
}
if (fdname == "parmvalue") {
var clsname = objthis.attr("class");
if ((clsname.indexOf("datetimebox") >= 0) || (clsname.indexOf("datebox") >= 0)) {
//$fieldDateFormatorYYYY_MM_DD
row.parmvalue = objthis.textbox("getValue");
} else if (clsname.indexOf("combo") >= 0) {
row.parmvalue = objthis.combobox("getValue");
} else {
row.parmvalue = objthis.textbox("getValue");
}
}
});
if (row.parmname != undefined)
data.push(row);
});
if (checkNotNull(data))
return data;
}
}<file_sep>/src/com/corsair/server/html/CHtmlTemplateJS.java
package com.corsair.server.html;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.Login;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.util.CServletProperty;
import com.corsair.server.util.HttpTookit;
public class CHtmlTemplateJS {
public static void testHtmlInit(String srcfname) throws Exception {
File srcf = new File(srcfname);
Document srcDoc = Jsoup.parse(srcf, "UTF-8");
Elements ets = srcDoc.getElementsByTag("script");
Element fe = null;
String s = "";
for (Element et : ets) {
if ("text/javascript".equalsIgnoreCase(et.attr("type")) && ("cserver_js").equalsIgnoreCase(et.attr("style"))) {
if (fe == null)
fe = et;
s = s + et.html();
}
}
String fcs = null;
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
try {
cx.evaluateString(scope, s, null, 0, null);
int FormType = htmlUtil.parIntParm(scope, "formtype", 1);
boolean allowAtt = htmlUtil.parBoolParm(scope, "allowAtt", true);
boolean allowWF = htmlUtil.parBoolParm(scope, "allowWF", true);
setPageMailLine(srcDoc, FormType);
setPageAllowWF(srcDoc, allowWF);
setPageAllowAtt(srcDoc, allowAtt);
fcs = CHtmlTemplateJS.parComUrls(scope);
if (fcs == null)
fcs = "";
} catch (Exception e) {
e.printStackTrace();
} finally {
Context.exit();
}
if (fe != null) {
String s1 = fe.html();
s1 = fcs + "\n" + s1;
fe.text(s1);
}
String newhtml = srcDoc.html();
newhtml = newhtml.replace("<", "<");
newhtml = newhtml.replace(">", ">");
newhtml = newhtml.replace("&", "&");
// newhtml = HtmlCompressor.compress(newhtml); //貌似内嵌js压缩有有问题
// Logsw.debug(newhtml);
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(srcfname), "UTF-8");
out.write(newhtml);
out.flush();
out.close();
} catch (Exception e) {
throw new Exception("文件【" + srcfname + "】写入错误!");
}
}
public static String parComUrls(Scriptable scope) throws Exception {
HttpServletRequest request = CSContext.getRequest();
String basePath = null;
if (request != null) {
basePath = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() != 80)
basePath = basePath + ":" + request.getServerPort();
basePath = basePath + request.getContextPath();
} else {
InetAddress ia = InetAddress.getLocalHost();
basePath = "http://" + ia.getHostAddress() + ":" + CServletProperty.getServerPort("http")
+ "/" + CServletProperty.getContextPath();
}
Object fobj = scope.get("comUrls", scope);
if ((fobj == null) || (fobj.equals(Scriptable.NOT_FOUND)))
return null;
if (!(fobj instanceof NativeArray))
throw new Exception("comUrls变量必须为JS数组");
NativeArray comUrls = (NativeArray) fobj;
HttpTookit ht = new HttpTookit();
Shwuser admin = Login.getAdminUser();
String rst = ht.doGet(basePath + "/web/login/dologin.co?username=" + admin.username.getValue() + "&userpass=" + admin.userpass.getValue()
+ "&version=1.1", null);
String jsfuncs = "";
for (Object jo : comUrls) {
NativeObject o = (NativeObject) jo;
String index = o.get("index").toString();
String type = o.get("type").toString();
boolean multiple = (o.get("multiple") == null) ? false : Boolean.valueOf(o.get("multiple").toString());
String url = o.get("url").toString();
String valueField = o.get("valueField").toString();
String textField = o.get("textField").toString();
if (url.startsWith("/"))
url = basePath + url;
else
url = basePath + "/" + url;
boolean iswie = (o.get("iswie") == null) ? false : Boolean.valueOf(o.get("iswie").toString());
// System.out.println(index + " iswie:" + iswie);
// if (o.get("iswie") != null)
// System.out.println("iswie:" + o.get("iswie").toString());
CcomUrl co = new CcomUrl(ht, index, type, multiple, url, valueField, textField);
if (!iswie)
jsfuncs = jsfuncs + "\n" + co.fetchJSFunction();
}
return jsfuncs;
}
// public static void parlistGridColumns(Scriptable scope, Document srcDoc) throws Exception {
// Object fobj = scope.get("listGridColumns", scope);
// if (!(fobj instanceof NativeArray))
// throw new Exception("listGridColumns变量必须为JS数组");
// NativeArray comUrls = (NativeArray) fobj;
// for (Object jo : comUrls) {
// NativeObject o = (NativeObject) jo;
// String field = o.get("field").toString();
// String title = o.get("title").toString();
// String width = o.get("width").toString();
// if (o.get("formatter") != null) {
// String formatter = o.get("formatter").toString();
// }
// if (o.get("editor") != null) {
// String editor = o.get("editor").toString();
// }
// // System.out.println(field);
// }
// }
public static void setPageMailLine(Document srcDoc, int formtype) {
if (formtype == 2) {// simple form
Element e = srcDoc.getElementById("main_form_div_id");
if (e != null) {
e.attr("data-options", "region:'center',border:false");
e = srcDoc.getElementById("detail_main_layout_id");
if (e != null)
e.remove();
}
}
}
public static void setPageAllowWF(Document srcDoc, boolean allowWF) {
if (!allowWF) {
Element e = srcDoc.getElementById("main_tab_wf_id");
if (e != null)
e.remove();
}
}
public static void setPageAllowAtt(Document srcDoc, boolean allowAtt) {
if (!allowAtt) {
Element e = srcDoc.getElementById("main_tab_att_id");
if (e != null)
e.remove();
}
}
}
<file_sep>/src/com/corsair/server/util/MatrixUtil.java
package com.corsair.server.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* @author shangwen
* Version 1是21 x 21的矩阵,
* Version 2是 25 x 25的矩阵,
* Version 3是29的尺寸,
* 每增加一个version,就会增加4的尺寸,公式是:(V-1)4 + 21(V是版本号) 最高Version 40,(40-1)4+21 = 177,所以最高是177 x 177的正方形
*/
public class MatrixUtil {
private final String CHARSET = "utf-8";
private final int BLACK = 0xFF000000;
private final int WHITE = 0xFFFFFFFF;
private String text = null; // 转二维码、条码的文本
private String textext = null;// 扩展文本用于显示在二维码图片下面
private String logofilename = null;// logo文件名
private int qcwidth = 300;// 二维码、条码大小
private int qcheight = 300;// 二维码、条码大小
private int logowidth = 65;// logo大小
private int logoheight = 65;// logo大小
public MatrixUtil() {
}
public MatrixUtil(String text) {
this.text = text;
}
public MatrixUtil(String text, String textext) {
this.text = text;
this.textext = textext;
}
/**
* 二维码图片写入文件
*
* @param text
* @param file
* @param w
* @param h
* @param format
* 文件格式字符串 如.jpg .png等
* @return
* @throws Exception
*/
public boolean toQrcodeFile(File file, String format) throws Exception {
BitMatrix matrix = toQRCodeMatrix();
if (matrix != null) {
try {
writeToFile(matrix, format, file);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
/**
* 二维码图片写入流
*
* @param stream
* @param format
* @return
* @throws Exception
*/
public boolean toQrcodeStream(OutputStream stream, String format) throws Exception {
BitMatrix matrix = toQRCodeMatrix();
if (matrix != null) {
try {
writeToStream(matrix, format, stream);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
// 条码
public boolean toBarCodeFile(File file, String format) throws Exception {
BitMatrix matrix = toBarCodeMatrix();
if (matrix != null) {
try {
writeToFile(matrix, format, file);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
private BitMatrix toQRCodeMatrix() {
int width = qcwidth;
width = (width < 300) ? 300 : width;// 最小300
width = (width > 2048) ? 2048 : width;// 最最大2048
int height = qcheight;
height = (height < 300) ? 300 : height;// 最小300
height = (height > 2048) ? 2048 : height;// 最最大2048
// 二维码的图片格式
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 生成二维码
// File outputFile = new File("d:"+File.separator+"new.gif");
// MatrixUtil.writeToFile(bitMatrix, format, outputFile);
return bitMatrix;
}
/**
* 根据点矩阵生成黑白图。
*
* @throws Exception
*/
private BufferedImage toBufferedImage(BitMatrix matrix) throws Exception {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
if ((logofilename != null) && (!logofilename.isEmpty()))
insertLogImage(image, logofilename, true);
if ((textext != null) && (!textext.isEmpty()))
insertExtText(image, textext);
return image;
}
/**
* 将字符串编成一维条码的矩阵
*/
private BitMatrix toBarCodeMatrix() {
int width = qcwidth;
width = (width < 200) ? 200 : width;// 最小
width = (width > 1024) ? 1024 : width;// 最最大
int height = qcheight;
height = (height < 20) ? 20 : height;// 最小
height = (height > 200) ? 200 : height;// 最最大
try {
// 文字编码
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
BarcodeFormat.CODE_128, width, height, hints);
return bitMatrix;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据矩阵、图片格式,生成文件。
*
* @throws Exception
*/
private void writeToFile(BitMatrix matrix, String format, File file)
throws Exception {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format "
+ format + " to " + file);
}
}
/**
* 将矩阵写入到输出流中。
*
* @throws Exception
*/
private void writeToStream(BitMatrix matrix, String format,
OutputStream stream) throws Exception {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
/**
* 解码,需要javase包。
*/
public String decode(File file) {
BufferedImage image;
try {
if (file == null || file.exists() == false) {
throw new Exception(" File not found:" + file.getPath());
}
image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
// 解码设置编码方式为:utf-8,
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param logoPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private void insertLogImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
int lwidth = logowidth;
lwidth = (lwidth < 50) ? 50 : lwidth;// 最小50
lwidth = (lwidth > 75) ? 75 : lwidth;// 最最大75
int lheight = logoheight;
lheight = (lheight < 50) ? 50 : lheight;// 最小50
lheight = (lheight > 75) ? 75 : lheight;// 最最大75
Image src = ImageIO.read(new File(logoPath));
// int width = src.getWidth(null);
// int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
// if (width > lwidth) {
// width = lwidth;
// }
// if (height > lheight) {
// height = lheight;
// }
Image image = src.getScaledInstance(lwidth, lheight, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(lwidth, lheight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (qcwidth - lwidth) / 2;
int y = (qcheight - lheight) / 2;
graph.drawImage(src, x, y, lwidth, lheight, null);
Shape shape = new RoundRectangle2D.Float(x, y, lwidth, lheight, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
private void insertExtText(BufferedImage source, String extstr) throws Exception {
Graphics2D graph = source.createGraphics();
// g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
graph.setColor(Color.BLACK); // 根据图片的背景设置水印颜色
Font f = new Font("宋体", Font.PLAIN, 20);
graph.setFont(f); // 设置字体
Point wh = getTextWH(graph, f, extstr);
int x = (qcwidth - wh.x) / 2;
int y = qcheight - 2;// - wh.y;//留两个像素编剧好了
// 设置水印的坐标
graph.drawString(extstr, x, y); // 画出水印
graph.dispose();
}
/**
* 计算一段文字的宽度和高度
*
* @param graph
* @param font
* @param content
* @return
*/
public static Point getTextWH(Graphics2D graph, Font font, String content) {
FontMetrics metrics = graph.getFontMetrics(font);
int width = 0;
for (int i = 0; i < content.length(); i++) {
width += metrics.charWidth(content.charAt(i));
}
int height = metrics.getHeight();
return new Point(width, height);
}
// get and set
public String getText() {
return text;
}
public String getTextext() {
return textext;
}
public String getLogofilename() {
return logofilename;
}
public int getQcwidth() {
return qcwidth;
}
public int getQcheight() {
return qcheight;
}
public int getLogowidth() {
return logowidth;
}
public int getLogoheight() {
return logoheight;
}
public MatrixUtil setText(String text) {
this.text = text;
return this;
}
public MatrixUtil setTextext(String textext) {
this.textext = textext;
return this;
}
public MatrixUtil setLogofilename(String logofilename) {
this.logofilename = logofilename;
return this;
}
public MatrixUtil setQcwidth(int qcwidth) {
this.qcwidth = qcwidth;
return this;
}
public MatrixUtil setQcheight(int qcheight) {
this.qcheight = qcheight;
return this;
}
public MatrixUtil setLogowidth(int logowidth) {
this.logowidth = logowidth;
return this;
}
public MatrixUtil setLogoheight(int logoheight) {
this.logoheight = logoheight;
return this;
}
}
<file_sep>/src/com/corsair/cjpa/LinkField.java
package com.corsair.cjpa;
/**
* 关联字段
*
* @author Administrator
*
*/
public class LinkField {
private String mfield;
private String lfield;
public LinkField(String mfield, String lfield) {
this.mfield = mfield;
this.lfield = lfield;
}
public String getMfield() {
return mfield;
}
public void setMfield(String mfield) {
this.mfield = mfield;
}
public String getLfield() {
return lfield;
}
public void setLfield(String lfield) {
this.lfield = lfield;
}
}
<file_sep>/src/com/corsair/dbpool/util/CJSONTree.java
package com.corsair.dbpool.util;
import java.io.ByteArrayOutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.dbpool.CDBConnection.DBType;
/**
* 树型JSON处理
*
* @author Administrator
*
*/
public class CJSONTree {
public static String Dataset2JSONTree(ResultSet rs, String idfd, String pidfd, boolean async) throws Exception {
List<HashMap<String, String>> rows = Dataset2List(rs);
List<HashMap<String, String>> rootrows = getRootRows(rows, idfd, pidfd);
return list2Json(rootrows, rows, idfd, pidfd, async);
}
public static JSONArray Dataset2JSON(ResultSet rs, String idfd, String pidfd, boolean async) throws Exception {
List<HashMap<String, String>> rows = Dataset2List(rs);
// System.out.println("rows:" + rows.size());
List<HashMap<String, String>> rootrows = getRootRows(rows, idfd, pidfd);
// System.out.println("rootrows:" + rootrows.size());
return list2json_o(rootrows, rows, idfd, pidfd, async);
}
private static JSONArray list2json_o(List<HashMap<String, String>> rows, List<HashMap<String, String>> allrows, String idfd, String pidfd, boolean async) {
JSONArray js = new JSONArray();
for (HashMap<String, String> row : rows) {
js.add(hashmap2json_o(row, allrows, idfd, pidfd, async));
}
return js;
}
private static String list2Json(List<HashMap<String, String>> rows, List<HashMap<String, String>> allrows, String idfd, String pidfd, boolean async)
throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartArray();
for (HashMap<String, String> row : rows) {
jg.writeRawValue(hashmap2json(row, allrows, idfd, pidfd, async));
}
jg.writeEndArray();
jg.close();
return baos.toString("utf-8");
}
private static List<HashMap<String, String>> getChildRows(HashMap<String, String> row, List<HashMap<String, String>> allrows, String idfd, String pidfd) {
List<HashMap<String, String>> chdrows = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> chdrow : allrows) {
if (chdrow.get(pidfd).equalsIgnoreCase(row.get(idfd))) {
chdrows.add(chdrow);
}
}
return chdrows;
}
public static List<HashMap<String, String>> Dataset2List(ResultSet rs) throws Exception {
return Dataset2List(DBType.mysql, rs);
}
public static List<HashMap<String, String>> Dataset2List(DBType dbtype, ResultSet rs) throws Exception {
List<HashMap<String, String>> datalist = new ArrayList<HashMap<String, String>>();
ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集的定义结构
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
HashMap<String, String> rowdata = new HashMap<String, String>();
for (int i = 1; i <= columnCount; i++) {
String fdname = rsmd.getColumnLabel(i);
if (dbtype == DBType.oracle)
fdname = fdname.toLowerCase();
rowdata.put(fdname, getvalue(rs, i, rsmd.getColumnType(i)));
}
datalist.add(rowdata);
}
return datalist;
}
private static JSONObject hashmap2json_o(HashMap<String, String> row, List<HashMap<String, String>> allrows, String idfd, String pidfd, boolean async) {
JSONObject rst = new JSONObject();
Iterator<Entry<String, String>> iter = row.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
rst.put(entry.getKey(), entry.getValue());
}
if (!async) {
List<HashMap<String, String>> chdrows = getChildRows(row, allrows, idfd, pidfd);
if (chdrows.size() > 0) {
JSONArray js = new JSONArray();
for (HashMap<String, String> chdrow : chdrows) {
JSONObject jo = hashmap2json_o(chdrow, allrows, idfd, pidfd, async);
js.add(jo);
}
rst.put("children", js);
}
}
return rst;
}
private static String hashmap2json(HashMap<String, String> row, List<HashMap<String, String>> allrows, String idfd, String pidfd, boolean async)
throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartObject();
Iterator<Entry<String, String>> iter = row.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
jg.writeStringField(entry.getKey(), entry.getValue());
}
if (!async) {
List<HashMap<String, String>> chdrows = getChildRows(row, allrows, idfd, pidfd);
if (chdrows.size() > 0) {
jg.writeArrayFieldStart("children");
for (HashMap<String, String> chdrow : chdrows) {
jg.writeRawValue(hashmap2json(chdrow, allrows, idfd, pidfd, async));
}
jg.writeEndArray();
}
}
jg.writeEndObject();
jg.close();
return baos.toString("utf-8");
}
/**
* 逻辑,对每一行如果没有任何一行是他的父亲,则为根
*
* @param datalist
* @param idfd
* @param pidfd
* @return
*/
private static List<HashMap<String, String>> getRootRows(List<HashMap<String, String>> datalist, String idfd, String pidfd) {
List<HashMap<String, String>> rootrows = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> row : datalist) {
boolean fd = false;
String pid = row.get(pidfd);
for (int i = 0; i < datalist.size(); i++) {
HashMap<String, String> row1 = datalist.get(i);
String id = row1.get(idfd);
// System.out.println("pid:" + pid + ";id:" + pid);
if (pid.equalsIgnoreCase(id)) {
fd = true;
break;
}
}
if (!fd) {
rootrows.add(row);
}
}
return rootrows;
}
private static String getvalue(final ResultSet rs, int colNum, int type) throws SQLException {
switch (type) {
case Types.ARRAY:
case Types.BLOB:
case Types.CLOB:
case Types.DISTINCT:
case Types.LONGVARBINARY:
case Types.VARBINARY:
case Types.BINARY:
case Types.REF:
case Types.STRUCT:
return "undefined";
case Types.DATE:
case Types.TIMESTAMP: {
Object value = null;
try {
value = rs.getObject(colNum);
} catch (Exception e) {
e.printStackTrace();
}
if (rs.wasNull() || (value == null))
return (null);
else {
String v = value.toString();
if (v.substring(v.length() - 2, v.length()).endsWith(".0"))
v = v.substring(0, v.length() - 2);
return (v);
}
}
default: {
Object value = rs.getObject(colNum);
if (rs.wasNull() || (value == null))
return (null);// ConstsSw.xml_null
else {
// System.out.println(type);
// System.out.println(value.toString());
return (value.toString());
}
}
}
}
}
<file_sep>/src/com/corsair/cjpa/CJPAXML.java
package com.corsair.cjpa;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* CJPA XML交互实现
*
* @author Administrator
*
*/
public abstract class CJPAXML extends CJPABase {
public CJPAXML() throws Exception {
}
/**
* 写入XML文件
*
* @param fname
* @throws IOException
*/
public void toxmlfile(String fname) throws IOException {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("cjpa");// 创建根节点
toxmlroot(root);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
FileOutputStream fos = new FileOutputStream(fname);
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.close();
}
/**
* 生成XML字符串
*
* @return
*/
public String toxml() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("cjpa");// 创建根节点
toxmlroot(root);
String xmlstr = document.asXML();
// System.out.println(xmlstr);
return xmlstr;
}
/**
* 将数据写入XML元素节点
*
* @param emt
*/
public void toxmlSimple(Element emt) {
for (CField cf : cFields) {
Element e = emt.addElement(cf.getFieldname());
if (!cf.isEmpty())
e.setText(cf.getValue());
}
}
/**
* 将数据写入XML元素节点(不包含行数据)
*
* @param emt
*/
public void fromxmlSimple(Element emt) {
List<Element> es = emt.elements();
for (Element e : es) {
String fdname = e.getName();
CField fd = cfield(fdname);
if (fd != null)
fd.setValue(e.getTextTrim());
}
}
/**
* 将数据写入XML元素节点
*
* @param root
*/
public void toxmlroot(Element root) {
root.addAttribute("tablename", tablename);
root.addAttribute("jpaclass", getClass().toString());
root.addAttribute("poolname", pool.pprm.name);
root.addAttribute("where", SqlWhere);
root.addAttribute("jpastat", getJpaStat().toString());
root.addAttribute("tag", String.valueOf(tag));
Element fields = root.addElement("fields");
for (CField cf : cFields) {
Element field = fields.addElement("field");
field.addAttribute("fieldname", cf.getFieldname());
field.addAttribute("size", String.valueOf(cf.getSize()));
field.addAttribute("fieldtype", String.valueOf(cf.getFieldtype()));
field.addAttribute("caption", cf.getCaption());
field.addAttribute("dicid", String.valueOf(cf.getDicid()));
field.addAttribute("codeid", String.valueOf(cf.getCodeid()));
field.addAttribute("nullable", String.valueOf(cf.isNullable()));
field.addAttribute("iskey", String.valueOf(cf.isIskey()));
field.addAttribute("readonly", String.valueOf(cf.isReadonly()));
field.addAttribute("visible", String.valueOf(cf.isVisible()));
field.addAttribute("changed", String.valueOf(cf.isChanged()));
field.addAttribute("value", cf.getValue());
field.addAttribute("sorindex", String.valueOf(cf.getSorIndex()));
}
Element linedatas = root.addElement("linedatas");
for (CJPALineData<CJPABase> line : cJPALileDatas) {
Element linedata = linedatas.addElement("linedata");
line.toxmlnode(linedata);
}
/*
* Element nodejpas = root.addElement("cjpas"); for (CJPABase cjpa : cJPAs) { Element cjparoot = nodejpas.addElement("cjpa"); ((CJPAXML) cjpa).toxmlroot(cjparoot); }
*/
}
/**
* 从XML加载数据
*
* @param xml
* @throws Exception
*/
public void fromxml(String xml) throws Exception {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
clear();
fromxmlroot(root);
}
/**
* 从XML节点加载数据
*
* @param root
* @throws Exception
*/
public void fromxmlroot(Element root) throws Exception {
if (!root.getName().equalsIgnoreCase("CJPA"))
return;
// this.tablename = root.attributeValue("tablename");
this.setJpaStat(CJPAStat.valueOf(root.attributeValue("jpastat").toUpperCase()));
// System.out.println("this.cJpaStat"+this.cJpaStat);
this.tag = Integer.valueOf(root.attributeValue("tag"));
this.SqlWhere = root.attributeValue("where");
// 载入普通字段值
@SuppressWarnings("unchecked")
List<Element> efields = root.element("fields").elements("field");
for (Element efield : efields) {
String fdname = efield.attributeValue("fieldname");
CField field = cfield(fdname);
if (field == null)
throw new Exception("JPA载入XML数据没发现字段<" + fdname + ">");
if (Integer.valueOf(efield.attributeValue("size")) != 0)
field.setSize(Integer.valueOf(efield.attributeValue("size")));
// field.setFieldtype(Integer.valueOf(efield.attributeValue("fieldtype")));
// field.setCaption(efield.attributeValue("caption"));
if (Integer.valueOf(efield.attributeValue("dicid")) != 0)
field.setDicid(Integer.valueOf(efield.attributeValue("dicid")));
if (Integer.valueOf(efield.attributeValue("codeid")) != 0)
field.setCodeid(Integer.valueOf(efield.attributeValue("codeid")));
if (!Boolean.valueOf(efield.attributeValue("nullable")))
field.setNullable(false);// 从严原则
if (Boolean.valueOf(efield.attributeValue("iskey")))
field.setIskey(true);
// field.setReadonly(Boolean.valueOf(efield.attributeValue("readonly")));
// field.setVisible(Boolean.valueOf(efield.attributeValue("visible")));
field.setValue(efield.attributeValue("value"));
field.setChanged(Boolean.valueOf(efield.attributeValue("changed")));
}
// 载入明细数据
@SuppressWarnings("unchecked")
List<Element> elinedatas = root.element("linedatas").elements("linedata");
for (Element elinedata : elinedatas) {
String entyclaname = elinedata.attributeValue("entityclas");
CJPALineData<CJPABase> clinedata = lineDataByEntyClasname(entyclaname);
if (clinedata == null)
continue;
// throw new Exception("<" + this.getClass().getName() +
// ">JPA载入明细数据,根据明细类名<" + entyclaname + ">没找到明细数据对象!");
clinedata.fromxmlnode(elinedata);
}
}
/**
* 创建EAI对象
*
* @param className
* @return
* @throws Exception
*/
public CJPABase newEaiObjcet(String className) throws Exception {
Class<?> CJPAcd = Class.forName(className);
if (!CJPABase.class.isAssignableFrom(CJPAcd)) {
throw new Exception(className + "必须从 com.corsair.server.cjpa.CJPA继承");
}
Class<?> paramTypes[] = {};
Constructor<?> cst = CJPAcd.getConstructor(paramTypes);
Object o = cst.newInstance();
return (CJPABase) (o);
}
}
<file_sep>/src/com/corsair/server/genco/COShwWf.java
package com.corsair.server.genco;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.cjpa.CJPAJSON;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.server.base.CSContext;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.CJPAWorkFlow;
import com.corsair.server.cjpa.CJPAWorkFlow2;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CorUtil;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.corsair.server.wordflow.Shwwfprocuser;
import com.corsair.server.wordflow.Shwwftemp;
import com.corsair.server.wordflow.Shwwftemplinkline;
import com.corsair.server.wordflow.Shwwftempproc;
@ACO(coname = "web.wf")
public class COShwWf {
@ACOAction(eventname = "getWftemp", Authentication = true, ispublic = true)
public String getWftemp() throws Exception {
String wftempid = CSContext.getParms().get("wftempid");
if ((wftempid == null) || wftempid.isEmpty())
throw new Exception("参数wftempid必须!");
return ((CJPAJSON) new Shwwftemp().findByID(wftempid)).tojson();
}
@ACOAction(eventname = "getWftemps", Authentication = true, ispublic = true)
public String getWftemps() throws Exception {
String fdrid = CSContext.getParms().get("fdrid");
if ((fdrid == null) || fdrid.isEmpty())
throw new Exception("参数fdrid必须!");
String sqlstr = "select * from shwwftemp a where a.fdrid=" + fdrid + " and EntID=" + CSContext.getCurEntID();
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getWffds", Authentication = true, ispublic = true)
public String getWffds() throws Exception {
String sqlstr = "select * from shwfdr a where a.fdtype=2 and superid<>0 and actived=1";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getwftemtypetree", Authentication = true, ispublic = true)
public String getwftemtypetree() throws Exception {
String sqlstr = "select * from shwwftemtype where 1=1 ";
return DBPools.defaultPool().opensql2jsontree(sqlstr, "wftpid", "superid", false);
}
@ACOAction(eventname = "saveWfTemp", Authentication = true, notes = "保存流程模板")
public String saveWfTemp() throws Exception {
JsonNode rootNode = new ObjectMapper().readTree(CSContext.getPostdata());
boolean isnew = rootNode.path("isnew").asBoolean();
String jsondata = rootNode.path("jsondata").toString();
Shwwftemp wft = (Shwwftemp) new Shwwftemp();
if (isnew)
wft.setJpaStat(CJPAStat.RSINSERT);
else
wft.setJpaStat(CJPAStat.RSUPDATED);
wft.fromjson(jsondata);
// wft.toxmlfile("c:\\" + wft.getClass().getSimpleName() + ".xml");
wft.save();
return wft.tojson();
}
@ACOAction(eventname = "copyWfTemp", Authentication = true, notes = "复制模板")
public String copyWfTemp() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String wftempid = CorUtil.hashMap2Str(parms, "wftempid", "需要参数【wftempid】");
String new_wftempname = CorUtil.hashMap2Str(parms, "new_wftempname", "需要参数【new_wftempname】");
Shwwftemp wft = new Shwwftemp();
CDBConnection con = wft.pool.getCon(this);
con.startTrans();
try {
wft.findByID(wftempid);
CJPALineData<Shwwftempproc> proces = wft.shwwftempprocs;
CJPALineData<Shwwftemplinkline> lines = wft.shwwftemplinklines;
for (CJPABase jpa : lines) {
Shwwftemplinkline line = (Shwwftemplinkline) jpa;
Shwwftempproc fproc = (Shwwftempproc) proces.getJPAByID(line.fromproctempid.getValue());
Shwwftempproc tproc = (Shwwftempproc) proces.getJPAByID(line.toproctempid.getValue());
TwoObject o2 = new TwoObject(fproc, tproc);
line._userdata = o2;
}
// System.out.println("1111:"+wft.tojson());
wft.clearAllId();
// System.out.println("2222:"+wft.tojson());
wft.checkOrCreateIDCode(con, true);
// System.out.println("3333:"+wft.tojson());
for (CJPABase jpa : lines) {
Shwwftemplinkline line = (Shwwftemplinkline) jpa;
TwoObject o2 = (TwoObject) line._userdata;
Shwwftempproc fproc = (Shwwftempproc) o2.obj1;
Shwwftempproc tproc = (Shwwftempproc) o2.obj2;
line.fromproctempid.setValue(fproc.proctempid.getValue());
line.toproctempid.setValue(tproc.proctempid.getValue());
}
wft.wftempname.setValue(new_wftempname);
wft.save(con);
con.submit();
return wft.tojson();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
/**
* @return 获取当前登录用户 活动流程数量
* @throws Exception
*/
@ACOAction(eventname = "wfcount", Authentication = true, ispublic = true)
public String getWFcount() throws Exception {
String sqlstr = " SELECT COUNT(*) AS ct"
+ " FROM (SELECT DISTINCT a.*"
+ " FROM shwwf a, shwwfproc b, shwwfprocuser c, (SELECT wfu.`userid`, wfu.`wftempid`"
+ " FROM `shwuser` u, `shwuser_wf_agent` wfu"
+ " WHERE u.`goout` = 1"
+ " AND u.`userid` = wfu.`userid`"
+ " AND wfu.`auserid` = " + CSContext.getUserID()
+ " ) ag"
+ " WHERE a.wfid = b.wfid"
+ " AND b.procid = c.procid"
+ " AND a.stat = 1"
+ " AND c.stat IN(1,3)"
+ " AND b.stat = 2"
+ " AND a.`wftemid` = ag.wftempid"
+ " AND c.`userid` = ag.userid"
+ " UNION"
+ " SELECT DISTINCT a.*"
+ " FROM shwwf a, shwwfproc b, shwwfprocuser c"
+ " WHERE a.wfid = b.wfid"
+ " AND b.procid = c.procid"
+ " AND a.stat = 1"
+ " AND c.stat IN(1,3)"
+ " AND b.stat = 2"
+ " AND c.userid = " + CSContext.getUserID()
+ " ) tb";
String rst = DBPools.defaultPool().opensql2json(sqlstr);
return rst;
}
// private HashMap<String, String> newBuildInParm(String id, String value) {
// HashMap<String, String> pm = new HashMap<String, String>();
// pm.put("id", id);
// pm.put("value", value);
// return pm;
// }
@ACOAction(eventname = "delWFTem", Authentication = true, notes = "删除流程模板")
public String delWFTem() throws Exception {
String wftempid = CorUtil.hashMap2Str(CSContext.parPostDataParms(), "wftempid", "需要参数wftempid");
Shwwftemp wft = (Shwwftemp) new Shwwftemp();
wft.findByID(wftempid);
if (wft.isEmpty())
throw new Exception("没有发现ID为【" + wftempid + "】的流程模板");
wft.delete();
return "{\"result\":\"ok\"}";
}
// @ACOAction(eventname = "getWFBuildInParms", Authentication = true)
// public String getWFBuildInParms() throws Exception {
// List<HashMap<String, String>> pms = new ArrayList<HashMap<String, String>>();
// pms.add(newBuildInParm("<#sysdatetime#/>", "系统时间"));
// pms.add(newBuildInParm("<#proctitle#/>", "节点标题"));
// return CJSON.List2JSON(pms);
// }
@ACOAction(eventname = "getWfCurProcedure", Authentication = true, ispublic = true)
public String getWfCurProcedure() throws Exception {
String wfid = CorUtil.hashMap2Str(CSContext.getParms(), "wfid", "需要参数wfid");
Shwwfproc proc = getWfCurProcedure(wfid);
if (proc == null)
return "{}";
else
return proc.tojson();
}
/**
* @param wfid
* @return 获取活动流程
* @throws Exception
*/
public static Shwwfproc getWfCurProcedure(String wfid) throws Exception {
String sqlstr = "SELECT procid FROM `shwwfproc` WHERE wfid=" + wfid + " AND stat=2 AND isbegin<>1 AND isend<>1";
List<HashMap<String, String>> cpros = DBPools.defaultPool().openSql2List(sqlstr);
if (cpros.size() <= 0)
return null;
String procid = cpros.get(0).get("procid").toString();
return (Shwwfproc) new Shwwfproc().findByID(procid);
}
/**
* @return 返回当前登录用户是否在流程活动节点里面 同时返回流程对象
* @throws Exception
*/
@ACOAction(eventname = "findWfInfo", Authentication = true, ispublic = true)
public String findWfInfo() throws Exception {
String wfid = CorUtil.hashMap2Str(CSContext.getParms(), "wfid", "需要参数wfid");
String userid = CSContext.getParms().get("userid");
if ((userid == null) || userid.isEmpty())
userid = CSContext.getUserID();
Shwwf wf = new Shwwf();
wf.findByID(wfid);
// 设置代理名;
// 判断当前用户是否参与活动节点
Shwwfproc proc = null;
if (wf.stat.getAsIntDefault(0) != 2) {
for (CJPABase jprc : wf.shwwfprocs) {
Shwwfproc proc1 = (Shwwfproc) jprc;
if ("2".equals(proc1.stat.getValue())) {
proc = proc1;
break;
}
}
}
Shwwfprocuser user = null;
if (proc != null)
user = CJPAWorkFlow2.checkProc(wf, proc, userid);
JSONObject rst = new JSONObject();
int userInActiveNode = (user != null) ? 1 : 2;
rst.put("userInActiveNode", userInActiveNode);
rst.put("wfinfo", wf.toJsonObj());
return rst.toString();
}
/**
* @return 流程管理界面获取流程
* @throws Exception
*/
@ACOAction(eventname = "getManageWFList", Authentication = true, ispublic = true)
public String getManageWFList() throws Exception {
String poolname = CorUtil.hashMap2Str(CSContext.getParms(), "poolname", "需要参数poolname");
String sqlstr = "SELECT * FROM shwwf WHERE stat=1 ORDER BY wfname, wfid DESC";
HashMap<String, CJPA> jpas = new HashMap<String, CJPA>();
CDBPool pool = DBPools.poolByName(poolname);
CDBConnection con = pool.getCon(this);
try {
JSONArray rst = con.opensql2json_o(sqlstr);
for (int i = 0; i < rst.size(); i++) {
JSONObject j = rst.getJSONObject(i);
CJPA jpa = getjpabyname(jpas, j.getString("clas"));
if (jpa == null)
throw new Exception("根据指定的类【" + j.getString("clas") + "】创建实体错误");
jpa.findByID(con, j.getString("ojcectid"), false);
if (jpa.isEmpty())
j.put("isexistobj", 2);
else
j.put("isexistobj", 1);
}
return rst.toString();
} finally {
con.close();
}
}
/**
* @return
* @throws Exception
*/
@ACOAction(eventname = "getWFLog", Authentication = true, ispublic = true, notes = "获取流程审批日志")
public String getWFLog() throws Exception {
String wfid = CorUtil.hashMap2Str(CSContext.getParms(), "wfid", "需要参数wfid");
String sqlstr = "select * from shwwfproclog where wfid=" + wfid + " ORDER BY actiontime";
return DBPools.defaultPool().opensql2json(sqlstr);
}
private CJPA getjpabyname(HashMap<String, CJPA> jpas, String jpaclass) throws Exception {
CJPA jpa = jpas.get(jpaclass);
if (jpa == null)
jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
else
jpa.clear();
return jpa;
}
}
<file_sep>/src/com/corsair/dbpool/util/CPoolSQLUtil.java
package com.corsair.dbpool.util;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;
/**
* 工具类
*
* @author Administrator
*
*/
public class CPoolSQLUtil {
/**
*
*/
public static int[] numFDType = { Types.BIT, Types.TINYINT, Types.SMALLINT, Types.INTEGER, Types.BIGINT, Types.FLOAT, Types.REAL, Types.DOUBLE,
Types.NUMERIC, Types.DECIMAL, Types.NULL, Types.BOOLEAN, Types.BINARY, Types.ROWID, Types.NCHAR };
public static int[] strFDType = { Types.CHAR, Types.VARCHAR, Types.LONGNVARCHAR, Types.LONGVARCHAR, Types.VARBINARY, Types.LONGVARBINARY, Types.NVARCHAR,
Types.LONGNVARCHAR, Types.SQLXML };
public static int[] dateFDType = { Types.DATE, Types.TIME, Types.TIMESTAMP };
public static int[] bloFDType = { Types.BLOB, Types.CLOB, Types.NCLOB };
public static boolean eInArray(int e, int[] arr) {
for (int i : arr) {
if (i == e) {
return true;
}
}
return false;
}
public static void setSqlPValue(PreparedStatement pstmt, int index, PraperedValue pv) throws SQLException {
if (eInArray(pv.getFieldtype(), dateFDType)) {
java.sql.Timestamp dt = (pv.getValue() == null) ? null : new java.sql.Timestamp(((Date) pv.getValue()).getTime());
pstmt.setTimestamp(index, dt);
} else {
pstmt.setObject(index, pv.getValue());
}
}
}
<file_sep>/src/com/corsair/server/generic/Shwdict.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwdict extends CJPA {
@CFieldinfo(fieldname = "dictid", iskey = true, notnull = true, datetype = Types.FLOAT)
public CField dictid; // ID
@CFieldinfo(fieldname = "dictcode", notnull = true, datetype = Types.VARCHAR)
public CField dictcode; // 编码
@CFieldinfo(fieldname = "dictname", notnull = true, datetype = Types.VARCHAR)
public CField dictname; // 名称
@CFieldinfo(fieldname = "dictvalue", notnull = true, datetype = Types.VARCHAR)
public CField dictvalue; // 词汇值
@CFieldinfo(fieldname = "pid", datetype = Types.FLOAT)
public CField pid; // 父ID
@CFieldinfo(fieldname = "dtype", datetype = Types.INTEGER)
public CField dtype; // 类别0 根 1 分类 2 词汇 3 词汇值
@CFieldinfo(fieldname = "idpath", datetype = Types.VARCHAR)
public CField idpath; // 路径
@CFieldinfo(fieldname = "usable", datetype = Types.FLOAT)
public CField usable; // 可用
@CFieldinfo(fieldname = "creator", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "note", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "language1", datetype = Types.VARCHAR)
public CField language1; //
@CFieldinfo(fieldname = "language2", datetype = Types.VARCHAR)
public CField language2; //
@CFieldinfo(fieldname = "language3", datetype = Types.VARCHAR)
public CField language3; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwdict() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/csession/CToken.java
package com.corsair.server.csession;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.Login;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.generic.Shwusertoken;
import com.corsair.server.util.DesSw;
/**Token管理
* @author Administrator
*
*/
public class CToken {
class TUpdateTokenTimeOut implements Runnable {
HashMap<String, String> parms;
public TUpdateTokenTimeOut(HashMap<String, String> parms) {
this.parms = parms;
}
public void run() {
try {
Object o = parms.get("token");
String token = (o == null) ? null : o.toString();
if (token == null)
return;
String tts = ConstsSw.getAppParm("token_timeout").toString();
int tt = (tts == null) ? 30 : Integer.valueOf(tts);
if (ConstsSw._allow_redis) {
RedisUtil.setfdexpire(token, tt * 60);
} else {
Shwusertoken stoken = new Shwusertoken();
stoken.findByID(token);
if (stoken.isEmpty()) {
return;
} else {
stoken.timeout.setAsLong(System.currentTimeMillis() + tt * 60000);
stoken.save();
}
}
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
// 更新Token time out
public void updateTokenTimeOut(HashMap<String, String> parms) throws Exception {
new Thread(new TUpdateTokenTimeOut(parms)).start();
}
// 根据Tonek重新登录
public static void autoLoginBytoken(HashMap<String, String> parms) throws Exception {
Object o = parms.get("token");
String token = (o == null) ? null : o.toString();
if (token == null)
return;
Shwusertoken stoken = new Shwusertoken();
if (ConstsSw._allow_redis) {
// 根据token重新登录
stoken.token.setValue(token);
stoken.userid.setValue(RedisUtil.gettokefdvalue(token, "userid"));
stoken.username.setValue(RedisUtil.gettokefdvalue(token, "username"));
stoken.sessionid.setValue(RedisUtil.gettokefdvalue(token, "sessionid"));
stoken.starttime.setValue(RedisUtil.gettokefdvalue(token, "starttime"));
stoken.timeout.setValue(RedisUtil.gettokefdvalue(token, "timeout"));
if (stoken.userid.getValue() == null)
return;
(new Login()).dologinweb(stoken.username.getValue(), "", 0.0, stoken);
} else {
stoken.findByID(token);
if (stoken.isEmpty()) {
Logsw.debug("重新登录Token【" + token + "】为空,登录失败");
return;
} else {
if (stoken.timeout.getAsLongDefault(0) < System.currentTimeMillis()) {
System.out.println("timeout:" + stoken.timeout.getAsLongDefault(0) + "-currentTime:" + System.currentTimeMillis());
Logsw.debug("重新登录Token【" + token + "】超时,登录失败");
return;
}
(new Login()).dologinweb(stoken.username.getValue(), "", 0.0, stoken);
}
}
}
// username userpass 二次加密 确保无逗号;
/**
* 根据用户资料创建登录token
*
* @param user
* @param validmit
* 有效时长(分钟) 5:表示 从创建时刻开始之后5分钟内有效
* @return 返回Token字符串
*/
public static String createUToken(Shwuser user, int validmit) {
try {
String uuid = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
String v = String.valueOf(new Date().getTime() + (validmit * 60000));
String userpass = DesSw.EncryStrHex(user.userpass.getValue(), ConstsSw._userkey);
String username = DesSw.EncryStrHex(user.username.getValue(), ConstsSw._userkey);
String utstr = uuid + "," + username + "," + userpass + "," + v;//
return DesSw.EncryStrHex(utstr, ConstsSw._userkey);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @param utstr
* 根据token登录
* @throws Exception
*/
public static void autoLoginByUtoken(String utstr) throws Exception {
String utstr1 = DesSw.DESryStrHex(utstr, ConstsSw._userkey);
// System.out.println("utstr1:" + utstr1);
String[] strs = utstr1.split(",");
String uuid = strs[0];
String username = DesSw.DESryStrHex(strs[1], ConstsSw._userkey);
String userpass = DesSw.DESryStrHex(strs[2], ConstsSw._userkey);
long v = Long.valueOf(strs[3]);
// if (v < new Date().getTime())
// throw new Exception("UserToken已经超时,需要重新登录");
new Login().dologinweb(username, userpass, 0.0, null);
}
// 有效期 validmit 分钟 为0时候使用系统参数token_timeout;没设置参数 默认30分钟
public static Shwusertoken createToken(Shwuser user, Shwusertoken atoken, String sessionid, int validmit) throws Exception {
Object spttout = ConstsSw.getAppParm("token_timeout");
int timeout = (validmit == 0) ? ((spttout == null) ? 30 : Integer.valueOf(spttout.toString())) : validmit;
return createToken(atoken, user.userid.getValue(), user.username.getValue(), sessionid, timeout);
}
public static Shwusertoken createToken(Shwusertoken atoken, String userid, String username, String sessionid, int timeout) throws Exception {
Shwusertoken token = (atoken == null) ? new Shwusertoken() : atoken;
// 是否删除该登录用户其它TOKEN?
token.userid.setValue(userid);
token.username.setValue(username);
token.sessionid.setValue(sessionid);
if (token.starttime.isEmpty())
token.starttime.setAsLong(System.currentTimeMillis());
token.timeout.setAsLong(System.currentTimeMillis() + timeout * 60000);
if (token.token.isEmpty()) {
String uuid = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
token.token.setValue(uuid);
}
if (ConstsSw._allow_redis) {
RedisUtil.settokenfdvalue(token.token.getValue(), "userid", token.userid.getValue());
RedisUtil.settokenfdvalue(token.token.getValue(), "username", token.username.getValue());
RedisUtil.settokenfdvalue(token.token.getValue(), "sessionid", token.sessionid.getValue());
RedisUtil.settokenfdvalue(token.token.getValue(), "starttime", token.starttime.getValue());
RedisUtil.settokenfdvalue(token.token.getValue(), "timeout", token.timeout.getValue());
RedisUtil.setfdexpire(token.token.getValue(), timeout * 60);
} else {
token.save();
}
return token;
}
}
<file_sep>/src/com/corsair/cjpa/util/LinkFieldItem.java
package com.corsair.cjpa.util;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 关联字段项
*
* @author Administrator
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface LinkFieldItem {
String mfield();
String lfield();
}
<file_sep>/src/com/hr/timer/TaskCalcDepartDayReport.java
package com.hr.timer;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.generic.Shworg;
import com.hr.attd.entity.Hrkq_bckqrst;
import com.hr.attd.entity.Hrkq_calc;
import com.hr.msg.entity.Hr_kq_day_report;
import com.hr.msg.entity.Hr_kq_depart_day_report;
import com.hr.util.DateUtil;
import com.hr.util.HRUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TaskCalcDepartDayReport extends TimerTask {
/*
* 查询有效部门组织
*/
private List<Shworg> FindOrg(String idpath) throws Exception{
List<Shworg>orgList=new ArrayList<Shworg>();
String sqlstr="";
if(idpath.equals("")){
sqlstr = "select code,extorgname,idpath from shworg where usable=1";
}else{
sqlstr = "select code,extorgname,idpath from shworg where usable=1 and idpath like '"+idpath+"%'";
}
Hr_kq_day_report report=new Hr_kq_day_report();
List<HashMap<String, String>> reportList = report.pool.openSql2List(sqlstr);
for(HashMap<String, String>entity :reportList)
{
Shworg org=new Shworg();
org.code.setValue(entity.get("code"));
org.extorgname.setValue(entity.get("extorgname"));
org.idpath.setValue(entity.get("idpath"));
orgList.add(org);
}
return orgList;
}
/*
*保存结果
*/
private void CalcReport(List<Shworg>orgList,String dqdate) throws Exception{
CJPALineData<Hr_kq_depart_day_report> saveReportList = new CJPALineData<Hr_kq_depart_day_report>(Hr_kq_depart_day_report.class);
for(Shworg org : orgList ){
Logsw.dblog(org.extorgname.getValue());
Hr_kq_depart_day_report saveReport= new Hr_kq_depart_day_report();
String reportOrgSql="select a.employee_code,a.empstatid,a.orgname,noclock,emnature,hiredday,t.cq,t2.qj,t3.cc,t4.tx from hr_employee a"+
" LEFT JOIN (select b.empno, '1' as cq from hrkq_swcdlst b WHERE DATE_FORMAT(b.skdate,'%Y-%m-%d')='"+dqdate+"' GROUP BY b.empno) as t on t.empno=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as qj from hrkq_holidayapp b WHERE (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeed>='"+dqdate+"') or (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeedtrue>='"+dqdate+"') and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t2 on t2.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as cc from hrkq_business_trip b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t3 on t3.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as tx from hrkq_wkoff b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t4 on t4.employee_code=a.employee_code"+
" where a.idpath like '"+org.idpath.getValue()+"%' and a.sp_name<>'项目实习生' and a.empstatid<>'12' and a.empstatid<>'13' and a.empstatid<>'0' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.hiredday<='"+dqdate+"'";
//Hr_kq_depart_day_report report=new Hr_kq_depart_day_report();
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(reportOrgSql);
int zz=reportList.size();
int cc=0;
int tx=0;
int qj=0;
int mdk=0;
int cq=0;
int tcwdk=0;//脱产无打卡
int ftcwdk=0;//非脱产无打卡
int rzdtwdk=0;//当天入职无打卡
for(HashMap<String, String>entity :reportList)
{
String scc="";
String stx="";
String sqj="";
String scq="";
if(entity.get("cc")!=null){
scc=entity.get("cc");
}
if(entity.get("tx")!=null){
stx=entity.get("tx");
}
if(entity.get("qj")!=null){
sqj=entity.get("qj");
}
if(entity.get("cq")!=null){
scq=entity.get("cq");
}
if(scc.equals("1")){
cc++;
}else if(stx.equals("1")){
tx++;
}else if(scq.equals("1")){
cq++;
}else if(sqj.equals("1")){
qj++;
}else{
//缺勤
if(entity.get("emnature").equals("脱产") && entity.get("noclock").equals("2")){
tcwdk++;
}else if(entity.get("emnature").equals("非脱产")&& entity.get("noclock").equals("2")){
ftcwdk++;
}
//统计当天入职无打卡
//System.out.print(entity.get("hiredday"));
String hiredday=Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByyyyy_mm_dd(entity.get("hiredday")));
if(hiredday.equals(dqdate))
{
rzdtwdk++;
}
}
if(entity.get("noclock").equals("1")){
mdk++;
cq++;
}
}
String ljSql="select count(1) as lj from hr_employee a where a.idpath like '"+org.idpath.getValue()+"%' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.ljdate='"+dqdate+"'";
List<HashMap<String, String>> ljlist = HRUtil.getReadPool().openSql2List(ljSql);
HashMap<String, String>entity=ljlist.get(0);
String dzmSql="select count(1) as dzm from hr_employee a where a.idpath like '"+org.idpath.getValue()+"%' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.empstatid='0' and a.hiredday<='"+dqdate+"'";
List<HashMap<String, String>> dzmlist = HRUtil.getReadPool().openSql2List(dzmSql);
HashMap<String, String>dzmentity=dzmlist.get(0);
saveReport.lj.setValue(Integer.valueOf(entity.get("lj")));
saveReport.dzm.setValue(Integer.valueOf(dzmentity.get("dzm")));
saveReport.orgcode.setValue(org.code.getValue());
saveReport.orgname.setValue(org.extorgname.getValue());
saveReport.cc.setValue(cc);
saveReport.tx.setValue(tx);
saveReport.qj.setValue(qj);
saveReport.mdk.setValue(mdk);
saveReport.cq.setValue(cq);
saveReport.tcwdk.setValue(tcwdk);
saveReport.ftcwdk.setValue(ftcwdk);
saveReport.rzdtwdk.setValue(rzdtwdk);
saveReport.zz.setValue(zz);
saveReport.date.setValue(dqdate);
saveReport.wdk.setValue(tcwdk+ftcwdk+rzdtwdk);
if(zz>0){
int dzm=Integer.valueOf(dzmentity.get("dzm")) ;
double sum=cq+cc+tx;
sum=sum/(zz+dzm)*100;
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if(sum>100){
saveReport.cqdcl.setValue("100%");
}else{
saveReport.cqdcl.setValue(sum+"%");
}
}else{
saveReport.cqdcl.setValue("0%");
}
if(zz>0){
int dzm=Integer.valueOf(dzmentity.get("dzm")) ;
double sum=cq+cc+tx;
sum=sum/(zz)*100;
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if(sum>100){
saveReport.cqdcl2.setValue("100%");
}else{
saveReport.cqdcl2.setValue(sum+"%");
}
}else{
saveReport.cqdcl2.setValue("0%");
}
//删除旧记录
String delSql="delete from Hr_kq_depart_day_report where date='"+dqdate+"' and orgcode='"+org.code.getValue()+"'";
int delNum=saveReport.pool.execsql(delSql);
saveReportList.add(saveReport);
if(saveReportList.size()==100){
//每1000条记录保存一次
saveReportList.saveBatchSimple();
saveReportList.clear();
}
}
if(saveReportList.size()>0){
saveReportList.saveBatchSimple();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int minute=calendar.get(Calendar.MINUTE);
int hour=calendar.get(Calendar.HOUR_OF_DAY);
//if(hour==5 && minute==15){
System.out.print("TaskCalcDepartDayReport,hour"+hour+":min"+minute);
if(hour==5 && minute==15){
Logsw.dblog("部门考勤运算开始");
CalcReport(FindOrg(""),DateUtil.getYerDate());
Logsw.dblog("部门考勤运算结束");
}
if(minute==59){
Reclac();
}
}catch(Exception e){
Logsw.dblog("部门考勤运算结束:"+e.toString());
}
}
/*
* 重新运算部门考勤统计
*/
private void Reclac() throws Exception{
//查询重新运算的任务
String clacSql="select * from hr_depart_kq_reclac where status='0'";
List<HashMap<String, String>> list = HRUtil.getReadPool().openSql2List(clacSql);
for(HashMap<String, String>entity :list)
{
String id=entity.get("id");
String idpath=entity.get("idpath");
String reclacDate=entity.get("reclac_date").replace(" 00:00:00", "");
//更新执行状态
String updateSql="update hr_depart_kq_reclac set status='1' where id="+id;
Hr_kq_depart_day_report report=new Hr_kq_depart_day_report();
report.pool.execsql(updateSql);
CalcReport(FindOrg(idpath),reclacDate);
}
}
}
<file_sep>/WebContent/webapp/js/common/jsonbanding.js
/**
* Created by shangwen on 2015-06-30.
*/
function getInputType(el) {
var cls = $(el).attr("class");
if ((cls.indexOf("easyui-datetimebox") >= 0) || (cls.indexOf("easyui-datebox") >= 0)) {
return 1;
} else if (cls.indexOf("easyui-combobox") >= 0) {
return 2;//combobox
} else if (cls.indexOf("easyui-combotree") >= 0) {
return 3;//combotree
} else if ((cls.indexOf("easyui-textbox") >= 0) || (cls.indexOf("easyui-validatebox") >= 0) || (cls.indexOf("easyui-numberbox") >= 0)) {
return 5;
} else if (cls.indexOf("corsair-label") >= 0) {
return 11;
}
}
function getEasuiFuncName(clsname) {
if (clsname == "easyui-datetimebox")
return "datetimebox";
else if (clsname == "easyui-datebox")
return "datebox";
else if (clsname == "easyui-combobox")
return "combobox";
else if (clsname == "easyui-combotree")
return "combotree";
else if (clsname == "easyui-textbox")
return "textbox";
else if (clsname == "easyui-validatebox")
return "validatebox";
else if (clsname == "easyui-numberbox")
return "numberbox";
}
function getInputLabel(lables, fdname) {
for (var i = 0; i < lables.length; i++) {
//var co = $.c_parseOptions($(lables[i]));
var co = lables[i].cop;
if (co.fdname == fdname) {
var lb = $(lables[i]);
return lb;
}
}
return undefined;
}
function TJSONBandingFrm() {
this.getInputArray = function (filter) {
var rst = {els_all: [], els_readonly: [], els_lables: []};
$(filter).find("input[cjoptions],select[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
this.cop = co;
this.et = getInputType(this);
if (co.readonly) {
rst.els_readonly.push(this);
$(this).attr("readonly", "readonly");
//$(this).css("background-color", "#F5F5F5");
}
rst.els_all.push(this);
});
$(filter).find("td[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
this.cop = co;
rst.els_lables.push(this);
});
return rst;
};
this.cparser = cparser;
function cparser(els_all) {
for (var i = 0; i < els_all.length; i++) {
var e = els_all[i];
var co = e.co;
if (co.easyui_class) {
$(e)[co.easyui_class](co);
}
}
}
this.acceptAllGrid = function (filter, jsondata) {
$(filter).find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = jsondata[id];
if ((tbdata) && ($(this).datagrid)) {
$(this).datagrid("acceptChanges");
}
});
};
this.clearMainData = function (els_all, grids) {
this.clearFrmData(els_all);
for (var i = 0; i < grids.length; i++) {
$C.grid.clearData(grids[i]);
}
};
this.setAllInputReadOnly = setAllInputReadOnly;
function setAllInputReadOnly(els_all, readonly) {
for (var i = 0; i < els_all.length; i++) {
setInputReadOnly(els_all[i], readonly);
}
}
this.setInputReadOnly = setInputReadOnly;
function setInputReadOnly(copInput, readonly) {
var tp = copInput.et;
var input = $(copInput);
if (tp == 1)
input.datetimebox({readonly: readonly});
if ((tp == 2) || (tp == 3))
input.combobox({readonly: readonly});
if (tp == 5)
input.textbox({readonly: readonly});
if (readonly) {
input.next().find("input:first").css("background-color", "#E8EEFA");
input.next().find("textarea:first").css("background-color", "#E8EEFA");
} else {
input.next().find("input:first").css("background-color", "#FFFFFF");
input.next().find("textarea:first").css("background-color", "#FFFFFF");
}
}
this.clearFrmData = function (els_all) {
for (var i = 0; i < els_all.length; i++) {
$(els_all[i]).textbox('setValue', "");
}
};
this.fromJsonData = function (els_all, jsondata) {
for (var i = 0; i < els_all.length; i++) {
var co = els_all[i].cop;
var v = jsondata[co.fdname];
setInputValue(els_all[i], v);
}
return true;
};
this.setInputValue = setInputValue;
function setInputValue(copInput, v) {
var co = copInput.cop;
var et = copInput.et;
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL") || (v == "")) {
$(copInput).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(copInput).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
case 3:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(copInput).combotree('setValues', "");
else {
$(copInput).combotree('setValues', v);
}
break;
}
case 11:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(copInput).attr("value", "");
else
$(copInput).attr("value", getDisplayValue(co, v));
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(copInput).textbox('setValue', "");
else {
var iscom = false;
try {
var opt = $(this).textbox("options");
iscom = (("valueField" in opt) && ("textField" in opt) && ("data" in opt));
} catch (e) {
//alert(e.message);
}
if ((co.dicgpid != undefined) || (co.comidx != undefined) || iscom) {
$(copInput).combobox('select', v);
} else
$(copInput).textbox('setValue', v);
}
break;
}
}
}
function gettreeDisplayValue(jsondata, valueField, textField, v) {
for (var i = 0; i < jsondata.length; i++) {
var row = jsondata[i];
if (row[valueField] == v)
return row[textField];
if (row.children) {
var dv = gettreeDisplayValue(row.children, valueField, textField, v);
if (dv) return dv;
}
}
}
function getDisplayValue(co, v) {
if (co) {
if (co.comidx) {
var conurl = eval("comUrl_" + co.comidx);
var jsondata = conurl.jsondata;
var type = conurl.type;
var valueField = conurl.valueField;
var textField = conurl.textField;
if (type == "combobox") {
for (var i = 0; i < jsondata.length; i++) {
var row = jsondata[i];
if (row[valueField] == v)
return row[textField];
}
}
if (type == "combotree") {
return gettreeDisplayValue(jsondata, valueField, textField, v);
}
} else if (co.formatter && (typeof co.formatter == 'function')) {
return co.formatter(v);
} else
return v;
} else
return v;
}
this.gridFromJSONdata = function (filter, jsondata) {
$(filter).find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = jsondata[id];
//alert("id:" + id + ":" + JSON.stringify(tbdata));
if ($(this).datagrid) {
if (tbdata != undefined) {
//if (tbdata.length > 0) 如果为空 也需要载入 数据 以载入数据和Grid的关联关系,否则空数据无法保存
$(this).datagrid("loadData", tbdata);
//else
// $(this).datagrid("loadData", []);
}
}
});
};
this.getInputValue = getInputValue;
function getInputValue(copInput) {
var co = copInput.cop;
var et = copInput.et;
switch (et) {
case 2:
return $(copInput).combobox("getValues");
case 3:
{
var ov = $(copInput).combotree("getValues");
if (ov)
return ov.toString();
else
return "";
}
case 11:
{
//获取显示值
}
default :
{
return $(copInput).textbox("getValue");
}
}
}
this.toJsonData = function (els_all, jsondata, isnew) {
for (var i = 0; i < els_all.length; i++) {
var input = els_all[i];
var co = input.cop;
jsondata[co.fdname] = getInputValue(input);
}
if (!isnew)
c_setJsonDefaultValue(els_all, jsondata, false);
return jsondata;
};
function c_setJsonDefaultValue(els_all, jsondata, isnew) {
var ctimes = ["createtime", "create_time"];
var utimes = ["updatetime", "update_time"];
var ctors = ["creator"];
var utors = ["updator"];
var ent = "entid";
var std = "stat";
var usb = "usable";
var vsb = "isvisible";
for (var i = 0; i < els_all.length; i++) {
var fdn = $.c_parseOptions($(els_all[i])).fdname;
if (isnew) {
if (ctimes.indexOf(fdn) >= 0) jsondata[fdn] = (new Date()).format("yyyy-MM-dd hh:mm:ss");
if (ctors.indexOf(fdn) >= 0) jsondata[fdn] = $C.UserInfo.username();
if (fdn == ent) jsondata[fdn] = $C.UserInfo.entid();
if (fdn == std) jsondata[fdn] = 1;
if (fdn == usb) jsondata[fdn] = 1;
if (fdn == vsb) jsondata[fdn] = 1;
}
else {
if (utimes.indexOf(fdn) >= 0) jsondata[fdn] = (new Date()).format("yyyy-MM-dd hh:mm:ss");
if (utors.indexOf(fdn) >= 0) jsondata[fdn] = $C.UserInfo.username();
}
}
}
this.checkNotNull = function (els_all, lables, jsondata, gdLinesNames, columnss) {
var msg = "";
for (var i = 0; i < els_all.length; i++) {
//var co = $.c_parseOptions($(els_all[i]));
var co = els_all[i].cop;
var et = getInputType(els_all[i]);
var v = jsondata[co.fdname];
var rdo = Boolean(co.readonly);
if ((co.required) && (!rdo) && ((v == null) || (!v) || (v == ""))) {
msg = msg + "<" + getInputLabel(lables, co.fdname).html() + "><br/>";
}
}
var lmsgs = [];
if (gdLinesNames && columnss) {
for (var i = 0; i < gdLinesNames.length; i++) {
var gln = gdLinesNames[i];
var columns = columnss[i];
var rows = jsondata[gln];
for (var j = 0; j < rows.length; j++) {
var row = rows[j];
for (var k = 0; k < columns.length; k++) {
var col = columns[k];
if ($.isArray(col)) {
for (m = 0; m < col.length; m++) {
var coll = col[m];
checkv(lmsgs, row, coll);
}
} else if (col.required) {
checkv(lmsgs, row, col);
}
}
}
}
}
if (lmsgs.length != 0) {
msg = msg + "明细行:<br>";
for (var i = 0; i < lmsgs.length; i++) {
msg = msg + lmsgs[i] + "<br>";
}
}
if (msg == "") return true;
else {
$.messager.alert('错误', msg + '不允许为空!', 'error');
return false;
}
function checkv(lmsgs, row, col) {
if (!col)return;
var v = row[col.field];
if ((col.required) && ((v == null) || (v == undefined) || (v.length == 0)))
addV(lmsgs, col.title);
}
function addV(lmsgs, v) {
for (var i = 0; i < lmsgs.length; i++) {
if (lmsgs[i] == v)
return;
}
lmsgs.push(v);
}
};
}<file_sep>/src/com/corsair/server/util/CExcelField.java
package com.corsair.server.util;
/*
* excel导入字段定义
* */
public class CExcelField {
private String caption;
private String fdname;
private boolean notnull = false;
private int col = -1;
public CExcelField(String caption, String fdname) {
this.caption = caption;
this.fdname = fdname;
}
public CExcelField(String caption, String fdname, boolean notnull) {
this.caption = caption;
this.fdname = fdname;
this.notnull = notnull;
}
public String getCaption() {
return caption;
}
public String getFdname() {
return fdname;
}
public boolean isNotnull() {
return notnull;
}
public int getCol() {
return col;
}
public void setCaption(String caption) {
this.caption = caption;
}
public void setFdname(String fdname) {
this.fdname = fdname;
}
public void setNotnull(boolean notnull) {
this.notnull = notnull;
}
public void setCol(int col) {
this.col = col;
}
}
<file_sep>/src/com/hr/.svn/pristine/cf/cfb513e8a487fce83a0c74011d0a937d0ed19be6.svn-base
package com.hr.util.wx;
import com.hr.msg.entity.Wx_msg_send;
import net.sf.json.JSONObject;
public class SendMsgUtil {
/**
* 通知发送(文字)
* @param touser 接受人,多人时用"|"分隔
* @param content 消息内容
* @return
*/
public static String sendText(String touser,String content){
String requestUrl =WeixinUtil.send_msg_url.replace("ACCESS_TOKEN", WeixinUtil.getAccessToken().getToken());
String msgType="text";
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"touser\":" + "\"" + touser + "\",");
//sb.append("\"toparty\":" + "\"" + toparty + "\",");
//sb.append("\"totag\":" + "\"" + totag + "\",");
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"agentid\":" + "\"" + WeixinUtil.agentid + "\",");
sb.append("\"text\":" + "{");
sb.append("\"content\":" + "\"" + content + "\",");
sb.append("}");
JSONObject result= WeixinUtil.HttpRequest(requestUrl, "POST", sb.toString());
if(result.get("errcode").toString().equals("42001")){
WeixinUtil.accessToken=null;
sendText(touser,content);
}
return result.toString();
}
/**
* 通知发送(图文)
* @param touser 接受人,多人时用"|"分隔
* @param title 消息标题
* @param description 消息内容
* @param url 点击时跳转的地址
* @return
*/
public static String sendNews(String touser,String title,String description,String url){
String requestUrl =WeixinUtil.send_msg_url.replace("ACCESS_TOKEN", WeixinUtil.getAccessToken().getToken());
String msgType="news";
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\"touser\":" + "\"" + touser + "\",");
//sb.append("\"toparty\":" + "\"" + toparty + "\",");
//sb.append("\"totag\":" + "\"" + totag + "\",");
sb.append("\"msgtype\":" + "\"" + msgType + "\",");
sb.append("\"agentid\":" + "\"" + WeixinUtil.agentid + "\",");
sb.append("\"news\":" + "{");
sb.append("\"articles\":" + "[");
sb.append("{");
sb.append("\"title\":" + "\"" + title + "\",");
sb.append("\"description\":" + "\"" + description + "\",");
sb.append("\"url\":" + "\"" + url + "\",");
//sb.append("\"picurl\":" + "\"" + picurl + "\"");
sb.append("}");
sb.append("]");
sb.append("}");
JSONObject result= WeixinUtil.HttpRequest(requestUrl, "POST", sb.toString());
return result.toString();
}
}
<file_sep>/src/com/corsair/cjpa/util/CFieldinfo.java
package com.corsair.cjpa.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.JPAControllerBase;
/**字段注解
* @author Administrator
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CFieldinfo {
boolean iskey() default false;
boolean notnull() default false;
boolean autoinc() default false;
int datetype() default Types.VARCHAR;
int dicid() default 0;
String dicclass() default "";// 类似于字典 但比字典更复杂的处理
int codeid() default 0;
String fieldname();
String caption() default "";
String save_dsfunc() default "";// 数据来源 通过类函数获取数据来源
String defvalue() default "";// 默认值
int precision() default 0;//数据长度
int scale() default 0;//小数位数
// Class<?> outkey() default CField.class;// 外键 插入时候 保证 外键对应的数据存在;
CkItem[] dcfds() default {};// 删除时候 检查约束性
}
<file_sep>/src/com/corsair/server/servlet/CRDispatcherServlet.java
package com.corsair.server.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.CSContext.ActionType;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.Login;
import com.corsair.server.base.Loginex;
import com.corsair.server.csession.CSession;
import com.corsair.server.csession.CToken;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.retention.COAcitonItem;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DesSw;
import com.corsair.server.util.TerminalType;
import net.sf.json.JSONObject;
public class CRDispatcherServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public enum ReqType {
rget, rpost;
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CSContext.setservlet(this);
CSContext.setResponse(resp);
CSContext.setactiontype(ActionType.actGet);
req.getSession(true);
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String rst = null;
try {
rst = callCOAction(req, resp, getCOActionkey(req), ReqType.rget);
} catch (Exception e) {
rst = CJSON.getErrJson(getClientErrmsg(e));
// resp.setStatus(500, e.toString());
Logsw.error(getStackTrace(e));
}
if (rst != null) {
// System.out.println("rst:" + rst);
PrintWriter out = resp.getWriter();
out.print(rst);
out.flush();
}
CSContext.removeResponse();
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CSContext.setservlet(this);
CSContext.setResponse(resp);
CSContext.setactiontype(ActionType.actPost);
req.getSession(true);
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String rst = null;
try {
rst = callCOAction(req, resp, getCOActionkey(req), ReqType.rpost);
} catch (Exception e) {
rst = CJSON.getErrJson(getClientErrmsg(e));
// resp.setStatus(500, e.toString());
Logsw.error(getStackTrace(e));
}
if (rst != null) {
// System.out.println("rst:" + rst);
PrintWriter out = resp.getWriter();
out.print(rst);
out.flush();
}
CSContext.removeResponse();
}
private String getCOActionkey(HttpServletRequest req) {
String s = req.getServletPath();
String coname = s.substring(s.indexOf("/") + 1, s.lastIndexOf("."));
return coname.replace("/", ".");
}
private String callCOAction(HttpServletRequest req, HttpServletResponse resp, String coname, ReqType rtype) throws Exception {
String postdata = null;
HashMap<String, String> parms = ServletUtil.parseGetParms(req); // for
// get
if (!ServletFileUpload.isMultipartContent(req)) {// 不是文件类型,解析出来
// System.out.print("不是上传文件");
postdata = ServletUtil.getPostData(req); // for post
CSContext.setPostdata(postdata);
CSContext.setIsMultipartContent(false);
} else {
// System.out.print("是上传文件");
CSContext.setIsMultipartContent(true);
}
CSContext.setParms(parms);
COAcitonItem actionitem = (COAcitonItem) ConstsSw._allCoClassName.get(coname);
if (actionitem == null) {
throw new Exception("没有找到注册的CO:" + coname);
}
printdebugmsg(actionitem, rtype, parms, postdata);
AuthChecked(actionitem, req, parms);// 权限检查
Class<?> coclass = Class.forName(actionitem.getClassname());
Method method = coclass.getMethod(actionitem.getMethodname(), new Class[] {});
if (method == null)
throw new Exception("没有找到满足条件的方法" + actionitem.getClassname() + "." + actionitem.getMethodname());
Object co = coclass.newInstance();
if (co == null)
throw new Exception("无法实例化CO类【" + actionitem.getClassname() + "】");
Object obj = method.invoke(co);
if (obj == null) {
return null;
} else
return obj.toString();
}
private void AuthChecked(COAcitonItem actionitem, HttpServletRequest req, HashMap<String, String> parms) throws Exception {
ACOAction cce = actionitem.getCce();
String trueip = ServletUtil.getIpAddr(req);
if (cce.isIntranet()) {// 内网
if ((trueip == null) || (trueip.isEmpty()))
throw new Exception("获取客户端IP错误");
if (!CorUtil.isInner(trueip))
throw new Exception("只允许内网执行:" + actionitem.getClassname() + "." + actionitem.getMethodname());
}
HttpSession session = req.getSession();
if (session.getAttribute("clientip") == null)
CSession.putvalue(session.getId(), "clientip", trueip);
if (!cce.Authentication())// 不需要登录
return;
if (!CSContext.logined()) {
autoLogin(req, parms);
} else {
// if (ConstsSw.getAppParmBoolean("websocket")) {
// CWebSessionSocket ssocket = CSContext.wbsktpool.getCreateSSocket(req.getSession().getId());
// if (ssocket != null)
// ssocket.setUserid(CSContext.getUserID());
// }
}
new CToken().updateTokenTimeOut(parms);
if (cce.Authentication()) {
if (!CSContext.logined())
throw new Exception("未登录用户不允许执行:" + actionitem.getClassname() + "." + actionitem.getMethodname());
if (!"1".equalsIgnoreCase(CSContext.getUserParmValue("usertype")))
CoAuthChecked(actionitem);
}
}
private void CoAuthChecked(COAcitonItem actionitem) throws Exception {
ACOAction cce = actionitem.getCce();
if (cce.ispublic())
return;
String cokey = actionitem.getKey();
String sqlstr = "SELECT mc.coname FROM `shwroleuser` ru,`shwrolemenu` rm,`shwmenuco` mc"
+ " WHERE ru.`roleid`=rm.`roleid` AND rm.`menuid`=mc.`menuid` AND ru.`userid`=" + CSContext.getUserID();
List<HashMap<String, String>> cos = DBPools.defaultPool().openSql2List(sqlstr);
for (HashMap<String, String> co : cos) {
if (cokey.equalsIgnoreCase(co.get("coname").toString()))
return;
}
throw new Exception("当前登录用户没有CO【" + cokey + "】权限");
}
private void printdebugmsg(COAcitonItem actionitem, ReqType rtype, HashMap<String, String> parms, String postdata) {
if (ConstsSw.getAppParmBoolean("Debug_Mode")) {
String dbugmsg = null;
if (rtype == ReqType.rget) {
String str = "\n";
if (parms != null)
for (String key : parms.keySet()) {
str = str + key + ":" + parms.get(key) + "\n";
}
dbugmsg = "CO get调用:" + actionitem.getClassname() + "." + actionitem.getMethodname() + " Parms:" + str;
}
if (rtype == ReqType.rpost) {
String str = "\n";
if (parms != null)
for (String key : parms.keySet()) {
str = str + key + ":" + parms.get(key) + "\n";
}
dbugmsg = "CO post调用:" + actionitem.getClassname() + "." + actionitem.getMethodname() + " Parms:" + str + " PostData:" + postdata;
}
Logsw.debug(dbugmsg);
}
}
public String getStackTrace(Throwable aThrowable) {
if (aThrowable == null) {
return "null";
}
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
public String getClientErrmsg(Exception e) {
String s = null;
if (e.getCause() != null)
s = e.getCause().getMessage();
else
s = e.getMessage();
if (s == null)
s = "null pointer error";
return s;
}
/**
* 新的登录方式
*
* @param request
* @throws Exception
*/
private void autoLoginByHttpHeadNew(HttpServletRequest request) throws Exception {
String al = ConstsSw.geAppParmStr("AutoLogin");
if ((al == null) || (al.equalsIgnoreCase("none")))
return;
String lgstr = request.getHeader("_lgstr");
if ((lgstr != null) && (!lgstr.isEmpty())) {
lgstr = URLDecoder.decode(lgstr, "utf-8");
JSONObject jo = JSONObject.fromObject(lgstr);
// System.out.println("jo:" + jo.toString());
String username = CorUtil.getJSONValue(jo, "username", "需要参数username");
String noncestr = CorUtil.getJSONValue(jo, "noncestr", "需要参数noncestr");
String timestr = CorUtil.getJSONValue(jo, "timestr", "需要参数timestr");
String md5sign = CorUtil.getJSONValue(jo, "md5sign", "需要参数md5sign");
String token = Loginex.dologinweb(username, noncestr, timestr, md5sign);
}
}
/**
* 旧的方式
*
* @param request
* @throws Exception
*/
private void autoLoginByHttpHead(HttpServletRequest request) throws Exception {
String al = ConstsSw.geAppParmStr("AutoLogin");
if ((al == null) || (al.equalsIgnoreCase("none")))
return;
if (!CSContext.logined()) {
String uname = request.getHeader("uname");
String pwd = request.getHeader("pwd");
if (((uname == null) || (uname.isEmpty()) || (pwd == null) || (pwd.isEmpty())) && request.getCookies() != null) {
for (Cookie ck : request.getCookies()) {
if ("uname".equalsIgnoreCase(ck.getName()))
uname = ck.getValue();
if ("pwd".equalsIgnoreCase(ck.getName()))
pwd = ck.getValue();
}
}
if ((uname == null) || (uname.isEmpty()) || (pwd == null) || (pwd.isEmpty())) {
// Logsw.debug("设置为自动登录,但是请求头并未包含登录信息,无法登录");
return;
}
uname = java.net.URLDecoder.decode(uname, "utf-8");
pwd = DesSw.EncryStrHex(pwd, ConstsSw._userkey);
if (al.equalsIgnoreCase("AllFlatform")) {// 所有平台自动登录
(new Login()).dologinweb(uname, pwd, 0.0, null);
} else {
if ((TerminalType.getTermKink(CSContext.getTermType()) == TerminalType.TermKink.desktop) && (al.equalsIgnoreCase("Desktop"))) {// 桌面端自动登录
(new Login()).dologinweb(uname, pwd, 0.0, null);
return;
}
if ((TerminalType.getTermKink(CSContext.getTermType()) == TerminalType.TermKink.mobile) && (al.equalsIgnoreCase("Mobile"))) {// 移动端自动登录
(new Login()).dologinweb(uname, pwd, 0.0, null);
return;
}
}
}
}
private void autoLogin(HttpServletRequest request, HashMap<String, String> parms) throws Exception {
CToken.autoLoginBytoken(parms);
if (CSContext.logined())
return;
String utoken = parms.get("utoken");
if ((utoken != null) && (!utoken.isEmpty())) {
CToken.autoLoginByUtoken(utoken);
}
if (CSContext.logined())
return;
autoLoginByHttpHeadNew(request);
if (CSContext.logined())
return;
autoLoginByHttpHead(request);
if (CSContext.logined())
return;
try {
if (CSContext.getPostdata() != null) {
HashMap<String, String> pprams = CSContext.parPostDataParms();
String lgstr = pprams.get("_lgstr");
// System.out.println("lgstr:" + lgstr);
if ((lgstr != null) && (!lgstr.isEmpty())) {
JSONObject jo = JSONObject.fromObject(lgstr);
// System.out.println("jo:" + jo.toString());
String username = CorUtil.getJSONValue(jo, "username", "需要参数username");
String noncestr = CorUtil.getJSONValue(jo, "noncestr", "需要参数noncestr");
String timestr = CorUtil.getJSONValue(jo, "timestr", "需要参数timestr");
String md5sign = CorUtil.getJSONValue(jo, "md5sign", "需要参数md5sign");
String token = Loginex.dologinweb(username, noncestr, timestr, md5sign);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/server/htmlex/CHtmlTemplatEx.java
package com.corsair.server.htmlex;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.html.CcomUrl;
import com.corsair.server.html.htmlUtil;
public class CHtmlTemplatEx {
public static void buildHtml(String srcfname) throws Exception {
Document srcDoc = meargHtml(srcfname);
List<CcomUrl> curls = chgHtmlWFMLATT(srcDoc);
CHtmlBuild.ParHtmlInput(srcDoc, curls);
String newhtml = srcDoc.html();
newhtml = newhtml.replace("<", "<");
newhtml = newhtml.replace(">", ">");
newhtml = newhtml.replace("&", "&");
try {
String outfname = "D:\\MyWorks2\\zy\\webservice\\tomcat71\\webapps\\dlhr\\webapp\\hr_perm\\aa.html";
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outfname), "UTF-8");
out.write(newhtml);
out.flush();
out.close();
} catch (Exception e) {
}
}
/**
* @param tempfname
* @param srcfname
* @throws Exception
*/
public static Document meargHtml(String srcfname) throws Exception {
// 文件分隔符替换
// System.out.println("11111111111111:" + srcfname);
File srcf = new File(srcfname);
Document srcDoc = Jsoup.parse(srcf, "UTF-8");
Element srcbody = srcDoc.getElementsByTag("body").get(0);
Element srchtml = srcDoc.getElementsByTag("html").get(0);
String tpfname = "D:\\MyWorks2\\zy\\webservice\\tomcat71\\webapps\\dlhr\\webapp\\templet\\default\\main_line_pop.html";
// gettemplatefname(srchtml.attr("template"));//
if (tpfname != null) {
File tmpFile = new File(tpfname);
if (!tmpFile.exists() || !tmpFile.isFile()) {
throw new Exception("模板文件【" + tpfname + "】不存在,或不是文件");
}
Document tmpDoc = Jsoup.parse(tmpFile, "UTF-8");
Element divNode = tmpDoc.getElementById("main_form_div_id");
if (divNode != null) {
Element et = srcbody.getElementById("maindata_id");
if (et == null) {
throw new Exception("HTML源文件【" + srcf.getName() + "】中ID为【maindata_id】的DOM不存在");
}
divNode.html(et.toString());
}
srcbody.getElementById("maindata_id").remove();
srcbody.append(tmpDoc.getElementsByTag("body").get(0).html());
} else {
}
return srcDoc;
}
private static String getOutFileName(String srcfname, String simplesrcfname, String wkname) throws Exception {
String fwkname = wkname;
if ((fwkname == null) || (fwkname.isEmpty())) {
throw new Exception("文件【" + srcfname + "】没有设置输出路径!");
}
String fsep = System.getProperty("file.separator");
fwkname = fwkname.replace("\\", fsep);
fwkname = fwkname.replace("/", fsep);
if (fwkname.substring(0, 1).equals(fsep))
fwkname = fwkname.substring(1);
if (!fwkname.substring(fwkname.length() - 1).equals(fsep))
fwkname = fwkname + fsep;
String dirname = ConstsSw._root_filepath + fwkname;
File file = new File(dirname);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
fwkname = dirname + simplesrcfname;
if (fwkname.equalsIgnoreCase(srcfname)) {
throw new Exception("文件【" + srcfname + "】有相同的输出文件路径!");
}
return fwkname;
}
private static String gettemplatefname(String tempfname) throws Exception {
String ftempfname = tempfname;
if ((ftempfname == null) || (ftempfname.isEmpty())) {
return null;
// throw new Exception("文件【" + srcfname + "】没有设置模板文件!");
}
String fsep = System.getProperty("file.separator");
ftempfname = ftempfname.replace("\\", fsep);
ftempfname = ftempfname.replace("/", fsep);
if (ftempfname.substring(0, 1).equals(fsep))
ftempfname = ftempfname.substring(1);
return ConstsSw._root_filepath + ftempfname;
}
public static List<CcomUrl> chgHtmlWFMLATT(Document srcDoc) throws Exception {
List<CcomUrl> rst = new ArrayList<CcomUrl>();
Elements ets = srcDoc.getElementsByTag("script");
Element fe = null;
String s = "";
for (Element et : ets) {
if ("text/javascript".equalsIgnoreCase(et.attr("type")) && ("cserver_js").equalsIgnoreCase(et.attr("style"))) {
if (fe == null)
fe = et;
s = s + et.html();
}
}
String fcs = null;
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
try {
cx.evaluateString(scope, s, null, 0, null);
int FormType = htmlUtil.parIntParm(scope, "formtype", 1);
boolean allowAtt = htmlUtil.parBoolParm(scope, "allowAtt", true);
boolean allowWF = htmlUtil.parBoolParm(scope, "allowWF", true);
setPageMailLine(srcDoc, FormType);
setPageAllowWF(srcDoc, allowWF);
setPageAllowAtt(srcDoc, allowAtt);
fcs = CHtmlJSRemoteCall.parComUrls(rst, scope);
if (fcs == null)
fcs = "";
} catch (Exception e) {
e.printStackTrace();
} finally {
Context.exit();
}
if (fe != null) {
String s1 = fe.html();
s1 = fcs + "\n" + s1;
fe.text(s1);
}
return rst;
}
public static void setPageMailLine(Document srcDoc, int formtype) {
if (formtype == 2) {// simple form
Element e = srcDoc.getElementById("main_form_div_id");
if (e != null) {
e.attr("data-options", "region:'center',border:false");
e = srcDoc.getElementById("detail_main_layout_id");
if (e != null)
e.remove();
}
}
}
public static void setPageAllowWF(Document srcDoc, boolean allowWF) {
if (!allowWF) {
Element e = srcDoc.getElementById("main_tab_wf_id");
if (e != null)
e.remove();
}
}
public static void setPageAllowAtt(Document srcDoc, boolean allowAtt) {
if (!allowAtt) {
Element e = srcDoc.getElementById("main_tab_att_id");
if (e != null)
e.remove();
}
}
}
<file_sep>/src/com/corsair/server/wordflow/FindWfTemp.java
package com.corsair.server.wordflow;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.server.cjpa.CJPA;
public class FindWfTemp {
public static String findwftemp(String jpaclass, String id) throws Exception {
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass.trim());
jpa.findByID(id.trim());
CJPALineData<Shwwftemp> wftems = findwftemp(jpa);
return wftems.tojson();
}
/**
* 返回模板对像id
* @param jpaclass
* @param id
* @return
* @throws Exception
*/
public static String findwftempid(String jpaclass, String id) throws Exception {
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass.trim());
jpa.findByID(id.trim());
CJPALineData<Shwwftemp> wftems = findwftemp(jpa);
if(wftems.size()>0){
return wftems.get(0).getid();
}else{
return null;
}
}
public static CJPALineData<Shwwftemp> findwftemp(CJPA jpa) throws Exception {
CJPALineData<Shwwftemp> wftems = new CJPALineData<Shwwftemp>(Shwwftemp.class);
String sqlstr = "select * from shwwftemp where stat=1 and clas='" + jpa.getClass().getName() + "'";
wftems.findDataBySQL(sqlstr, true, true);
for (int i = wftems.size() - 1; i >= 0; i--) {
if (!checkParms((Shwwftemp) wftems.get(i), jpa)) {
wftems.remove(i);
}
}
return wftems;
}
private static boolean checkParms(Shwwftemp wftem, CJPA jpa) throws Exception {
CJPALineData<Shwwftemparms> parms = wftem.shwwftemparmss;
for (CJPABase jpap : parms) {
Shwwftemparms parm = (Shwwftemparms) jpap;
if (!(checkRowParm(parm, jpa)))
return false;
}
return true;
}
private static boolean checkRowParm(Shwwftemparms parm, CJPA jpa) throws Exception {
// System.out.println("parm:" + parm.tojson());
CField field = jpa.cfieldbycfieldname(parm.parmname.getValue());
if (field == null) {
throw new Exception("流程启动条件字段【" + parm.parmname.getValue() + "】在JPA中不存在,请联系管理员!");
}
String reloper = parm.reloper.getValue();
int fdtype = field.getFieldtype();
String value = null;
if (!parm.parmvalue.isEmpty())
value = parm.parmvalue.getValue();
if ((value != null) && (value.equalsIgnoreCase("NULL")))
value = null;
if (value == null) {
if ("=".equalsIgnoreCase(reloper)) {
return field.isEmpty();
} else if ("<>".equalsIgnoreCase(reloper)) {
return !field.isEmpty();
} else
return false;
}
switch (fdtype) {
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP: {
if (">".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() > parm.parmvalue.getAsDatetime().getTime());
if ("<".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() < parm.parmvalue.getAsDatetime().getTime());
if (">=".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() >= parm.parmvalue.getAsDatetime().getTime());
if ("<=".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() <= parm.parmvalue.getAsDatetime().getTime());
if ("=".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() == parm.parmvalue.getAsDatetime().getTime());
if ("<>".equalsIgnoreCase(reloper))
return (field.getAsDatetime().getTime() != parm.parmvalue.getAsDatetime().getTime());
}
case Types.BIT:
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
case Types.NUMERIC:
case Types.DECIMAL: {
if (">".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) > parm.parmvalue.getAsFloatDefault(0));
if ("<".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) < parm.parmvalue.getAsFloatDefault(0));
if (">=".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) >= parm.parmvalue.getAsFloatDefault(0));
if ("<=".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) <= parm.parmvalue.getAsFloatDefault(0));
if ("=".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) == parm.parmvalue.getAsFloatDefault(0));
if ("<>".equalsIgnoreCase(reloper))
return (field.getAsFloatDefault(0) != parm.parmvalue.getAsFloatDefault(0));
}
default: {
if (">".equalsIgnoreCase(reloper))
return (field.getValue().compareTo(parm.parmvalue.getValue()) > 0);
if ("<".equalsIgnoreCase(reloper))
return (field.getValue().compareTo(parm.parmvalue.getValue()) < 0);
if (">=".equalsIgnoreCase(reloper))
return (field.getValue().compareTo(parm.parmvalue.getValue()) >= 0);
if ("<=".equalsIgnoreCase(reloper))
return (field.getValue().compareTo(parm.parmvalue.getValue()) <= 0);
if ("=".equalsIgnoreCase(reloper))
return (field.getValue().equalsIgnoreCase(parm.parmvalue.getValue()));
if ("<>".equalsIgnoreCase(reloper))
return (!field.getValue().equalsIgnoreCase(parm.parmvalue.getValue()));
if ("like".equalsIgnoreCase(reloper)) {
String v = field.getValue();
String pv = parm.parmvalue.getValue();
//System.out.println(field.getFieldname() + " " + v + " like " + pv);
if (pv.startsWith("%") && pv.endsWith("%")) {
pv = pv.replace("%", "");
return v.indexOf(pv) >= 0;
} else if (pv.startsWith("%")) {
pv = pv.replace("%", "");
return v.endsWith(pv);
} else if (pv.endsWith("%")) {
pv = pv.replace("%", "");
return v.startsWith(pv);
} else {
return v.equalsIgnoreCase(pv);
}
}
}
}
return false;
}
}
<file_sep>/src/com/corsair/server/generic/Shwusermessage.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwusermessage extends CJPA {
@CFieldinfo(fieldname = "mid", iskey = true, notnull = true, caption = "分配ID", datetype = Types.INTEGER)
public CField mid; // 分配ID
@CFieldinfo(fieldname = "senduserid", caption = "发送用户ID", datetype = Types.INTEGER)
public CField senduserid; // 发送用户ID
@CFieldinfo(fieldname = "sendusername", caption = "发送用户名", datetype = Types.VARCHAR)
public CField sendusername; // 发送用户名
@CFieldinfo(fieldname = "sendip", caption = "发送IP", datetype = Types.VARCHAR)
public CField sendip; // 发送IP
@CFieldinfo(fieldname = "touserid", notnull = true, caption = "接收用户ID", datetype = Types.INTEGER)
public CField touserid; // 接收用户ID
@CFieldinfo(fieldname = "tousername", notnull = true, caption = "接收用户名", datetype = Types.VARCHAR)
public CField tousername; // 接收用户名
@CFieldinfo(fieldname = "token", caption = "接收者token 用于自动登录", datetype = Types.VARCHAR)
public CField token; // 接收者token 用于自动登录
@CFieldinfo(fieldname = "msgtype", notnull = true, caption = "消息类型 1 文本 2 URL ", datetype = Types.INTEGER)
public CField msgtype; // 消息类型 1 文本 2 URL
@CFieldinfo(fieldname = "msgtitle", notnull = true, caption = "消息标题", datetype = Types.VARCHAR)
public CField msgtitle; // 消息标题
@CFieldinfo(fieldname = "msgcontext", notnull = true, caption = "消息内容", datetype = Types.VARCHAR)
public CField msgcontext; // 消息内容
@CFieldinfo(fieldname = "msgurl", caption = "消息连接", datetype = Types.VARCHAR)
public CField msgurl; // 消息连接
@CFieldinfo(fieldname = "senddate", notnull = true, caption = "发送时间", datetype = Types.TIMESTAMP)
public CField senddate; // 发送时间
@CFieldinfo(fieldname = "readdate", caption = "阅读时间", datetype = Types.TIMESTAMP)
public CField readdate; // 阅读时间
@CFieldinfo(fieldname = "isreaded", caption = "是否已读", datetype = Types.INTEGER)
public CField isreaded; // 是否已读
@CFieldinfo(fieldname = "readip", notnull = false, caption = "发送IP", datetype = Types.VARCHAR)
public CField readip; // 发送IP
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "制单人", datetype = Types.VARCHAR)
public CField creator; // 制单人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "制单时间", datetype = Types.TIMESTAMP)
public CField createtime; // 制单时间
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwusermessage() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/d4/d41f58c6c9d71ed0a808028c43dd1d638d8ba2d0.svn-base
package com.hr.attd.ctr;
import java.util.Date;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.attd.entity.Hrkq_overtime;
import com.hr.attd.entity.Hrkq_resign;
import com.hr.attd.entity.Hrkq_resignline;
import com.hr.attd.entity.Hrkq_sched_line;
import com.hr.attd.entity.Hrkq_swcdlst;
import com.hr.card.entity.Hr_ykt_card;
import com.hr.perm.entity.Hr_employee;
import com.hr.util.DateUtil;
import com.hr.util.HRUtil;
public class CtrHrkq_resign extends JPAController {
@Override
public void BeforeWFStartSave(CJPA jpa, Shwwf wf, CDBConnection con, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
wf.subject.setValue(((Hrkq_resign) jpa).rescode.getValue());
if (isFilished) {
doinsertSWCardInfo(jpa, con);
}
}
@Override
public void BeforeWFStart(CJPA jpa, String wftempid, CDBConnection con) throws Exception {
// 检查当月已经提交的因私签批数量
checkysretimes(jpa, con);
checkValidDate(jpa);
}
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
checkresigned(jpa);// 不能用这个con
if (isFilished) {
doinsertSWCardInfo(jpa, con);
}
}
@Override
public String OnCCoVoid(CDBConnection con, CJPA jpa) throws Exception {
dodelSWCardInfo(jpa, con);
return null;
}
private void checkresigned(CJPA jpa) throws NumberFormatException, Exception {
Hrkq_resign r = (Hrkq_resign) jpa;
CJPALineData<Hrkq_resignline> ls = r.hrkq_resignlines;
for (CJPABase j : ls) {
Hrkq_resignline l = (Hrkq_resignline) j;
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM `hrkq_resign` h, `hrkq_resignline` l"
+ " WHERE h.resid =l.resid AND l.isreg=1"
+ " AND l.`kqdate`='" + l.kqdate.getValue() + "' AND h.`er_id`=" + r.er_id.getValue() + " AND l.`sclid`=" + l.sclid.getValue()
+ " AND h.`stat`>1 AND h.`stat`<10";
if (Integer.valueOf(r.pool.openSql2List(sqlstr).get(0).get("ct")) != 0)
throw new Exception("考勤日期【" + Systemdate.getStrDateyyyy_mm_dd(l.kqdate.getAsDatetime()) + "】班次号【" + l.bcno.getValue() + "】存在已经提交的补签记录");
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc,
Shwwfproc nxtproc, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doinsertSWCardInfo(jpa, con);
}
}
@Override
public String OnCCoSave(CDBConnection con, CJPA jpa) throws Exception {
Hrkq_resign r = (Hrkq_resign) jpa;
if (r.stat.getAsIntDefault(0) <= 1) {// 制单状态保存 重新计算次数 保存之前 没有默认值 所有 为0
checkresignlines(con, r);
Date resdate = r.resdate.getAsDatetime();
int rgedtimes = getResignTimesMonth(r.resid.getValue(), r.res_type.getAsIntDefault(0), r.er_id.getValue(), resdate);// 本月因私已签卡次数
int curtimes = getCurTimes(r);
// System.out.println("curtimes:" + curtimes);
r.res_times.setAsInt(rgedtimes + curtimes);
}
return null;
}
private String parkqdt(Date kqdate, String time) {
// System.out.println("time:" + time);
Date rdate = kqdate;
String rtime = time;
String fs = rtime.substring(0, 1).toUpperCase();
if (fs.equalsIgnoreCase("Y")) {// 前一天
rdate = Systemdate.dateDayAdd(rdate, -1);
rtime = rtime.substring(1, rtime.length());
} else if (fs.equalsIgnoreCase("T")) {// 后一天
rdate = Systemdate.dateDayAdd(rdate, 1);
rtime = rtime.substring(1, rtime.length());
}
// rtime = rtime.substring(1, rtime.length() - 1);
String rst = Systemdate.getStrDateyyyy_mm_dd(rdate) + " " + rtime;
// System.out.println("parkqdt:" + rst);
return rst;
}
private void checkresignlines(CDBConnection con, Hrkq_resign r) throws Exception {
Hrkq_sched_line sl = new Hrkq_sched_line();
CJPALineData<Hrkq_resignline> ls = r.hrkq_resignlines;
for (CJPABase j : ls) {
Hrkq_resignline l = (Hrkq_resignline) j;
if (l.isreg.getAsIntDefault(0) == 1) {
Date kqdate = l.kqdate.getAsDatetime();
String sdt = Systemdate.getStrDateyyyy_mm_dd(kqdate);
sl.clear();
sl.findByID(l.sclid.getValue());
if (sl.isEmpty()) {
throw new Exception("ID为【" + l.sclid.getValue() + "】的班次不存在");
}
Date dtbg, dted;
if (l.sxb.getAsInt() == 1) {
dtbg = Systemdate.getDateByStr(parkqdt(kqdate, sl.frvtimebg.getValue()));
dted = Systemdate.getDateByStr(parkqdt(kqdate, sl.frvtimeed.getValue()));
} else {
dtbg = Systemdate.getDateByStr(parkqdt(kqdate, sl.tovtimebg.getValue()));
dted = Systemdate.getDateByStr(parkqdt(kqdate, sl.tovtimeed.getValue()));
}
String sqlstr = "select count(*) ct from hrkq_swcdlst where empno='" + r.employee_code.getValue()
+ "' and skdate>='" + Systemdate.getStrDate(dtbg) + "' and skdate<='" + Systemdate.getStrDate(dted) + "'";
if (Integer.valueOf(con.openSql2List(sqlstr).get(0).get("ct")) > 0)
throw new Exception("工号【" + r.employee_code.getValue() + "】在【" + sdt + "】班次【" + sl.bcno.getValue() + "】已经打卡,不允许补签");
}
}
}
private int getCurTimes(Hrkq_resign r) {
CJPALineData<Hrkq_resignline> ls = r.hrkq_resignlines;
int curtimes = 0;// 本次签卡次数
for (CJPABase j : ls) {
Hrkq_resignline l = (Hrkq_resignline) j;
if ((l.isreg.getAsIntDefault(0) == 1) && (l.getJpaStat() != CJPAStat.RSDEL))
curtimes++;
}
return curtimes;
}
private void checkysretimes(CJPA jpa, CDBConnection con) throws Exception {
Hrkq_resign r = (Hrkq_resign) jpa;
if (r.res_type.getAsIntDefault(0) == 1)// 因公不管
return;
int curtimes = getCurTimes(r);
if (curtimes == 0)
throw new Exception("所有班次没有签卡,不予提交");
Hr_employee emp = new Hr_employee();
emp.findByID(r.er_id.getValue(), false);
if (emp.isEmpty())
throw new Exception("没有找到ID为【" + r.er_id.getValue() + "】的在职员工资料");
// int resigntimes = emp.resigntimes.getAsIntDefault(3);// 允许签卡次数
Date resdate = r.resdate.getAsDatetime();
int rgedtimes = getResignTimesMonth(null, 2, r.er_id.getValue(), resdate);// 本月因私已签卡次数
// if ((rgedtimes + curtimes) > resigntimes)
// throw new Exception("本月累计已提交签卡【" + rgedtimes + "】+本次签卡【" + curtimes + "】>月度允许因私签卡次数【" + resigntimes + "】");
r.res_times.setAsInt(rgedtimes + curtimes);// 更新补签次数
r.save(con);
}
// 获取当月已经提交补签次数 res_type 1 因公 2因私
public static int getResignTimesMonth(String resid, int res_type, String er_id, Date resdate) throws Exception {
String sdb = Systemdate.getStrDateByFmt(resdate, "yyyy-MM-01");
String sde = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(resdate, 1), "yyyy-MM-01");
String sqlstr = "SELECT COUNT(*) ct FROM hrkq_resign m,hrkq_resignline l"
+ " WHERE m.resid=l.resid and m.res_type=" + res_type + " AND stat>1 AND stat<=9 AND m.er_id=" + er_id
+ " AND m.resdate>='" + sdb + "' AND m.resdate<'" + sde + "' AND l.isreg=1 and l.ri_times=1";
if ((resid != null) && (!resid.isEmpty()))
sqlstr = sqlstr + " and m.resid<>" + resid;
return Integer.valueOf((new Hrkq_resign()).pool.openSql2List(sqlstr).get(0).get("ct"));
}
private void doinsertSWCardInfo(CJPA jpa, CDBConnection con) throws Exception {
Hrkq_resign r = (Hrkq_resign) jpa;
Hrkq_swcdlst sw = new Hrkq_swcdlst();
String sqlstr = "SELECT * FROM hr_employee WHERE er_id=" + r.er_id.getValue();
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty())
throw new Exception("没有找到ID为【" + r.er_id.getValue() + "】的在职员工资料");
String card_number = null;
if (emp.card_number.isEmpty()) {
sqlstr = "SELECT * FROM `hr_ykt_card` WHERE er_id=" + emp.er_id.getValue()
+ " ORDER BY createtime DESC ";
Hr_ykt_card yc = new Hr_ykt_card();
yc.findBySQL(sqlstr);
if (yc.isEmpty())
throw new Exception("员工【" + r.employee_name.getValue() + "】无卡号");
else
card_number = yc.card_number.getValue();
} else
card_number = emp.card_number.getValue();
for (CJPABase jpal : r.hrkq_resignlines) {
Hrkq_resignline rl = (Hrkq_resignline) jpal;
String daystr = Systemdate.getStrDateByFmt(rl.kqdate.getAsDatetime(), "yyyy-MM-dd");
if (rl.isreg.getAsInt() == 1) {
// String timestr = daystr + " " + rl.rgtime.getValue();
Date skdate = gettimebybltime(daystr, rl.rgtime.getValue());
sw.clear();
sw.card_number.setValue(card_number); // 卡号
sw.empno.setValue(emp.employee_code.getValue());
sw.skdate.setAsDatetime(skdate); // yyyy-MM-dd hh:mm:ss
sw.sktype.setAsInt(2); // 1 刷卡 2 签卡
sw.synid.setAsInt(0);
sw.readerno.setValue(rl.reslid.getValue());// 补签的时候 是补签明细表
sw.save(con);// 貌似不支持事务处理
}
}
// 自动重新计算 当月考勤
}
/**
* 根据班次时间 返回日期,考虑跨天解析
*
* @param daystr
* @param timestr
* @return
*/
private Date gettimebybltime(String daystr, String timestr) {
int tp = 0;
String tstr = timestr;
if (timestr.substring(0, 1).equalsIgnoreCase("Y")) {// 前一天
tp = -1;
tstr = timestr.substring(1, timestr.length());
}
if (timestr.substring(0, 1).equalsIgnoreCase("T")) {// 后一天
tp = 1;
tstr = timestr.substring(1, timestr.length());
}
String dtstr = daystr + " " + tstr;
// System.out.println("dtstr:" + dtstr);
Date rst = Systemdate.getDateByStr(daystr + " " + tstr);
rst = Systemdate.dateDayAdd(rst, tp);
return rst;
}
/**
* 删除补签信息
*
* @param jpa
* @param con
* @throws Exception
*/
private void dodelSWCardInfo(CJPA jpa, CDBConnection con) throws Exception {
Hrkq_resign r = (Hrkq_resign) jpa;
for (CJPABase jpal : r.hrkq_resignlines) {
Hrkq_resignline rl = (Hrkq_resignline) jpal;
if (rl.isreg.getAsInt() == 1) {
String sqlstr = "DELETE FROM hrkq_swcdlst WHERE sktype=2 AND readerno=" + rl.reslid.getValue();
// System.out.println(sqlstr);
con.execsql(sqlstr, true);
}
}
}
private void checkValidDate(CJPA jpa) throws Exception{
if (HRUtil.hasRoles("58"))// 单据维护员 和 管理员
return;
Hrkq_resign r = (Hrkq_resign) jpa;
CJPALineData<Hrkq_resignline> ls = r.hrkq_resignlines;
for (CJPABase j : ls) {
Hrkq_resignline l = (Hrkq_resignline) j;
if (l.isreg.getAsIntDefault(0) == 1) {
Date kqdate = l.kqdate.getAsDatetime();
//String sdt = Systemdate.getStrDateyyyy_mm_dd(kqdate);
long advanceDays = Long.valueOf(HrkqUtil.getParmValue("KQ_RESIGN_BSDAY"));
//long advanceDays=2;
if(advanceDays>0){
long betweenDays= DateUtil.getBetweenDays(kqdate, new Date());
System.out.print("advanceDays="+advanceDays+"betweenDays="+betweenDays);
Logsw.dblog("advanceDays="+advanceDays+"betweenDays="+betweenDays);
if(betweenDays>advanceDays){
throw new Exception("不能提交【"+advanceDays+"】天前的表单");
}
}
}
}
}
}
<file_sep>/src/com/corsair/server/genco/doc/CODoc.java
package com.corsair.server.genco.doc;
//http://demo.kalcaddle.com/index.php
import java.util.HashMap;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.ctrl.CtrlDoc;
import com.corsair.server.ctrl.CtrlDoc.SACL;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shw_physic_file_refer;
import com.corsair.server.generic.Shwfdr;
import com.corsair.server.generic.Shwfdracl;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.UpLoadFileEx;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
/**
* 文档CO
*
* @author Administrator
*
*/
@ACO(coname = "web.doc")
public class CODoc {
private static int PUBLIC_ORG_FOLDER = 1;// 公共目录
private static int USER_FOLDER = 2;// 个人目录
private static int SHARE_FOLDER = 3;// 分享目录
private static int RECYCLE_FOLDER = 4;// 回收站目录
@ACOAction(eventname = "getDocFolders", Authentication = true, notes = "", ispublic = true)
public String getDocFolders() throws Exception {
String id = CorUtil.hashMap2Str(CSContext.getParms(), "id");
int superid = ((id == null) || (id.isEmpty())) ? 0 : Integer.valueOf(id);
JSONArray rst = CtrlDoc.getFoldersBySuperid(superid);
return rst.toString();
}
@ACOAction(eventname = "createFloder", Authentication = true, notes = "", ispublic = true)
public String createFloder() throws Exception {
HashMap<String, String> parms = CSContext.parPostDataParms();
String id = CorUtil.hashMap2Str(parms, "id", "需要参数ID");
String name = CorUtil.hashMap2Str(parms, "name", "需要参数name");
Shwfdr fdr = new Shwfdr();
fdr.findByID(id);
if (fdr.isEmpty()) {
throw new Exception("文件夹【" + id + "】不存在 ");
}
// 权限检查
SACL acl = CtrlDoc.getCurAclALL(fdr.toJsonObj(), 2);
if (!((acl == SACL.ADMIN) || (acl == SACL.WD) || (acl == SACL.W)))
throw new Exception("文件夹权限不足");
return CtrlDoc.createNewFolder(fdr, name).tojson();
}
@ACOAction(eventname = "removeFolderOrFiles", Authentication = true, notes = "", ispublic = true)
public String removeFolderOrFiles() throws Exception {
JSONObject dinfo = JSONObject.fromObject(CSContext.getPostdata());
String rfdrid = dinfo.getString("rfdrid");
JSONArray rfs = dinfo.getJSONArray("data");
Shwfdr rfdr = new Shwfdr();
rfdr.findByID(rfdrid);
if (rfdr.isEmpty())
throw new Exception("文件夹【" + rfdrid + "】不存在 ");
for (int i = 0; i < rfs.size(); i++) {
JSONObject rf = rfs.getJSONObject(i);
int type = rf.getInt("type");
if (type == 1) {// folder
String fdrid = rf.getString("fdrid");
Shwfdr fdr = new Shwfdr();
fdr.findByID(fdrid);
if (fdr.isEmpty())
throw new Exception("文件夹【" + fdrid + "】不存在 ");
// 权限检查
CtrlDoc.removeFolder(fdr);
} else if (type == 2) {// file
String pfid = rf.getString("pfid");
CtrlDoc.revomeFolderFile(rfdr, pfid);
} else
throw new Exception("");
}
return "{\"result\":\"OK\"}";
}
/*
* @ACOAction(eventname = "getFolderAcl", Authentication = true, notes =
* "获取当前登陆用户文件夹或文件权限", ispublic = true) public String getFolderAcl() throws
* Exception { String id = CorUtil.hashMap2Str(CSContext.getParms(), "id",
* "需要参数id"); // 1 文件权限 2 文件夹权限 int atp =
* Integer.valueOf(CorUtil.hashMap2Str(CSContext.getParms(), "atp",
* "需要参数atp")); // SACL acl = CtrlDoc.getCurAclALL(id, atp); // return
* "{\"result\":\"" + acl.ordinal() + "\"}"; return null; }
*/
@ACOAction(eventname = "getFolderAcled", Authentication = true, notes = "获取当前文件夹权限授予情况", ispublic = true)
public String getFolderAcled() throws Exception {
String id = CorUtil.hashMap2Str(CSContext.getParms(), "id", "需要参数id");
// 1 文件权限 2 文件夹权限
int atp = Integer.valueOf(CorUtil.hashMap2Str(CSContext.getParms(), "atp", "需要参数atp"));
String sqlstr = null;
if (atp == 1) {
sqlstr = "SELECT * FROM shwfdracl a WHERE a.objid=" + id + " AND ((a.acltype=2)OR(a.acltype=4))";
} else if (atp == 2) {
sqlstr = "SELECT * FROM shwfdracl a WHERE a.objid=" + id + " AND ((a.acltype=1)OR(a.acltype=3))";
} else {
throw new Exception("参数错误,atp为1或2");
}
Shwfdracl acl = new Shwfdracl();
return acl.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "setFolderAcl", Authentication = true, notes = "当前登陆用户给文件夹或文件授权", ispublic = true)
public String setFolderAcl() throws Exception {
JSONArray parms = (JSONArray) JSONSerializer.toJSON(CSContext.getPostdata());
for (int i = 0; i < parms.size(); i++) {
// 文件夹ID,文件ID
// 机构ID 或 用户ID
// 权限类型 1:文件夹对机构 2 文件对机构 3 文件夹对个人 4文件对个人
// 权限 1 修改 2 删除3 路由不需要授权
JSONObject parm = parms.getJSONObject(i);
String ownername = null;
String ownerid = parm.getString("ownerid");
int acltype = Integer.valueOf(parm.getInt("acltype"));
if ((acltype == 1) || (acltype == 2)) {
Shworg org = new Shworg();
org.findByID(ownerid);
if (org.isEmpty())
throw new Exception("机构【" + ownerid + "】没发现");
ownername = org.orgname.getValue();
} else if ((acltype == 3) || (acltype == 4)) {
Shwuser user = new Shwuser();
user.findByID(ownerid);
if (user.isEmpty())
throw new Exception("用户【" + ownerid + "】没发现");
ownername = user.username.getValue();
} else {
throw new Exception("参数错误");
}
CtrlDoc.newacl(parm.getString("id"), ownerid, ownername, acltype, SACL.values()[parm.getInt("access")],
Systemdate.getDateByStr(parm.getString("statime")),
Systemdate.getDateByStr(parm.getString("endtime")));
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "removeFolderAcl", Authentication = true, notes = "当前登陆用户取消文件夹或文件授权", ispublic = true)
public String removeFolderAcl() throws Exception {
JSONArray parms = (JSONArray) JSONSerializer.toJSON(CSContext.getPostdata());
for (int i = 0; i < parms.size(); i++) {
JSONObject parm = parms.getJSONObject(i);
String aclid = parm.getString("aclid");
Shwfdracl acl = new Shwfdracl();
acl.findByID(aclid);
if (acl.isEmpty()) {
throw new Exception("权限【" + aclid + "】不存在");
}
int acltype = acl.acltype.getAsInt();
if ((acltype == 3) || (acltype == 4)) {
if (acl.ownerid.getValue().equals(CSContext.getUserID())) {
throw new Exception("不能删除给自己的授权");
}
}
// 检查是否有管理员权限
acl.delete();
}
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "getFolderAttr", Authentication = true, notes = "", ispublic = true)
public String getFolderAttr() throws NumberFormatException, Exception {
HashMap<String, String> parms = CSContext.getParms();
int acltype = Integer.valueOf(CorUtil.hashMap2Str(parms, "type", "需要参数type"));
String fdrid = CorUtil.hashMap2Str(parms, "id", "需要参数type");
return CtrlDoc.getFolderAttr(acltype, fdrid);
}
@ACOAction(eventname = "UpdateFloderName", Authentication = true, notes = "", ispublic = true)
public String UpdateFloderName() throws Exception {
HashMap<String, String> parms = CSContext.parPostDataParms();
String id = CorUtil.hashMap2Str(parms, "id", "需要参数ID");
String name = CorUtil.hashMap2Str(parms, "name", "需要参数name");
Shwfdr fdr = new Shwfdr();
fdr.findByID(id);
if (fdr.isEmpty()) {
throw new Exception("文件夹【" + id + "】不存在 ");
}
// 权限检查
SACL acl = CtrlDoc.getCurAclALL(fdr.toJsonObj(), 2);
if (!((acl == SACL.ADMIN) || (acl == SACL.WD) || (acl == SACL.W)))
throw new Exception("文件夹权限不足");
if (name.equals(fdr.fdrname.getValue())) {
throw new Exception("文件名相同");
}
fdr.fdrname.setValue(name);
fdr.save();
return fdr.tojson();
}
@ACOAction(eventname = "UpdateFileName", Authentication = true, notes = "", ispublic = true)
public String UpdateFileName() throws Exception {
HashMap<String, String> parms = CSContext.parPostDataParms();
String fdrid = CorUtil.hashMap2Str(parms, "fdrid", "需要参数fdrid");
String pfid = CorUtil.hashMap2Str(parms, "pfid", "需要参数pfid");
String name = CorUtil.hashMap2Str(parms, "name", "需要参数name");
Shwfdr fdr = new Shwfdr();
fdr.findByID(fdrid);
if (fdr.isEmpty()) {
throw new Exception("文件夹【" + fdrid + "】不存在 ");
}
// 权限检查
SACL acl = CtrlDoc.getCurAclALL(fdr.toJsonObj(), 2);
if (!((acl == SACL.ADMIN) || (acl == SACL.WD) || (acl == SACL.W)))
throw new Exception("文件夹权限不足");
UpLoadFileEx.updateDisplayName(pfid, name);
Shw_physic_file pf = new Shw_physic_file();
return ((Shw_physic_file) pf.findByID(pfid)).tojson();
}
@ACOAction(eventname = "uploadfile", Authentication = true)
public String uploadfile() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(true);
CDBConnection con = DBPools.defaultPool().getCon("CODoc.uploadfile");
con.startTrans();
try {
HashMap<String, String> parms = CSContext.getParms();
String fdrid = CorUtil.hashMap2Str(parms, "fdrid", "没有选择文件夹");
for (CJPABase jpa : pfs) {
Shw_physic_file pf = (Shw_physic_file) jpa;
Shw_physic_file_refer pfr = new Shw_physic_file_refer();
pfr.referid.setValue(fdrid);
pfr.pfrtype.setAsInt(CtrlDoc.FILEREF_FOLDER);
pfr.pfid.setValue(pf.pfid.getValue());
pfr.save(con);
}
con.submit();
return pfs.tojson();
} catch (Exception e) {
con.rollback();
removeallfls(pfs);
throw e;
}
}
private void removeallfls(CJPALineData<Shw_physic_file> pfs) throws Exception {
if (pfs.size() > 0) {
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
}
@ACOAction(eventname = "getFolderDocs", Authentication = true, ispublic = true)
public String getFolderDocs() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String fdrid = CorUtil.hashMap2Str(parms, "fdrid", "没有选择文件夹");
JSONArray folders = CtrlDoc.getFoldersBySuperid(Integer.valueOf(fdrid));
String sqlstr = "SELECT f.* FROM shw_physic_file f,shw_physic_file_refer fr WHERE f.pfid=fr.pfid AND fr.pfrtype=1 AND fr.referid=" + fdrid;
JSONArray files = DBPools.defaultPool().opensql2json_O(sqlstr);
for (int i = 0; i < folders.size(); i++) {
folders.getJSONObject(i).put("type", 1);
}
for (int i = 0; i < files.size(); i++) {
files.getJSONObject(i).put("type", 2);
folders.add(files.getJSONObject(i));
}
return folders.toString();
}
// @ACOAction(eventname = "downloadFolder", Authentication = true, ispublic
// = true)
// public String downloadFolder() throws Exception {
// HashMap<String, String> parms = CSContext.getParms();
// String fdrid = CorUtil.hashMap2Str(parms, "fdrid", "没有选择文件夹");
// CtrlDoc.downfolder(fdrid);
// return null;
// }
@ACOAction(eventname = "downloadFiles", Authentication = true, ispublic = true)
public String downloadFiles() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String dinfo = CorUtil.hashMap2Str(parms, "dinfo", "需要参数【dinfo】");
JSONArray dinf = JSONArray.fromObject(dinfo);
if (dinf.size() == 0) {
throw new Exception("没有选择下载的文件!");
}
CtrlDoc.downfiles(dinf);
return null;
}
// inpaste: false,
// rfdrid: undefined,//如果是剪切 剪切后需要刷新的文件夹
// cporct: undefined,//复制还是剪切
// sinfo: undefined,//复制的文件和文件夹
// dfdrid: undefined//目标文件夹id
@ACOAction(eventname = "Paste", Authentication = true, ispublic = true)
public String Paste() throws Exception {
HashMap<String, String> parms = CSContext.parPostDataParms();
int acttp = Integer.valueOf(CorUtil.hashMap2Str(parms, "cporct", "需要参数cporct"));
String sinfo = CorUtil.hashMap2Str(parms, "sinfo", "需要参数sinfo");// 源文件夹ID
String dfdrid = CorUtil.hashMap2Str(parms, "dfdrid", "需要参数dfdrid");// 目标文件夹
String rfdrid = CorUtil.hashMap2Str(parms, "rfdrid");// 目标文件夹
JSONArray sinf = JSONArray.fromObject(sinfo);
if (sinf.size() == 0) {
throw new Exception("没有选择复制的文件!");
}
CtrlDoc.Paste(acttp, dfdrid, rfdrid, sinf);
return "{\"result\":\"OK\"}";
}
}
<file_sep>/src/com/corsair/server/util/PackageClass.java
package com.corsair.server.util;
public class PackageClass {
private String fname;// 文件名
private String claname;// 类名
public PackageClass(String fname, String claname) {
this.fname = fname;
this.claname = claname;
}
public String getClaname() {
return claname;
}
public void setClaname(String claname) {
this.claname = claname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
}
<file_sep>/src/com/hr/.svn/pristine/69/698d987b2957acd4c273753c4bc1b301184e5d9e.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_balcklist extends CJPA {
@CFieldinfo(fieldname = "blid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField blid; // ID
@CFieldinfo(fieldname = "id_number", notnull = true, caption = "身份证号", datetype = Types.VARCHAR)
public CField id_number; // 身份证号
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_balcklist() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/cjpa/CJPAManager.java
package com.corsair.server.cjpa;
import java.lang.reflect.Method;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.DBPools;
import com.corsair.server.base.CodeXML;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.base.Tcode_xml;
/**
* 不要了
*
* @author Administrator
*
*/
public class CJPAManager {
// public String wfMain(String xml) throws Exception {
// try {
// Tcode_xml cx = CodeXML.DecCodeRequest(xml);
// int code = cx.code;
// Document document = DocumentHelper.parseText(cx.xml);
// Element employees = document.getRootElement();
// String jpaclass = employees.element("jpaclass").getText();
// String xmldata = employees.element("xmldata").getText();
// CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(jpaclass);
// String rst = "";
// switch (code) {
// case ConstsSw.code_of_JPAWFFindTemp: {
// rst = jpa._findWfTem(xmldata);
// break;
// }
// case ConstsSw.code_of_JPAWFCreateByTemp: {
// rst = jpa._createWFByTemp(xmldata);
// break;
// }
// case ConstsSw.code_of_JPAWFSubmit: {
// rst = jpa._submitWF(xmldata);
// break;
// }
// case ConstsSw.code_of_JPAWFReject: {
// rst = jpa._rejectWF(xmldata);
// break;
// }
// case ConstsSw.code_of_JPAWFBreak: {
// rst = jpa._breakWF(xmldata);
// break;
// }
// case ConstsSw.code_of_JPAWFTransfer: {
// rst = jpa._transferWF(xmldata);
// break;
// }
//
// default: {
// throw new Exception("流程主函数未定义编码");
// }
//
// }
// return CodeXML.AddCodeStr(ConstsSw.code_of_JPAWFMain, rst);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// throw new Exception(e.getLocalizedMessage());
// }
// }
//
// public String callAction(String xml) throws Exception {
// Document document = DocumentHelper.parseText(xml);
// Element employees = document.getRootElement();
// String action = employees.element("action").getText();
// int actiontype = Integer.valueOf(employees.element("actiontype").getText());
// String entclass = employees.element("entclass").getText();
// String jpadata = employees.element("jpadata").getText();
// String xmlparm = employees.element("xmlparm").getText();
// CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(entclass);
// jpa.fromxml(jpadata);
// if (ConstsSw.getAppParmBoolean("Debug_Mode")) {
// // String fname = "c:\\" + entclass + ".xml";
// // jpa.toxmlfile(fname);
// // System.out.println("调试模式输出JPA XML对象:" + fname);
// }
// try {
// String result = null;
// if (actiontype == 0) {
// result = callvoidAction(jpa, entclass, action, xmlparm);
// } else { // if (actiontype == 1)
// result = callStrAction(jpa, entclass, action, xmlparm);
// }
// return CodeXML.AddCodeStr(ConstsSw.code_of_Call_JPAAction, result);
// } catch (Exception e) {
// throw e;
// }
// }
//
// private String callvoidAction(CJPA jpa, String entclass, String action, String xmlparm) throws Exception {
// Method method;
// try {
// Class<?> CJPAcd = Class.forName(entclass);
// if ((xmlparm == null) || xmlparm.isEmpty())
// method = CJPAcd.getMethod(action);
// else
// method = CJPAcd.getMethod(action, new Class[] { String.class });
// } catch (Exception e) {
// e.printStackTrace();
// throw new Exception("类<" + entclass + ">没找到或其方法<" + action + ">没找到");
// }
// if ((xmlparm == null) || xmlparm.isEmpty())
// method.invoke(jpa);
// else
// method.invoke(jpa, xmlparm);
// return Boolean.valueOf(true).toString();
// }
//
// private String callStrAction(CJPA jpa, String entclass, String action, String xmlparm) throws Exception {
// Method method;
// try {
//
// Class<?> CJPAcd = Class.forName(entclass);
// if ((xmlparm == null) || xmlparm.isEmpty())
// method = CJPAcd.getMethod(action);
// else
// method = CJPAcd.getMethod(action, new Class[] { String.class });
// } catch (Exception e) {
// e.printStackTrace();
// throw new Exception("类<" + entclass + ">没找到或其方法<" + action + ">没找到");
// }
// Object rsobject;
// if ((xmlparm == null) || xmlparm.isEmpty())
// rsobject = method.invoke(jpa);
// else
// rsobject = method.invoke(jpa, xmlparm);
// return rsobject.toString();
// }
//
// public String fetchLineDatasByOwner(String xml) throws Exception {
// Document document = DocumentHelper.parseText(xml);
// Element employees = document.getRootElement();
// String lineclass = employees.element("linejpaclass").getText();
// String entclass = employees.element("entclass").getText();
// String jpadata = employees.element("jpadata").getText();
// CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(entclass);
// jpa.fromxml(jpadata);
// CJPALineData<CJPABase> cline = jpa.lineDataByEntyClasname(lineclass);
// if (cline == null) {
// throw new Exception("fetchLineDatasByOwner方法中,根据<" + lineclass + ">未能找到明细数据对象");
// }
// cline.setLazy(false);
// cline.loadDataByOwner(true, true);
//
// document = DocumentHelper.createDocument();
// Element root = document.addElement("linedata");// 创建根节点
// cline.toxmlnode(root);
// String result = document.asXML();
//
// return CodeXML.AddCodeStr(ConstsSw.code_of_JPALinesByOwner, result);
// }
//
// public String fetchLineDatasBySQL(String xml) throws Exception {
// Document document = DocumentHelper.parseText(xml);
// Element employees = document.getRootElement();
// String sqlstr = employees.element("sqlstr").getText();
// String lineclass = employees.element("linejpaclass").getText();
// String poolname = employees.element("poolname").getText();
// CJPALineData<CJPABase> line = CjpaUtil.newJPALinedatas(lineclass);
//
// if ((poolname == null) || poolname.isEmpty()) {
// line.setPool(DBPools.poolByName(poolname));
// } else {
// line.setPool(DBPools.defaultPool());
// }
//
// if (line.getPool() == null)
// throw new Exception("<" + poolname + ">的数据库连接池未找到!");
// line.findDataBySQL(sqlstr, true, true);
// document = DocumentHelper.createDocument();
// Element root = document.addElement("linedata");// 创建根节点
// line.toxmlnode(root);
// String result = document.asXML();
// // System.out.println(result);
// return CodeXML.AddCodeStr(ConstsSw.code_of_JPALinesBySQL, result);
// }
//
// public String initDPAPorpertyByJPA(String xmlstr) throws Exception {
// Document document = DocumentHelper.parseText(xmlstr);
// Element employees = document.getRootElement();
// String entclass = employees.element("entclass").getText();
// CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(entclass);
// return jpa.toxml();
// }
}
<file_sep>/src/com/corsair/server/util/ImageUtil.java
package com.corsair.server.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import javax.imageio.ImageIO;
import com.corsair.dbpool.util.Logsw;
public class ImageUtil {
private static String DEFAULT_PREVFIX = "thumb_";
private static Boolean DEFAULT_FORCE = false;
/**
* <p>
* Title: thumbnailImage
* </p>
* <p>
* Description: 根据图片路径生成缩略图
* </p>
*
* @param imagePath
* 原图片路径
* @param w
* 缩略图宽
* @param h
* 缩略图高
* @param prevfix
* 生成缩略图的前缀
* @param force
* 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)
*/
public String thumbnailImage(File imgFile, int w, int h, String prevfix, boolean force) {
String rst = null;
if (imgFile.exists()) {
try {
// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG,
// JPEG, WBMP, GIF, gif]
String types = Arrays.toString(ImageIO.getReaderFormatNames());
String suffix = null;
// 获取图片后缀
if (imgFile.getName().indexOf(".") > -1) {
suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
}// 类型和图片后缀全部小写,然后判断后缀是否合法
if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0) {
Logsw.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
return null;
}
Image img = ImageIO.read(imgFile);
if (!force) {
// 根据原图与要求的缩略图比例,找到最合适的缩略图比例
int width = img.getWidth(null);
int height = img.getHeight(null);
if ((width * 1.0) / w < (height * 1.0) / h) {
if (width > w) {
h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
}
} else {
if (height > h) {
w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0)));
}
}
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
g.dispose();
String p = imgFile.getPath();
// 将图片保存在原目录并加上前缀
rst = p.substring(0, p.lastIndexOf(File.separator)) + File.separator + prevfix + imgFile.getName();
ImageIO.write(bi, suffix, new File(rst));
} catch (IOException e) {
try {
Logsw.error("generate thumbnail image failed.", e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} else {
Logsw.error("the image is not exist.");
}
return rst;
}
public String thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force) {
File imgFile = new File(imagePath);
return thumbnailImage(imgFile, w, h, prevfix, force);
}
public String thumbnailImage(String imagePath, int w, int h, boolean force) {
return thumbnailImage(imagePath, w, h, DEFAULT_PREVFIX, force);
}
public String thumbnailImage(String imagePath, int w, int h) {
return thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
}
/**
* 在源图片上设置水印文字
*
* @param srcImagePath
* 源图片路径
* @param alpha
* 透明度(0<alpha<1)
* @param font
* 字体(例如:宋体)
* @param fontStyle
* 字体格式(例如:普通样式--Font.PLAIN、粗体--Font.BOLD )
* @param fontSize
* 字体大小
* @param color
* 字体颜色(例如:黑色--Color.BLACK)
* @param inputWords
* 输入显示在图片上的文字
* @param x
* 文字显示起始的x坐标
* @param y
* 文字显示起始的y坐标
* @param imageFormat
* 写入图片格式(png/jpg等)
* @param toPath
* 写入图片路径
* @throws IOException
*/
public static void alphaWords2Image(String srcImagePath, float alpha, String font,
int fontStyle, int fontSize, Color color, String inputWords, int x,
int y, String imageFormat, String toPath) throws IOException {
FileOutputStream fos = null;
try {
BufferedImage image = ImageIO.read(new File(srcImagePath));
// 创建java2D对象
Graphics2D g2d = image.createGraphics();
// 用源图像填充背景
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(),
null, null);
// 设置透明度
AlphaComposite ac = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
// 设置文字字体名称、样式、大小
g2d.setFont(new Font(font, fontStyle, fontSize));
g2d.setColor(color);// 设置字体颜色
for (String line : inputWords.split("\n")) {
if ((line != null) && (!line.isEmpty()))
g2d.drawString(line, x, y += g2d.getFontMetrics().getHeight());
}
// g2d.drawString(inputWords, x, y); // 输入水印文字及其起始x、y坐标
g2d.dispose();
fos = new FileOutputStream(toPath);
ImageIO.write(image, imageFormat, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}
}
<file_sep>/src/com/hr/salary/ctr/CtrHr_salary_teamaward.java
package com.hr.salary.ctr;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.hr.salary.entity.Hr_salary_teamaward;
import com.hr.salary.entity.Hr_salary_teamaward_line;
import com.hr.salary.entity.Hr_salary_teamaward_line_emps;
import com.hr.util.HRUtil;
public class CtrHr_salary_teamaward extends JPAController{
@Override
public String OnCCoVoid(CDBConnection con, CJPA jpa) throws Exception {
// TODO Auto-generated method stub
if (!HRUtil.hasRoles("19")) {// 薪酬管理员
throw new Exception("当前登录用户没有权限使用该功能!");
}
return null;
}
@Override
public void BeforeSave(CJPABase jpa, CDBConnection con, boolean selfLink)
throws Exception {
// TODO Auto-generated method stub
Hr_salary_teamaward tw=(Hr_salary_teamaward)jpa;
CJPALineData<Hr_salary_teamaward_line> twls=tw.hr_salary_teamaward_lines;
float linettpay=0;
for(int i=0;i<twls.size();i++){
Hr_salary_teamaward_line twl=(Hr_salary_teamaward_line)twls.get(i);
float lcp=twl.canpay.getAsFloatDefault(0);
CJPALineData<Hr_salary_teamaward_line_emps> twles=twl.hr_salary_teamaward_line_empss;
float empttpay=0;
for(int j=0;j<twles.size();j++){
Hr_salary_teamaward_line_emps twle=(Hr_salary_teamaward_line_emps)twles.get(j);
float edp=twle.descriprev.getAsFloatDefault(0);
float esp=lcp*edp/100;
float erp=lcp*edp/100;
int ispt=Integer.parseInt(twle.isparttime.getValue());
if(ispt==1){//兼职
int ptnums=Integer.parseInt(twle.ptnums.getValue());
ptnums=ptnums+1;
erp=erp/ptnums;
}
twle.realpay.setAsFloat(erp);
twle.shouldpay.setAsFloat(esp);
empttpay=empttpay+erp;
}
twl.lrealpay.setAsFloat(empttpay);
linettpay=linettpay+empttpay;
}
tw.ttpay.setAsFloat(linettpay);
}
private void checkdate(CJPA jpa, CDBConnection con) throws Exception{
Hr_salary_teamaward tw=(Hr_salary_teamaward)jpa;
CtrSalaryCommon.checkTeamWardValidDate(tw.applydate.getAsDate());
}
@Override
public void BeforeWFStart(CJPA jpa, String wftempid, CDBConnection con)
throws Exception {
// TODO Auto-generated method stub
checkdate(jpa,con);
}
}
<file_sep>/src/com/corsair/server/generic/Shwmenuco.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwmenuco extends CJPA {
@CFieldinfo(fieldname = "mcid", iskey = true, notnull = true, caption = "menuid", datetype = Types.INTEGER)
public CField mcid; // menuid
@CFieldinfo(fieldname = "menuid", notnull = true, caption = "menuid", datetype = Types.INTEGER)
public CField menuid; // menuid
@CFieldinfo(fieldname = "coname", notnull = true, caption = "coname", datetype = Types.VARCHAR)
public CField coname; // coname
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwmenuco() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/corsair/dbpool/DBPools.java
package com.corsair.dbpool;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.corsair.dbpool.util.ICBDLog;
/**
* 多个连接池
*
* @author Administrator
*
*/
public class DBPools {
private static List<CDBPool> dbpools = new ArrayList<CDBPool>();
private static ICBDLog cblog = null;
/**
* @return
*/
public static List<CDBPool> getDbpools() {
return dbpools;
}
public DBPools() {
}
/**
* 添加连接池
*
* @param value
*/
public static void addPool(CDBPool value) {
dbpools.add(value);
}
public static CDBPool defaultPool() {
for (CDBPool p : dbpools) {
if (p.pprm.isdefault) {
return p;
}
}
return null;
}
/**
* 根据名称获取连接池
*
* @param poolname
* @return
*/
public static CDBPool poolByName(String poolname) {
if ((poolname == null) || (poolname.isEmpty())) {
return defaultPool();
}
for (CDBPool p : dbpools) {
if (p.pprm.name.equals(poolname)) {
return p;
}
}
return null;
}
/**
* 获取日志对象
*
* @return
*/
public static ICBDLog getCblog() {
return cblog;
}
public static void setCblog(ICBDLog cblog) {
DBPools.cblog = cblog;
}
/**
* 安全关闭数据集
*
* @param s
* @param r
*/
public static void safeCloseS_R(Statement s, ResultSet r) {
if (r != null)
try {
r.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null)
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/server/util/CorUtil.java
package com.corsair.server.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
public class CorUtil {
public static String sql2 = "";
public static boolean isStrEmpty(String str) {
return ((str == null) || (str.isEmpty()));
}
public static boolean isNumeric(String str) {
if (str.isEmpty())
return false;
return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
}
private static boolean isStrMath1(String value1, String relo, String value2) {
if (value1 == null) {
if (relo.equalsIgnoreCase("=")) {
return value2 == null;
}
if (relo.equalsIgnoreCase(">")) {
return false;
}
if (relo.equalsIgnoreCase("<")) {
return value2 != null;
}
if (relo.equalsIgnoreCase("<=")) {
return (false || (value2 == null));
}
if (relo.equalsIgnoreCase(">=")) {
return value2 == null;
}
if (relo.equalsIgnoreCase("<>") || (relo.equalsIgnoreCase("!="))) {
return value2 != null;
}
} else if (value2 == null) {
if (relo.equalsIgnoreCase("=")) {
return value1 == null;
}
if (relo.equalsIgnoreCase(">")) {
return value1 != null;
}
if (relo.equalsIgnoreCase("<")) {
return false;
}
if (relo.equalsIgnoreCase("<=")) {
return (false || (value1 == null));
}
if (relo.equalsIgnoreCase(">=")) {
return true;
}
if (relo.equalsIgnoreCase("<>") || (relo.equalsIgnoreCase("!="))) {
return value1 != null;
}
}
return false;
}
public static boolean isStrMath(String value1, String relo, String value2) throws Exception {
if (isStrEmpty(relo))
throw new Exception("文本计算时候发现运算符号为空!");
// if ((value1 == null) || (value2 == null))
// throw new Exception("文本计算时候发现值为NULL!");
// System.out.println("isStrMath:" + value1 + relo + value2);
if (relo.equalsIgnoreCase("any")) {
return true;
}
if ((value2 != null) && (value2.equalsIgnoreCase("null") || (value2.isEmpty()))) {
value2 = null;
}
if ((value1 != null) && (value1.isEmpty())) {
value1 = null;
}
if ((value1 == null) || (value2 == null)) {
return isStrMath1(value1, relo, value2);
}
boolean ismic = (isNumeric(value1) && isNumeric(value2));
float v1 = 0;
float v2 = 0;
if (ismic) {
v1 = Float.valueOf(value1);
v2 = Float.valueOf(value2);
}
if (relo.equalsIgnoreCase("=")) {
if (ismic)
return (v1 == v2);
else
return (value1.equals(value2));
}
if (relo.equalsIgnoreCase(">")) {
if (ismic)
return (v1 > v2);
else
return (value1.compareTo(value2) > 0);
}
if (relo.equalsIgnoreCase("<")) {
if (ismic)
return (v1 < v2);
else
return (value1.compareTo(value2) < 0);
}
if (relo.equalsIgnoreCase(">=")) {
if (ismic)
return (v1 >= v2);
else
return (value1.compareTo(value2) >= 0);
}
if (relo.equalsIgnoreCase("<=")) {
if (ismic)
return (v1 <= v2);
else
return (value1.compareTo(value2) <= 0);
}
if (relo.equalsIgnoreCase("<>") || (relo.equalsIgnoreCase("!="))) {
if (ismic)
return (v1 != v2);
else
return (!value1.equals(value2));
}
throw new Exception("文本计算时运算符<" + relo + ">未定义!");
}
public static String getDicDisplay(int dicgid, String dictvalue) throws Exception {
String sqlstr = "select language1 from shwdict where pid=" + dicgid + " and dictvalue='" + dictvalue + "' and usable=1";
List<HashMap<String, String>> dicvs = DBPools.defaultPool().openSql2List(sqlstr);
if (dicvs.size() == 0)
return null;
return dicvs.get(0).get("language1").toString();
}
public static String hashMap2Str(HashMap<String, String> hm, String fdname) {
Object o = hm.get(fdname);
if (o == null)
return null;
else
return o.toString();
}
/**
* 从JSON对象获取属性值,没有返回NULL
*
* @param jo
* @param fdname
* @return
* @throws Exception
*/
public static String getJSONValue(JSONObject jo, String fdname) throws Exception {
if (jo.has(fdname)) {
return jo.getString(fdname);
} else
return null;
}
/**
* 从JSON对象获取属性值,没有返回默认
*
* @param jo
* @param fdname
* @param dvalue
* @return
* @throws Exception
*/
public static String getJSONValueDefault(JSONObject jo, String fdname, String dvalue) throws Exception {
if (jo.has(fdname)) {
String rst = jo.getString(fdname);
if (rst == null) {
return dvalue;
}
return rst;
} else
return dvalue;
}
/**
* 从JSON对象获取属性值,没有报错
*
* @param jo
* @param fdname
* @param errmsg
* @return
* @throws Exception
*/
public static String getJSONValue(JSONObject jo, String fdname, String errmsg) throws Exception {
if (jo.has(fdname)) {
String rst = jo.getString(fdname);
if (rst == null) {
throw new Exception(errmsg);
}
return rst;
} else
throw new Exception(errmsg);
}
public static int getJSONAsInt(JSONObject jo, String fdname, String errmsg) throws Exception {
if (jo.has(fdname)) {
String rst = jo.getString(fdname);
if (rst == null) {
throw new Exception(errmsg);
}
return Integer.valueOf(rst);
} else
throw new Exception(errmsg);
}
public static int getJSONAsIntDefault(JSONObject jo, String fdname, int dft) {
if (jo.has(fdname)) {
String rst = jo.getString(fdname);
if (rst == null) {
return dft;
}
try {
return Integer.valueOf(rst);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return dft;
}
} else
return dft;
}
// /////////////
public static String hashMap2Str(HashMap<String, String> hm, String fdname, String notfinderr) throws Exception {
Object o = hm.get(fdname);
if (o == null)
throw new Exception(notfinderr);
else
return o.toString();
}
// 获取 JSONParm 值
public static String getJSONParmValue(List<JSONParm> jps, String parmname, String errmsg) throws Exception {
String rst = getJSONParmValue(jps, parmname);
if (rst == null)
throw new Exception(errmsg);
return rst;
}
// 获取 JSONParm 值
public static String getJSONParmValue(List<JSONParm> jps, String parmname) throws Exception {
JSONParm rst = getJSONParm(jps, parmname);
if (rst == null)
return null;
return rst.getParmvalue();
}
// 获取 JSONParm
public static JSONParm getJSONParm(List<JSONParm> jps, String parmname, String errmsg) throws Exception {
JSONParm rst = getJSONParm(jps, parmname);
if (rst == null)
throw new Exception(errmsg);
return rst;
}
// 获取 JSONParm
public static JSONParm getJSONParm(List<JSONParm> jps, String parmname) {
for (JSONParm jp : jps) {
if (jp.getParmname().equals(parmname))
return jp;
}
return null;
}
/**
* @param jps
* @param parmname
* @return 获取参数列表
*/
public static List<JSONParm> getJSONParms(List<JSONParm> jps, String parmname) {
List<JSONParm> rst = new ArrayList<JSONParm>();
for (JSONParm jp : jps) {
if (jp.getParmname().equals(parmname))
rst.add(jp);
}
return rst;
}
// 获取随机字符串
public static final String randomString(int length) {
Random randGen = new Random();
char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
if (length < 1) {
return null;
}
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}
/**
* 以62进制(字母加数字)生成19位UUID,最短的UUID,区分大小写
*
* @return
*/
public static String getShotuuid() {
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder();
sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
sb.append(digits(uuid.getMostSignificantBits(), 4));
sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
sb.append(digits(uuid.getLeastSignificantBits(), 12));
return sb.toString();
}
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return UUIDNumbers.toString(hi | (val & (hi - 1)), UUIDNumbers.MAX_RADIX)
.substring(1);
}
// 解析URL参数
public static List<NameValuePair> ParseUrlParm(String url) {
String ps = url.substring(url.indexOf("?") + 1, url.length());
return URLEncodedUtils.parse(ps, Charset.forName("UTF-8"));
}
public static String ParseUrlParm(String url, String parmname) {
if (parmname == null)
return null;
List<NameValuePair> ps = ParseUrlParm(url);
for (NameValuePair p : ps) {
if (parmname.equals(p.getName())) {
return p.getValue();
}
}
return null;
}
public static String ParseUrlParm(String url, String parmname, String errmsg) throws Exception {
String rst = ParseUrlParm(url, parmname);
if (rst == null)
throw new Exception(errmsg);
return rst;
}
/**
* 内网IP是以下面几个段的IP.用户可以自己设置.常用的内网IP地址:
* 10.0.0.0~10.255.255.255
* 172.16.0.0~172.31.255.255
* 192.168.0.0~192.168.255.255
*
* @param ip
* @return
*/
public static boolean isInner(String ip) {
// 正则表达式=。// =、懒得做文字处理了、
String reg = "(10|172|192)\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";
Pattern p = Pattern.compile(reg);
Matcher matcher = p.matcher(ip);
return matcher.find();
}
/**
* 获取服务器URL路径
* 如果有HttpServletRequest ,从Req中获取,
* 否则从配置文件中获取端口
*
* @return
* @throws Exception
*/
public static String getBasePath() throws Exception {
HttpServletRequest request = CSContext.getRequest();
String basePath = null;
if (request != null) {
basePath = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() != 80)
basePath = basePath + ":" + request.getServerPort();
basePath = basePath + request.getContextPath();
} else {
Object o = ConstsSw.getAppParm("DomainName");
String dname = (o == null) ? null : o.toString();
if ((dname == null) || (dname.isEmpty())) {
InetAddress ia = InetAddress.getLocalHost();
dname = ia.getHostAddress();
}
basePath = "http://" + dname + ":" + CServletProperty.getServerPort("http")
+ "/" + CServletProperty.getContextPath();
}
return basePath;
}
}
<file_sep>/WebContent/webapp/js/common/cpopinfo.js
/**
* Created by shangwen on 2016/6/14.
* for jsonbanding1.js
*/
function CPopInfoWindow(options) {
var issetEditValue = false;
var voptions = options;
if (!voptions.windowfilter)
throw new Error("没有设置windowfilter属性!");
var iwobj = $(voptions.windowfilter);
if (iwobj.attr('class').indexOf("easyui-window") < 0)
throw new Error("非easyui-window窗口,不允许弹出!");
var els_all = [];//所有输入框对象
var lables = [];
var JSONBandingFrm = new TJSONBandingFrm();//数据绑定
initbts();//初始化按钮事件
function initbts() {
var els = JSONBandingFrm.getInputArray(voptions.windowfilter);
els_all = els.els_all;
//els_readonly = els.els_readonly;
lables = els.els_lables;
initInput();
var bts = iwobj.find("a[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
el.onclick = function () {
acceptAllGrid();
//从界面获取数据
var jdata = iwobj.c_toJsonData(voptions.jsonData, voptions.isNew);
//获取列表数据
//需要重新load grid 数据吗? 可能不需要!
if (!JSONBandingFrm.checkNotNull(els_all, lables, jdata)) return false;
if (voptions.afterGetData) {
voptions.afterGetData(jdata);
}
if ((voptions.onOK) && (voptions.onOK(voptions.isNew, jdata)))
iwobj.window('close');
};
}
if (co.caction == "act_cancel") {
el.onclick = function () {
if (voptions.onCancel) {
var errmsg = voptions.onCancel();
if (errmsg)alert(errmsg);
}
iwobj.window('close');
}
}
});
}
function initInput() {
for (var i = 0; i < els_all.length; i++) {
var co = $.c_parseOptions($(els_all[i]));
var obj = $(els_all[i]);
var iscombox = false;
if (co.comidx != undefined) {
iscombox = true;
var conurl = eval("comUrl_" + co.comidx);
var jsondata = conurl.jsondata;
var type = conurl.type;
var valueField = conurl.valueField;
var textField = conurl.textField;
if (jsondata != undefined) {
if (frmvoptions.onInitInputComboboxDict) {
frmvoptions.onInitInputComboboxDict(co, jsondata);
}
if (type == "combobox") {
obj.combobox({
data: jsondata,
valueField: valueField,
textField: textField
});
obj.combobox({onChange: onValueChange});
}
if (type == "combotree") {
obj.combotree("loadData", jsondata);
obj.combotree({onChange: onValueChange});
}
}
} else {
var et = getInputType(els_all[i]);
if (et == 1) {
obj.datetimebox({onChange: onValueChange});
} else
obj.textbox({onChange: onValueChange});
}
if (iscombox) {
var input = obj.combobox("textbox");
//alert(input.parent().html());
//alert(input.attr("class"));
//input.keydown(function () {
//alert("fdsa");
//});
} else {
var input = obj.textbox("textbox");
//input.bind('keydown', function (e) {
//console.error("textkeydown:" + keyCode);
//});
}
if (co.required) {
var tv = getInputLabel(lables, co.fdname);//$(this).parent().prev();
if (tv)
tv.html(tv.html() + "(<span style='color: red'>*</span>)");
}
if (!co.readonly) {
setInputReadOnly($(obj), false);
} else {
setInputReadOnly($(obj), true);
}
}
}
function setInputReadOnly(input, readonly) {
//alert(input.next().find("input:first").parent().html());
var tp = getInputType(input[0]);
if (tp == 1)
input.datetimebox({readonly: readonly});
if ((tp == 2) || (tp == 3))
input.combobox({readonly: readonly});
if (tp == 5)
input.textbox({readonly: readonly});
if (readonly) {
input.next().find("input:first").css("background-color", "#E8EEFA");
input.next().find("textarea:first").css("background-color", "#E8EEFA");
} else {
input.next().find("input:first").css("background-color", "#FFFFFF");
input.next().find("textarea:first").css("background-color", "#FFFFFF");
}
}
this.show = show;
function show(options) {
if (options)
extendOptions(options);
if (voptions.isNew)
iwobj.c_setJsonDefaultValue(voptions.jsonData, true);
clearInputData();
setData2Input();
setData2Grid();
iwobj.window({onOpen: onWindowShow});
iwobj.window('open');
iwobj.find(".easyui-tabs").each(function (index, el) {
$(this).tabs("select", 0);
});
}
this.extendOptions = extendOptions;
function extendOptions(NewOptions) {
voptions = $.extend(voptions, NewOptions);
}
this.getOptions = function () {
return voptions;
};
function onWindowShow() {
if (voptions.onShow) {
voptions.onShow(voptions.jsonData);
}
}
function clearInputData() {
iwobj.find("input[cjoptions]").each(function (index, el) {
var tp = $(this).attr("type");
if (tp == "checkbox")
$(this).attr("checked", false);
else
$(this).textbox('setValue', "");
});
iwobj.find("table[cjoptions][class*='easyui-datagrid']").each(function (index, el) {
$(this).datagrid("loadData", []);
});
iwobj.find("table[cjoptions][class*='easyui-treegrid']").each(function (index, el) {
$(this).treegrid("loadData", []);
});
}
this.getFieldValue = function (fdname) {
var v = $getInputValue(els_all, fdname);
if (v)
return v;
else
return voptions.jsonData[fdname];
};
this.setFieldValue = setFieldValue;
function setFieldValue(fdname, value) {
issetEditValue = true;
try {
voptions.jsonData[fdname] = value;
var iput = findElinput(els_all, fdname);
if (iput) {
setInputValue(iput, value);
}
}
finally {
issetEditValue = false;
}
}
function findElinput(els_all, fdname) {
for (var i = 0; i < els_all.length; i++) {
var co = $.c_parseOptions($(els_all[i]));
if (co.fdname == fdname) {
return els_all[i]
}
}
return undefined;
}
function setData2Input() {
JSONBandingFrm.fromJsonData(els_all, voptions.jsonData);
}
function setData2Grid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = voptions.jsonData[id];
if ($(this).datagrid) {
if (tbdata != undefined) {
//if (tbdata.length > 0) 如果为空 也需要载入 数据 以载入数据和Grid的关联关系,否则空数据无法保存
$(this).datagrid("loadData", tbdata);
//else
// $(this).datagrid("loadData", []);
}
}
});
}
function setInputValue(iput, value) {
var co = $.c_parseOptions($(iput));
var et = getInputType(iput);
var v = value;
switch (et) {
case 1:
{
if ((v == undefined) || (v == null) || (v == "NULL") || (v == "")) {
$(iput).datetimebox('setValue', "");
} else {
var dt = (new Date()).fromStr(v);
$(iput).datetimebox('setValue', dt.toUIDatestr());
}
break;
}
case 3://combotree
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(iput).combotree('setValues', "");
else {
$(iput).combotree('setValues', v);
}
break;
}
default:
{
if ((v == undefined) || (v == null) || (v == "NULL"))
$(iput).textbox('setValue', "");
else {
if (co.dicgpid || co.comidx) {
$(iput).combobox('select', v);
} else
$(iput).textbox('setValue', v);
}
break;
}
}
}
function acceptAllGrid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = voptions.jsonData[id];
if ((tbdata) && ($(this).datagrid)) {
$(this).datagrid("acceptChanges");
}
});
}
function $getInputValue(els_all, fdname) {
for (var i = 0; i < els_all.length; i++) {
var co = $.c_parseOptions($(els_all[i]));
var et = getInputType(els_all[i]);
if (co.fdname == fdname) {
var v = $(els_all[i]).textbox("getValue");
return v;
}
}
return undefined;
}
function onValueChange(newValue, oldValue) {
var obj = $(this);
var co = $.c_parseOptions(obj);
if ((co != undefined) && (voptions.onEditChanged) && (!issetEditValue)) {
voptions.onEditChanged(co.fdname, newValue, oldValue);
}
}
}
<file_sep>/src/com/corsair/dbpool/util/CResultSetMetaData.java
package com.corsair.dbpool.util;
import java.util.ArrayList;
public class CResultSetMetaData<T> extends ArrayList<CResultSetMetaDataItem> {
private static final long serialVersionUID = 1L;
}
<file_sep>/src/com/corsair/server/websocket/CWebSocketPool.java
package com.corsair.server.websocket;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.corsair.server.base.ConstsSw;
public class CWebSocketPool {
private List<CWebSocket> sockets = Collections.synchronizedList(new ArrayList<CWebSocket>());
public CWebSocket getSocket(String sid, String vport) {
if ((sid == null) || sid.isEmpty())
return null;
if ((vport == null) || vport.isEmpty())
return null;
for (CWebSocket socket : sockets) {
if (sid.equals(socket.getSessionid()) && vport.equals(socket.getVport()))
return socket;
}
return null;
}
//不存就创建
public CWebSocket addSocket(String vport,String sid) throws Exception {
CWebSocket rst = getSocket(sid, vport);
if (rst != null)
return rst;
Object oc= ConstsSw._allSocketClassName.get(vport);
if(oc==null)
throw new Exception("websocket虚拟端口【"+vport+"】未定义");
Class<CWebSocket> sktcls= ((CWebsocketClas) oc).getSocketclass();
Class<?> paramTypes[] = { String.class, String.class };
Constructor<?> cst = null;
try {
cst = sktcls.getConstructor(paramTypes);
Object o = cst.newInstance(sid, vport);
rst = (CWebSocket) (o);
} catch (Exception e) {
Object o;
o = sktcls.newInstance();
rst = (CWebSocket) (o);
}
sockets.add(rst);
return rst;
}
public void sendJSON(String userid, String vport, String jsonstr) {
if ((userid == null) || userid.isEmpty())
return;
if ((vport == null) || vport.isEmpty())
return;
List<CWebSocket> usersockets = getSocketByUser(userid);
for (CWebSocket socket : usersockets) {
if (vport.equals(socket.getVport())) {
System.out.println("do send message:" + socket.getVport());
socket.sendJSON(jsonstr);
}
}
}
public List<CWebSocket> getSocketByUser(String userid) {
List<CWebSocket> rst = new ArrayList<CWebSocket>();
if (userid == null)
return rst;
for (CWebSocket socket : sockets) {
if (userid.equals(socket.getUserid())) {
rst.add(socket);
}
}
return rst;
}
public void removeSocket(String sid, String vport) {
CWebSocket socket = getSocket(sid, vport);
if (socket != null)
sockets.remove(socket);
}
public List<CWebSocket> getSockets() {
return sockets;
}
}
<file_sep>/src/com/hr/.svn/pristine/f1/f15e8bdfcb67281e4a9b0198cb73b64b513d2f80.svn-base
package com.hr.salary.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import com.hr.salary.ctr.CtrHr_salary_hotsub_qual_cancel;
import java.sql.Types;
@CEntity(caption="高温补贴资格终止",tablename="Hr_salary_hotsub_qual_cancel",controller=CtrHr_salary_hotsub_qual_cancel.class)
public class Hr_salary_hotsub_qual_cancel extends CJPA {
@CFieldinfo(fieldname ="hsqc_id",iskey=true,notnull=true,precision=20,scale=0,caption="高温补贴资格终止ID",datetype=Types.INTEGER)
public CField hsqc_id; //高温补贴资格终止ID
@CFieldinfo(fieldname ="hsqc_code",codeid=137,notnull=true,precision=16,scale=0,caption="高温补贴资格终止编码",datetype=Types.VARCHAR)
public CField hsqc_code; //高温补贴资格终止编码
@CFieldinfo(fieldname ="canceldate",notnull=true,precision=10,scale=0,caption="终止时间",datetype=Types.DATE)
public CField canceldate; //终止时间
@CFieldinfo(fieldname ="cancelreason",notnull=true,precision=512,scale=0,caption="终止原因",datetype=Types.VARCHAR)
public CField cancelreason; //终止原因
@CFieldinfo(fieldname ="orgid",notnull=true,precision=10,scale=0,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname ="orgcode",notnull=true,precision=16,scale=0,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname ="orgname",notnull=true,precision=128,scale=0,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname ="substype",notnull=true,precision=1,scale=0,caption="津贴类型",defvalue="3",datetype=Types.INTEGER)
public CField substype; //津贴类型
@CFieldinfo(fieldname ="startdate",precision=19,scale=0,caption="开始时间",datetype=Types.TIMESTAMP)
public CField startdate; //开始时间
@CFieldinfo(fieldname ="enddate",precision=19,scale=0,caption="结束时间",datetype=Types.TIMESTAMP)
public CField enddate; //结束时间
@CFieldinfo(fieldname ="applyreason",notnull=true,precision=512,scale=0,caption="申请原因",datetype=Types.VARCHAR)
public CField applyreason; //申请原因
@CFieldinfo(fieldname ="sp_id",precision=20,scale=0,caption="标准职位ID",datetype=Types.INTEGER)
public CField sp_id; //标准职位ID
@CFieldinfo(fieldname ="sp_code",precision=16,scale=0,caption="标准职位编码",datetype=Types.VARCHAR)
public CField sp_code; //标准职位编码
@CFieldinfo(fieldname ="sp_name",precision=128,scale=0,caption="标准职位名称",datetype=Types.VARCHAR)
public CField sp_name; //标准职位名称
@CFieldinfo(fieldname ="substand",precision=6,scale=2,caption="津贴标准",datetype=Types.DECIMAL)
public CField substand; //津贴标准
@CFieldinfo(fieldname ="hsql_id",notnull=true,precision=20,scale=0,caption="高温补贴资格明细ID",datetype=Types.INTEGER)
public CField hsql_id; //高温补贴资格明细ID
@CFieldinfo(fieldname ="remark",precision=512,scale=0,caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname ="wfid",precision=20,scale=0,caption="wfid",datetype=Types.INTEGER)
public CField wfid; //wfid
@CFieldinfo(fieldname ="attid",precision=20,scale=0,caption="attid",datetype=Types.INTEGER)
public CField attid; //attid
@CFieldinfo(fieldname ="stat",notnull=true,precision=2,scale=0,caption="流程状态",datetype=Types.INTEGER)
public CField stat; //流程状态
@CFieldinfo(fieldname ="entid",notnull=true,precision=5,scale=0,caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname ="idpath",notnull=true,precision=256,scale=0,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname ="creator",notnull=true,precision=32,scale=0,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname ="createtime",notnull=true,precision=19,scale=0,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname ="updator",precision=32,scale=0,caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname ="updatetime",precision=19,scale=0,caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
@CFieldinfo(fieldname ="property1",precision=32,scale=0,caption="备用字段1",datetype=Types.VARCHAR)
public CField property1; //备用字段1
@CFieldinfo(fieldname ="property2",precision=64,scale=0,caption="备用字段2",datetype=Types.VARCHAR)
public CField property2; //备用字段2
@CFieldinfo(fieldname ="property3",precision=32,scale=0,caption="备用字段3",datetype=Types.VARCHAR)
public CField property3; //备用字段3
@CFieldinfo(fieldname ="property4",precision=32,scale=0,caption="备用字段4",datetype=Types.VARCHAR)
public CField property4; //备用字段4
@CFieldinfo(fieldname ="property5",precision=32,scale=0,caption="备用字段5",datetype=Types.VARCHAR)
public CField property5; //备用字段5
@CFieldinfo(fieldname ="usable",notnull=true,precision=1,scale=0,caption="有效",defvalue="1",datetype=Types.INTEGER)
public CField usable; //有效
@CFieldinfo(fieldname ="orghrlev",precision=1,scale=0,caption="orghrlev",datetype=Types.INTEGER)
public CField orghrlev; //orghrlev
@CFieldinfo(fieldname ="emplev",precision=2,scale=0,caption="emplev",datetype=Types.INTEGER)
public CField emplev; //emplev
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_salary_hotsub_qual_cancel() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/65/654a42be73bd8687d7f2dc37dd4e5b8893bc11bd.svn-base
package com.hr.salary.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import com.hr.salary.ctr.CtrHr_salary_structure;
import java.sql.Types;
@CEntity(caption="工资结构设置",controller =CtrHr_salary_structure.class)
public class Hr_salary_structure extends CJPA {
@CFieldinfo(fieldname="stru_id",iskey=true,notnull=true,precision=20,scale=0,caption="工资结构ID",datetype=Types.BIGINT)
public CField stru_id; //工资结构ID
@CFieldinfo(fieldname="stru_code",codeid=123,notnull=true,precision=64,scale=0,caption="工资结构编码",datetype=Types.VARCHAR)
public CField stru_code; //工资结构编码
@CFieldinfo(fieldname="stru_name",precision=64,scale=0,caption="工资结构名",datetype=Types.VARCHAR)
public CField stru_name; //工资结构名
@CFieldinfo(fieldname="kqtype",precision=1,scale=0,caption="出勤机制",datetype=Types.INTEGER)
public CField kqtype; //出勤机制
@CFieldinfo(fieldname="checklev",precision=1,scale=0,caption="绩效考核层级",datetype=Types.INTEGER)
public CField checklev; //绩效考核层级
@CFieldinfo(fieldname="basewage",precision=5,scale=2,caption="基本工资",datetype=Types.DECIMAL)
public CField basewage; //基本工资
@CFieldinfo(fieldname="otwage",precision=5,scale=2,caption="固定加班工资",datetype=Types.DECIMAL)
public CField otwage; //固定加班工资
@CFieldinfo(fieldname="skillwage",precision=5,scale=2,caption="技能工资",datetype=Types.DECIMAL)
public CField skillwage; //技能工资
@CFieldinfo(fieldname="meritwage",precision=5,scale=2,caption="绩效工资",datetype=Types.DECIMAL)
public CField meritwage; //绩效工资
@CFieldinfo(fieldname="strutype",precision=1,scale=0,caption="工资结构类型",datetype=Types.INTEGER)
public CField strutype; //工资结构类型
@CFieldinfo(fieldname="remark",precision=512,scale=0,caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
@CFieldinfo(fieldname="wfid",precision=20,scale=0,caption="wfid",datetype=Types.INTEGER)
public CField wfid; //wfid
@CFieldinfo(fieldname="attid",precision=20,scale=0,caption="attid",datetype=Types.INTEGER)
public CField attid; //attid
@CFieldinfo(fieldname="stat",notnull=true,precision=2,scale=0,caption="流程状态",datetype=Types.INTEGER)
public CField stat; //流程状态
@CFieldinfo(fieldname="idpath",notnull=true,precision=256,scale=0,caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="entid",notnull=true,precision=5,scale=0,caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname="creator",notnull=true,precision=32,scale=0,caption="创建人",datetype=Types.VARCHAR)
public CField creator; //创建人
@CFieldinfo(fieldname="createtime",notnull=true,precision=19,scale=0,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="updator",precision=32,scale=0,caption="更新人",datetype=Types.VARCHAR)
public CField updator; //更新人
@CFieldinfo(fieldname="updatetime",precision=19,scale=0,caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //更新时间
@CFieldinfo(fieldname="attribute1",precision=32,scale=0,caption="备用字段1",datetype=Types.VARCHAR)
public CField attribute1; //备用字段1
@CFieldinfo(fieldname="attribute2",precision=32,scale=0,caption="备用字段2",datetype=Types.VARCHAR)
public CField attribute2; //备用字段2
@CFieldinfo(fieldname="attribute3",precision=32,scale=0,caption="备用字段3",datetype=Types.VARCHAR)
public CField attribute3; //备用字段3
@CFieldinfo(fieldname="attribute4",precision=32,scale=0,caption="备用字段4",datetype=Types.VARCHAR)
public CField attribute4; //备用字段4
@CFieldinfo(fieldname="attribute5",precision=32,scale=0,caption="备用字段5",datetype=Types.VARCHAR)
public CField attribute5; //备用字段5
@CFieldinfo(fieldname="usable",notnull=true,precision=1,scale=0,caption="usable",defvalue="1",datetype=Types.INTEGER)
public CField usable; //usable
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_salary_structure() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/salary/ctr/CtrHr_salary_hotsub.java
package com.hr.salary.ctr;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.hr.salary.entity.Hr_salary_hotsub;
import com.hr.salary.entity.Hr_salary_hotsub_line;
public class CtrHr_salary_hotsub extends JPAController{
@Override
public void BeforeWFStart(CJPA jpa, String wftempid, CDBConnection con)
throws Exception {
// TODO Auto-generated method stub
checkdate(jpa, con);
checkemps(jpa,con);
}
private void checkdate(CJPA jpa, CDBConnection con) throws Exception{
Hr_salary_hotsub hs=(Hr_salary_hotsub)jpa;
CtrSalaryCommon.checkHotSubValidDate(hs.applydate.getAsDate());
}
private void checkemps(CJPA jpa, CDBConnection con) throws Exception{
Hr_salary_hotsub hs=(Hr_salary_hotsub)jpa;
CJPALineData<Hr_salary_hotsub_line> hsls=hs.hr_salary_hotsub_lines;
for(int i=0;i<hsls.size();i++){
Hr_salary_hotsub_line hsl=(Hr_salary_hotsub_line)hsls.get(i);
String sqlstr="SELECT COUNT(*) AS ct FROM `hr_salary_hotsub` hs,`hr_salary_hotsub_line` hsl "+
" WHERE hs.applydate='"+hs.applydate.getValue()+"' AND hsl.hs_id=hs.hs_id AND hsl.er_id="+hsl.er_id.getValue()+" AND hs.stat>1";
int ct=Integer.valueOf(con.opensql2json_o(sqlstr).getJSONObject(0).getString("ct"));
if(ct>0){
throw new Exception("在【"+hs.applydate.getValue()+"】月份里员工【"+hsl.employee_code.getValue()+"】已提交高温补贴申请,不能再次提交");
}
}
}
}
<file_sep>/src/com/corsair/server/util/TerminalType.java
package com.corsair.server.util;
/**
* 终端编码
*
* @author Administrator
*
*/
public class TerminalType {
public enum TermKink {
desktop, mobile;
}
public enum TermType {
iPhone, iPod, android, win_Phone, blackBerry, symbian, windows, macintosh, linux, freeBSD, sunOS, unKnow, delphiclt, wx_android, wx_iphone;
}
// PC:[Boland,Windows,MSIE,Macintosh,Linux,FreeBSD,SunOS];
// Mobile:[iPhone,iPod,Android,Windows Phone,BlackBerry,Symbian]
// 微信:userAgent:Mozilla/5.0 (Linux; Android 5.1.1; vivo X6SPlus D Build/LMY47V; wv)
// AppleWebKit/537.36 (KHTML, like Gecko)
// Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/043909
// Mobile Safari/537.36 MicroMessenger/6.6.5.1280(0x26060533) NetType/WIFI Language/zh_CN
public static TermType getTerminalType(String userAgent) {
if (userAgent == null)
return TermType.unKnow;
if (userAgent.indexOf("MicroMessenger") >= 0) {// 微信
if (userAgent.indexOf("iPhone") >= 0)
return TermType.wx_iphone;
if (userAgent.indexOf("Android") >= 0)
return TermType.wx_android;
} else {
if (userAgent.indexOf("iPhone") >= 0)
return TermType.iPhone;
if (userAgent.indexOf("iPod") >= 0)
return TermType.iPod;
if (userAgent.indexOf("Android") >= 0)
return TermType.android;
}
if (userAgent.indexOf("Windows Phone") >= 0)
return TermType.win_Phone;
if (userAgent.indexOf("BlackBerry") >= 0)
return TermType.blackBerry;
if (userAgent.indexOf("Boland") >= 0)
return TermType.delphiclt;
if (userAgent.indexOf("Windows") >= 0)
return TermType.windows;
if (userAgent.indexOf("Macintosh") >= 0)
return TermType.macintosh;
if (userAgent.indexOf("Linux") >= 0)
return TermType.linux;
if (userAgent.indexOf("FreeBSD") >= 0)
return TermType.freeBSD;
if (userAgent.indexOf("SunOS") >= 0)
return TermType.sunOS;
if (userAgent.indexOf("MSIE") >= 0)
return TermType.windows;
return TermType.unKnow;
}
public static TermKink getTermKink(TermType tt) {
TermType[] dts = { TermType.windows, TermType.macintosh, TermType.linux, TermType.freeBSD, TermType.sunOS, TermType.unKnow, TermType.delphiclt };
for (TermType dt : dts) {
if (dt == tt)
return TermKink.desktop;
}
return TermKink.mobile;
}
}
<file_sep>/src/com/hr/.svn/pristine/d7/d7299d7127c9c35b35c31325a209332955db8857.svn-base
package com.hr.portals.co;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.dbpool.DBPools;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.perm.entity.Hr_employee;
import com.hr.util.HRUtil;
@ACO(coname = "web.hr.Portalsm")
public class COHr_portalsm {
@ACOAction(eventname = "getEmpInfo", Authentication = true, ispublic = true, notes = "获取人员信息")
public String getimageid() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_employee t WHERE t.employee_code = '" + username + "'";
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty()) {
throw new Exception("当前登录用户无对应人事资料");
}
return emp.tojson();
}
@ACOAction(eventname = "getEmpInfoNotice", Authentication = true, ispublic = true, notes = "获取人员通知信息")
public String getEmpInfoNotice() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_employee t WHERE t.employee_code = '" + username + "'";
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty()) {
throw new Exception("当前登录用户无对应人事资料");
}
Shworg deforg = CSContext.getUserDefaultOrg();
boolean isorgmanger = HRUtil.hasPostions("6");// 岗位是部门负责人
boolean isomorerom = isorgmanger || HRUtil.hasRoles("3,60,16");// 岗位是部门负责人
// 或
// 角色是人事经理人事专员
int days = Integer.valueOf(HrkqUtil.getParmValue("TRYNOTICEBEFOREDAY"));// 试用考察提前通知X天
// trystat 试用期人事状态 试用期中、试用过期、试用延期、己转正、试用不合格
// wfresult 评审结果 1 同意转正 2 延长试用 3 试用不合格
// 试用转正提醒数量
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_entry_try t,hr_employee e " + "WHERE t.hwc_namezl <>'OO' "
+ " AND((t.trystat = 2 OR t.trystat = 1) AND t.promotionday <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY) "
+ " OR (t.trystat=3 AND t.delaypromotionday<= DATE_SUB(NOW(), INTERVAL -" + days + " DAY))) "
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
if (isorgmanger)
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
else
sqlstr = sqlstr + " and t.er_id=" + emp.er_id.getValue();
int syzztxnum = Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));// 试用转正提醒数量
// 试用转正延期数量
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_entry_try t,hr_employee e " + "WHERE t.trystat=3 and t.hwc_namezl <>'OO'"
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
if (isomorerom)
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
else
sqlstr = sqlstr + " and t.er_id=" + emp.er_id.getValue();
int syzzyxnum = Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));// 试用转正延期数量
// 考察转正提醒数量
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_transfer_try t,hr_employee e " + "WHERE t.hwc_namezl <> 'OO' "
+ "AND ((t.trystat = 2 OR t.trystat = 1) AND t.probationdate <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY) "
+ " OR (t.trystat = 3 AND t.delaypromotionday <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY))) "
+ " AND e.empstatid > 1 AND e.empstatid < 10 AND e.er_id = t.er_id ";
if (isorgmanger)
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
else
sqlstr = sqlstr + " and t.er_id=" + emp.er_id.getValue();
int kczztxnum = Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));// 考察转正提醒数量
// 考察转正延期数量
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_transfer_try t,hr_employee e " + "WHERE t.trystat=3 and t.hwc_namezl <>'OO'"
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
if (isomorerom)
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
else
sqlstr = sqlstr + " and t.er_id=" + emp.er_id.getValue();
int kczzyqnum = Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));// 考察转正延期数量
JSONObject rst = new JSONObject();
if (isorgmanger)
rst.put("isorgmanger", 1);
else
rst.put("isorgmanger", 2);
if (isomorerom)
rst.put("isomorerom", 1);
else
rst.put("isomorerom", 2);
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hrrl_declare d1,hr_employee e "
+ "WHERE d1.rer_id=e.er_id AND e.empstatid<10 AND e.empstatid>0 AND d1.useable=1 AND d1.stat=9 " + "AND d1.rltype1=1 AND d1.rer_id="
+ emp.er_id.getValue() + " AND NOT EXISTS( " + " SELECT 1 FROM hrrl_declare d2 WHERE d2.rltype1=1 AND d2.er_id=d1.rer_id AND d2.useable=1 "
+ " AND d1.rltype2=d2.rltype2 AND rer_id=d1.er_id AND d2.dcldate>=d1.dcldate)";
int glgxsbtx = Integer.valueOf(emp.pool.openSql2List(sqlstr).get(0).get("ct"));// 关联关系申报提醒
rst.put("syzztxnum", syzztxnum);
rst.put("syzzyxnum", syzzyxnum);
rst.put("kczztxnum", kczztxnum);
rst.put("kczzyqnum", kczzyqnum);
rst.put("glgxsbtx", glgxsbtx);
return rst.toString();
}
@ACOAction(eventname = "getGLGXNoticeNotice", Authentication = true, ispublic = true, notes = "获取关联关系通知列表")
public String getGLGXNoticeNotice() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_employee t WHERE t.employee_code = '" + username + "'";
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty()) {
throw new Exception("当前登录用户无对应人事资料");
}
sqlstr = "SELECT d1.* from hrrl_declare d1,hr_employee e " + "WHERE d1.rer_id=e.er_id AND e.empstatid<10 AND e.empstatid>0 AND d1.useable=1 "
+ "AND d1.rltype1=1 AND d1.rer_id=" + emp.er_id.getValue() + " AND NOT EXISTS( "
+ " SELECT 1 FROM hrrl_declare d2 WHERE d2.rltype1=1 AND d2.er_id=d1.rer_id AND d2.useable=1 "
+ " AND d1.rltype2=d2.rltype2 AND rer_id=d1.er_id AND d2.dcldate>=d1.dcldate)";
sqlstr = sqlstr + " LIMIT 300";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getSyzztxlist", Authentication = true, ispublic = true, notes = "获取试用转正通知列表")
public String getSyzztxlist() throws Exception {
String username = CSContext.getUserName();
int days = Integer.valueOf(HrkqUtil.getParmValue("TRYNOTICEBEFOREDAY"));// 试用考察提前通知X天
// String sqlstr = "SELECT * FROM hr_entry_try " +
// "WHERE hwc_namezl <>'OO' and (trystat =2 OR trystat=1 ) AND
// promotionday<=DATE_SUB(NOW(),INTERVAL " + days + " DAY)";
String sqlstr = "SELECT t.* FROM hr_entry_try t,hr_employee e " + "WHERE t.hwc_namezl <>'OO' "
+ " AND((t.trystat = 2 OR t.trystat = 1) AND t.promotionday <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY) "
+ " OR (t.trystat=3 AND t.delaypromotionday<= DATE_SUB(NOW(), INTERVAL -" + days + " DAY))) "
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
sqlstr = sqlstr + " order by IF(e.employee_code='" + username + "',0,1) ";
sqlstr = sqlstr + " LIMIT 300";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getSyzzyqlist", Authentication = true, ispublic = true, notes = "获取试用转正延期列表")
public String getSyzzyqlist() throws Exception {
// String sqlstr = "SELECT * FROM hr_entry_try " +
// "WHERE hwc_namezl <>'OO' and trystat=3 ";
String username = CSContext.getUserName();
String sqlstr = "SELECT t.* FROM hr_entry_try t,hr_employee e " + "WHERE t.trystat=3 and t.hwc_namezl <>'OO'"
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
sqlstr = sqlstr + " order by IF(e.employee_code='" + username + "',0,1) ";
sqlstr = sqlstr + " LIMIT 300";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getSyzztxinfo", Authentication = true, ispublic = true, notes = "获取个人试用转正提示信息")
public String getSyzztxinfo() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_employee t WHERE t.employee_code = '" + username + "'";
Hr_employee emp = new Hr_employee();
emp.findBySQL(sqlstr, false);
if (emp.isEmpty()) {
throw new Exception("当前登录用户无对应人事资料");
}
sqlstr = "SELECT * FROM hr_entry_try WHERE employee_code='" + username + "'";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getkczzlist", Authentication = true, ispublic = true, notes = "获取考察转正通知列表")
public String getkczzlist() throws Exception {
String username = CSContext.getUserName();
int days = Integer.valueOf(HrkqUtil.getParmValue("TRYNOTICEBEFOREDAY"));// 试用考察提前通知X天
// String sqlstr = "SELECT * FROM hr_transfer_try " +
// "WHERE (trystat =2 OR trystat=1 ) and hwc_namezl <>'OO' AND
// probationdate<=DATE_SUB(NOW(),INTERVAL " + days + " DAY)";
String sqlstr = "SELECT t.* FROM hr_transfer_try t,hr_employee e " + "WHERE t.hwc_namezl <> 'OO' "
+ "AND ((t.trystat = 2 OR t.trystat = 1) AND t.probationdate <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY) "
+ " OR (t.trystat = 3 AND t.delaypromotionday <= DATE_SUB(NOW(), INTERVAL -" + days + " DAY))) "
+ " AND e.empstatid > 1 AND e.empstatid < 10 AND e.er_id = t.er_id ";
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
sqlstr = sqlstr + " order by IF(e.employee_code='" + username + "',0,1) ";
sqlstr = sqlstr + " LIMIT 300";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getkcyclist", Authentication = true, ispublic = true, notes = "获取考察延长通知列表")
public String getkcyclist() throws Exception {
String username = CSContext.getUserName();
// String sqlstr = "SELECT * FROM hr_transfer_try " +
// "WHERE trystat=3 and hwc_namezl <>'OO' ";
String sqlstr = "SELECT t.* FROM hr_transfer_try t,hr_employee e " + "WHERE t.trystat=3 and t.hwc_namezl <>'OO'"
+ " AND e.empstatid>1 AND e.empstatid<10 AND e.er_id=t.er_id";
sqlstr = sqlstr + CSContext.getIdpathwhere().replace("idpath", "t.idpath");
sqlstr = sqlstr + " order by IF(e.employee_code='" + username + "',0,1) ";
sqlstr = sqlstr + " LIMIT 300";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "getkcyxinfo", Authentication = true, ispublic = true, notes = "获取个人考察延期提示信息")
public String getkcyxinfo() throws Exception {
String username = CSContext.getUserName();
String sqlstr = "SELECT * FROM hr_transfer_try WHERE employee_code='" + username + "' ORDER BY createtime DESC";
return DBPools.defaultPool().opensql2json(sqlstr);
}
////
@ACOAction(eventname = "getMySubmitWFS", Authentication = true, ispublic = true, notes = "获取我提交的流程")
public String getMySubmitWFS() throws Exception {
String sqlstr = "select DISTINCT * from (SELECT tp.wftempname, a.* ,p.procname,p.arivetime,p.procid " + " FROM shwwf a, shwwftemp tp ,shwwfproc p "
+ " WHERE a.stat = 1 " + " AND a.wftemid = tp.wftempid " + " AND a.wfid=p.wfid" + " AND p.isbegin<>1" + " AND p.isend<>1"
+ " AND p.stat=2" + " AND a.submituserid =" + CSContext.getUserID() + " ORDER BY a.createtime DESC ) tb where 1=1 ";
JSONArray rts = DBPools.defaultPool().opensql2json_O(sqlstr);
for (int i = 0; i < rts.size() - 1; i++) {
JSONObject jo = rts.getJSONObject(i);
sqlstr = "SELECT u.displayname,u.userid FROM shwwfproc p,shwwfprocuser u" + " WHERE p.procid=u.procid AND p.stat=2 AND u.stat IN(1,3) AND p.wfid="
+ jo.getString("wfid");
String names = "";
String uids = "";
List<HashMap<String, String>> us = DBPools.defaultPool().openSql2List(sqlstr);
for (int j = 0; j < us.size(); j++) {
HashMap<String, String> u = us.get(j);
names = names + u.get("displayname") + ",";
uids = uids + u.get("userid") + ",";
}
if (!names.isEmpty())
names = names.substring(0, names.length() - 1);
if (!uids.isEmpty())
uids = uids.substring(0, uids.length() - 1);
jo.put("curusers", names);
jo.put("curuserids", uids);
}
return rts.toString();
}
@ACOAction(eventname = "getEmpAddrInfos", Authentication = true, ispublic = true, notes = "获取通讯录")
public String getEmpAddrInfos() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
String sqlstr = "SELECT e.orgid,e.orgcode,e.orgname,e.employee_name,e.sp_name,e.lv_num,a.* " + " FROM hr_employee e,hr_interfaceempaddr a"
+ " WHERE e.employee_code=a.employee_code";
if ((orgid != null) && (!orgid.isEmpty())) {
sqlstr = sqlstr + " and e.orgid=" + orgid;
}
return new CReport(sqlstr, null).findReport();
}
}
<file_sep>/src/com/corsair/server/base/Tcode_xml.java
package com.corsair.server.base;
/**
* 过时
*
* @author Administrator
*
*/
public class Tcode_xml {
public int code;
public String xml;
}
<file_sep>/WebContent/webapp/js/common/orguser.js
/**
* Created by Administrator on 2014-09-24.
*/
$(document).ready(function () {
$("iframe").css("display", "block");
initGrids();
$("#orggridform").c_initDictionary();
$("#shwUserInfoForm").c_initDictionary();
getorgs();
});
function initGrids() {
$C.grid.initComFormaters({
comUrls: [
{
index: "dic5",
type: "combobox",
url: _serUrl + "/web/dict/getdictvalues.co?dicid=5",
valueField: 'dictvalue',
textField: 'language1'
},
{
index: "rol",
type: "combobox",
url: $C.cos.getRolesByUserID(),
valueField: 'roleid',
textField: 'rolename'
},
{
index: "opt",
type: "combobox",
url: $C.cos.getOptionsByUserID(),
valueField: 'positionid',
textField: 'positiondesc'
}
], onOK: function () {
$("#userinfo_orgs").datagrid({
columns: [
[
{
field: 'extorgname',
width: 300,
title: '机构'
},
{
field: 'isdefault',
width: 80,
title: '默认机构',
formatter: $C.grid.comFormaters['dic5'],
editor: $C.grid.comEditors['dic5']
},
{
field: 'inheritrole',
width: 80,
title: '继承权限',
formatter: $C.grid.comFormaters['dic5'],
editor: $C.grid.comEditors['dic5']
}
]
]
});
$("#userinfo_roles").datagrid({
columns: [
[
{
field: 'roleid',
width: 200,
title: '系统角色',
formatter: $C.grid.comFormaters['rol'],
editor: $C.grid.comEditors['rol']
}
]
]
});
$("#userinfo_postions").datagrid({
columns: [
[
{
field: 'positionid',
width: 200,
title: '系统岗位',
formatter: $C.grid.comFormaters['opt']
}
]
]
});
$("#shworg_finds").datagrid({
columns: [[
{
field: 'forgname',
width: 200,
title: '机构名称'
}
]]
});
}
});
}
var selectPostionsPW = undefined;
function userinfo_postions_append() {
var url = _serUrl + "/web/user/getorgs.co?type=gridtree";
var wo = {
id: "selectPostionsPW",
JPAClass: "com.corsair.server.generic.Shwposition", //对应后台JPAClass名
multiRow: true,
idField: 'positionid',
showTitle: false,
autoFind: true,
width: "500px",//
height: "400px",//
gdListColumns: [
{field: 'positiondesc', title: '流程岗位', width: 120}
],
onResult: function (rows) {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!$C.grid.getRowByField("#userinfo_postions", row.positionid, "positionid")) {
$("#userinfo_postions").datagrid("appendRow", {positionid: row.positionid});
}
}
}
};
if (!selectPostionsPW) {
selectPostionsPW = new TSearchForm(wo);
}
selectPostionsPW.show();
}
function getorgs() {
var url = _serUrl + "/web/user/getOrgsByLged.co?type=gridtree";
$("#orggrid").treegrid({
onClickRow: function (row) {
findorguser();
}, onDblClickRow: function (rowIndex, rowData) {
showOrgInfo($C.action.Edit);
},
onContextMenu: onOrgContextMenu,
url: url,
loadFilter: function (data, parentId) {
return data;
}
});
}
function setstateclosed(nodes) {
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
node.state = "closed";
if (node.children != undefined) {
setstateclosed(node.children);
}
}
}
function findorguser(userid) {
var node = $('#orggrid').treegrid('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的机构!', 'error');
return;
}
$ajaxjsonget($C.cos.userlistbyorg() + "?orgid=" + node.orgid,
function (jsondata) {
$("#usergrid").datagrid({
data: jsondata,
onDblClickRow: function (rowIndex, rowData) {
shwUserAction($C.action.Edit);
}
});
if (userid) {
var currow = undefined;
var us = $("#usergrid").datagrid("getRows");
for (var i = 0; i < us.length; i++) {
var u = us[i];
if (u.userid == userid) {
currow = u;
break;
}
}
if (currow) {
var idx = $("#usergrid").datagrid("getRowIndex", currow);
$("#usergrid").datagrid("selectRow", idx);
}
}
},
function (XMLHttpRequest, textStatus, errorThrown) {
alert("查询机构用户错误!");
}
);
}
/*var wdinfoex = {
isNew: false,
jsonData: data,
onOK: procok,
afterGetData:procgetdata(jsondata),
onCancel: proccancel,
onShow: onshow,
otherData: {}
}*/
function showOrgInfo(tp) {
var node = $('#orggrid').treegrid('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的机构!', 'error');
return;
}
var isnew, jsondata;
if (tp == $C.action.New) {//新建
isnew = true;
jsondata = {superid: node.orgid};//可加入初始化数据
}
if (tp == $C.action.Del) {//删除
if (node.children != undefined) {
$.messager.alert('错误', '有子机构不允许删除!', 'error');
return;
}
//delete from server
$.messager.confirm('提示', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delOrg + "?orgid=" + node.orgid, function (jsondata) {
if (jsondata.result == "OK")
$('#orggrid').treegrid("remove", node.orgid);
}, function () {
alert("删除机构错误!");
})
}
});
return;
}
if (tp == $C.action.Edit) {//编辑
isnew = false;
jsondata = node;
}
$("#orgeditwindow").c_popInfo({
isNew: isnew,
jsonData: jsondata,
onShow: function () {
$C.grid.clearData("shworg_finds");
if (!isnew) {
var url = _serUrl + "/web/user/getfindorgs.co?orgid=" + node.orgid;
$ajaxjsonget(url, function (jsondata) {
$("#shworg_finds").datagrid("loadData", jsondata);
}, function () {
$.messager.alert('错误', '获取查询机构列表错误!', 'error');
});
}
},
onOK: function (jsondata) {
//do save
if (isnew) {
jsondata.orgid = getnewid("shworg");
jsondata.idpath = node.idpath + jsondata.orgid + ",";
jsondata = {isnew: true, jsondata: jsondata};
} else {
jsondata = {isnew: false, jsondata: jsondata};
}
jsondata.jsondata.shworg_finds = $("#shworg_finds").datagrid("getData").rows;
var postdata = $.extend(true, {}, jsondata);//不上传子机构数据
postdata.jsondata.children = [];
$ajaxjsonpost($C.cos.saveOrg(), JSON.stringify(postdata), function (jsondata) {
var newdata = $.extend(jsondata.jsondata, jsondata);
//newdata.id = newdata.orgid;//兼容grid
//jsondata.children = chlds;
if (isnew) {
$('#orggrid').treegrid("append", {
parent: node.orgid,
data: [newdata]
})
} else {
$('#orggrid').treegrid("update", {id: newdata.orgid, row: newdata});
}
}, function () {
$.messager.alert('错误', '保存错误!', 'error');
});
return true;
}
});
}
var select_OrgFindIDP_pw = undefined;
function onADDFindIDPOrg() {
var node = $('#orggrid').treegrid('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的机构!', 'error');
return;
}
var url = _serUrl + "/web/user/getOrgsByLged.co?type=list&extorgname=true";
var wo = {
id: "select_OrgFindIDP_pw",
coURL: url,
orderStr: " orgid asc ",
multiRow: false,
autoFind: false,//是否自动查询
extParms: [],//扩展参数
width: "500px",//
height: "300px",//
gdListColumns: [
{field: 'extorgname', title: '机构', width: 400, notfind: true},
{field: 'orgname', title: '机构', width: 100, hidden: true}
],
onResult: function (rows) {
if (rows.length > 0) {
var row = rows[0];
if (row.idpath.substr(0, node.idpath.length) == node.idpath) {
$.messager.alert('错误', '不允许选择【当前机构】或【当前机构的子机构】!', 'error');
return;
}
if (!$C.grid.getRowByField('#shworg_finds', row.orgid, "forgid")) {
var data = {
orgid: node.orgid,
forgid: row.orgid,
forgname: row.extorgname,
fcode: row.code,
fidpath: row.idpath
};
$("#shworg_finds").datagrid("appendRow", data);
}
}
}
};
if (!select_OrgFindIDP_pw) {
select_OrgFindIDP_pw = new TSearchForm(wo);
}
select_OrgFindIDP_pw.show();
}
function getOrgRow(jsondata, orgid) {
for (var i = 0; i < jsondata.length; i++) {
var jd = jsondata[i];
if (jd.orgid == orgid) {
return jd;
} else {
if (jd.children != undefined) {
var rst = getOrgRow(jd.children, orgid);
if (rst != undefined) {
return rst;
}
}
}
}
return undefined;
}
function orgfindAction(tp) {
if (tp == $C.action.New) {
onADDFindIDPOrg();
//$C.grid.append('shworg_finds', {orgid: node.id}, true);
}
if (tp == $C.action.Del) {
var row = $('#shworg_finds').datagrid('getSelected');
if (row == undefined) {
$.messager.alert('错误', '没选定的查询机构!', 'error');
return;
}
var idx = $('#shworg_finds').datagrid("getRowIndex", row);
$('#shworg_finds').datagrid("deleteRow", idx);
}
}
function shwUserAction(tp) {
var org = $('#orggrid').treegrid('getSelected');
var row = $('#usergrid').datagrid('getSelected');
var idx = $('#usergrid').datagrid("getRowIndex", row);
var isnew;
if (tp == $C.action.New) {//新建
isnew = true;
var jsondata = {actived: 1, usertype: 2};
}
if (tp == $C.action.Del) {//删除
if (!row) {
$.messager.alert('错误', '没选定的用户!', 'error');
return;
}
//del
$.messager.confirm('提醒', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delUser + "?userid=" + row.userid, function (jsondata) {
if (jsondata.result == "OK")
$('#usergrid').datagrid("deleteRow", idx);
}, function () {
$.messager.alert('错误', '删除用户错误!', 'error');
});
}
});
return;
}
if (tp == $C.action.Reload) {//重置密码
if (!row) {
$.messager.alert('错误', '没选定的用户!', 'error');
return;
}
$.messager.confirm('提醒', '确认重置密码?', function (r) {
if (r) {
var url = _serUrl + "/web/login/reSetPWD.co";
var jsondata = JSON.stringify({userid: row.userid});
$ajaxjsonpost(url, jsondata, function (jsondata) {
if (jsondata.result) {
$.messager.alert('注意', '密码重置为[' + jsondata.result + ']请牢记新密码!', 'warning');
}
}, function (err) {
$.messager.alert('错误', '重置密码错误:' + err, 'error');
});
}
});
return;
}
if (tp == $C.action.Edit) {//编辑
if (!row) {
$.messager.alert('错误', '没选定的用户!', 'error');
return;
}
var jsondata = row;
isnew = false;
}
$("#usereditwindow").c_popInfo({
isNew: isnew,
jsonData: jsondata,
onOK: function (jsondata) {
$C.grid.accept("userinfo_orgs");
$C.grid.accept("userinfo_roles");
$C.grid.accept("userinfo_postions");
var orgdata = $("#userinfo_orgs").datagrid("getData").rows;
var roledata = $("#userinfo_roles").datagrid("getData").rows;
var posidata = $("#userinfo_postions").datagrid("getData").rows;
jsondata = {isnew: isnew, orgs: orgdata, roles: roledata, positions: posidata, jsondata: jsondata};
//console.error(JSON.stringify(jsondata));
$ajaxjsonpost($C.cos.saveUser(), JSON.stringify(jsondata), function (jsondata) {
if (isnew) {
$('#usergrid').datagrid('appendRow', jsondata);
} else {
$('#usergrid').datagrid('updateRow', {index: idx, row: jsondata});
}
}, function () {
alert("保存资料错误!");
});
return true;
},
onShow: function () {
if (isnew) {
$C.grid.clearData("userinfo_orgs");
$C.grid.clearData("userinfo_roles");
$C.grid.clearData("userinfo_postions");
$C.grid.append("userinfo_orgs", {
isdefault: 1,
inheritrole: 1,
orgid: org.orgid,
extorgname: org.extorgname
}, false);
} else {
getOrgsData();
getRolesData();
getOptionsData();
}
}
});
function getOrgsData() {
if (row.userid)
$ajaxjsonget($C.cos.getOrgsByUserID() + "?userid=" + row.userid, function (jsondata) {
$("#userinfo_orgs").datagrid({data: jsondata});
}, function () {
alert("getOrgsData错误");
})
}
function getRolesData() {
if (row.userid)
$ajaxjsonget($C.cos.getRolesByUserID() + "?userid=" + row.userid, function (jsondata) {
$("#userinfo_roles").datagrid({data: jsondata});
}, function () {
alert("错误");
})
}
function getOptionsData() {
if (row.userid)
$ajaxjsonget($C.cos.getOptionsByUserID() + "?userid=" + row.userid, function (jsondata) {
$("#userinfo_postions").datagrid({data: jsondata});
}, function () {
alert("错误");
})
}
}
function doFind(ty) {
if (ty == 1) {
onSelectOrg();
}
if (ty == 2) {
onFinduser();
}
}
var select_Org_pw = undefined;
function onSelectOrg() {
var url = _serUrl + "/web/user/getOrgsByLged.co?type=list&extorgname=true";
var wo = {
id: "select_Org_pw",
coURL: url,
orderStr: " orgid asc ",
multiRow: false,
autoFind: false,//是否自动查询
extParms: [],//扩展参数
width: "500px",//
height: "300px",//
gdListColumns: [
{field: 'extorgname', title: '机构', width: 400, notfind: true},
{field: 'orgname', title: '机构', width: 100, hidden: true}
]
};
if (!select_Org_pw) {
select_Org_pw = new TSearchForm(wo);
}
select_Org_pw.extendOptions({
onResult: function (rows) {
if (rows.length > 0) {
var row = rows[0];
doSelectOrg(row.orgid);
}
}
});
select_Org_pw.show();
}
function doFindOrgs(nodes, r) {
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.orgname.indexOf(r) >= 0) {
doSelectOrg(node.orgid);
return;
}
if (node.children) {
doFindOrgs(node.children, r);
}
}
}
function doSelectOrg(orgid) {
try {
$('#orggrid').treegrid('expandTo', orgid);
$('#orggrid').treegrid('select', orgid);
} catch (e) {
//alert(e.name + ": " + e.message);
}
}
var select_user_pw = undefined;
function onFinduser() {
var url = _serUrl + "/web/user/findOrgUserByLogined.co";
var wo = {
id: "select_user_pw",
coURL: url,
multiRow: false,
idField: 'userid',
autoFind: false,//是否自动查询
gdListColumns: [
{field: 'username', title: '登录名', width: 100},
{field: 'displayname', title: '姓名', width: 100},
{field: 'extorgname', title: '机构', width: 500, notfind: true}//不作为查询条件
],
onResult: function (rows) {
if (rows.length > 0) {
var row = rows[0];
doSelectOrg(row.orgid);
try {
findorguser(row.userid);
} catch (e) {
//alert(e.name + ": " + e.message);
}
}
}
};
if (!select_user_pw) {
select_user_pw = new TSearchForm(wo);
}
select_user_pw.show();
}
function onOrgContextMenu(e, row) {
if (row) {
e.preventDefault();
$(this).treegrid('select', row.orgid);
$('#orgmenu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
}
var cur_orgAction = 0;
var cur_node = null;
var select_OrgAppend2_pw = undefined;
//tp 1 并入 2 调整所属父机构 3 更名 4 注销
function orgAction(tp) {
var node = $('#orggrid').treegrid('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的机构!', 'error');
return;
}
cur_node = node;
cur_orgAction = tp;
if (tp == 1) {
$.messager.confirm('警告', '当前机构下所有资料将并入选择的机构,当前机构资料将被清空,是否继续?', function (r) {
if (r) {
$.messager.confirm('提示', '根据系统数据量大小,系统将占有较长时间运算,是否继续?', function (r) {
if (r) {
onSelectOrg2Appendto(node);
}
});
}
});
}
if (tp == 2) {
$.messager.confirm('警告', '将当前机构调整至选择机构下,是否继续?', function (r) {
if (r) {
$.messager.confirm('提示', '根据系统数据量大小,系统将占有较长时间运算,是否继续?', function (r) {
if (r) {
onSelectOrg2Appendto(node);
}
});
}
});
}
if (tp == 3) {
$.messager.prompt('输入', '请修改机构名称', function (r) {
if (r) {
if (r == node.orgname)
return;
var url = _serUrl + "/web/user/updateOrgName.co";
var data = {
orgid: node.orgid,
orgname: r
};
$ajaxjsonpost(url, JSON.stringify(data), function (jsdata) {
node.orgname = jsdata.orgname;
$('#orggrid').treegrid('update', {
id: node.orgid,
row: node
});
}, function (err) {
alert(err);
});
}
});
$('.messager-input').val(node.orgname).focus();
}
}
function onSelectOrg2Appendto(node) {
var url = _serUrl + "/web/user/getOrgsByLged.co?type=list&extorgname=true";
var wo = {
id: "select_Org_pw",
coURL: url,
orderStr: " orgid asc ",
multiRow: false,
autoFind: false,//是否自动查询
extParms: [],//扩展参数
width: "500px",//
height: "300px",//
gdListColumns: [
{field: 'extorgname', title: '机构', width: 400, notfind: true},
{field: 'orgname', title: '机构', width: 100, hidden: true}
]
};
if (!select_OrgAppend2_pw) {
select_OrgAppend2_pw = new TSearchForm(wo);
}
select_OrgAppend2_pw.extendOptions({
onResult: function (rows) {
if (rows.length > 0) {
var row = rows[0];
var data = {
tp: cur_orgAction,
sorgid: node.orgid,
dorgid: row.orgid
};
var url = _serUrl + "/web/user/putOrg2Org.co";
$ajaxjsonpost(url, JSON.stringify(data), function (jsdata) {
if (jsdata.result == "OK") {
if (cur_orgAction == 2) {
$('#orggrid').treegrid("remove", cur_node.orgid);
var parms = {
parent: row.orgid,
data: [cur_node]
};
$('#orggrid').treegrid('append', parms);
}
if (cur_orgAction == 1) {
if (cur_node.children) {
var ns = JSON.stringify(cur_node.children);
var nodes = JSON.parse(ns);
var oids = [];
for (var i = 0; i < nodes.length; i++) {
oids.push(nodes[i].orgid);
}
for (var i = 0; i < oids.length; i++) {
$('#orggrid').treegrid('remove', oids[i]);
}
var parms = {
parent: row.orgid,
data: nodes
};
$('#orggrid').treegrid('append', parms);
}
}
}
}, function (err) {
alert(err);
});
}
}
});
select_OrgAppend2_pw.show();
}
var findOrg2UserOrg_pw = undefined;
function findOrg2UserOrg() {
var url = _serUrl + "/web/user/getOrgsByLged.co?type=list&extorgname=true";
var wo = {
id: "select_Org_pw",
coURL: url,
orderStr: " orgid asc ",
multiRow: false,
autoFind: false,//是否自动查询
extParms: [],//扩展参数
width: "500px",//
height: "300px",//
gdListColumns: [
{field: 'extorgname', title: '机构', width: 400, notfind: true},
{field: 'orgname', title: '机构', width: 100, hidden: true}
]
};
if (!findOrg2UserOrg_pw) {
findOrg2UserOrg_pw = new TSearchForm(wo);
}
findOrg2UserOrg_pw.extendOptions({
onResult: function (rows) {
if (rows.length > 0) {
var row = rows[0];
if (!$C.grid.getRowByField("#userinfo_orgs", [row.orgid], ["orgid"])) {
var r = {};
r.orgid = row.orgid;
r.extorgname = row.extorgname;
r.isdefault = 2;
r.inheritrole = 1;
$C.grid.append('userinfo_orgs', r, true);
}
}
}
});
findOrg2UserOrg_pw.show();
}
<file_sep>/src/com/corsair/server/weixin/WXUtil.java
package com.corsair.server.weixin;
import java.io.File;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.util.Base64;
import com.corsair.server.util.CorUtil;
import com.corsair.server.weixin.entity.Shwwxapp;
import com.corsair.server.weixin.entity.Shwwxappqrcode;
import com.corsair.server.weixin.entity.Shwwxapptag;
import com.corsair.server.weixin.entity.Wx_received_msg;
import com.corsair.server.weixin.entity.Wx_user;
import com.corsair.server.weixin.entity.Wx_user_tag;
public class WXUtil {
/**
* @author shangwen
* 普通消息
* text 文本消息 image 图片消息 voice 语音消息 voice 视频消息 shortvideo 小视频消息
* location 地理位置消息 link 链接消息
* 事件消息
* subscribe 关注 subscribe_SCAN 扫描带参数二维码事件 unsubscribe 取消关注事件
* SCAN LOCATION 上报地理位置事件
* 菜单事件
* CLICK 点击菜单拉取消息时的事件推送 VIEW 点击菜单跳转链接时的事件推送
* auth2 鉴权
* 多客服
* OlS_notol 如果启用在线客服转发 , 收到任何普通消息将转发在线客服; 暂时先取消 还不确定
* KF_switch_session 多客服转接 貌似微信取消了 没找到
* 设备
* DeviceText 收到设备信息 DeviceEvent_Bind 设备绑定 DeviceEvent_UNBind 设备取消绑定
*
*/
public enum MsgType {
text, image, voice, video, shortvideo, location, link, subscribe, subscribe_SCAN, unsubscribe,
SCAN, LOCATION, CLICK, VIEW, auth2, OlS_notol, KF_switch_session, DeviceText, DeviceEvent_Bind,
DeviceEvent_UNBind,sendTemplateMsgFinish
}
// OlS_notol 客服不在线
/**
* 调用定义好的监听方法
*
* @param appid
* @param mstype
* @param postparms
*/
public static void callEventListener(String appid, MsgType mstype, Map<String, String> postparms) {
try {
WXEventListener el = getEventListener(appid);
if (el != null)
el.onEvent(appid, mstype, postparms);
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* 回复默认文本消息
*
* @param appid
* @param openid
* @param text_atrep_msg
* 返回值 表示需要调用默认发送方法
*/
public static boolean callReplayTextMessage(String appid, String openid, String text_atrep_msg) {
try {
WXEventListener el = getEventListener(appid);
if (el != null)
return el.onReplayTextMessage(appid, openid, text_atrep_msg);
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return true;
}
/** 回复默认图文消息
* @param appid
* @param openid
* @param newsid
* @return
*/
public static boolean callReplayNewsMessage(String appid, String openid, String newsid) {
try {
WXEventListener el = getEventListener(appid);
if (el != null)
return el.onReplayNewsMessage(appid, openid, newsid);
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return true;
}
public static WXEventListener getEventListener(String appid) throws Exception {
String lcname = WXAppParms.getAppParm(appid, "WxEventListener", "没有设置WxEventListener参数");// ConstsSw.geAppParmStr("WxEventListener");
if ((lcname == null) || lcname.isEmpty())
return null;
Class<?> clazz = Class.forName(lcname);
if (!WXEventListener.class.isAssignableFrom(clazz))
throw new Exception("微信事件监听类【" + lcname + "】必须实现【com.corsair.server.weixin.WXEventListener】接口");
return (WXEventListener) clazz.newInstance();
}
public static long getWXDatetime() {
return Math.round((double) System.currentTimeMillis() / 1000);
}
public static String createWXSha1Sign(HashMap<String, String> map) throws Exception {
Object[] key_arr = map.keySet().toArray();
Arrays.sort(key_arr);
String strA = "";
for (Object key : key_arr) {
Object o = map.get(key);
if (o == null)
continue;
String value = o.toString();
if (value.isEmpty())
continue;
strA = strA + key + "=" + value + "&";
}
if (strA.isEmpty())
throw new Exception("没有需要签名的数据");
else
strA = strA.substring(0, strA.length() - 1);
// System.out.println("strA:" + strA);
String rst = DigestUtils.sha1Hex(strA);
// System.out.println("sha1Str:" + rst);
return rst;
}
public static boolean checkSign(String Tonken, String signature, String timestamp, String nonce) throws Exception {
String[] tmpArr = { Tonken, timestamp, nonce };
Arrays.sort(tmpArr);
String strtmp = "";
for (String s : tmpArr) {
strtmp = strtmp + s;
}
String temstr = DigestUtils.sha1Hex(strtmp);
return signature.equalsIgnoreCase(temstr);
}
/**
* 解析微信消息成map,参数大小写不变
*
* @param xml
* @return
* @throws Exception
*/
public static Map<String, String> parePostData(String xml) throws Exception {
Map<String, String> rst = new HashMap<String, String>();
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
for (int i = 0; i < root.elements().size(); i++) {
Element el = (Element) root.elements().get(i);
rst.put(el.getName(), el.getTextTrim());
}
return rst;
}
public static void createMenu(String appid) throws Exception {
String fsep = System.getProperty("file.separator");
// String fname = ConstsSw._root_filepath + "WEB-INF" + fsep + "conf" +
// fsep + "weixinmenu.json";
String fname = ConstsSw._root_filepath + "WEB-INF" + fsep + "conf" + fsep + "wxmenu" + fsep;
fname = fname + appid + ".json";
File f = new File(fname);
if (f.exists() && f.isFile()) {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(f);
String ms = rootNode.toString();
String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + getTonken(appid);
String rst = WXHttps.postHttps(url, null, ms.trim());
// System.out.println("创建微信菜单:" + rst);
} else {
throw new Exception("微信菜单文件【" + fname + "】不存在");
}
}
/**
* 创建默认菜单
*
* @param appid
* @return
* @throws Exception
*/
public static String createMenuex(String appid) throws Exception {
Shwwxapp app = WXAppParms.getByAppID(Integer.valueOf(appid));
if (app.menujson.isEmpty())
throw new Exception("未设置菜单内容");
return createMenuex(app.wxappid.getValue(), app.menujson.getValue());
// {"errcode":0,"errmsg":"ok"}
}
public static String createMenuex(String appid, String menujson) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + getTonken(appid);
return WXHttps.postHttps(url, null, menujson);
}
/**
* 获取菜单,包括默认菜单和tag菜单
*
* @param appid
* @return
* @throws Exception
*/
public static String getWXOnlineMenu(String appid) throws Exception {
Shwwxapp app = WXAppParms.getByAppID(Integer.valueOf(appid));
String url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + getTonken(app.wxappid.getValue());
return WXHttps.getHttps(url, null);
// {"errcode":0,"errmsg":"ok"}
}
/**
* 只删除微信端菜单 本地不动,否则删错了会死人滴
*
* @param appid
* @return
* @throws Exception
*/
public static String deleteallmenu(String appid) throws Exception {
Shwwxapp app = WXAppParms.getByAppID(Integer.valueOf(appid));
String url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + getTonken(app.wxappid.getValue());
return WXHttps.getHttps(url, null);
// {"errcode":0,"errmsg":"ok"}
}
/**
* 创建标签菜单
*
* @param tag
* @throws Exception
*/
public static void createTagMenuex(Shwwxapptag tag) throws Exception {
if (tag.tagmenujson.isEmpty())
throw new Exception("未设置菜单内容");
if (tag.tagid.isEmpty())
throw new Exception("没有tagid,可能是tag未同步到微信");
Shwwxapp app = WXAppParms.getByAppID(tag.appid.getAsInt());
String rst = createTagMenuex(app, tag.tagid.getValue(), tag.tagmenujson.getValue());
JSONObject jrst = JSONObject.fromObject(rst);
tag.wxtagmenuid.setValue(jrst.getString("menuid")); // {"menuid":"208379533"}
tag.save();
}
public static String createTagMenuex(Shwwxapp app, String tagid, String tagmenujson) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" + getTonken(app.wxappid.getValue());
JSONObject mj = JSONObject.fromObject(tagmenujson);
JSONObject mcj = new JSONObject();
mcj.put("tag_id", tagid);
mj.put("matchrule", mcj);
return WXHttps.postHttps(url, null, mj.toString());
}
/**
* 移除标签菜单
*
* @param tag
* @throws Exception
*/
public static void delTagMenuex(Shwwxapptag tag) throws Exception {
if (tag.wxtagmenuid.isEmpty())
throw new Exception("微信菜单ID为空");
Shwwxapp app = WXAppParms.getByAppID(tag.appid.getAsInt());
delTagMenuex(app, tag.wxtagmenuid.getValue());
tag.wxtagmenuid.setValue(null);
tag.save();
}
/**
* 移除标签菜单 不处理标签菜单ID
*
* @param app
* @param menuid
* @throws Exception
*/
public static void delTagMenuex(Shwwxapp app, String menuid) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=" + getTonken(app.wxappid.getValue());
JSONObject mj = new JSONObject();
mj.put("menuid", menuid);
String rst = WXHttps.postHttps(url, null, mj.toString());
}
/**
* 按标签删除所有标签菜单,不处理标签菜单ID
*
* @param app
* @param tagid
* @throws Exception
*/
public static void detTagMenmuex(Shwwxapp app, String tagid) throws Exception {
String mstr = getWXOnlineMenu(app.appid.getValue());
JSONObject moj = JSONObject.fromObject(mstr);
if (moj.has("conditionalmenu")) {
JSONArray ms = moj.getJSONArray("conditionalmenu");
for (int i = 0; i < ms.size(); i++) {
JSONObject m = ms.getJSONObject(i);
if (m.has("matchrule") && (m.getJSONObject("matchrule").has("group_id"))) {
String group_id = m.getJSONObject("matchrule").getString("group_id");
if (tagid.equals(group_id)) {
String menuid = m.getString("menuid");
delTagMenuex(app, menuid);
}
}
}
}
}
/**
* 创建微信标签
*
* @param appid
* @param tgid
* @return
* @throws Exception
*/
public static String createWXTag(Shwwxapptag tag) throws Exception {
Shwwxapp app = WXAppParms.getByAppID(tag.appid.getAsInt());
String url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
// { "tag" : { "name" : "广东"//标签名 } }
JSONObject jo = new JSONObject();
JSONObject jotag = new JSONObject();
jotag.put("name", tag.tagname.getValue());
jo.put("tag", jotag);
return WXHttps.postHttps(url, null, jo.toString());
}
/**
* 更新本地微信标签
*
* @param app
* @throws Exception
*/
public static void updateWXTag(Shwwxapp app) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
// { "tag" : { "name" : "广东"//标签名 } }
String rst = WXHttps.getHttps(url, null);
System.out.println(rst);
JSONObject jrst = JSONObject.fromObject(rst);
JSONArray tags = jrst.getJSONArray("tags");
Shwwxapptag tg = new Shwwxapptag();
String sqlstr = "update shwwxapptag set wxusable=2 where appid=" + app.appid.getValue();
tg.pool.execsql(sqlstr);// 更新前先设置所有tag 微信标志不可用
for (int i = 0; i < tags.size(); i++) {
JSONObject tag = tags.getJSONObject(i);
// { "id":1, "name":"每天一罐可乐星人", "count":0 //此标签下粉丝数 }
String tagid = tag.getString("id");
String tagname = tag.getString("name");
String uscount = tag.getString("count");
sqlstr = "select * from shwwxapptag where appid=" + app.appid.getValue() + " and tagid=" + tagid;
tg.clear();
tg.findBySQL(sqlstr);
if (!tg.isEmpty()) {// 根据appid 和 tagid 检索,如果有则更新其它属性
tg.tagname.setValue(tagname);
tg.uscount.setValue(uscount);
tg.wxusable.setAsInt(1);
tg.save();
} else {
sqlstr = "select * from shwwxapptag where appid=" + app.appid.getValue() + " and tagname='" + tagname + "'";
tg.findBySQL(sqlstr);
if (!tg.isEmpty()) {// 根据appid 和 tagname 检索,如果有则更新其它属性
tg.tagid.setValue(tagid);
tg.uscount.setValue(uscount);
tg.wxusable.setAsInt(1);
tg.save();
} else {// 还没找到则新建一个
tg.clear();
tg.tagid.setValue(tagid);
tg.appid.setValue(app.appid.getValue());
tg.tagname.setValue(tagname);
tg.uscount.setValue(uscount);
tg.wxusable.setAsInt(1);
tg.save();
}
}
}
// 更新缓存数据
sqlstr = "select * from shwwxapptag where appid=" + app.appid.getValue();
app.shwwxapptags.clear();
app.shwwxapptags.findDataBySQL(sqlstr);
}
public static void doSaveReceivedMsg(WXUtil.MsgType msgtype, Map<String, String> postparms) {
try {
Wx_received_msg rm = new Wx_received_msg();
rm.fromusername.setValue(postparms.get("FromUserName").toString());
rm.createtime.setValue(postparms.get("CreateTime").toString());
rm.msgtype.setValue(postparms.get("MsgType").toString());
switch (msgtype) {
case text:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.content.setValue(postparms.get("Content").toString());
break;
case image:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.picurl.setValue(postparms.get("PicUrl").toString());
rm.mediaid.setValue(postparms.get("MediaId").toString());
break;
case voice:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.title.setValue(postparms.get("Format").toString());
rm.mediaid.setValue(postparms.get("MediaId").toString());
break;
case video:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.title.setValue(postparms.get("ThumbMediaId").toString());
rm.mediaid.setValue(postparms.get("MediaId").toString());
break;
case location:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.location_x.setValue(postparms.get("Location_X").toString());
rm.location_y.setValue(postparms.get("Location_Y").toString());
rm.scale.setValue(postparms.get("Scale").toString());
rm.label.setValue(postparms.get("Label").toString());
break;
case link:
rm.msgid.setValue(postparms.get("MsgId").toString());
rm.title.setValue(postparms.get("Title").toString());
rm.description.setValue(postparms.get("Description").toString());
rm.url.setValue(postparms.get("Url").toString());
break;
case subscribe:
case unsubscribe:
rm.event.setValue(postparms.get("Event").toString());
break;
case subscribe_SCAN:
rm.event.setValue(postparms.get("Event").toString());
rm.eventkey.setValue(postparms.get("EventKey").toString());
break;
case SCAN:
rm.event.setValue(postparms.get("Event").toString());
rm.eventkey.setValue(postparms.get("EventKey").toString());
break;
case LOCATION:
rm.event.setValue(postparms.get("Event").toString());
rm.latitude.setValue(postparms.get("Latitude").toString());
rm.longitude.setValue(postparms.get("Longitude").toString());
rm.precision.setValue(postparms.get("Precision").toString());
break;
case CLICK:
rm.event.setValue(postparms.get("Event").toString());
rm.eventkey.setValue(postparms.get("EventKey").toString());
break;
case VIEW:
rm.event.setValue(postparms.get("Event").toString());
rm.eventkey.setValue(postparms.get("EventKey").toString());
break;
}
rm.save();
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* 获取单个用户信息
*
* @param appid
* @param openid
* @param subscribed
* @return
* @throws Exception
*/
public static Wx_user getSingleWXUser(String appid, String openid) {// , boolean subscribed
try {
Shwwxapp app = WXAppParms.getByWXAppID(appid);
if ((app == null) || app.isEmpty()) {
throw new Exception("APPID【" + appid + "】参数未发现");
}
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getTonken(appid)
+ "&openid=" + openid + "&lang=zh_CN";
String rsp = WXHttps.getHttps(url, null);
JSONObject ju = JSONObject.fromObject(rsp);
return updateLocalWxUserInfo(app, ju);
} catch (Exception e) {
try {
Logsw.error(e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
}
/**
* 根据返回详细信息 更新本地微信粉丝信息
* {
* "subscribe": 1,
* "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
* "nickname": "Band",
* "sex": 1,
* "language": "zh_CN",
* "city": "广州",
* "province": "广东",
* "country": "中国",
* "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
* "subscribe_time": 1382694957,
* "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
* "remark": "",
* "groupid": 0,
* "tagid_list":[128,2],
* "subscribe_scene": "ADD_SCENE_QR_CODE",
* "qr_scene": 98765,
* "qr_scene_str": ""
* }
* 或
* {
* "subscribe": 0,
* "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg"
* }
*
* @param ju
* @throws Exception
*/
private static Wx_user updateLocalWxUserInfo(Shwwxapp app, JSONObject ju) throws Exception {
String openid = ju.getString("openid");
Wx_user user = new Wx_user();
String sqlstr = "select * from wx_user where openid='" + openid + "'";
user.findBySQL(sqlstr);
if (ju.getInt("subscribe") == 1) {
user.subscribe.setValue("1");
user.openid.setValue(openid);
user.nickname.setValue(ju.getString("nickname"));
user.b64nickname.setValue(Base64.EncodeStringBase64(ju.getString("nickname")));
Integer isex = ju.getInt("sex");
if (isex == 1)
user.sex.setAsInt(2);
else if (isex == 2)
user.sex.setAsInt(1);
else
user.sex.setAsInt(0);
user.city.setValue(ju.getString("city"));
user.country.setValue(ju.getString("country"));
user.province.setValue(ju.getString("province"));
user.language.setValue(ju.getString("language"));
user.headimgurl.setValue(ju.getString("headimgurl"));
user.subscribe_time.setValue(ju.getString("subscribe_time"));
user.remark.setValue(ju.getString("remark"));
user.subscribe_scene.setValue(ju.getString("subscribe_scene"));
user.qr_scene.setValue(ju.getString("qr_scene"));
user.qr_scene_str.setValue(ju.getString("qr_scene_str"));
} else {
String nsstr = WXAppParms.getAppParm(app, "NeedSubscribe");
if (nsstr != null) {
nsstr = nsstr.trim();
int ns = Integer.valueOf(nsstr);
if (ns == 1) {
String surl = WXAppParms.getAppParm(app, "SubscribeUrl");
if ((surl == null) || (surl.trim().isEmpty()))
throw new Exception("需要设置参数【SubscribeUrl】");
CSContext.getResponse().sendRedirect(surl);
return null;
}
}
user.subscribe.setValue("0");
user.openid.setValue(openid);
}
user.appid.setValue(app.wxappid.getValue());
user.update_time.setAsDatetime(new Date());
user.save();
updateUserTag(user, ju.getString("tagid_list"));
return user;
}
/**
* 更新微信粉丝 的 tags
*
* @param user
* @param tagid_list
* "tagid_list":[128,2]
* @throws Exception
*/
private static void updateUserTag(Wx_user user, String tagid_list) throws Exception {
if ((tagid_list == null) || (tagid_list.isEmpty()))
return;
Shwwxapp app = WXAppParms.getByWXAppID(user.appid.getValue());
if ((app == null) || app.isEmpty()) {
throw new Exception("APPID【" + user.appid.getValue() + "】参数未发现");
}
Wx_user_tag ut = new Wx_user_tag();
String sqlstr = "delete from wx_user_tag where wxuserid=" + user.wxuserid.getValue();
ut.pool.execsql(sqlstr);
if (tagid_list.startsWith("["))
tagid_list = tagid_list.substring(1, tagid_list.length());
if (tagid_list.endsWith("]"))
tagid_list = tagid_list.substring(0, tagid_list.length() - 1);
String[] ids = tagid_list.split(",");
for (String id : ids) {
if ((id == null) || (id.isEmpty()))
continue;
Shwwxapptag tag = WXAppParms.getTag(app, id);
if (tag == null) {// 去同步tag
throw new Exception("tagid为【" + id + "】的tag不存在,试着先同步tags");
}
ut.clear();
ut.wxuserid.setValue(user.wxuserid.getValue());// wxuserid
ut.openid.setValue(user.openid.getValue()); // openid
ut.tgid.setValue(tag.tgid.getValue()); // 平台ID
ut.appid.setValue(app.appid.getValue());// 平台appid
ut.tagid.setValue(id); // 微信tagid 一开始允许为空,同步后不能为空
ut.tagname.setValue(tag.tagname.getValue()); // tag名称
ut.save();
}
}
// // 通过Oauth2.0授权后获取用户资料
// public static Wx_user updateWXUserByOAuth2(String access_token, String appid, String openid) {
// try {
// String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
// String rsp = WXHttps.getHttps(url, null);
// HashMap<String, String> data = CJSON.Json2HashMap(rsp);
// Wx_user user = new Wx_user();
// String sqlstr = "select * from wx_user where openid='" + openid + "'";
// user.findBySQL(sqlstr);
// if (user.isEmpty())
// user.subscribe.setValue("0");
// user.appid.setValue(appid);
// user.openid.setValue(getMapStr(data, "openid"));
// user.nickname.setValue(getMapStr(data, "nickname"));
// user.b64nickname.setValue(Base64.EncodeStringBase64(getMapStr(data, "nickname")));
// Integer isex = Integer.valueOf(getMapStr(data, "sex").trim());
// if (isex == 1)
// user.sex.setAsInt(2);
// else if (isex == 2)
// user.sex.setAsInt(1);
// else
// user.sex.setAsInt(0);
// user.city.setValue(getMapStr(data, "city"));
// user.country.setValue(getMapStr(data, "country"));
// user.province.setValue(getMapStr(data, "province"));
// user.language.setValue("zh_CN");
// user.headimgurl.setValue(getMapStr(data, "headimgurl"));
// user.unionid.setValue(getMapStr(data, "unionid"));
// user.update_time.setAsDatetime(new Date());
// user.privilege.setValue(getMapStr(data, "privilege"));
// user.save();
// updateUserTag(user, getMapStr(data, "tagid_list"));
// return user;
// } catch (Exception e) {
// try {
// Logsw.error(e);
// } catch (Exception e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// return null;
// }
// }
private static String getMapStr(HashMap<String, String> map, String key) {
if (map.get(key) == null)
return null;
else
return map.get(key).toString();
}
public static Wx_user findUser(String appid, String openid) throws Exception {
Wx_user user = new Wx_user();
user.findBySQL("select * from wx_user where openid='" + openid + "'");
if (user.isEmpty()) {
user = getSingleWXUser(appid, openid);
}
return user;
}
/**
* @param wxappid
* @return
* @throws Exception
*/
public static String getTonken(String wxappid) throws Exception {
if ((wxappid == null) || wxappid.isEmpty())
throw new Exception("获取Tonken【appid】不允许为空");
String pn = WXAppParms.getAppParm(wxappid, "WxDbpool");
CDBPool pool = DBPools.poolByName(pn);
String sqlstr = "select tonken from wx_access_tonken where appid='" + wxappid + "'";
List<HashMap<String, String>> rows = pool.openSql2List(sqlstr);
if (rows.size() <= 0) {
throw new Exception("没有发现Tonken,请确认,Tonken服务是否运行");
} else {
return rows.get(0).get("tonken").toString();
}
}
/**
* @param wxappid
* @return
* @throws Exception
*/
public static String getTicket(String wxappid) throws Exception {
String pn = WXAppParms.getAppParm(wxappid, "WxDbpool");
CDBPool pool = DBPools.poolByName(pn);
String sqlstr = "select ticket from wx_access_tonken where appid='" + wxappid + "'";
List<HashMap<String, String>> rows = pool.openSql2List(sqlstr);
if (rows.size() <= 0) {
throw new Exception("没有发现ticket,请确认,ticket服务是否运行");
} else {
return rows.get(0).get("ticket").toString();
}
}
// 获取在线客服信息
// kf_account 完整客服账号,格式为:账号前缀@公众号微信号
// status 客服在线状态 1:pc在线,2:手机在线。若pc和手机同时在线则为 1+2=3
// kf_id 客服工号
// auto_accept 客服设置的最大自动接入数
// accepted_case 客服当前正在接待的会话数
public static List<HashMap<String, String>> getOnLineServerList(String appid) {
try {
String url = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=" + getTonken(appid);
String rsp = WXHttps.getHttps(url, null);
// {"kf_online_list":[]}
HashMap<String, String> rst = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rsp);
rsp = rootNode.path("kf_online_list").toString();
List<HashMap<String, String>> oss = CJSON.parArrJson(rsp);
return oss;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
// <ToUserName><![CDATA[touser]]></ToUserName>
// <FromUserName><![CDATA[fromuser]]></FromUserName>
// <CreateTime>1399197672</CreateTime>
// <MsgType><![CDATA[event]]></MsgType>
// <Event><![CDATA[kf_switch_session]]></Event>
// <FromKfAccount><![CDATA[test1@test]]></FromKfAccount>
// <ToKfAccount><![CDATA[test2@test]]></ToKfAccount>
public static void createKFSession(String appid, Map<String, String> postparms) {
String rst = null;
try {
String ToKfAccount = postparms.get("ToKfAccount").toString();
String FromUserName = postparms.get("FromUserName").toString();
String url = " https://api.weixin.qq.com/customservice/kfsession/create?access_token=" + getTonken(appid);
String data = "{\"kf_account\": \"" + ToKfAccount + "\","
+ "\"openid\" : \"" + FromUserName + "\","
+ "\"text\" : \"这是一段附加信息\"}";
rst = WXHttps.postHttps(url, null, data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("rst" + rst);
}
// {"total":7,"count":7,"data":{"openid":["<KEY>","<KEY>",
// "<KEY>","<KEY>","<KEY>",
// "oIDso1Mrt5R0R30ramu8k4_-llVQ","<KEY>"]},
// "next_openid":"<KEY>h<KEY>"}
public static void updateAllUser(Shwwxapp app) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
// +"&next_openid=NEXT_OPENID"
String rst = WXHttps.getHttps(url, null);
JSONObject jr = JSONObject.fromObject(rst);
int loadedcount = 0;
int total = jr.getInt("total");
int count = jr.getInt("count");
loadedcount = loadedcount + count;
String next_openid = jr.getString("next_openid");
JSONArray jopenids = jr.getJSONObject("data").getJSONArray("openid");
parseOpenIDList(app, jopenids);// 解析OPENID 列表 并处理
while (loadedcount < total) {
url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + WXUtil.getTonken(app.wxappid.getValue()) + "&next_openid=" + next_openid;
rst = WXHttps.getHttps(url, null);
jr = JSONObject.fromObject(rst);
total = jr.getInt("total");
count = jr.getInt("count");
loadedcount = loadedcount + count;
next_openid = jr.getString("next_openid");
jopenids = jr.getJSONObject("data").getJSONArray("openid");
parseOpenIDList(app, jopenids);// 解析OPENID 列表 并处理
}
}
/**
* 将获取到的openid列表 按100 个包装成获取详情的json
*
* @param jopenids
* ["openid1","openid2"]
* @throws Exception
*/
private static void parseOpenIDList(Shwwxapp app, JSONArray jopenids) throws Exception {
int total = jopenids.size();
final int tmax = 100;// 批量拉取 每次最多100
int pages = ((total % tmax) == 0) ? total / tmax : (total / tmax) + 1; // 页数-1
System.out.println("pages:" + pages);
for (int p = 0; p <= pages; p++) {
JSONArray ids = new JSONArray();
for (int i = 0; i < tmax; i++) {
int idx = p * tmax + i;
if (idx >= total)
break;
JSONObject id = new JSONObject();
id.put("openid", jopenids.getString(idx));
id.put("lang", "zh_CN");
ids.add(id);
}
if (ids.size() <= 0)
return;
getWXUserInfo(app, ids);
}
}
/**
* 通过openids 批量获取 用户详情
*
* @param ids
* 不超过100个
* [
* {
* "openid": "otvxTs4dckWG7imySrJd6jSi0CWE",
* "lang": "zh_CN"
* },
* {
* "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg",
* "lang": "zh_CN"
* }
* ]
* @throws Exception
*/
private static void getWXUserInfo(Shwwxapp app, JSONArray ids) throws Exception {
if (ids.size() <= 0)
return;
String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
JSONObject data = new JSONObject();
data.put("user_list", ids);
String rst = WXHttps.postHttps(url, null, data.toString());
// System.out.println("rst:" + rst);
JSONArray jus = JSONObject.fromObject(rst).getJSONArray("user_info_list");
for (int i = 0; i < jus.size(); i++) {
JSONObject ju = jus.getJSONObject(i);
updateLocalWxUserInfo(app, ju); // 更新用户资料
}
}
/**
* 为批量用户取消标签
*
* @param app
* @param jopenids
* ["openid1","openid2"] 长度不能超过50
* @param tagid
* @throws Exception
*/
public static void cancelUserTag(Shwwxapp app, JSONArray jopenids, int tagid) throws Exception {
if (jopenids.size() <= 0)
return;
if (jopenids.size() > 50)
throw new Exception("用户数量不能大于50");
String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
JSONObject data = new JSONObject();
data.put("openid_list", jopenids);
data.put("tagid", tagid);
String rst = WXHttps.postHttps(url, null, data.toString());
JSONObject jrst = JSONObject.fromObject(rst);
if (jrst.getInt("errcode") == 0) {
String ids = "";
for (int i = 0; i < jopenids.size(); i++) {
ids = ids + "'" + jopenids.getString(i) + "',";
}
if (!ids.isEmpty())
ids = ids.substring(0, ids.length() - 1);
String sqlstr = "DELETE FROM wx_user_tag WHERE tagid=" + tagid + " AND openid IN(" + ids + ") and appid=" + app.appid.getValue();
app.pool.execsql(sqlstr);
}
}
/**
* 为批量用户打标签
*
* @param app
* @param jopenids
* ["openid1","openid2"] 长度不能超过50
* @param tagid
* @throws Exception
*/
public static void addUserTag(Shwwxapp app, JSONArray jopenids, int tgid) throws Exception {
System.out.println("addUserTag:" + jopenids.size());
if (jopenids.size() <= 0)
return;
if (jopenids.size() > 50)
throw new Exception("用户数量不能大于50");
String sqlstr = "SELECT tgid,appid,tagid,tagname FROM shwwxapptag WHERE appid=" + app.appid.getValue() + " AND tgid=" + tgid;
Shwwxapptag tag = new Shwwxapptag();
tag.findBySQL(sqlstr);
if (tag.isEmpty())
throw new Exception("【" + app.wxappid.getValue() + "】标签不存在【" + tgid + "】");
String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
JSONObject data = new JSONObject();
data.put("openid_list", jopenids);
data.put("tagid", tag.tagid.getValue());
String rst = WXHttps.postHttps(url, null, data.toString());
System.out.println("rst:" + rst);
JSONObject jrst = JSONObject.fromObject(rst);
if (jrst.getInt("errcode") == 0) {
Wx_user_tag ut = new Wx_user_tag();
Wx_user user = new Wx_user();
for (int i = 0; i < jopenids.size(); i++) {
String openid = jopenids.getString(i);
sqlstr = "select * from wx_user where appid='" + app.wxappid.getValue() + "' and openid='" + openid + "'";
user.findBySQL(sqlstr);
if (user.isEmpty())
throw new Exception("微信用户不存在");
ut.clear();
sqlstr = "SELECT * FROM wx_user_tag WHERE tagid=" + tag.tagid.getValue() + " AND appid=" + app.appid.getValue() + " AND openid='" + jopenids.getString(i) + "'";
ut.findBySQL(sqlstr);
ut.wxuserid.setValue(user.wxuserid.getValue());// wxuserid
ut.openid.setValue(user.openid.getValue()); // openid
ut.tgid.setValue(tag.tgid.getValue()); // 平台ID
ut.appid.setValue(app.appid.getValue());// 平台appid
ut.tagid.setAsInt(tag.tagid.getAsInt()); // 微信tagid 一开始允许为空,同步后不能为空
ut.tagname.setValue(tag.tagname.getValue()); // tag名称
ut.save();
}
}
}
/**
* @param app
* @param expire_seconds
* 超时秒 0永久
* @param scene_id
* @param scene_str
* 如果为null 则创建 id的
* @throws Exception
*/
public static Shwwxappqrcode getWXQrcode(Shwwxapp app, int expire_seconds, int scene_id, String scene_str) throws Exception {
Shwwxappqrcode qc = new Shwwxappqrcode();
String sqlstr = null;
if ((scene_str == null) || (scene_str.isEmpty())) {
sqlstr = "SELECT * FROM shwwxappqrcode WHERE appid=" + app.appid.getValue() + " AND scene_id=" + scene_id + " AND (expiretime=0 OR expiretime<UNIX_TIMESTAMP(NOW()))";
} else {
sqlstr = "SELECT * FROM shwwxappqrcode WHERE appid=" + app.appid.getValue() + " AND scene_str='" + scene_str + "' AND (expiretime=0 OR expiretime<UNIX_TIMESTAMP(NOW()))";
}
qc.findBySQL(sqlstr);
if (!qc.isEmpty())
return qc;
JSONObject data = new JSONObject();
JSONObject action_info = new JSONObject();
JSONObject scene = new JSONObject();
String action_name = null;
if (expire_seconds == 0) {// 永久
qc.expiretime.setAsInt(0);
if ((scene_str == null) || (scene_str.isEmpty())) {// 永久整数
action_name = "QR_LIMIT_SCENE";
scene.put("scene_id", scene_id);
} else {// 永久字符串
action_name = "QR_LIMIT_STR_SCENE";
scene.put("scene_str", scene_str);
}
} else {
data.put("action_name", "QR_LIMIT_SCENE");
qc.expiretime.setAsLong(System.currentTimeMillis() / 1000 + expire_seconds);
if ((scene_str == null) || (scene_str.isEmpty())) {// 临时整数
action_name = "QR_SCENE";
scene.put("scene_id", scene_id);
} else {// 临时字符串
action_name = "QR_STR_SCENE";
scene.put("scene_str", scene_str);
}
}
data.put("action_name", action_name);
action_info.put("scene", scene);
data.put("action_info", action_info);
String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + WXUtil.getTonken(app.wxappid.getValue());
String rst = WXHttps.postHttps(url, null, data.toString());
System.out.println("rst:" + rst);
JSONObject jrst = JSONObject.fromObject(rst);
qc.ticket.setValue(jrst.getString("ticket"));
qc.url.setValue(jrst.getString("url"));
qc.scene_id.setAsInt(scene_id);
qc.scene_str.setValue(scene_str);
qc.appid.setValue(app.appid.getValue());
qc.save();
return qc;
}
}
<file_sep>/WebContent/webapp/js/common/icefallWorkFlow.min.js
/**
* Created by Administrator on 2014-10-22.
*/
WFEdit.prototype.loadFromWftemp = function (wftempdata) {
this.removeall();
for (var i = 0; i < wftempdata.shwwftempprocs.length; i++) {
var nodedata = wftempdata.shwwftempprocs[i];
//nodedata.stated = nodedata.stat;
nodedata.title = nodedata.proctempname;
nodedata.users = [];
for (var j = 0; j < nodedata.shwwftempprocusers.length; j++) {
nodedata.users.push({username: nodedata.shwwftempprocusers[j].displayname});
}
this.addNode(nodedata);
}
for (var i = 0; i < wftempdata.shwwftemplinklines.length; i++) {
var linedata = wftempdata.shwwftemplinklines[i];
if (!linedata.idx) linedata.idx = 0;
if (linedata.lltitle && (linedata.lltitle.length > 0))
linedata.title = linedata.lltitle + "(" + linedata.idx + ")";
else
linedata.title = linedata.lltitle;
var fNode = this.findNodeByWftemID(linedata.fromproctempid);
var tNode = this.findNodeByWftemID(linedata.toproctempid);
this.addLine(linedata, fNode, tNode);
}
this.reSetScroll();
};
WFEdit.prototype.findNodeByWftemID = function (wftid) {
var nodes = this.nodes();
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
//alert(node.getData().proctempid + " " + wftid);
if (node.getData().proctempid == wftid)
return node;
}
return null;
};
WFEdit.prototype.loadFromWf = function (wfdata) {
this.removeall();
for (var i = 0; i < wfdata.shwwfprocs.length; i++) {
var nodedata = wfdata.shwwfprocs[i];
nodedata.title = nodedata.procname;
nodedata.stated = nodedata.stat;
nodedata.users = [];
for (var j = 0; j < nodedata.shwwfprocusers.length; j++) {
var us = nodedata.shwwfprocusers[j];
var dt = parseInt(us.stat);
if (dt == 3) {
nodedata.users.push({username: us.displayname + "(驳回)"});
} else if (dt == 2) {
nodedata.users.push({username: us.displayname + "(完成)"});
} else
nodedata.users.push({username: us.displayname});
}
this.addNode(nodedata);
}
for (var i = 0; i < wfdata.shwwflinklines.length; i++) {
var linedata = wfdata.shwwflinklines[i];
linedata.title = linedata.lltitle;
var fNode = this.findNodeByWfID(linedata.fromprocid);
var tNode = this.findNodeByWfID(linedata.toprocid);
this.addLine(linedata, fNode, tNode);
}
this.reSetScroll();
};
WFEdit.prototype.findNodeByWfID = function (procid) {
var nodes = this.nodes();
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
//alert(node.getData().proctempid + " " + wftid);
if (node.getData().procid == procid)
return node;
}
return null;
};<file_sep>/src/com/hr/.svn/pristine/34/34dbd682c9c0b5ff76c36516ab51eae9f020db7d.svn-base
package com.hr.base.entity;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
@CEntity()
public class Hr_prolevel extends CJPA {
@CFieldinfo(fieldname = "lv_id", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField lv_id; // ID
@CFieldinfo(fieldname = "lv_num", notnull = true, caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "hg_id", notnull = true, caption = "职等ID", datetype = Types.INTEGER)
public CField hg_id; // 职等ID
@CFieldinfo(fieldname = "usable", caption = "有效状态", datetype = Types.INTEGER)
public CField usable; // 有效状态
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_prolevel() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/base/ConstsSw.java
package com.corsair.server.base;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.JPAControllerBase;
import com.corsair.server.ctrl.OnChangeOrgInfoListener;
import com.corsair.server.eai.EAIController;
import com.corsair.server.eai.PropertiesHelper;
import com.corsair.server.generic.Shwsystemparms;
import com.corsair.server.listener.SWSpecClass;
import com.corsair.server.util.DesSw;
import com.corsair.server.util.IPDataHandler;
import com.corsair.server.weixin.TonkenReflash;
/**
* 常量
*
* @author Administrator
*
*/
public class ConstsSw {
/**
* 是否启用redis,启用后session里面东西将保存到redis
*/
public static boolean _allow_redis = false;
public static String _redis_ip = null;
public static int _redis_port = 0;
public static int _redis_timeout = 0;
// public static long debug_zip_time = 0;
// public static long debug_base64_time = 0;
/**
* 好像EAI调用的吧?很久没用不记得了!!!!!!!!!!!
*/
public static EAIController eaicontroller = null;
/**
* 微信2小时更新一次的token
*/
public static TonkenReflash tonkenReflash = null;
/**
* ip地址解析对象
*/
public static IPDataHandler iphandler = null;
// // user session
public static final String session_logined = "LOGINED";
public static final String session_username = "USERNAME";
public static final String session_userpwd = "<PASSWORD>";
public static final String session_logintime = "LOGINTIME";
public static final String session_activetime = "ACTIVETIME";
public static final String session_remoteaddr = "REMOTEADDR";
// //
// public static final String MSG_OF_LOGIN_ACCESS = "Login Accessed";
// public static String spms_ltable = "";// 表
// public static String spms_luserfd = "";// 用户名字段
// public static String spms_lpwdfd = "";// 用户密码字段
// public static String spms_lstaufd = "";// 用户状态字段
// public static float spms_llowestver = 0;// 最低版本
// public static String spms_ls_dftv = "";// 允许登录的值
// public static List<String[]> spms_lnotallvs = new ArrayList<String[]>();// 不允许登录的值和提示信息
/**
* corsair.properties参数列表
*/
public static HashMap<Object, Object> _app_parms = new HashMap<Object, Object>();
/**
* Shwsystemparms表中的参数列表
*/
public static CJPALineData<Shwsystemparms> _sys_parms = null;
/**
* CO请求处理列表
*/
public static HashMap<String, Object> _allCoClassName = new HashMap<String, Object>(); // 所有co请求
/**
* 特殊类列表 如servetContextInit
*/
public static List<SWSpecClass> _allSpecClass = new ArrayList<SWSpecClass>();//
/**
* 所有 websocket 类
*/
public static HashMap<String, Object> _allSocketClassName = new HashMap<String, Object>(); //
/**
* 公用JPAController
*/
public static JPAControllerBase publicJPAController = null;
/**
* 机构信息变化监听器
*/
public static OnChangeOrgInfoListener _onchgorginfolestener;//
/**
* 文件变化监听器
*/
public static FileAlterationMonitor fmonitor = null;//
public static final int dbk_BLOB = 1;
public static final int dbk_CLOB = 2;
// public static Category[] _categoryArray = new Category[4];
/**
* 中间件路径 D:\MyWorks2\zy\webservice\tomcat71\
*/
public static String _service_path;
/**
* 系统应用路径 ,如:D:\MyWorks2\zy\webservice\tomcat71\webapps\dlhr\
*/
public static String _root_path;
/**
* 系统附件文件路径
*/
public static String _root_filepath;
/**
* EAI XML配置文件路径
*/
public static String eaiXMLFilePath;
/**
* EAI XML模板文件路径
*/
public static String excelModelPath;
/**
* 不求记得了
*/
public static PropertiesHelper eaiDatesProtertys;
public static final String _userkey = "Shangwen_!@#";
/**
* 获取应用参数
*
* @param key
* @return
*/
public static Object getAppParm(String key) {
return _app_parms.get(key);
}
/**
* 获取应用参数,不存在就报错
*
* @param key
* @param errmsg
* @return
* @throws Exception
*/
public static String geAppParmStr_E(String key, String errmsg) throws Exception {
Object o = _app_parms.get(key);
if (o == null) {
throw new Exception(errmsg);
}
return o.toString();
}
/**
* 获取Boolean类型应用参数
*
* @param key
* @return
*/
public static boolean getAppParmBoolean(String key) {
if (_app_parms.get(key) == null)
return false;
else
return Boolean.valueOf(_app_parms.get(key).toString().trim());
}
/**
* 获取int类型应用参数
*
* @param key
* @return
*/
public static int getAppParmInt(String key) {
return Integer.valueOf(_app_parms.get(key).toString());
}
/**
* 获取String类型应用参数
*
* @param key
* @return
*/
public static String geAppParmStr(String key) {
Object o = _app_parms.get(key);
if (o == null)
return null;
else
return o.toString();
}
/**
* 获取String类型系统参数
*
* @param parmname
* @return
*/
public static String getSysParm(String parmname) {
for (CJPABase jpa : _sys_parms) {
Shwsystemparms sp = (Shwsystemparms) jpa;
if (sp.parmname.getValue().equals(parmname)) {
return sp.parmvalue.getValue();
}
}
return null;
}
/**
* 获取boolean类型系统参数
*
* @param parmname
* @return
*/
public static boolean getSysParmBoolean(String parmname) {
String pv = getSysParm(parmname);
if (pv == null)
return false;
return Boolean.valueOf(pv);
}
/**
* 获取int类型系统参数
*
* @param parmname
* @return
*/
public static int getSysParmInt(String parmname) {
String pv = getSysParm(parmname);
if (pv == null)
return 0;
return Integer.valueOf(pv);
}
/**
* 获取int类型系统参数,没有或格式错误返回默认值
*
* @param parmname
* @param dftv
* @return
*/
public static int getSysParmIntDefault(String parmname, int dftv) {
String pv = getSysParm(parmname);
if (pv == null)
return dftv;
try {
return Integer.valueOf(pv);
} catch (NumberFormatException e) {
return dftv;
}
}
/**
* 按用户密码加密算法,加密字符串
*
* @param value
* @return
* @throws Exception
*/
public static String EncryUserPassword(String value) throws Exception {
return DesSw.EncryStrHex(value, ConstsSw._userkey);
}
/**
* 按用户密码解密算法,解密字符串
*
* @param value
* @return
* @throws IOException
*/
public static String DESryUserPassword(String value) throws IOException {
return DesSw.DESryStrHex(value, ConstsSw._userkey);
}
}
<file_sep>/src/com/corsair/dbpool/CDBConnection.java
package com.corsair.dbpool;
import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.CJSONTree;
import com.corsair.dbpool.util.CPoolSQLUtil;
import com.corsair.dbpool.util.CResultSetMetaData;
import com.corsair.dbpool.util.CResultSetMetaDataItem;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
public class CDBConnection {
/**
* 数据连接Session状态
*
* @author Administrator
*
*/
public enum ConStat {
ready, inuse
}
/**
* 数据库类型
*
* @author Administrator
*
*/
public enum DBType {
sqlserver, hsql, mysql, oracle, unknow
};
private DBPoolParms pprm;
public CDBPool pool;
private Object owner;// 谁申请的
public Connection con;
private ConStat stat;
private String key; // 数据库session 唯一序号
private long time; // 最后活动时间
private String lastcmd = null;// 最后执行的命令
private long lastcmdstarttime = 0;// 最后命令开始时间
private String curUserName; // 不知道能不能获取到
private String clientIP;// 客户端IP
private boolean distimeout = false;// 禁止超时
/**
* 数据库连接宿主
*
* @param owner
*/
public void setOwner(Object owner) {
this.owner = owner;
}
/**
* 活动时间
*
* @return
*/
public long getTime() {
return time;
}
/**
* 连接标识
*
* @return
*/
public String getKey() {
return key;
}
/**
* 返回状态
*
* @return
*/
public ConStat getStat() {
return stat;
}
/**
* 使用中
*
* @return
*/
public boolean isInUse() {
return (stat == ConStat.inuse);
}
// public Connection getCon() {
// return con;
// }
// 是否允许执行命令
private void check2CMD() throws Exception {
if (stat != ConStat.inuse) {
throw new Exception("非使用中的连接【" + key + "】,不允许执行命令(或连接已被连接池回收)");
}
}
/**
* 开始数据库事务
*/
public void startTrans() {
try {
check2CMD();
if (DBPools.getCblog() != null)
DBPools.getCblog().writelog(this, "开始事务");
if (!con.getAutoCommit()) {
throw new Exception("开始事务处理错误:已经是事务处理");
}
time = System.currentTimeMillis();
con.setAutoCommit(false);
} catch (Exception e) {
Logsw.error(e.getMessage());
}
}
/**
* @return 是否在事务中
*/
public boolean isInTrans() {
try {
return (!con.getAutoCommit());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/**
* 提交事务
*/
public void submit() {
try {
check2CMD();
if (DBPools.getCblog() != null)
DBPools.getCblog().writelog(this, "提交事务");
if (con.getAutoCommit()) {
throw new Exception("提交事务错误:未在事务处理状态");
}
time = System.currentTimeMillis();
lastcmd = "commit";
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
con.commit();
} catch (Exception e) {
Logsw.error(e.getMessage());
} finally {
try {
con.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close();
}
}
/**
* 回滚事务
*/
public void rollback() {
try {
check2CMD();
if (DBPools.getCblog() != null)
DBPools.getCblog().writelog(this, "回滚事务");
if (con.getAutoCommit()) {
throw new Exception("回滚事务错误:未在事务处理状态");
}
time = System.currentTimeMillis();
lastcmd = "rollback";
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
con.rollback();
} catch (Exception e) {
Logsw.error(e.getMessage());
} finally {
try {
con.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close();
}
}
/**
* @return 数据库类型
*/
public DBType getDBType() {
try {
time = System.currentTimeMillis();
DatabaseMetaData dbmd = this.con.getMetaData();
String dataBaseType = dbmd.getDatabaseProductName(); // 获取数据库类型
if (("Microsoft SQL Server").equals(dataBaseType)) {
return DBType.sqlserver;
} else if (("HSQL Database Engine").equals(dataBaseType)) {
return DBType.hsql;
} else if (("MySQL").equals(dataBaseType)) {
return DBType.mysql;
} else if (("Oracle").equals(dataBaseType)) {
return DBType.oracle;
} else {
return DBType.unknow;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return DBType.unknow;
}
/**
* 创建连接
*
* @param pool 连接池
* @param pprm 连接参数
* @throws Exception
*/
public CDBConnection(CDBPool pool, DBPoolParms pprm) throws Exception {
this.pprm = pprm;
Class.forName(pprm.dirver);
// jdbc:mysql://172.16.31.10:23306/yhdata?characterEncoding=utf-8&autoReconnect=true&useSSL=true
// jdbc:sqlserver://192.168.217.129:1433; DatabaseName=testdb
// jdbc:oracle:thin:@192.168.142.128:1521:orcl
Connection conn = DriverManager.getConnection(pprm.url, pprm.user, pprm.password);
con = conn;
UUID uuid = UUID.randomUUID();
stat = ConStat.ready;
key = uuid.toString();
time = System.currentTimeMillis();
this.pool = pool;
}
/**
* 打开(标记为使用状态)
*
* @param owner
*/
public void open(Object owner) {
try {
if (!con.getAutoCommit())// 在事务处理中的连接 一定要回滚 否则可能造成数据库死锁
con.rollback();
stat = ConStat.inuse;
time = System.currentTimeMillis();
this.owner = owner;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
/**
* 关闭(标记为未使用状态)
*/
public void close() {
// pool.closeCon(this);
try {
if (!con.getAutoCommit())// 在事务处理中的连接 一定要回滚 否则可能造成数据库死锁
con.rollback();
owner = null;
stat = ConStat.ready;
time = 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
// lock.unlock();
}
}
/**
* 断开从数据库的连接
*/
public void disConnect() {
close();
if (con != null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
/**
* @return 判断是否可用
*/
public boolean isValid() {
try {
if (con == null)
return false;
if (con.isClosed())
return false;
if (getDBType() != DBType.oracle) // oracle 调用这个方法报错
if (!con.isValid(0))
return false;
return true;
// return ((con != null) && (!con.isClosed()) && con.isValid(0));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/**
* @return 检测是否超时
*/
public boolean isUsesTimeout() {
boolean rst = false;
if ((stat == ConStat.inuse) && (!distimeout)) {// 在使用中的,且 没有禁止超时
// 检查时间
int scend = (int) ((System.currentTimeMillis() - time) / 1000);
if (scend > pprm.timeout) {
rst = true;
}
}
return rst;
}
/**
* 执行sql语句
*
* @param sqlstr
* @return
* @throws Exception
*/
public int execsql(String sqlstr) throws Exception {
return execsql(sqlstr, false);
}
/**
* 执行sql语句
*
* @param sqlstr
* @param dbginfo 是否打印日志
* @return
* @throws Exception
*/
public int execsql(String sqlstr, boolean dbginfo) throws Exception {
// if (dbginfo)
Logsw.debug("DBConnect 执行 SQL:" + sqlstr);
int rst = 0;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
try {
stmt = this.con.createStatement();
rst = stmt.executeUpdate(sqlstr);
} finally {
DBPools.safeCloseS_R(stmt, null);
}
if (dbginfo)
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
// throw new Exception("执行SQL错误【" + sqlstr + "】错误信息【" +
// e.getMessage() + "】");
}
return rst;
}
/**
* 执行多行sql语句
*
* @param sqls
* @throws Exception
*/
public void execSqls(List<String> sqls) throws Exception {
execSqls(sqls, true);
}
public void execSqls(List<String> sqls, Boolean dbginfo) throws Exception {
// if (dbginfo)
// Logsw.debug("DBConnect 批量执行 SQL:" + getsql(sqls));
try {
time = System.currentTimeMillis();
lastcmd = "executeBatch:" + sqls.toString();
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement smt = null;
try {
smt = con.createStatement();
for (String sql : sqls) {
smt.addBatch(sql);
}
smt.executeBatch();
} finally {
DBPools.safeCloseS_R(smt, null);
}
if (dbginfo)
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + getsql(sqls) + ";耗时:" + (et - time) + "】");
}
} catch (Exception e) {
throw e;
}
}
private String getsql(List<String> sqls) {
String rst = "";
for (String sql : sqls) {
rst = rst + sql + "\n\r";
}
return rst;
}
/**
* 执行sql语句 返回分页的 json 字符串
*
* @param psql
* @param page
* @param pagesize
* @return
* @throws Exception
*/
public String opensql2json(PraperedSql psql, int page, int pagesize) throws Exception {
String yxsqlstr = psql.getSqlstr();
psql.setSqlstr("select count(*) ct from (" + psql.getSqlstr() + ") tb");
int size = Integer.valueOf(openSql2List(psql).get(0).get("ct").toString());// //有问题
String psqlstr = null;
if (page < 1)
page = 1;
if (getDBType() == DBType.mysql)
psqlstr = yxsqlstr + " limit " + (page - 1) * pagesize + "," + pagesize;
if (getDBType() == DBType.oracle)
psqlstr = "SELECT * FROM( SELECT A.*,ROWNUM num FROM (" + yxsqlstr + " )A WHERE ROWNUM<=" + ((page - 1) * pagesize + pagesize) + ")WHERE num> "
+ (page - 1) * pagesize;
psql.setSqlstr(psqlstr);
String js = opensql2json(psql, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartObject();
jg.writeNumberField("total", size);
jg.writeFieldName("rows");
jg.writeRawValue(js);
jg.writeEndObject();
jg.close();
return baos.toString("utf-8");
}
private int getsqlrstsize(String sqlstr) throws Exception {
String nsql = "select count(*) ct from (" + sqlstr + ") tb";
int size = Integer.valueOf(openSql2List(nsql).get(0).get("ct").toString());
return size;
}
/**
* @param sqlstr
* @param page
* 当前页 -1表示不分页
* @param pagesize
* 每页行数
* @return
*/
private String getPagedSqlstr(String sqlstr, int page, int pagesize) {
if (page == -1)
return sqlstr;
String psqlstr = sqlstr;
if (page < 1)
page = 1;
if (getDBType() == DBType.mysql)
psqlstr = sqlstr + " limit " + (page - 1) * pagesize + "," + pagesize;
if (getDBType() == DBType.oracle)
psqlstr = "SELECT * FROM( SELECT A.*,ROWNUM num FROM (" + sqlstr + " )A WHERE ROWNUM<=" + ((page - 1) * pagesize + pagesize) + ")WHERE num> "
+ (page - 1) * pagesize;
return psqlstr;
}
/**
* 执行sql语句 返回分页的 json 字符串
*
* @param sqlstr
* @param page
* @param pagesize
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr, int page, int pagesize) throws Exception {
int size = getsqlrstsize(sqlstr);
String psqlstr = getPagedSqlstr(sqlstr, page, pagesize);
String js = opensql2json(psqlstr);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartObject();
jg.writeNumberField("total", size);
jg.writeFieldName("rows");
jg.writeRawValue(js);
jg.writeEndObject();
jg.close();
return baos.toString("utf-8");
}
/**
* @param sqlstr
* @param page
* @param pagesize
* @return 分页查询
* @throws Exception
*/
public JSONObject opensql2json_o(String sqlstr, int page, int pagesize) throws Exception {
return opensql2json_o(sqlstr, page, pagesize, false);
}
/**
* @param sqlstr
* @param page
* @param pagesize
* @param withMetaData 是否包含元数据
* @return 分页查询
* @throws Exception
*/
public JSONObject opensql2json_o(String sqlstr, int page, int pagesize, boolean withMetaData) throws Exception {
JSONObject rst = new JSONObject();
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
int size = getsqlrstsize(sqlstr);
String psqlstr = getPagedSqlstr(sqlstr, page, pagesize);
// System.out.println("sqlstr:" + psqlstr);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(psqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + psqlstr + ";耗时:" + (et - time) + "】");
}
JSONArray rows = CJSON.Dataset2JSON_O(rs);
rst.put("page", page);
rst.put("total", size);
rst.put("rows", rows);
if (withMetaData) {
rst.put("metadata", CJSON.getMetaData_O(rs));
}
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行sql语句 返回 json 数组
*
* @param sqlstr
* @return
* @throws Exception
*/
public JSONArray opensql2json_o(String sqlstr) throws Exception {
Logsw.debug("执行查询:" + sqlstr);
JSONArray rst = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
rst = CJSON.Dataset2JSON_O(rs);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行sql语句 返回 json 数组
*
* @param psql
* @return
* @throws Exception
*/
public JSONArray opensql2json_o(PraperedSql psql) throws Exception {
Logsw.debug("执行查询:" + psql.getSqlstr());
JSONArray rst = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = psql.getSqlstr();
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = this.con.prepareStatement(psql.getSqlstr());
for (int i = 0; i < psql.getParms().size(); i++) {
PraperedValue pv = psql.getParms().get(i);
CPoolSQLUtil.setSqlPValue(pstmt, i + 1, pv);
}
rs = pstmt.executeQuery();
rst = CJSON.Dataset2JSON_O(rs);
} finally {
DBPools.safeCloseS_R(pstmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + psql.getSqlstr(), e);
}
return rst;
}
/**
* 执行sql语句 返回 json 字符串
*
* @param psql
* @param dbginfo
* @return
* @throws Exception
*/
public String opensql2json(PraperedSql psql, boolean dbginfo) throws Exception {
// if (dbginfo)
Logsw.debug("执行查询:" + psql.getSqlstr());
String rst = "[]";
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = psql.getSqlstr();
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = this.con.prepareStatement(psql.getSqlstr());
for (int i = 0; i < psql.getParms().size(); i++) {
PraperedValue pv = psql.getParms().get(i);
CPoolSQLUtil.setSqlPValue(pstmt, i + 1, pv);
}
rs = pstmt.executeQuery();
if (dbginfo)
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + psql.getSqlstr() + ";耗时:" + (et - time) + "】");
}
rst = CJSON.Dataset2JSON(rs);
} finally {
DBPools.safeCloseS_R(pstmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + psql.getSqlstr(), e);
}
return rst;
}
/**
* 执行sql语句 返回 json 字符串
*
* @param sqlstr
* @param dbginfo
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr, boolean dbginfo) throws Exception {
// if (dbginfo)
// Logsw.debug("执行查询:" + sqlstr);
String rst = "[]";
try {
check2CMD();
if (DBPools.getCblog() != null) {
DBPools.getCblog().writelog(this, "【计划执行SQL:" + sqlstr + "】");
}
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (dbginfo)
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL耗时:" + (et - time) + "】");
}
rst = CJSON.Dataset2JSON(rs);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行sql语句 返回 json 字符串
*
* @param sqlstr
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr) throws Exception {
return opensql2json(sqlstr, true);
}
/**
* 执行sql语句 返回 json 字符串
*
* @param psql
* @return
* @throws Exception
*/
public String openrowsql2json(PraperedSql psql) throws Exception {
JSONArray jos = opensql2json_o(psql);
if (jos.size() > 0) {
return jos.get(0).toString();
} else {
return "{}";
}
}
public String openrowsql2json(String sqlstr) throws Exception {
// Logsw.debug("执行查询:" + sqlstr);
String rst = "{}";
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集的定义结构
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
int columnCount = rsmd.getColumnCount();
if (rs.next())
rst = CJSON.DatasetRow2JSON(rs, rsmd, columnCount);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行sql语句 返回树型 json 数组
*
* @param sqlstr
* @param idfd 主键
* @param pidfd 父字段
* @param async 是否异步
* @return
* @throws Exception
*/
public JSONArray opensql2jsontree_o(String sqlstr, String idfd, String pidfd, boolean async) throws Exception {
// Logsw.debug("执行查询:" + sqlstr);
JSONArray rst = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
rst = CJSONTree.Dataset2JSON(rs, idfd, pidfd, async);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行sql语句 返回树型 json 字符串
*
* @param sqlstr
* @param idfd 主键
* @param pidfd 父字段
* @param async
* @return
* @throws Exception
*/
public String opensql2jsontree(String sqlstr, String idfd, String pidfd, boolean async) throws Exception {
// Logsw.debug("执行查询:" + sqlstr);
String rst = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
rst = CJSONTree.Dataset2JSONTree(rs, idfd, pidfd, async);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
/**
* 执行SQL语句,返回列表数据
*
* @param psql
* @return
* @throws Exception
*/
public List<HashMap<String, String>> openSql2List(PraperedSql psql) throws Exception {
// Logsw.debug("执行查询:" + psql.getSqlstr());
List<HashMap<String, String>> records = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = psql.getSqlstr();
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.prepareStatement(psql.getSqlstr());
for (int i = 0; i < psql.getParms().size(); i++) {
PraperedValue pv = psql.getParms().get(i);
CPoolSQLUtil.setSqlPValue(stmt, i + 1, pv);
}
rs = stmt.executeQuery();
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + psql.getSqlstr() + ";耗时:" + (et - time) + "】");
}
records = CJSONTree.Dataset2List(getDBType(), rs);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + psql.getSqlstr(), e);
}
return records;
}
/**
* 执行SQL语句,返回列表数据
*
* @param sqlstr
* @return
* @throws Exception
*/
public List<HashMap<String, String>> openSql2List(String sqlstr) throws Exception {
// Logsw.debug("执行查询:" + sqlstr);
List<HashMap<String, String>> records = null;
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
records = CJSONTree.Dataset2List(getDBType(), rs);
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return records;
}
/**
* 执行SQL语句,返回列表数据
*
* @param sqlstr
* @param cls
* @return
* @throws Exception
*/
public List<CJPABase> openSql2List(String sqlstr, Class<?> cls) throws Exception {
if (!CJPABase.class.isAssignableFrom(cls)) {
throw new Exception(cls.getName() + "必须是 com.corsair.server.cjpa.CJPA的子类");
}
CJPALineData<CJPABase> rst = new CJPALineData<CJPABase>(cls);
rst.findDataBySQL(sqlstr, true, true);
return rst;
}
/**
* 获取数据集描述
*
* @param sqlstr
* @return
* @throws Exception
*/
public CResultSetMetaData<CResultSetMetaDataItem> getsqlMetadata(String sqlstr) throws Exception {
// Logsw.debug("执行查询:" + sqlstr);
CResultSetMetaData<CResultSetMetaDataItem> rst = new CResultSetMetaData<CResultSetMetaDataItem>();
try {
check2CMD();
time = System.currentTimeMillis();
lastcmd = sqlstr;
if (pool.getIct() != null) {
setCurUserName(pool.getIct().getCurUserName());
setClientIP(pool.getIct().getClentIP());
}
setLastcmdstarttime(time);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = this.con.createStatement();
rs = stmt.executeQuery(sqlstr);
if (DBPools.getCblog() != null) {
long et = System.currentTimeMillis();
DBPools.getCblog().writelog(this, "【执行SQL:" + sqlstr + ";耗时:" + (et - time) + "】");
}
ResultSetMetaData rsmt = rs.getMetaData();
for (int i = 1; i <= rsmt.getColumnCount(); i++) {
rst.add(new CResultSetMetaDataItem(rsmt, i));
}
} finally {
DBPools.safeCloseS_R(stmt, rs);
}
} catch (Exception e) {
Logsw.error("连接池执行SQL错误:" + sqlstr, e);
}
return rst;
}
public Object getOwner() {
return owner;
}
public String getLastcmd() {
return lastcmd;
}
public void setLastcmd(String lastcmd) {
this.lastcmd = lastcmd;
}
public long getLastcmdstarttime() {
return lastcmdstarttime;
}
public void setLastcmdstarttime(long lastcmdstarttime) {
this.lastcmdstarttime = lastcmdstarttime;
}
public String getCurUserName() {
return curUserName;
}
public void setCurUserName(String curUserName) {
this.curUserName = curUserName;
}
public String getClientIP() {
return clientIP;
}
public void setClientIP(String clientIP) {
this.clientIP = clientIP;
}
public boolean isDistimeout() {
return distimeout;
}
public void setDistimeout(boolean distimeout) {
this.distimeout = distimeout;
}
}
<file_sep>/src/com/hr/asset/entity/Hr_asset_register.java
package com.hr.asset.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.generic.Shw_attach;
import com.hr.asset.co.COHr_asset_register;
import java.sql.Types;
@CEntity(controller=COHr_asset_register.class)
public class Hr_asset_register extends CJPA {
@CFieldinfo(fieldname="asset_register_id",iskey = true, notnull=true,caption="登记号ID",datetype=Types.INTEGER)
public CField asset_register_id; //asset_register_id
@CFieldinfo(fieldname="asset_register_num",codeid=94,caption="登记号",datetype=Types.VARCHAR)
public CField asset_register_num; //asset_register_num
@CFieldinfo(fieldname="asset_item_id",caption="资产物料ID",datetype=Types.INTEGER)
public CField asset_item_id; //asset_item_id
@CFieldinfo(fieldname="asset_item_code",caption="物料编码",datetype=Types.VARCHAR)
public CField asset_item_code; //asset_item_code
@CFieldinfo(fieldname="asset_item_name",caption="物料名称",datetype=Types.VARCHAR)
public CField asset_item_name; //asset_item_name
@CFieldinfo(fieldname="asset_type_id",caption="类型ID",datetype=Types.INTEGER)
public CField asset_type_id; //asset_type_id
@CFieldinfo(fieldname="asset_type_code",caption="类型编码",datetype=Types.VARCHAR)
public CField asset_type_code; //asset_type_code
@CFieldinfo(fieldname="asset_type_name",caption="类型名称",datetype=Types.VARCHAR)
public CField asset_type_name; //asset_type_name
@CFieldinfo(fieldname="brand",caption="品牌",datetype=Types.VARCHAR)
public CField brand; //brand
@CFieldinfo(fieldname="model",caption="型号",datetype=Types.VARCHAR)
public CField model; //model
@CFieldinfo(fieldname="original_value",caption="原值",datetype=Types.VARCHAR)
public CField original_value; //original_value
@CFieldinfo(fieldname="net_value",caption="净值",datetype=Types.VARCHAR)
public CField net_value; //net_value
@CFieldinfo(fieldname="uom",caption="单位",datetype=Types.VARCHAR)
public CField uom; //uom
@CFieldinfo(fieldname="service_life",caption="报废年限",datetype=Types.INTEGER)
public CField service_life; //service_life
@CFieldinfo(fieldname="acquired_date",caption="购置日期",datetype=Types.TIMESTAMP)
public CField acquired_date; //acquired_date
@CFieldinfo(fieldname="deploy_qty",caption="配置数量",datetype=Types.INTEGER)
public CField deploy_qty; //deploy_qty
@CFieldinfo(fieldname="deploy_area",caption="配置区域",datetype=Types.VARCHAR)
public CField deploy_area; //deploy_area
@CFieldinfo(fieldname="deploy_restaurant",caption="配置餐厅",datetype=Types.VARCHAR)
public CField deploy_restaurant; //deploy_restaurant
@CFieldinfo(fieldname="deploy_restaurant_id",caption="配置餐厅id",datetype=Types.INTEGER)
public CField deploy_restaurant_id; //deploy_restaurant_id
@CFieldinfo(fieldname="keep_own",caption="保管人",datetype=Types.VARCHAR)
public CField keep_own; //keep_own
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //remark
@CFieldinfo(fieldname="wfid",caption="wfid",datetype=Types.INTEGER)
public CField wfid; //wfid
@CFieldinfo(fieldname="attid",caption="attid",datetype=Types.INTEGER)
public CField attid; //attid
@CFieldinfo(fieldname="stat",caption="表单状态",datetype=Types.INTEGER)
public CField stat; //stat
@CFieldinfo(fieldname="idpath",caption="idpath",datetype=Types.VARCHAR)
public CField idpath; //idpath
@CFieldinfo(fieldname="entid",caption="entid",datetype=Types.INTEGER)
public CField entid; //entid
@CFieldinfo(fieldname="creator",caption="创建人",datetype=Types.VARCHAR)
public CField creator; //creator
@CFieldinfo(fieldname="createtime",caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //createtime
@CFieldinfo(fieldname="updator",caption="更新人",datetype=Types.VARCHAR)
public CField updator; //updator
@CFieldinfo(fieldname="updatetime",caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //updatetime
@CFieldinfo(fieldname="attribute1",caption="attribute1",datetype=Types.VARCHAR)
public CField attribute1; //attribute1
@CFieldinfo(fieldname="attribute2",caption="attribute2",datetype=Types.TIMESTAMP)
public CField attribute2; //attribute2
@CFieldinfo(fieldname="attribute3",caption="attribute3",datetype=Types.VARCHAR)
public CField attribute3; //attribute3
@CFieldinfo(fieldname="attribute4",caption="attribute4",datetype=Types.VARCHAR)
public CField attribute4; //attribute4
@CFieldinfo(fieldname="attribute5",caption="attribute5",datetype=Types.VARCHAR)
public CField attribute5; //attribute5
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
@CLinkFieldInfo(jpaclass = Shw_attach.class, linkFields = { @LinkFieldItem(lfield = "attid", mfield = "attid") })
public CJPALineData<Shw_attach> shw_attachs;
public Hr_asset_register() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/47/47548a63e139025997c10aa224650be6cd30abae.svn-base
package com.hr.msg.co;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CReport;
import com.hr.msg.entity.Hr_kq_depart_day_report;
import com.hr.util.DateUtil;
import com.hr.util.HRUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@ACO(coname = "web.hrkq.report")
public class COHr_kq_day_report extends JPAController {
@ACOAction(eventname = "findkqcalreport", Authentication = false, notes = "查询考勤异常结果")
public String findkqcalreport() throws Exception {
String[] notnull = {};
// String[] ignParms = { "ym" };// 忽略的查询条件
String sqlstr = "SELECT r.no_card_num,r.make_up_num,r.date,r.yer_no_card_num,r.yer_no_card_times,e.employee_code,e.employee_name,e.orgname,e.sp_name"
+" from Hr_kq_day_report r inner JOIN hr_employee e on r.er_id =e.er_id order by date desc";
System.out.print(sqlstr);
return new CReport(HRUtil.getReadPool(), sqlstr, " date desc ", notnull).findReport();
}
/**
* 部门异常考勤
* @return
* @throws Exception
*/
@ACOAction(eventname = "findorgkqdayreport", Authentication = false, notes = "统计部门日考勤")
public String findorgkqdayreport() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
JSONParm paramincludechild = CjpaUtil.getParm(jps, "includechild");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpdqdatebegin = CjpaUtil.getParm(jps, "dqdatebegin");
if (jpdqdatebegin == null)
throw new Exception("需要参数【dqdate】");
JSONParm jpdqdateend = CjpaUtil.getParm(jps, "dqdateend");
if (jpdqdateend == null)
throw new Exception("需要参数【dqdate】");
boolean includechild=false;
if(Boolean.valueOf(paramincludechild.getParmvalue())){
includechild=true;
}
String zjWhere="";
// JSONParm zj = CjpaUtil.getParm(jps, "zj");
// if(zj!=null){
// zjWhere=zj.getReloper()+zj.getParmvalue();
// }
String orgcode = jporgcode.getParmvalue();
String dqdatebegin=jpdqdatebegin.getParmvalue();
String dqdateend=jpdqdateend.getParmvalue();
if(dqdatebegin.contains("/")){
dqdatebegin=DateUtil.DateParseYYYYMMDD(dqdatebegin);
}
if(dqdateend.contains("/")){
dqdateend=DateUtil.DateParseYYYYMMDD(dqdateend);
}
String sqlstr = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr);
if (org.isEmpty()){
throw new Exception("编码为【" + orgcode + "】的机构不存在");
}
String scols = urlparms.get("cols");
JSONArray dws= new JSONArray();
long between =DateUtil.getBetweenDays(Systemdate.getDateYYYYMMDD(dqdatebegin), Systemdate.getDateYYYYMMDD(dqdateend));
if(between<0){
throw new Exception("开始日期不允许大于截止日期");
}
for(int i=0;i<=between;i++){
//计算出需要统计的日期
String dqdate=Systemdate.getStrDateyyyy_mm_dd(Systemdate.dateDayAdd(Systemdate.getDateYYYYMMDD(dqdatebegin), i));
System.out.print(dqdate);
//.replace(" 00:00:00", "")
if(includechild){
if(org.code.getValue().equals("00000001")){
//新宝要两级下级
List<Shworg>orgs=HRUtil.getChildByOrg(org,2);
for(Shworg shworg :orgs){
if(Systemdate.getStrDateyyyy_mm_dd(new Date()).equals(dqdate)){
getKqRealTime(shworg,dqdate,dws,zjWhere);
}else{
getKqHistroy(shworg,dqdate,dws);
}
}
}else{
//其余的1级下级
List<Shworg>orgs=HRUtil.getChildByOrg(org,1);
for(Shworg shworg :orgs){
if(Systemdate.getStrDateyyyy_mm_dd(new Date()).equals(dqdate)){
getKqRealTime(shworg,dqdate,dws,zjWhere);
}else{
getKqHistroy(shworg,dqdate,dws);
}
}
}
}else{
//不包含子机构
if(Systemdate.getStrDateyyyy_mm_dd(new Date()).equals(dqdate)){
getKqRealTime(org,dqdate,dws,zjWhere);
}else{
getKqHistroy(org,dqdate,dws);
}
}
}
if (scols == null) {
return dws.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
/**
* 异常考勤名细
* @return
* @throws Exception
*/
@ACOAction(eventname = "findorgdetialkqdayreport", Authentication = false, notes = "异常考勤明细")
public String findorgdetialkqdayreport() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpdqdate = CjpaUtil.getParm(jps, "dqdate");
if (jpdqdate == null)
throw new Exception("需要参数【dqdate】");
String orgcode = jporgcode.getParmvalue();
String dqdate = jpdqdate.getParmvalue();
String sqlstr = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr);
if (org.isEmpty()){
throw new Exception("编码为【" + orgcode + "】的机构不存在");
}
if(dqdate.isEmpty()){
throw new Exception("请输入查询日期");
}
String scols = urlparms.get("cols");
JSONArray dws= new JSONArray();
//dws.add(0, org.toJsonObj());
if(Systemdate.getStrDateyyyy_mm_dd(new Date()).equals(dqdate)){
//当天
getKqDeltailRealTime(org,dqdate,dws);
}else{
//历史
getHistoryDetailRecord(org,dqdate,dws);
}
if (scols == null) {
return dws.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
/**
* 部门考勤统计实时
* @param org
* @param dqdate
* @param dws
* @throws Exception
*/
private void getKqRealTime(Shworg org,String dqdate,JSONArray dws,String zjWhere)throws Exception{
JSONObject dw = new JSONObject();
String reportOrgSql="select a.employee_code,a.empstatid,a.orgname,noclock,emnature,hiredday,t.cq,t2.qj,t3.cc,t4.tx from hr_employee a"+
" LEFT JOIN (select b.empno, '1' as cq from hrkq_swcdlst b WHERE DATE_FORMAT(b.skdate,'%Y-%m-%d')='"+dqdate+"' GROUP BY b.empno) as t on t.empno=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as qj from hrkq_holidayapp b WHERE (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeed>='"+dqdate+"') or (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeedtrue>='"+dqdate+"') and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t2 on t2.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as cc from hrkq_business_trip b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t3 on t3.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as tx from hrkq_wkoff b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t4 on t4.employee_code=a.employee_code"+
" where a.idpath like '"+org.idpath.getValue()+"%' and a.sp_name<>'项目实习生' and a.empstatid<>'12' and a.empstatid<>'13' and a.empstatid<>'0' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.hiredday<='"+dqdate+"'";
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(reportOrgSql);
int zz=reportList.size();
int cc=0;
int tx=0;
int qj=0;
int mdk=0;
int cq=0;
int tcwdk=0;//脱产无打卡
int ftcwdk=0;//非脱产无打卡
int rzdtwdk=0;//当天入职无打卡
int lj=0;
for(HashMap<String, String>entity :reportList)
{
String scc="";
String stx="";
String sqj="";
String scq="";
if(entity.get("cc")!=null){
scc=entity.get("cc");
}
if(entity.get("tx")!=null){
stx=entity.get("tx");
}
if(entity.get("qj")!=null){
sqj=entity.get("qj");
}
if(entity.get("cq")!=null){
scq=entity.get("cq");
}
if(scc.equals("1") && entity.get("noclock").equals("2")){
cc++;
}else if(stx.equals("1") && entity.get("noclock").equals("2")){
tx++;
}else if(scq.equals("1") && entity.get("noclock").equals("2")){
cq++;
}else if(sqj.equals("1") && entity.get("noclock").equals("2")){
qj++;
}else{
//缺勤
if(entity.get("emnature").equals("脱产") && entity.get("noclock").equals("2")){
tcwdk++;
}else if(entity.get("emnature").equals("非脱产")&& entity.get("noclock").equals("2")){
ftcwdk++;
}
//统计当天入职无打卡
//System.out.print(entity.get("hiredday"));
String hiredday=Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByyyyy_mm_dd(entity.get("hiredday")));
if(hiredday.equals(dqdate))
{
rzdtwdk++;
}
}
if(entity.get("noclock").equals("1")){
mdk++;
cq++;
}
}
//另外查询当天离职
String ljSql="select count(1) as lj from hr_employee a where a.idpath like '"+org.idpath.getValue()+"%' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.ljdate='"+dqdate+"'";
List<HashMap<String, String>> ljlist = HRUtil.getReadPool().openSql2List(ljSql);
HashMap<String, String>entity=ljlist.get(0);
String dzmSql="select count(1) as dzm from hr_employee a where a.idpath like '"+org.idpath.getValue()+"%' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.empstatid='0' and a.hiredday<='"+dqdate+"'";
List<HashMap<String, String>> dzmlist = HRUtil.getReadPool().openSql2List(dzmSql);
HashMap<String, String>dzmentity=dzmlist.get(0);
dw.put("numlj",entity.get("lj"));
dw.put("numdzm", dzmentity.get("dzm"));
dw.put("orgname",org.extorgname.getValue());
dw.put("numcc",cc);
dw.put("numtx", tx);
dw.put("numqj", qj);
dw.put("nummdk", mdk);
dw.put("numcq", cq);
dw.put("numtcwdk",tcwdk);
dw.put("numftcwdk", ftcwdk);
dw.put("numrzdtwdk", rzdtwdk);
dw.put("numzz", zz);
dw.put("date", dqdate);
if(zz>0){
int dzm=Integer.valueOf(dzmentity.get("dzm")) ;
double sum=cq+cc+tx;
sum=sum/(zz+dzm)*100;
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if(sum>100){
dw.put("cqdcl", "100%");
}else{
dw.put("cqdcl", sum+"%");
}
}else{
dw.put("cqdcl", "0%");
}
if(zz>0){
double sum=cq+cc+tx;
sum=sum/zz*100;
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if(sum>100){
dw.put("cqdcl2", "100%");
}else{
dw.put("cqdcl2", sum+"%");
}
}else{
dw.put("cqdcl2", "0%");
}
dws.add(dw);
}
/**
* 部门考勤统计日结
* @param org
* @param dqdate
* @param dws
* @throws Exception
*/
private void getKqHistroy(Shworg org,String dqdate,JSONArray dws)throws Exception{
JSONObject dw = new JSONObject();
String sql="select * from hr_kq_depart_day_report where orgcode='"+org.code.getValue()+"' and date='"+dqdate+"' limit 1";
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(sql);
for(HashMap<String, String>entity :reportList)
{
dw.put("numlj",entity.get("lj"));
dw.put("numdzm", entity.get("dzm"));
dw.put("orgname",entity.get("orgname"));
dw.put("numcc",entity.get("cc"));
dw.put("numtx", entity.get("tx"));
dw.put("numqj", entity.get("qj"));
dw.put("nummdk", entity.get("mdk"));
dw.put("numcq", entity.get("cq"));
dw.put("numtcwdk",entity.get("tcwdk"));
dw.put("numftcwdk", entity.get("ftcwdk"));
dw.put("numrzdtwdk", entity.get("rzdtwdk"));
dw.put("numzz", entity.get("zz"));
dw.put("date", entity.get("date"));
dw.put("cqdcl", entity.get("cqdcl"));
dw.put("cqdcl2", entity.get("cqdcl2"));
dws.add(dw);
}
}
/**
/**
* 查询部门当天异常考勤明细
* @param org
* @param dqdate
* @param dws
* @throws Exception
*/
private void getKqDeltailRealTime(Shworg org,String dqdate,JSONArray dws)throws Exception{
String reportOrgSql="select a.employee_code,a.employee_name,a.orgname,a.empstatid,a.emnature,b.description,hiredday,sp_name, lv_num,t.cq,t2.qj,t3.cc,t4.tx from hr_employee a "+
" INNER JOIN hr_employeestat b on a.empstatid=b.statvalue"+
" LEFT JOIN (select b.empno, '1' as cq from hrkq_swcdlst b WHERE DATE_FORMAT(b.skdate,'%Y-%m-%d')='"+dqdate+"' GROUP BY b.empno) as t on t.empno=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as qj from hrkq_holidayapp b WHERE (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeed>='"+dqdate+"') or (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeedtrue>='"+dqdate+"') and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t2 on t2.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as cc from hrkq_business_trip b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t3 on t3.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as tx from hrkq_wkoff b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t4 on t4.employee_code=a.employee_code"+
" where a.idpath like '"+org.idpath.getValue()+"%' and sp_name<>'项目实习生' and a.empstatid<>'12' and a.empstatid<>'13' and a.hiredday<'"+dqdate+"' and a.noclock='2'";
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(reportOrgSql);
for(HashMap<String, String>entity : reportList){
JSONObject dw = new JSONObject();
String status="";
String remark="";
if((entity.get("cc"))!=null){
status="出差";
}
else if(entity.get("tx")!=null){
status="调休";
}
else if(entity.get("cq")!=null){
continue;
}
else if(entity.get("qj")!=null){
status="请假";
}
else if (entity.get("cq")==null){
status="无打卡";
remark="完全无打卡";
}
if(!"".equals(status)){
dw.put("date", dqdate);
dw.put("employee_code", entity.get("employee_code"));
dw.put("employee_name", entity.get("employee_name"));
dw.put("orgname", entity.get("orgname"));
dw.put("description", entity.get("description"));
dw.put("hiredday", entity.get("hiredday").replace(" 00:00:00", ""));
dw.put("sp_name", entity.get("sp_name"));
dw.put("lv_num", entity.get("lv_num"));
dw.put("status", status);
dw.put("emnature", entity.get("emnature"));
dw.put("remark", remark);
dws.add(dw);
}
}
}
/**
* 考勤异常明细查询(历史)
* @param org
* @param dqdate
* @param dws
* @throws Exception
*/
private void getHistoryDetailRecord(Shworg org,String dqdate,JSONArray dws)throws Exception{
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(dqdate)));
Date eddate=Systemdate.dateDayAdd(bgdate, 1);
//String strbgdate = Systemdate.getStrDateyyyy_mm_dd(bgdate);
//String streddate = Systemdate.getStrDateyyyy_mm_dd(eddate);
String findZzSql = "select er_id, employee_code,employee_name,orgname,a.empstatid,a.emnature,b.description,hiredday,sp_name, lv_num "+
" from hr_employee a INNER JOIN hr_employeestat b on a.empstatid=b.statvalue"+
" where a.noclock='2' and a.idpath like '"+org.idpath.getValue()+"%' and hiredday<='"+dqdate+"' and (ljdate>='"+dqdate+"' or ljdate='0000-00-00' or ljdate is NULL)";
Hr_kq_depart_day_report report=new Hr_kq_depart_day_report();
List<HashMap<String, String>> zzList = HRUtil.getReadPool().openSql2List(findZzSql);
List<String>wpbList=new ArrayList<String>();//无排版队列
for(HashMap<String, String>entity : zzList){
JSONObject dw = new JSONObject();
String employee_code=entity.get("employee_code");
String er_id=entity.get("er_id");
//先查一下考勤结果报表
//1 正常 2 迟到 3早退 4未打卡 5 出差 6 请假 7 调休8签卡 9 迟到 10 早退 11 迟到早退 12 旷工(旷工)
String findKqResultSql="select frtime,totime, lrst,frst,trst from hrkq_bckqrst where kqdate='"+dqdate+"' and er_id='"+er_id+"'";
String status="";
String remark="";
List<HashMap<String, String>> kqResultList = report.pool.openSql2List(findKqResultSql);
if(kqResultList.size()==0){
//没有排班,取打卡表
wpbList.add(employee_code);
}else if (kqResultList.size()==1){
//只有1个班,直接取结果
String frtime=kqResultList.get(0).get("frtime");
String totime=kqResultList.get(0).get("totime");
String lrst=kqResultList.get(0).get("lrst");//班次结果
String frst=kqResultList.get(0).get("frst");//上班打卡结果
String trst=kqResultList.get(0).get("trst");//下班打卡结果
if(frst.equals("4")||(trst.equals("4"))){
status="无打卡";
if(frst.equals("4")){
remark+=";"+frtime;
}if(trst.equals("4")){
remark+=";"+totime;
}if(remark.length()>0){
remark= remark.replaceFirst(";", "");
}
}else if(lrst.equals("5")){
status="出差";
}else if(lrst.equals("6")){
status="请假";
}else if(lrst.equals("7")){
status="调休";
}
if(frst.equals("4")&&trst.equals("4")){
remark="完全无打卡";
}
}else if(kqResultList.size()==2){
//有两个班,优先12,再到567
String frtime=kqResultList.get(0).get("frtime");
String totime=kqResultList.get(0).get("totime");
String lrst=kqResultList.get(0).get("lrst");//班次结果
String frst=kqResultList.get(0).get("frst");
String trst=kqResultList.get(0).get("trst");
String frtime1=kqResultList.get(1).get("frtime");
String totime1=kqResultList.get(1).get("totime");
String lrst1=kqResultList.get(1).get("lrst");//班次结果
String frst1=kqResultList.get(1).get("frst");
String trst1=kqResultList.get(1).get("trst");
if(frst.equals("4") || trst.equals("4")|| frst1.equals("4") || trst1.equals("4")){
status="无打卡";
if(frst.equals("4")){
remark+=";"+frtime;
}if(trst.equals("4")){
remark+=";"+totime;
}if(frst1.equals("4")){
remark+=";"+frtime1;
}if(trst1.equals("4")){
remark+=";"+totime1;
}
if(remark.length()>0){
remark= remark.replaceFirst(";", "");
}
}else if(lrst.equals("5")||lrst1.equals("5")){
status="出差";
}else if(lrst.equals("6")||lrst1.equals("6")){
status="请假";
}else if(lrst.equals("7")||lrst1.equals("7")){
status="调休";
}
if(frst.equals("4") && trst.equals("4")&& frst1.equals("4") && trst1.equals("4")){
remark="完全无打卡";
}
}else if(kqResultList.size()==3){
//有两个班,优先12,再到567
String frtime=kqResultList.get(0).get("frtime");
String totime=kqResultList.get(0).get("totime");
String lrst=kqResultList.get(0).get("lrst");//班次结果
String frst=kqResultList.get(0).get("frst");
String trst=kqResultList.get(0).get("trst");
String frtime1=kqResultList.get(1).get("frtime");
String totime1=kqResultList.get(1).get("totime");
String lrst1=kqResultList.get(1).get("lrst");//班次结果
String frst1=kqResultList.get(1).get("frst");
String trst1=kqResultList.get(1).get("trst");
String frtime2=kqResultList.get(2).get("frtime");
String totime2=kqResultList.get(2).get("totime");
String lrst2=kqResultList.get(2).get("lrst");//班次结果
String frst2=kqResultList.get(2).get("frst");
String trst2=kqResultList.get(2).get("trst");
if(frst.equals("4") || trst.equals("4")|| frst1.equals("4") || trst1.equals("4")||frst2.equals("4") || trst2.equals("4")){
status="无打卡";
if(frst.equals("4")){
remark+=";"+frtime;
}if(trst.equals("4")){
remark+=";"+totime;
}if(frst1.equals("4")){
remark+=";"+frtime1;
}if(trst1.equals("4")){
remark+=";"+totime1;
}if(frst2.equals("4")){
remark+=";"+frtime2;
}if(trst2.equals("4")){
remark+=";"+totime2;
}
if(remark.length()>0){
remark= remark.replaceFirst(";", "");
}
}else if(lrst.equals("5")||lrst1.equals("5")||lrst2.equals("5")){
status="出差";
}else if(lrst.equals("6")||lrst1.equals("6")||lrst2.equals("6")){
status="请假";
}else if(lrst.equals("7")||lrst1.equals("7")||lrst2.equals("7")){
status="调休";
}
if(frst.equals("4") && trst.equals("4")&& frst1.equals("4") && trst1.equals("4")&& frst2.equals("4") && trst2.equals("4")){
remark="完全无打卡";
}
}
if(!"".equals(status)){
dw.put("date", dqdate);
dw.put("employee_code", entity.get("employee_code"));
dw.put("employee_name", entity.get("employee_name"));
dw.put("orgname", entity.get("orgname"));
dw.put("description", entity.get("description"));
dw.put("hiredday", entity.get("hiredday").replace(" 00:00:00", ""));
dw.put("sp_name", entity.get("sp_name"));
dw.put("lv_num", entity.get("lv_num"));
dw.put("emnature", entity.get("emnature"));
dw.put("status", status);
dw.put("remark", remark);
dws.add(dw);
}
}
//没有排班的统一查询
if(wpbList.size()>0){
String ids=tranInSql(wpbList);
String reportSql = "select a.employee_code,employee_name,orgname,a.empstatid,a.emnature,b.description,hiredday,sp_name, lv_num,t.cq,t2.qj,t3.cc,t4.tx"+
" from hr_employee a INNER JOIN hr_employeestat b on a.empstatid=b.statvalue"+
" LEFT JOIN (select b.empno, '1' as cq from hrkq_swcdlst b WHERE DATE_FORMAT(b.skdate,'%Y-%m-%d')='"+dqdate+"' GROUP BY b.empno) as t on t.empno=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as qj from hrkq_holidayapp b WHERE ((DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeed>='"+dqdate+"') or (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='"+dqdate+"' and b.timeedtrue>='"+dqdate+"')) and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t2 on t2.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as cc from hrkq_business_trip b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t3 on t3.employee_code=a.employee_code"+
" LEFT JOIN (select b.employee_code, '1' as tx from hrkq_wkoff b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='"+dqdate+"' and b.end_date>='"+dqdate+"' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t4 on t4.employee_code=a.employee_code"+
" where a.employee_code in ("+ids+")";
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(reportSql);
for(HashMap<String, String>kq : reportList){
JSONObject dw = new JSONObject();
String status="";
String remark="";
if((kq.get("cc"))!=null){
status="出差";
}
else if(kq.get("tx")!=null){
status="调休";
}
else if(kq.get("qj")!=null){
status="请假";
}
else if (kq.get("cq")==null){
status="无打卡";
remark="完全无打卡";
}
if(!"".equals(status)){
dw.put("date", dqdate);
dw.put("employee_code", kq.get("employee_code"));
dw.put("employee_name", kq.get("employee_name"));
dw.put("orgname", kq.get("orgname"));
dw.put("description", kq.get("description"));
dw.put("hiredday", kq.get("hiredday").replace(" 00:00:00", ""));
dw.put("sp_name", kq.get("sp_name"));
dw.put("lv_num", kq.get("lv_num"));
dw.put("emnature", kq.get("emnature"));
dw.put("status", status);
dw.put("remark", remark);
dws.add(dw);
}
}
}
}
/**
* 数据转换成字符用于SQLIN操作
* @param ids
* @return
*/
public String tranInSql(List<String>ids){
StringBuffer idsStr = new StringBuffer();
for (int i = 0; i < ids.size(); i++) {
if (i > 0) {
idsStr.append(",");
}
idsStr.append("'").append(ids.get(i)).append("'");
}
System.out.print(idsStr.toString());
return idsStr.toString();
}
}
<file_sep>/src/com/hr/perm/entity/Hr_transfer_try.java
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_transfer_try extends CJPA {
@CFieldinfo(fieldname = "transfertry_id", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField transfertry_id; // ID
@CFieldinfo(fieldname = "emptranf_id", notnull = true, caption = "调动单ID", datetype = Types.INTEGER)
public CField emptranf_id; // 调动单ID
@CFieldinfo(fieldname = "emptranfcode", notnull = true, caption = "调用编码", datetype = Types.VARCHAR)
public CField emptranfcode; // 调用编码
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "人事档案ID", datetype = Types.INTEGER)
public CField er_id; // 人事档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "employee_name", notnull = true, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "degree", caption = "学历", datetype = Types.INTEGER)
public CField degree; // 学历
@CFieldinfo(fieldname = "id_number", notnull = true, caption = "身份证号", defvalue = "0", datetype = Types.VARCHAR)
public CField id_number; // 身份证号
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "部门名称", datetype = Types.VARCHAR)
public CField orgname; // 部门名称
@CFieldinfo(fieldname = "ospid", notnull = true, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称
@CFieldinfo(fieldname = "hwc_namezl", caption = "职类", datetype = Types.VARCHAR)
public CField hwc_namezl; // 职类
@CFieldinfo(fieldname = "hg_name", caption = "职等名称", datetype = Types.VARCHAR)
public CField hg_name; // 职等名称
@CFieldinfo(fieldname = "lv_num", caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "entrydate", notnull = true, caption = "入职日期", datetype = Types.TIMESTAMP)
public CField entrydate; // 入职日期
@CFieldinfo(fieldname = "tranfcmpdate", caption = "调动生效时间", datetype = Types.TIMESTAMP)
public CField tranfcmpdate; // 调动生效时间
@CFieldinfo(fieldname = "probation", caption = "考察期", datetype = Types.INTEGER)
public CField probation; // 考察期
@CFieldinfo(fieldname = "probationdate", notnull = true, caption = "转正日期 第一次约定的考察到期", datetype = Types.TIMESTAMP)
public CField probationdate; // 转正日期 第一次约定的考察到期
@CFieldinfo(fieldname = "probationdatetrue", caption = "实际转正日期 根据转正评审结果确定 如延长考察期则为空", datetype = Types.TIMESTAMP)
public CField probationdatetrue; // 实际转正日期 根据转正评审结果确定 如延长考察期则为空
@CFieldinfo(fieldname = "wfresult", caption = "评审结果 1 同意转正 2 延长试用 3 考察不合格", datetype = Types.INTEGER)
public CField wfresult; // 评审结果 1 同意转正 2 延长试用 3 考察不合格
@CFieldinfo(fieldname = "delayprobation", caption = "延长考察期", datetype = Types.INTEGER)
public CField delayprobation; // 延长考察期
@CFieldinfo(fieldname = "delaypromotionday", caption = "延期待转正时间 根据延长考察期自动计算,多次延期累计计算", datetype = Types.TIMESTAMP)
public CField delaypromotionday; // 延期待转正时间 根据延长考察期自动计算,多次延期累计计算
@CFieldinfo(fieldname = "delaypromotiondaytrue", caption = "延期实际转正时间", datetype = Types.TIMESTAMP)
public CField delaypromotiondaytrue; // 延期实际转正时间
@CFieldinfo(fieldname = "delaywfresult", caption = "评审结果 1 同意转正 2 延长考察 3 考察不合格", datetype = Types.INTEGER)
public CField delaywfresult; // 评审结果 1 同意转正 2 延长考察 3 考察不合格
@CFieldinfo(fieldname = "delaytimes", caption = "延期次数", datetype = Types.INTEGER)
public CField delaytimes; // 延期次数
@CFieldinfo(fieldname = "trystat", notnull = true, caption = "考察期人事状态 考察期中、考察过期、考察延期、己转正、考察不合格", datetype = Types.INTEGER)
public CField trystat; // 考察期人事状态 考察期中、考察过期、考察延期、己转正、考察不合格
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1 //记录自动转正信息
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_transfer_try() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/08/0894c4aa58fed6f4aa807e148d411b873ebd5dd3.svn-base
package com.hr.access.co;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.access.entity.Hr_access_list;
import com.hr.asset.entity.Hr_asset_type;
@ACO(coname = "web.hr.Access")
public class COHr_access_list extends JPAController {
@Override
public String OnCCoDel(CDBConnection con, Class<CJPA> jpaclass, String typeid) throws Exception {
if (jpaclass.isAssignableFrom(Hr_access_list.class)) {
String sqlstr = "SELECT IFNULL(COUNT(*),0) oc FROM hr_access_emauthority_list t WHERE t.access_list_id = " + typeid;
if (Integer.valueOf(con.openSql2List(sqlstr).get(0).get("oc")) != 0)
throw new Exception("门禁已经被授权,不允许删除");
}
return null;
}
// Excel导入
@ACOAction(eventname = "ImpListExcel", Authentication = true, ispublic = false, notes = "导入Excel")
public String ImpListExcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
Workbook workbook = WorkbookFactory.create(file);
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_access_list at = new Hr_access_list();
CDBConnection con = at.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
Shworg org = new Shworg();
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String sqlstr = "SELECT * FROM shworg WHERE `code`='" + v.get("orgcode") + "'";
org.findBySQL(sqlstr);
if (org.isEmpty())
throw new Exception("编码为【" + v.get("orgcode") + "】的机构不存在");
rst++;
at.clear();
at.access_list_code.setValue(v.get("access_list_code"));
at.access_list_model.setValue(v.get("access_list_model"));
at.access_list_name.setValue(v.get("access_list_name"));
at.orgid.setValue(org.orgid.getValue());
at.orgcode.setValue(org.code.getValue());
at.extorgname.setValue(org.extorgname.getValue());
at.idpath.setValue(org.idpath.getValue());
at.deploy_area.setValue(v.get("deploy_area"));
at.remarks.setValue(v.get("remarks"));
at.stat.setValue("9");
at.save(con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("门禁编码", "access_list_code", false));
efields.add(new CExcelField("门禁型号", "access_list_model", false));
efields.add(new CExcelField("门禁名称", "access_list_name", true));
efields.add(new CExcelField("机构编码", "orgcode", false));
efields.add(new CExcelField("机构全称", "extorgname", false));
efields.add(new CExcelField("配置区域", "deploy_area", false));
efields.add(new CExcelField("备注", "remarks", false));
return efields;
}
}
<file_sep>/src/com/corsair/server/eai/CEAIParam.java
package com.corsair.server.eai;
public class CEAIParam extends CEAIParamDBInfo {
public CEAIParam(String xmlfname) throws Exception {
super(xmlfname);
// TODO Auto-generated constructor stub
}
public CChildEAIParm getChdEaiByParam(CEAIParam eaip) {
for (CChildEAIParm cdeai : getChildeais()) {
if (cdeai.getCdeaiparam().equals(eaip)) {
return cdeai;
}
}
return null;
}
}
<file_sep>/src/com/corsair/server/weixin/entity/Wx_user.java
package com.corsair.server.weixin.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Wx_user extends CJPA {
@CFieldinfo(fieldname = "wxuserid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField wxuserid; // ID
@CFieldinfo(fieldname = "appid", precision = 64, scale = 0, caption = "wxappid", datetype = Types.VARCHAR)
public CField appid; // wxappid
@CFieldinfo(fieldname = "subscribe", caption = "关注状态", datetype = Types.INTEGER)
public CField subscribe; // 关注状态
@CFieldinfo(fieldname = "openid", caption = "openid", datetype = Types.VARCHAR)
public CField openid; // openid
@CFieldinfo(fieldname = "nickname", caption = "nickname", datetype = Types.VARCHAR)
public CField nickname; // nickname
@CFieldinfo(fieldname = "b64nickname", caption = "base64昵称", datetype = Types.VARCHAR)
public CField b64nickname; // base64昵称
@CFieldinfo(fieldname = "sex", caption = "性别 1 男 2女 3 不男不女", datetype = Types.INTEGER)
public CField sex; // 性别 1 男 2女 3 不男不女
@CFieldinfo(fieldname = "city", caption = "城市", datetype = Types.VARCHAR)
public CField city; // 城市
@CFieldinfo(fieldname = "province", caption = "省份", datetype = Types.VARCHAR)
public CField province; // 省份
@CFieldinfo(fieldname = "country", caption = "国家", datetype = Types.VARCHAR)
public CField country; // 国家
@CFieldinfo(fieldname = "language", caption = "语言", datetype = Types.VARCHAR)
public CField language; // 语言
@CFieldinfo(fieldname = "headimgurl", caption = "头像", datetype = Types.VARCHAR)
public CField headimgurl; // 头像
@CFieldinfo(fieldname = "subscribe_time", caption = "关注时间", datetype = Types.INTEGER)
public CField subscribe_time; // 关注时间
@CFieldinfo(fieldname = "unionid", caption = "统一ID", datetype = Types.VARCHAR)
public CField unionid; // 统一ID
@CFieldinfo(fieldname = "remark", precision = 64, scale = 0, caption = "公众号运营者对粉丝的备注", datetype = Types.VARCHAR)
public CField remark; // 公众号运营者对粉丝的备注
@CFieldinfo(fieldname = "subscribe_scene", precision = 32, scale = 0, caption = "返回用户关注的渠道来源", datetype = Types.VARCHAR)
public CField subscribe_scene;
// 返回用户关注的渠道来源,ADD_SCENE_SEARCH 公众号搜索,ADD_SCENE_ACCOUNT_MIGRATION 公众号迁移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE
// 扫描二维码,ADD_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
@CFieldinfo(fieldname = "qr_scene", precision = 16, scale = 0, caption = "二维码扫码场景(开发者自定义)", datetype = Types.VARCHAR)
public CField qr_scene; // 二维码扫码场景(开发者自定义)
@CFieldinfo(fieldname = "qr_scene_str", precision = 128, scale = 0, caption = "二维码扫码场景描述(开发者自定义)", datetype = Types.VARCHAR)
public CField qr_scene_str; // 二维码扫码场景描述(开发者自定义)
@CFieldinfo(fieldname = "update_time", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField update_time; // 更新时间
@CFieldinfo(fieldname = "mobil", caption = "mobil", datetype = Types.VARCHAR)
public CField mobil; // mobil
@CFieldinfo(fieldname = "name", caption = "用户姓名", datetype = Types.VARCHAR)
public CField name; // 用户姓名
@CFieldinfo(fieldname = "addr", caption = "地址", datetype = Types.VARCHAR)
public CField addr; // 地址
@CFieldinfo(fieldname = "privilege", caption = "特权", datetype = Types.VARCHAR)
public CField privilege; // 特权
@CFieldinfo(fieldname = "inickname", caption = "ICEFALL昵称", datetype = Types.VARCHAR)
public CField inickname; // ICEFALL昵称
@CFieldinfo(fieldname = "iheadimgurl", caption = "ICEFALL头像", datetype = Types.VARCHAR)
public CField iheadimgurl; // ICEFALL头像
@CFieldinfo(fieldname = "isignature", caption = "ICEFALL个性签名", datetype = Types.VARCHAR)
public CField isignature; // ICEFALL个性签名
@CFieldinfo(fieldname = "itruename", caption = "真实姓名", datetype = Types.VARCHAR)
public CField itruename; // 真实姓名
@CFieldinfo(fieldname = "userid", caption = "系统登录用户", datetype = Types.INTEGER)
public CField userid; // 系统登录用户
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Wx_user() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/f7/f70f28d094fe91f5cacbf84700a2c6f910ed1a0b.svn-base
package com.hr.base.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "机构职位月结(编制)")
public class Hr_month_orgposition extends CJPA {
@CFieldinfo(fieldname = "mid", iskey = true, autoinc = true, notnull = true, precision = 20, scale = 0, caption = "ID", datetype = Types.INTEGER)
public CField mid; // ID
@CFieldinfo(fieldname = "yearmonth", notnull = true, precision = 7, scale = 0, caption = "年月", datetype = Types.VARCHAR)
public CField yearmonth; // 年月
@CFieldinfo(fieldname = "ospid", notnull = true, precision = 20, scale = 0, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, precision = 16, scale = 0, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "pid", notnull = true, precision = 20, scale = 0, caption = "上级职位ID", datetype = Types.INTEGER)
public CField pid; // 上级职位ID
@CFieldinfo(fieldname = "pname", precision = 128, scale = 0, caption = "上级职位名称", datetype = Types.VARCHAR)
public CField pname; // 上级职位名称
@CFieldinfo(fieldname = "orgid", notnull = true, precision = 20, scale = 0, caption = "机构ID", datetype = Types.INTEGER)
public CField orgid; // 机构ID
@CFieldinfo(fieldname = "orgname", notnull = true, precision = 64, scale = 0, caption = "机构名称", datetype = Types.VARCHAR)
public CField orgname; // 机构名称
@CFieldinfo(fieldname = "sp_id", notnull = true, precision = 10, scale = 0, caption = "标准ID", datetype = Types.INTEGER)
public CField sp_id; // 标准ID
@CFieldinfo(fieldname = "sp_name", precision = 128, scale = 0, caption = "标准职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 标准职位名称
@CFieldinfo(fieldname = "gtitle", precision = 32, scale = 0, caption = "职衔", datetype = Types.VARCHAR)
public CField gtitle; // 职衔
@CFieldinfo(fieldname = "lv_num", notnull = true, precision = 4, scale = 1, caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "hg_name", precision = 128, scale = 0, caption = "职等", datetype = Types.VARCHAR)
public CField hg_name; // 职等
@CFieldinfo(fieldname = "hwc_namezl", precision = 128, scale = 0, caption = "职类", datetype = Types.VARCHAR)
public CField hwc_namezl; // 职类
@CFieldinfo(fieldname = "hwc_namezq", precision = 128, scale = 0, caption = "职群", datetype = Types.VARCHAR)
public CField hwc_namezq; // 职群
@CFieldinfo(fieldname = "hwc_namezz", precision = 128, scale = 0, caption = "职种", datetype = Types.VARCHAR)
public CField hwc_namezz; // 职种
@CFieldinfo(fieldname = "quota", precision = 10, scale = 0, caption = "编制数量", defvalue = "0", datetype = Types.INTEGER)
public CField quota; // 编制数量
@CFieldinfo(fieldname = "isadvtech", precision = 1, scale = 0, caption = "高级技术专业人才", defvalue = "2", datetype = Types.INTEGER)
public CField isadvtech; // 高级技术专业人才
@CFieldinfo(fieldname = "isoffjob", precision = 1, scale = 0, caption = "脱产", defvalue = "1", datetype = Types.INTEGER)
public CField isoffjob; // 脱产
@CFieldinfo(fieldname = "issensitive", precision = 1, scale = 0, caption = "敏感岗位", defvalue = "2", datetype = Types.INTEGER)
public CField issensitive; // 敏感岗位
@CFieldinfo(fieldname = "iskey", precision = 1, scale = 0, caption = "关键岗位", defvalue = "2", datetype = Types.INTEGER)
public CField iskey; // 关键岗位
@CFieldinfo(fieldname = "ishighrisk", precision = 1, scale = 0, caption = "高危岗位", defvalue = "2", datetype = Types.INTEGER)
public CField ishighrisk; // 高危岗位
@CFieldinfo(fieldname = "isneedadtoutwork", precision = 1, scale = 0, caption = "离职审计", defvalue = "2", datetype = Types.INTEGER)
public CField isneedadtoutwork; // 离职审计
@CFieldinfo(fieldname = "isdreamposition", precision = 1, scale = 0, caption = "梦想职位", defvalue = "2", datetype = Types.INTEGER)
public CField isdreamposition; // 梦想职位
@CFieldinfo(fieldname = "idpath", precision = 250, scale = 0, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_month_orgposition() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/genco/COHtmlTemplate.java
package com.corsair.server.genco;
import java.util.HashMap;
import java.util.List;
import com.corsair.dbpool.util.CJSON;
import com.corsair.server.base.CSContext;
import com.corsair.server.html.CHtmlTemplate;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
/**
* HTML模板CO
*
* @author Administrator
*
*/
@ACO(coname = "web.htmltem")
public class COHtmlTemplate {
@ACOAction(eventname = "getTmfTree", Authentication = false)
public String getTmfTree() throws Exception {
return CHtmlTemplate.getSrc2JsonTree();
}
@ACOAction(eventname = "reBuildHtmls", Authentication = false)
public String reBuildHtmls() throws Exception {
HashMap<String, String> pparms = CSContext.parPostDataParms();
String nodestr = pparms.get("node");
String rootpath = null;
if (nodestr != null) {
HashMap<String, String> node = CJSON.Json2HashMap(nodestr);
rootpath = node.get("path");
}
List<String> fnnames = CHtmlTemplate.getSrcList(rootpath);
for (String s : fnnames) {
CHtmlTemplate.buildHtml(s);
}
return "{\"result\":\"OK\"}";
}
}
<file_sep>/WebContent/webapp/js/common/cwf2.js
function jsDraw2DX() {
}
jsDraw2DX._RefID = 0; //Reference IDs used for <defs> in SVG
jsDraw2DX._isVML = false; //_isVML is true if SVG is not supported and only VML is supported
//Global Functions
//Check browser for IE
jsDraw2DX.checkIE = function () {
if (navigator.appName == 'Microsoft Internet Explorer') {
var version = 9;
if (navigator.appVersion.indexOf('MSIE') != -1) {
version = parseFloat(navigator.appVersion.split('MSIE')[1]);
}
if (version < 9) { //SVG support provided for IE9 & onwards
jsDraw2DX._isVML = true;
}
}
};
//Internal global utility factorial function
jsDraw2DX.fact = function (n) {
var res = 1;
for (var i = 1; i <= n; i++) {
res = res * i;
}
return res;
};
//Initialization of the library
jsDraw2DX.init = function () {
jsDraw2DX.checkIE();
if (jsDraw2DX._isVML) {
document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
var vmlElements = ['fill', 'stroke', 'path', 'textpath'];
for (var i = 0, l = vmlElements.length; i < l; i++) {
document.createStyleSheet().addRule('v\\:' + vmlElements[i], 'behavior: url(#default#VML);');
}
}
};
//Global Startup
jsDraw2DX.init();
//jxGraphics class holds basic drawing parameters like origin, scale, co-ordinate system.
//It also holds drawing div, svg/vml root elements and array of the drawn shapes.
function jxGraphics(graphicsDivElement) {
//Private member variables
this.origin = new jxPoint(0, 0);
this.scale = 1;
this.coordinateSystem = 'default'; //Possible values 'default' or 'cartecian'
//Private member variables
var _shapes = new Array(); //Array of shapes drawn with the graphics
var _graphicsDiv, _svg, _vml, _defs;
if (graphicsDivElement) {
_graphicsDiv = graphicsDivElement;
_graphicsDiv.style.overflow = 'hidden';
}
else
_graphicsDiv = document.body; //Document will be used directly for drawing
//SVG, VML Initialization
if (!jsDraw2DX._isVML) {
_svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
_graphicsDiv.appendChild(_svg);
_defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
_svg.appendChild(_defs);
_svg.style.position = 'absolute';
_svg.style.top = '0px';
_svg.style.left = '0px';
_svg.style.width = _graphicsDiv.style.width;
_svg.style.height = _graphicsDiv.style.height;
}
else {
_vml = document.createElement('v:group');
_vml.style.position = 'absolute';
_vml.style.top = '0px';
_vml.style.left = '0px';
_graphicsDiv.appendChild(_vml);
}
//Internal utility methods
//Defs (for SVG only)
this.getDefs = getDefs;
function getDefs() {
return _defs;
}
//Adds shape to the _shapes array
this.addShape = addShape;
function addShape(shape) {
var ind = this.indexOfShape(shape);
if (ind < 0)
_shapes.push(shape);
}
//Removes shape from the _shapes array
this.removeShape = removeShape;
function removeShape(shape) {
var ind = this.indexOfShape(shape);
if (ind >= 0)
_shapes.splice(ind, 1);
}
//Public Methods
//Get the type
this.getType = getType;
function getType() {
return 'jxGraphics';
}
//Graphics Div
this.getDiv = getDiv;
function getDiv() {
return _graphicsDiv;
}
//SVG
this.getSVG = getSVG;
function getSVG() {
return _svg;
}
//VML
this.getVML = getVML;
function getVML() {
return _vml;
}
//Conversion of logical point to physical point based on coordinate system, origin and scale.
this.logicalToPhysicalPoint = logicalToPhysicalPoint;
function logicalToPhysicalPoint(point) {
if (this.coordinateSystem.toLowerCase() == 'cartecian') {
return new jxPoint(Math.round(point.x * this.scale + this.origin.x), Math.round(this.origin.y - point.y * this.scale))
}
else {
return new jxPoint(Math.round(point.x * this.scale + this.origin.x), Math.round(point.y * this.scale + this.origin.y))
}
}
//Draws a specified shape
this.draw = draw;
function draw(shape) {
return shape.draw(this);
}
//Removes a specified shape
this.remove = remove;
function remove(shape) {
return shape.remove(this);
}
this.removeall = function () {
for (var i = _shapes.length - 1; i >= 0; i--) {
this.remove(_shapes[i]);
}
};
//Redraws all the shapes
this.redrawAll = redrawAll;
function redrawAll() {
for (ind in _shapes) {
_shapes[ind].draw(this);
}
}
//Gets the count of the shape drawn on the graphics
this.getShapesCount = getShapesCount;
function getShapesCount() {
return _shapes.length;
}
//Gets the shape object drawn on the graphics at specific index
this.getShape = getShape;
function getShape(index) {
return _shapes[index];
}
//Gets the index of the shape
this.indexOfShape = indexOfShape;
function indexOfShape(shape) {
var ind = -1, length = _shapes.length;
for (var i = 0; i < length; i++) {
if (shape == _shapes[i]) {
ind = i;
}
}
return ind;
}
}
//jxColor class holds the color information and provides some color related basic functions.
function jxColor() {
//Member variables
var _color = '#000000';
switch (arguments.length) {
//Color Hex or Named or rgb()
case 1:
_color = arguments[0];
break;
//RGB Color
case 3:
var red = arguments[0];
var green = arguments[1];
var blue = arguments[2];
_color = jxColor.rgbToHex(red, green, blue);
break;
}
//Public Methods
//Get the type
this.getType = getType;
function getType() {
return 'jxColor';
}
//Get the hexa-decimal or named color value of the object
this.getValue = getValue;
function getValue() {
return _color;
}
}
//Static-Shared Utility Methods of jxColor
//Convert RGB color to Hex color
jxColor.rgbToHex = function (redValue, greenValue, blueValue) {
//Check argument values
if (redValue < 0 || redValue > 255 || greenValue < 0 || greenValue > 255 || blueValue < 0 || blueValue > 255) {
return false;
}
var colorDec = Math.round(blueValue) + 256 * Math.round(greenValue) + 65536 * Math.round(redValue);
return '#' + zeroPad(colorDec.toString(16), 6);
//Internal method, add zero padding to the left. Used for building hexa-decimal string.
function zeroPad(val, count) {
var valZeropad = val + '';
while (valZeropad.length < count) {
valZeropad = '0' + valZeropad;
}
return valZeropad;
}
};
//Convert Hex color to RGB color
jxColor.hexToRgb = function (hexValue) {
var redValue, greenValue, blueValue;
if (hexValue.charAt(0) == '#') {
hexValue = hexValue.substring(1, 7);
}
redValue = parseInt(hexValue.substring(0, 2), 16);
greenValue = parseInt(hexValue.substring(2, 4), 16);
blueValue = parseInt(hexValue.substring(4, 6), 16);
//Check argument values
if (redValue < 0 || redValue > 255 || greenValue < 0 || greenValue > 255 || blueValue < 0 || blueValue > 255) {
return false;
}
return new Array(redValue, greenValue, blueValue);
};
//jxFont class holds the font information which can be used by other objects in object oriented way.
function jxFont(family, size, style, weight, variant) {
//Public Properties with default value null
this.family = null;
this.size = null;
this.style = null;
this.weight = null;
this.variant = null;
//Object Construction
if (family)
this.family = family;
if (weight)
this.weight = weight;
if (size)
this.size = size;
if (style)
this.style = style;
if (variant)
this.variant = variant;
//Internal utility methods
//Apply font settings to SVG text
this.updateSVG = updateSVG;
function updateSVG(_svgvmlObj) {
if (this.family)
_svgvmlObj.setAttribute('font-family', this.family);
else
_svgvmlObj.setAttribute('font-family', '');
if (this.weight)
_svgvmlObj.setAttribute('font-weight', this.weight);
else
_svgvmlObj.setAttribute('font-weight', '');
if (this.size)
_svgvmlObj.setAttribute('font-size', this.size);
else
_svgvmlObj.setAttribute('font-size', '');
if (this.style)
_svgvmlObj.setAttribute('font-style', this.style);
else
_svgvmlObj.setAttribute('font-style', '');
if (this.variant)
_svgvmlObj.setAttribute('font-variant', this.variant);
else
_svgvmlObj.setAttribute('font-variant', '');
}
//Apply font settings to VML textpath
this.updateVML = updateVML;
function updateVML(vmlTextPath) {
if (this.family)
vmlTextPath.style.fontFamily = "'" + this.family + "'";
else
vmlTextPath.style.fontFamily = '';
if (this.weight)
vmlTextPath.style.fontWeight = this.weight;
else
vmlTextPath.style.fontWeight = '';
if (this.size)
vmlTextPath.style.fontSize = this.size;
else
vmlTextPath.style.fontSize = '';
if (this.style)
vmlTextPath.style.fontStyle = this.style;
else
vmlTextPath.style.fontStyle = '';
if (this.variant)
vmlTextPath.style.fontVariant = this.variant;
else
vmlTextPath.style.fontVariant = '';
}
//Public Methods
this.getType = getType;
function getType() {
return 'jxFont';
}
}
//Internal Static/Shared Methods of jxFont
//To remove font setting of SVG text (font=null)
jxFont.updateSVG = function (_svgvmlObj) {
_svgvmlObj.setAttribute('font-family', '');
_svgvmlObj.setAttribute('font-weight', '');
_svgvmlObj.setAttribute('font-size', '');
_svgvmlObj.setAttribute('font-style', '');
_svgvmlObj.setAttribute('font-variant', '');
};
//Remove font settings of VML textpath (font=null)
jxFont.updateVML = function (vmlTextPath) {
vmlTextPath.style.fontFamily = '';
vmlTextPath.style.fontWeight = '';
vmlTextPath.style.fontSize = '';
vmlTextPath.style.fontStyle = '';
vmlTextPath.style.fontVariant = '';
};
//jxPen class holds the drawing pen/stroke information.
//Mainly it holds the color and width values to be used for 2D drawing.
//Acts like a pen for drawing.
function jxPen(color, width, dashStyle) {
//Public Properties
this.color = null; //color proprty of jxColor type
this.width = null; //width property
this.dashStyle = null; //for dotted and dashed line
//Object construction
if (color)
this.color = color;
else
this.color = new jxColor('#000000'); //default black color
if (width)
this.width = width;
else
this.width = '1px'; //1px default value
if (dashStyle)
this.dashStyle = dashStyle;
//Internal utility methods
//Update the svg to apply pen settings
this.updateSVG = updateSVG;
function updateSVG(_svgvmlObj) {
_svgvmlObj.setAttribute('stroke', this.color.getValue()); //moyh
_svgvmlObj.setAttribute('stroke-width', this.width); //moyh
if (this.dashStyle) {
var w = parseInt(this.width);
switch (this.dashStyle.toLowerCase()) {
case 'shortdash':
_svgvmlObj.setAttribute('stroke-dasharray', w * 3 + ' ' + w);
break;
case 'shortdot':
_svgvmlObj.setAttribute('stroke-dasharray', w + ' ' + w);
break;
case 'shortdashdot':
_svgvmlObj.setAttribute('stroke-dasharray', w * 3 + ' ' + w + ' ' + w + ' ' + w);
break;
case 'shortdashdotdot':
_svgvmlObj.setAttribute('stroke-dasharray', w * 3 + ' ' + w + ' ' + w + ' ' + w + ' ' + w + ' ' + w);
break;
case 'dot':
_svgvmlObj.setAttribute('stroke-dasharray', w + ' ' + w * 3);
break;
case 'dash':
_svgvmlObj.setAttribute('stroke-dasharray', w * 4 + ' ' + w * 3);
break;
case 'longdash':
_svgvmlObj.setAttribute('stroke-dasharray', w * 8 + ' ' + w * 3);
break;
case 'dashdot':
_svgvmlObj.setAttribute('stroke-dasharray', w * 4 + ' ' + w * 3 + ' ' + w + ' ' + w * 3);
break;
case 'longdashdot':
_svgvmlObj.setAttribute('stroke-dasharray', w * 8 + ' ' + w * 3 + ' ' + w + ' ' + w * 3);
break;
case 'longdashdotdot':
_svgvmlObj.setAttribute('stroke-dasharray', w * 8 + ' ' + w * 3 + ' ' + w + ' ' + w * 3 + ' ' + w + ' ' + w * 3);
break;
default:
_svgvmlObj.setAttribute('stroke-dasharray', this.dashStyle);
break;
}
}
}
//Update the vml to apply pen settings
this.updateVML = updateVML;
function updateVML(_svgvmlObj) {
_svgvmlObj.Stroke.JoinStyle = 'miter';
_svgvmlObj.Stroke.MiterLimit = '5';
_svgvmlObj.StrokeColor = this.color.getValue();
_svgvmlObj.StrokeWeight = this.width;
if (this.dashStyle)
_svgvmlObj.Stroke.DashStyle = this.dashStyle;
if (parseInt(this.width) == 0)
_svgvmlObj.Stroked = 'False';
}
//Public Methods
this.getType = getType;
function getType() {
return 'jxPen';
}
}
//jxBrush class holds the drawing fill information.
//Mainly it holds the fill color values and fill type to be used for filling 2D drawing.
//Acts like a brush for drawing.
function jxBrush(color, fillType) {
//Public Properties
this.color = null; //color proprty of jxColor type
this.fillType = null; //fillType property 'solid','lin_grad'='linear_gradient',proposed:'rad_grad'='radial_gradiant' or 'pattern'
this.color2 = null; //second color for gradient fill type
this.angle = null;
//Construction of the object
if (color)
this.color = color;
else
this.color = new jxColor('#000000'); //Default black color
if (fillType)
this.fillType = fillType;
else
this.fillType = 'solid'; //Default fillType other values 'linear-gradient'='lin-grad' (more to come)
//Set rest of defaults
this.color2 = new jxColor('#FFFFFF'); //Default color2
//Internal utility functions
//Update the svg to apply brush settings
this.updateSVG = updateSVG;
function updateSVG(_svgvmlObj, defs) {
var fillId = null, oldChild;
fillId = _svgvmlObj.getAttribute('fill');
if (fillId) {
if (fillId.substr(0, 5) == 'url(#') {
fillId = fillId.substr(5, fillId.length - 6);
oldChild = document.getElementById(fillId);
}
else
fillId = null;
}
if (this.fillType == 'linear-gradient' || this.fillType == 'lin-grad') {
var linearGradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient');
if (fillId)
defs.replaceChild(linearGradient, oldChild);
else
defs.appendChild(linearGradient);
var stop1 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
linearGradient.appendChild(stop1);
var stop2 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
linearGradient.appendChild(stop2);
jsDraw2DX._RefID++;
linearGradient.setAttribute('id', 'jsDraw2DX_RefID_' + jsDraw2DX._RefID);
if (this.angle != null)
linearGradient.setAttribute('gradientTransform', 'rotate(' + this.angle + ' 0.5 0.5)');
else
linearGradient.setAttribute('gradientTransform', 'rotate(0 0.5 0.5)');
stop1.setAttribute('offset', '0%');
stop1.setAttribute('style', 'stop-color:' + this.color.getValue() + ';stop-opacity:1');
stop2.setAttribute('offset', '100%');
stop2.setAttribute('style', 'stop-color:' + this.color2.getValue() + ';stop-opacity:1');
linearGradient.appendChild(stop1);
linearGradient.appendChild(stop2);
_svgvmlObj.setAttribute('fill', 'url(#' + 'jsDraw2DX_RefID_' + jsDraw2DX._RefID + ')');
}
else
_svgvmlObj.setAttribute('fill', this.color.getValue());
}
//Update the vml to apply brush settings
this.updateVML = updateVML;
function updateVML(vmlFill) {
vmlFill.On = 'true';
if (this.fillType == 'solid') {
vmlFill.Type = 'solid';
vmlFill.Color = this.color.getValue();
vmlFill.Color2 = '';
vmlFill.Angle = 270;
}
else {
vmlFill.Type = 'gradient';
if (this.angle != null)
vmlFill.Angle = 270 - this.angle;
else
vmlFill.Angle = 270;
vmlFill.Color = this.color.getValue();
vmlFill.Color2 = this.color2.getValue();
}
}
//Public Methods
this.getType = getType;
function getType() {
return 'jxBrush';
}
}
//jxPoint class holds the 2D drawing point information.
//It holds values of x and y coordinates of the point.
function jxPoint(x, y) {
//Public Properties
this.x = x;
this.y = y;
//Public Methods
//Get the type
this.getType = getType;
function getType() {
return 'jxPoint';
}
}
//Class to hold information and draw line shape
function jxLine(fromPoint, toPoint, pen) {
//Public Properties
this.fromPoint = fromPoint;
this.toPoint = toPoint;
this.pen = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object Construction
if (pen)
this.pen = pen;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'line');
else
_svgvmlObj = document.createElement('v:line');
//Public Methods
this.getType = getType;
function getType() {
return 'jxLine';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw line shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var fromPoint, toPoint;
fromPoint = graphics.logicalToPhysicalPoint(this.fromPoint);
toPoint = graphics.logicalToPhysicalPoint(this.toPoint);
var colorValue, penWidth, isFirst = false;
colorValue = this.pen.color.getValue();
penWidth = this.pen.width;
var x1, y1, x2, y2;
x1 = fromPoint.x;
y1 = fromPoint.y;
x2 = toPoint.x;
y2 = toPoint.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
_svgvmlObj.setAttribute('x1', x1);
_svgvmlObj.setAttribute('y1', y1);
_svgvmlObj.setAttribute('x2', x2);
_svgvmlObj.setAttribute('y2', y2);
}
else {
var vml = graphics.getVML();
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.From = x1 + ',' + y1;
_svgvmlObj.To = x2 + ',' + y2;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw rectangle shape
function jxRect(point, width, height, pen, brush) {
//Public Properties
this.point = point;
this.width = width;
this.height = height;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
this.getElement = getElement;
function getElement() {
return _svgvmlObj;
}
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
else
_svgvmlObj = document.createElement('v:rect');
//Public Methods
this.getType = getType;
function getType() {
return 'jxRect';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw rectangle shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var point, scale;
point = graphics.logicalToPhysicalPoint(this.point);
scale = graphics.scale;
var x1, y1;
x1 = point.x;
y1 = point.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Settings
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('x', x1);
_svgvmlObj.setAttribute('y', y1);
_svgvmlObj.setAttribute('width', scale * this.width);
_svgvmlObj.setAttribute('height', scale * this.height);
_svgvmlObj.style.position = 'absolute';
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.width = scale * this.width;
_svgvmlObj.style.height = scale * this.height;
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.top = y1;
_svgvmlObj.style.left = x1;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw polyline shape
function jxPolyline(points, pen, brush) {
//Public Properties
this.points = points;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
else
_svgvmlObj = document.createElement('v:polyline');
//Public Methods
this.getType = getType;
function getType() {
return 'jxPolyline';
}
this.getElement = getElement;
function getElement() {
return _svgvmlObj;
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw polyline shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array(), pointsList = '';
for (ind in this.points) {
points[ind] = graphics.logicalToPhysicalPoint(this.points[ind]);
}
for (ind in points) {
pointsList = pointsList + points[ind].x + ',' + points[ind].y + ' ';
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Settings
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Settings
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.setAttribute('points', pointsList);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.Points.Value = pointsList;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw polygon shape
function jxPolygon(points, pen, brush) {
//Public Properties
this.points = points;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
else
_svgvmlObj = document.createElement('v:polyline');
//Public Methods
this.getType = getType;
function getType() {
return 'jxPolygon';
}
this.getElement = getElement;
function getElement() {
return _svgvmlObj;
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw polygon shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array(), pointsList = '';
for (ind in this.points) {
points[ind] = graphics.logicalToPhysicalPoint(this.points[ind]);
}
for (ind in points) {
pointsList = pointsList + points[ind].x + ',' + points[ind].y + ' ';
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Settings
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Settings
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.setAttribute('points', pointsList);
}
else {
pointsList = pointsList + points[0].x + ',' + points[0].y;
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.Points.Value = pointsList;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw circle shape
function jxCircle(center, radius, pen, brush) {
//Public Properties
this.center = center;
this.radius = radius;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
else
_svgvmlObj = document.createElement('v:oval');
//Public Methods
this.getType = getType;
function getType() {
return 'jxCircle';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw circle shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var center, scale;
center = graphics.logicalToPhysicalPoint(this.center);
scale = graphics.scale;
var cx, cy;
cx = center.x;
cy = center.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('cx', cx);
_svgvmlObj.setAttribute('cy', cy);
_svgvmlObj.setAttribute('r', scale * this.radius);
_svgvmlObj.style.position = 'absolute';
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.width = scale * this.radius * 2;
_svgvmlObj.style.height = scale * this.radius * 2;
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.top = cy - scale * this.radius;
_svgvmlObj.style.left = cx - scale * this.radius;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw ellipse shape
function jxEllipse(center, width, height, pen, brush) {
//Public Properties
this.center = center;
this.width = width;
this.height = height;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'ellipse');
else
_svgvmlObj = document.createElement('v:oval');
//Public Methods
this.getType = getType;
function getType() {
return 'jxEllipse';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw ellipse shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var center, scale;
center = graphics.logicalToPhysicalPoint(this.center);
scale = graphics.scale;
var cx, cy;
cx = center.x;
cy = center.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Settings
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('cx', cx);
_svgvmlObj.setAttribute('cy', cy);
_svgvmlObj.setAttribute('rx', scale * this.width / 2);
_svgvmlObj.setAttribute('ry', scale * this.height / 2);
_svgvmlObj.style.position = 'absolute';
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.width = scale * this.width;
_svgvmlObj.style.height = scale * this.height;
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.top = cy - scale * this.height / 2;
_svgvmlObj.style.left = cx - scale * this.width / 2;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw elliptical arc shape
function jxArc(center, width, height, startAngle, arcAngle, pen, brush) {
//Public properties
this.center = center;
this.width = width;
this.height = height;
this.startAngle = startAngle;
this.arcAngle = arcAngle;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:arc');
//Public Methods
this.getType = getType;
function getType() {
return 'jxArc';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw arc shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var center, scale;
center = graphics.logicalToPhysicalPoint(graphics);
scale = graphics.scale;
var cx, cy;
cx = this.center.x;
cy = this.center.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
//Calculation of coordinates of ellipse based on angle
var a, b, r1, r2, x1, x2, y1, y2, sa, ea;
a = scale * this.width / 2;
b = scale * this.height / 2;
sa = this.startAngle * Math.PI / 180;
r1 = a * b / Math.sqrt(b * b * Math.cos(sa) * Math.cos(sa) + a * a * Math.sin(sa) * Math.sin(sa));
x1 = r1 * Math.cos(sa);
y1 = r1 * Math.sin(sa);
x1 = cx + x1;
y1 = cy + y1;
ea = (startAngle + arcAngle) * Math.PI / 180;
r2 = a * b / Math.sqrt(b * b * Math.cos(ea) * Math.cos(ea) + a * a * Math.sin(ea) * Math.sin(ea));
x2 = r2 * Math.cos(ea);
y2 = r2 * Math.sin(ea);
x2 = cx + x2;
y2 = cy + y2;
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
if (arcAngle > 180)
_svgvmlObj.setAttribute('d', 'M' + x1 + ' ' + y1 + ' A' + a + ' ' + b + ' 0 1 1 ' + x2 + ' ' + y2);
else
_svgvmlObj.setAttribute('d', 'M' + x1 + ' ' + y1 + ' A' + a + ' ' + b + ' 0 0 1 ' + x2 + ' ' + y2);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
var a, b, r1, r2, sa, ea, sat, eat, endAngle;
endAngle = this.startAngle + this.arcAngle;
startAngle = this.startAngle % 360;
endAngle = endAngle % 360;
a = scale * this.width / 2;
b = scale * this.height / 2;
sa = this.startAngle * Math.PI / 180;
r1 = a * b / Math.sqrt(b * b * Math.cos(sa) * Math.cos(sa) + a * a * Math.sin(sa) * Math.sin(sa));
sat = Math.asin(r1 * Math.sin(sa) / b) * 180 / Math.PI;
if (this.startAngle > 270)
sat = 360 + sat;
else if (this.startAngle > 90)
sat = 180 - sat;
ea = endAngle * Math.PI / 180;
r2 = a * b / Math.sqrt(b * b * Math.cos(ea) * Math.cos(ea) + a * a * Math.sin(ea) * Math.sin(ea));
eat = Math.asin(r2 * Math.sin(ea) / b) * 180 / Math.PI;
if (endAngle > 270)
eat = 360 + eat;
else if (endAngle > 90)
eat = 180 - eat;
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.width = scale * this.width;
_svgvmlObj.style.height = scale * this.height;
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.left = cx - scale * this.width / 2;
_svgvmlObj.style.top = cy - scale * this.height / 2;
sat = sat + 90;
if (sat > 360)
_svgvmlObj.StartAngle = sat % 360;
else
_svgvmlObj.StartAngle = sat;
eat = eat + 90;
if (eat > 360) {
if (sat <= 360)
_svgvmlObj.StartAngle = sat - 360;
_svgvmlObj.EndAngle = eat % 360;
}
else
_svgvmlObj.EndAngle = eat;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw elliptical arc sector(pie) shape
function jxArcSector(center, width, height, startAngle, arcAngle, pen, brush) {
//Public Properties
//Check for 360 arcAngle in chrome
this.center = center;
this.width = width;
this.height = height;
this.startAngle = startAngle;
this.arcAngle = arcAngle;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:shape');
//Public Methods
this.getType = getType;
function getType() {
return 'jxArcSector';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw arc sector (pie) shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var center, scale;
center = graphics.logicalToPhysicalPoint(this.center);
scale = graphics.scale;
var cx, cy;
cx = center.x;
cy = center.y;
//Calculation of coordinates of ellipse based on angle
var a, b, r1, r2, x1, x2, y1, y2, sa, ea;
a = scale * this.width / 2;
b = scale * this.height / 2;
sa = this.startAngle * Math.PI / 180;
r1 = a * b / Math.sqrt(b * b * Math.cos(sa) * Math.cos(sa) + a * a * Math.sin(sa) * Math.sin(sa));
x1 = r1 * Math.cos(sa);
y1 = r1 * Math.sin(sa);
x1 = cx + x1;
y1 = cy + y1;
ea = (this.startAngle + this.arcAngle) * Math.PI / 180;
r2 = a * b / Math.sqrt(b * b * Math.cos(ea) * Math.cos(ea) + a * a * Math.sin(ea) * Math.sin(ea));
x2 = r2 * Math.cos(ea);
y2 = r2 * Math.sin(ea);
x2 = cx + x2;
y2 = cy + y2;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
if (arcAngle > 180)
_svgvmlObj.setAttribute('d', 'M' + cx + ' ' + cy + ' L' + x1 + ' ' + y1 + ' A' + a + ' ' + b + ' 0 1 1 ' + x2 + ' ' + y2 + ' Z');
else
_svgvmlObj.setAttribute('d', 'M' + cx + ' ' + cy + ' L' + x1 + ' ' + y1 + ' A' + a + ' ' + b + ' 0 0 1 ' + x2 + ' ' + y2 + ' Z');
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
var t, l, h, w;
t = Math.min(y2, Math.min(cy, y1));
l = Math.min(x2, Math.min(cx, x1));
h = Math.max(y2, Math.max(cy, y1)) - t;
w = Math.max(x2, Math.max(cx, x1)) - l;
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.height = 1;
_svgvmlObj.style.width = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
_svgvmlObj.Path = 'M' + cx + ',' + cy + ' AT' + (cx - a) + ',' + (cy - b) + ',' + (cx + a) + ',' + (cy + b) + ',' + Math.round(x2) + ',' + Math.round(y2) + ',' + Math.round(x1) + ',' + Math.round(y1) + ' X E';
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw curve shape
function jxCurve(points, pen, brush, tension) {
//Public Properties
this.points = points;
this.pen = null;
this.brush = null;
this.tension = 1;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (tension != null)
this.tension = tension;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:shape');
//Public Methods
this.getType = getType;
function getType() {
return 'jxCurve';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw curve shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array();
for (ind in this.points) {
points[ind] = graphics.logicalToPhysicalPoint(this.points[ind]);
}
var path, ten = this.tension, pDpoints = new Array(), b1points = new Array(), b2points = new Array();
for (var i in points) {
i = parseInt(i);
if (i == 0)
pDpoints[i] = new jxPoint(ten * (points[1].x - points[0].x) / 2, ten * (points[1].y - points[0].y) / 2);
else if (i == points.length - 1)
pDpoints[i] = new jxPoint(ten * (points[i].x - points[i - 1].x) / 2, ten * (points[i].y - points[i - 1].y) / 2);
else
pDpoints[i] = new jxPoint(ten * (points[i + 1].x - points[i - 1].x) / 2, ten * (points[i + 1].y - points[i - 1].y) / 2);
}
for (var i in points) {
i = parseInt(i);
if (i == points.length - 1) {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i].x - pDpoints[i].x / 3, points[i].y - pDpoints[i].y / 3);
}
else {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i + 1].x - pDpoints[i + 1].x / 3, points[i + 1].y - pDpoints[i + 1].y / 3);
}
}
for (var i in points) {
i = parseInt(i);
if (i == 0)
path = 'M' + points[i].x + ',' + points[i].y;
if (i < points.length - 1)
path = path + ' C' + Math.round(b1points[i].x) + ',' + Math.round(b1points[i].y) + ',' + Math.round(b2points[i].x) + ',' + Math.round(b2points[i].y) + ',' + Math.round(points[i + 1].x) + ',' + Math.round(points[i + 1].y);
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('d', path);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
path = path + ' E';
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.width = 1;
_svgvmlObj.style.height = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
_svgvmlObj.Path = path;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw closed curve shape
function jxClosedCurve(points, pen, brush, tension) {
//Public Properties
this.points = points;
this.pen = null;
this.brush = null;
this.tension = 1;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
var _svgvmlObj = null;
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (tension != null)
this.tension = tension;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:shape');
//Public Methods
this.getType = getType;
function getType() {
return 'jxClosedCurve';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw closed curve shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array();
for (ind in this.points) {
points[ind] = graphics.logicalToPhysicalPoint(this.points[ind]);
}
var path, n = points.length - 1, ten = this.tension, pDpoints = new Array(), b1points = new Array(), b2points = new Array();
for (i in points) {
i = parseInt(i);
if (i == 0)
pDpoints[i] = new jxPoint(ten * (points[1].x - points[n].x) / 2, ten * (points[1].y - points[n].y) / 2);
else if (i == points.length - 1)
pDpoints[i] = new jxPoint(ten * (points[0].x - points[i - 1].x) / 2, ten * (points[0].y - points[i - 1].y) / 2);
else
pDpoints[i] = new jxPoint(ten * (points[i + 1].x - points[i - 1].x) / 2, ten * (points[i + 1].y - points[i - 1].y) / 2);
}
for (i in points) {
i = parseInt(i);
if (i == points.length - 1) {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[0].x - pDpoints[0].x / 3, points[0].y - pDpoints[0].y / 3);
}
else {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i + 1].x - pDpoints[i + 1].x / 3, points[i + 1].y - pDpoints[i + 1].y / 3);
}
}
for (i in points) {
i = parseInt(i);
if (i == 0)
path = 'M' + points[i].x + ',' + points[i].y;
if (i < points.length - 1)
path = path + ' C' + Math.round(b1points[i].x) + ',' + Math.round(b1points[i].y) + ',' + Math.round(b2points[i].x) + ',' + Math.round(b2points[i].y) + ',' + Math.round(points[i + 1].x) + ',' + Math.round(points[i + 1].y);
if (i == points.length - 1)
path = path + ' C' + Math.round(b1points[i].x) + ',' + Math.round(b1points[i].y) + ',' + Math.round(b2points[i].x) + ',' + Math.round(b2points[i].y) + ',' + Math.round(points[0].x) + ',' + Math.round(points[0].y);
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('d', path);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
path = path + ' E';
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.width = 1;
_svgvmlObj.style.height = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
_svgvmlObj.Path = path;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw bezier shape
function jxBezier(points, pen, brush) {
//Public Properties
this.points = points;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:shape');
this.getsvgvmlOjb = getsvgvmlOjb;
function getsvgvmlOjb() {
return _svgvmlObj;
}
//Public Methods
this.getType = getType;
function getType() {
return 'jxBezier';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw bezier shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array();
for (ind in this.points) {
points[ind] = graphics.logicalToPhysicalPoint(this.points[ind]);
}
var path;
if (points.length > 4) {
var pDpoints = new Array();
var b1points = new Array();
var b2points = new Array();
//Calculate bezier points
var res_points = new Array();
var n = points.length - 1;
var bx, by, i, ic, t, tstep = 10 * Math.min(1 / Math.abs(points[n].x - points[0].x), 1 / Math.abs(points[n].y - points[0].y));
ic = 0;
for (t = 0; t < 1; t += tstep) {
x = 0;
y = 0;
for (i = 0; i <= n; i++) {
bx = Math.pow(t, i) * Math.pow((1 - t), n - i) * points[i].x;
if (i != 0 || i != n) {
bx = bx * jsDraw2DX.fact(n) / jsDraw2DX.fact(i) / jsDraw2DX.fact(n - i);
}
x = x + bx;
by = Math.pow(t, i) * Math.pow((1 - t), n - i) * points[i].y;
if (i != 0 || i != n) {
by = by * jsDraw2DX.fact(n) / jsDraw2DX.fact(i) / jsDraw2DX.fact(n - i);
}
y = y + by;
}
res_points[ic] = new jxPoint(x, y);
ic++;
}
res_points[ic] = new jxPoint(points[n].x, points[n].y);
points = res_points;
//result points curve
tension = 1;
for (i in points) {
i = parseInt(i);
if (i == 0)
pDpoints[i] = new jxPoint(tension * (points[1].x - points[0].x) / 2, tension * (points[1].y - points[0].y) / 2);
else if (i == points.length - 1)
pDpoints[i] = new jxPoint(tension * (points[i].x - points[i - 1].x) / 2, tension * (points[i].y - points[i - 1].y) / 2);
else
pDpoints[i] = new jxPoint(tension * (points[i + 1].x - points[i - 1].x) / 2, tension * (points[i + 1].y - points[i - 1].y) / 2);
}
for (i in points) {
i = parseInt(i);
if (i == 0) {
b1points[i] = new jxPoint(points[0].x + pDpoints[0].x / 3, points[0].y + pDpoints[0].y / 3);
b2points[i] = new jxPoint(points[1].x - pDpoints[1].x / 3, points[1].y - pDpoints[1].y / 3);
}
else if (i == points.length - 1) {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i].x - pDpoints[i].x / 3, points[i].y - pDpoints[i].y / 3);
}
else {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i + 1].x - pDpoints[i + 1].x / 3, points[i + 1].y - pDpoints[i + 1].y / 3);
}
}
for (i in points) {
i = parseInt(i);
if (i == 0)
path = 'M' + points[i].x + ',' + points[i].y;
if (i < points.length - 1)
path = path + ' C' + Math.round(b1points[i].x) + ',' + Math.round(b1points[i].y) + ',' + Math.round(b2points[i].x) + ',' + Math.round(b2points[i].y) + ',' + Math.round(points[i + 1].x) + ',' + Math.round(points[i + 1].y);
}
}
else {
if (points.length == 4) {
path = ' M' + points[0].x + ',' + points[0].y + ' C' + points[1].x + ',' + points[1].y + ' ' + points[2].x + ',' + points[2].y + ' ' + points[3].x + ',' + points[3].y;
}
else if (points.length == 3) {
if (!jsDraw2DX._isVML) {
path = ' M' + points[0].x + ',' + points[0].y + ' Q' + points[1].x + ',' + points[1].y + ' ' + points[2].x + ',' + points[2].y;
}
else {
//Since QB command of VML does not work, converting one contol point to two
var c1point = new jxPoint(2 / 3 * points[1].x + 1 / 3 * points[0].x, 2 / 3 * points[1].y + 1 / 3 * points[0].y);
var c2point = new jxPoint(2 / 3 * points[1].x + 1 / 3 * points[2].x, 2 / 3 * points[1].y + 1 / 3 * points[2].y);
path = ' M' + points[0].x + ',' + points[0].y + ' C' + Math.round(c1point.x) + ',' + Math.round(c1point.y) + ' ' + Math.round(c2point.x) + ',' + Math.round(c2point.y) + ' ' + points[2].x + ',' + points[2].y;
}
}
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Setting
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('d', path);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
path = path + ' E';
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.width = 1;
_svgvmlObj.style.height = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
_svgvmlObj.Path = path;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw function graph shape
function jxFunctionGraph(fn, xMin, xMax, pen, brush) {
//Public Properties
this.fn = fn;
this.xMin = xMin;
this.xMax = xMax;
this.pen = null;
this.brush = null;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'path');
else
_svgvmlObj = document.createElement('v:shape');
//Public Methods
this.getType = getType;
function getType() {
return 'jxFunctionGraph';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Validate the function equation
this.validate = validate;
function validate(fn) {
fn = fn.replace(/x/g, 1);
with (Math) {
try {
eval(fn);
return true;
}
catch (ex) {
return false;
}
}
}
//Draw function graph shape on the jxGraphics
this.draw = draw;
function draw(graphics) {
var points = new Array();
var path, pDpoints;
var pDpoints = new Array();
var b1points = new Array();
var b2points = new Array();
//Validate the function
if (!this.validate(fn))
return;
//Calculate function graph points
var x, y, ic = 0;
for (x = xMin; x < xMax; x++) {
with (Math) {
y = eval(fn.replace(/x/g, x));
}
points[ic] = graphics.logicalToPhysicalPoint(new jxPoint(x, y));
ic++;
}
with (Math) {
y = eval(fn.replace(/x/g, xMax));
}
points[ic] = graphics.logicalToPhysicalPoint(new jxPoint(x, y));
ic++;
//result points curve
tension = 1;
for (i in points) {
i = parseInt(i);
if (i == 0)
pDpoints[i] = new jxPoint(tension * (points[1].x - points[0].x) / 2, tension * (points[1].y - points[0].y) / 2);
else if (i == points.length - 1)
pDpoints[i] = new jxPoint(tension * (points[i].x - points[i - 1].x) / 2, tension * (points[i].y - points[i - 1].y) / 2);
else
pDpoints[i] = new jxPoint(tension * (points[i + 1].x - points[i - 1].x) / 2, tension * (points[i + 1].y - points[i - 1].y) / 2);
}
for (i in points) {
i = parseInt(i);
if (i == 0) {
b1points[i] = new jxPoint(points[0].x + pDpoints[0].x / 3, points[0].y + pDpoints[0].y / 3);
b2points[i] = new jxPoint(points[1].x - pDpoints[1].x / 3, points[1].y - pDpoints[1].y / 3);
}
else if (i == points.length - 1) {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i].x - pDpoints[i].x / 3, points[i].y - pDpoints[i].y / 3);
}
else {
b1points[i] = new jxPoint(points[i].x + pDpoints[i].x / 3, points[i].y + pDpoints[i].y / 3);
b2points[i] = new jxPoint(points[i + 1].x - pDpoints[i + 1].x / 3, points[i + 1].y - pDpoints[i + 1].y / 3);
}
}
for (i in points) {
i = parseInt(i);
if (i == 0)
path = 'M' + points[i].x + ',' + points[i].y;
if (i < points.length - 1)
path = path + ' C' + Math.round(b1points[i].x) + ',' + Math.round(b1points[i].y) + ',' + Math.round(b2points[i].x) + ',' + Math.round(b2points[i].y) + ',' + Math.round(points[i + 1].x) + ',' + Math.round(points[i + 1].y);
}
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj);
//Apply Brush Settings
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
_svgvmlObj.setAttribute('d', path);
}
else {
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
path = path + ' E';
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.width = 1;
_svgvmlObj.style.height = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
_svgvmlObj.Path = path;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw text string
function jxText(point, text, font, pen, brush, angle) {
//Public Properties
this.point = point;
this.text = text;
this.font = null;
this.pen = null;
this.brush = null;
this.angle = 0;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
this.getElement = getElement;
function getElement() {
return _svgvmlObj;
}
//Object construction
if (font)
this.font = font;
if (pen)
this.pen = pen;
if (brush)
this.brush = brush;
if (angle)
this.angle = angle;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'text');
else
_svgvmlObj = document.createElement('v:shape');
this.getsvgvmlOjb = getsvgvmlOjb;
function getsvgvmlOjb() {
return _svgvmlObj;
}
//Public Methods
this.getType = getType;
function getType() {
return 'jxText';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw text string on the jxGraphics
this.draw = draw;
function draw(graphics) {
var point;
point = graphics.logicalToPhysicalPoint(this.point);
var x, y;
x = point.x;
y = point.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
//Apply Pen Settings
if (!this.pen)
_svgvmlObj.setAttribute('stroke', 'none');
else
this.pen.updateSVG(_svgvmlObj, this);
//Apply Brush Settings
if (!this.brush)
_svgvmlObj.setAttribute('fill', 'none');
else {
this.brush.updateSVG(_svgvmlObj, graphics.getDefs());
}
//Apply Font Settings
if (this.font)
this.font.updateSVG(_svgvmlObj);
else
jxFont.updateSVG(_svgvmlObj);
_svgvmlObj.setAttribute('x', x);
_svgvmlObj.setAttribute('y', y);
_svgvmlObj.setAttribute('transform', 'rotate(' + this.angle + ' ' + x + ',' + y + ')');
_svgvmlObj.textContent = this.text;
}
else {
var vml = graphics.getVML(), vmlFill, vmlPath, vmlTextPath;
if (_isFirst) {
vmlTextPath = document.createElement('v:textpath');
vmlTextPath.On = 'True';
vmlTextPath.style['v-text-align'] = 'left';
_svgvmlObj.appendChild(vmlTextPath);
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
vmlFill = _svgvmlObj.fill;
vmlTextPath = _svgvmlObj.firstChild;
//Apply Pen Setting
if (!this.pen)
_svgvmlObj.Stroked = 'False';
else
this.pen.updateVML(_svgvmlObj);
//Apply Brush Setting
vmlFill = _svgvmlObj.fill;
if (!this.brush)
vmlFill.On = 'false';
else
this.brush.updateVML(vmlFill);
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.height = 1;
_svgvmlObj.CoordSize = 1 + ' ' + 1;
vmlPath = _svgvmlObj.Path;
vmlPath.TextPathOk = 'true';
vmlPath.v = 'M' + x + ',' + y + ' L' + (x + 100) + ',' + y + ' E';
vmlTextPath.String = this.text;
//Apply Font Settings
if (this.font)
this.font.updateVML(vmlTextPath);
else
jxFont.updateVML(vmlTextPath);
_svgvmlObj.style.display = '';
var x1, y1, r, a;
r = (_svgvmlObj.clientHeight / 2 * 0.8);
a = this.angle;
x = Math.round(x + r * Math.sin(a * Math.PI / 180));
y = Math.round(y - r * Math.cos(a * Math.PI / 180));
x1 = Math.round(x + Math.cos(a * Math.PI / 180) * 100);
y1 = Math.round(y + Math.sin(a * Math.PI / 180) * 100);
_svgvmlObj.Path = 'M' + x + ',' + y + ' L' + x1 + ',' + y1 + ' E';
_svgvmlObj.style.width = 1;
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
//Class to hold information and draw image
function jxImage(point, url, width, height, angle) {
//Private memeber variables
this.point = point;
this.url = url;
this.width = width;
this.height = height;
this.angle = 0;
//Private member variables
var _svgvmlObj, _isFirst = true;
var _graphics;
//Object construction
if (angle)
this.angle = angle;
if (!jsDraw2DX._isVML)
_svgvmlObj = document.createElementNS('http://www.w3.org/2000/svg', 'image');
else
_svgvmlObj = document.createElement('v:image');
//Public Methods
this.getType = getType;
function getType() {
return 'jxImage';
}
//Events Handling Ability
this.addEventListener = addEventListener;
function addEventListener(eventName, handler) {
if (_svgvmlObj.addEventListener)
_svgvmlObj.addEventListener(eventName, handlerWrapper, false);
else if (_svgvmlObj.attachEvent)
_svgvmlObj.attachEvent('on' + eventName, handlerWrapper);
var currentObj = this;
function handlerWrapper(evt) {
handler(evt, currentObj);
}
}
//Draw image on the jxGraphics
this.draw = draw;
function draw(graphics) {
var point, scale;
point = graphics.logicalToPhysicalPoint(this.point);
scale = graphics.scale;
var x, y;
x = point.x;
y = point.y;
_svgvmlObj.style.display = 'none';
if (!jsDraw2DX._isVML) {
var svg = graphics.getSVG();
if (_isFirst) {
svg.appendChild(_svgvmlObj);
_isFirst = false;
}
_svgvmlObj.setAttribute('x', x);
_svgvmlObj.setAttribute('y', y);
_svgvmlObj.setAttribute('height', scale * this.height);
_svgvmlObj.setAttribute('width', scale * this.width);
_svgvmlObj.setAttribute('preserveAspectRatio', 'none');
_svgvmlObj.setAttributeNS('http://www.w3.org/1999/xlink', 'href', this.url);
_svgvmlObj.setAttribute('transform', 'rotate(' + this.angle + ' ' + x + ',' + y + ')');
}
else {
with (Math) {
var x1, y1, ang = this.angle, a = this.angle * PI / 180, w, h, m1, m2, m3, m4;
w = scale * this.width;
h = scale * this.height;
x1 = x;
y1 = y;
if (abs(ang) > 360)
ang = ang % 360;
if (ang < 0)
ang = 360 + ang;
//Rotation point
if (ang >= 0 && ang < 90) {
y1 = y;
x1 = x - (h * sin(a));
}
else if (ang >= 90 && ang < 180) {
y1 = y - h * sin(a - PI / 2);
x1 = x - (w * sin(a - PI / 2) + h * cos(a - PI / 2));
}
else if (ang >= 180 && ang < 270) {
y1 = y - (w * sin(a - PI) + h * cos(a - PI));
x1 = x - w * cos(a - PI);
}
else if (ang >= 270 && ang <= 360) {
x1 = x;
y1 = y - w * cos(a - 1.5 * PI);
}
//Matrix for rotation
m1 = cos(a);
m2 = -sin(a);
m3 = sin(a);
m4 = cos(a);
}
var vml = graphics.getVML(), vmlFill;
if (_isFirst) {
vml.appendChild(_svgvmlObj);
_isFirst = false;
}
_svgvmlObj.style.width = w;
_svgvmlObj.style.height = h;
_svgvmlObj.style.position = 'absolute';
_svgvmlObj.style.top = y1;
_svgvmlObj.style.left = x1;
_svgvmlObj.style.filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand',M11=" + m1 + ',M12=' + m2 + ',M21=' + m3 + ',M22=' + m4 + ") filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale');";
}
_svgvmlObj.style.display = '';
if (_graphics && graphics != _graphics) {
_graphics.removeShape(this);
}
_graphics = graphics;
_graphics.addShape(this);
}
//Removes shape from the graphics drawing
this.remove = remove;
function remove() {
if (_graphics) {
if (!jsDraw2DX._isVML) {
var svg = _graphics.getSVG();
svg.removeChild(_svgvmlObj);
}
else {
var vml = _graphics.getVML();
vml.removeChild(_svgvmlObj);
}
_graphics.removeShape(this);
_graphics = null;
_isFirst = true;
}
}
//Show the already drawn shape
this.show = show;
function show() {
_svgvmlObj.style.display = '';
}
//Hide the already drawn shape
this.hide = hide;
function hide() {
_svgvmlObj.style.display = 'none';
}
}
////////////////////////////////////wf edit////////////////////////
function WFEdit(wfOptions) {
var ntp_Begin = 1, ntp_End = 2, ntp_Normal = 3;
this.ntp_Begin = ntp_Begin;
this.ntp_End = ntp_End;
this.ntp_Normal = ntp_Normal;
var wfOptions = wfOptions;
var activeOnClick = (wfOptions.activeOnClick == undefined) ? true : wfOptions.activeOnClick;
this.nodes = function () {
return nodes;
};
this.lines = function () {
return lines;
};
this.readonly = false;
var data = (wfOptions.data) ? wfOptions.data : undefined;
this.getData = function () {
var aprocs = [];
var alines = [];
for (var i = 0; i < lines.length; i++) {
var aline = lines[i];
if (wfOptions.onGetLineData) {
wfOptions.onGetLineData(aline);
}
alines.push(lines[i].getData());
}
for (var i = 0; i < nodes.length; i++) {
aprocs.push(nodes[i].getData());
}
return {procs: aprocs, lines: alines};
};
var activeNode = undefined, activeLine = undefined, resizeObj = undefined;
this.getActiveNode = function () {
return activeNode;
};
this.getActiveLine = function () {
return activeLine;
};
var nodes = [], lines = [], draging = false, resizeing = false, resizetype = 0;
var titleColor = "#DBEAFC", bodyColor = "white", nomalBorderColor = "#5CB3E7", ActiveBorderColor = "red", backColor = "#BACFE4", FlishedBorderColor = '#387F00';
var titleH = 25;
var defaultNodeWidth = 100, defaultNodeHeight = 150;
var pen_nomal = new jxPen(new jxColor(nomalBorderColor), 1);
var pen_active = new jxPen(new jxColor(ActiveBorderColor), 1);
var pen_flished = new jxPen(new jxColor(FlishedBorderColor), 1);
var br_title = new jxBrush(new jxColor(titleColor));
var br_body = new jxBrush(new jxColor(bodyColor));
var mousexy;
var grMain = wfOptions.el;
if (!grMain) {
grMain = document.body;
} else
grMain.style.overflow = "auto";
var graphicsDiv = document.createElement("div");
grMain.appendChild(graphicsDiv);
graphicsDiv.style.left = 0 + "px";
graphicsDiv.style.top = 0 + "px";
graphicsDiv.style.width = grMain.clientWidth + "px";
graphicsDiv.style.height = grMain.clientHeight + "px";
// alert(grMain.clientWidth + " " + grMain.clientHeight);
graphicsDiv.onmousemove = onMouseMove;
var gr = new jxGraphics(graphicsDiv);
this.addNode = function (data) {
var newNode = new WFNode(this, data, wfOptions);
nodes.push(newNode);
return newNode;
};
this.removeNode = function (node) {
node.remove();
if (node == activeNode)
activeNode = null;
node = null;
};
this.addLine = function (data, fNode, tNode) {
var newLine = new WFLine(this, data, fNode, tNode);
if (!isExiitsLine(newLine))
lines.push(newLine);
return newLine;
};
this.removeLine = function (line) {
line.remove();
line = null;
};
this.removeall = function () {
gr.removeall();
nodes = [];
lines = [];
activeNode = undefined;
activeLine = undefined;
resizeObj = undefined;
};
function isExiitsLine(line) {
for (var i = 0; i < lines.length; i++) {
if (line == lines[i])
return lines[i];
}
return null;
}
this.initBEnodes = function () {
this.removeall();
var ndata = {
left: 10,
top: 10,
width: defaultNodeWidth,
height: defaultNodeHeight,
title: "开始",
isbegin: 1,
isend: 2
};
this.addNode(ndata);
ndata = {
left: graphicsDiv.clientWidth - defaultNodeWidth - 20,
top: 10,
width: defaultNodeWidth,
height: defaultNodeHeight,
title: "结束",
isend: 1,
isbegin: 2
};
this.addNode(ndata);
};
if (wfOptions.initBENodes) {
this.initBEnodes();
}
function WFNode(aowner, data, wfOptions) {
this.isActive = false;
this.getData = function () {
return data;
};
var owner = aowner;
this.owner = owner;
var title = "节点名称";
this.title = function () {
return title
};
this.nodeType = function () {
if (data.isbegin == 1)
return ntp_Begin;
else if (data.isend == 1)
return ntp_End;
else
return ntp_Normal;
};
var title_shap, title_text, body_shap;
var body_shap_circle, title_text_circle;
var user_texts = [];
this.setzIndex = setzIndex;
function setzIndex(zidx) {
if (!zidx) return;
if (title_shap && title_shap.getElement)
title_shap.getElement().style.zIndex = zidx;
if (title_text && title_text.getElement)
title_text.getElement().style.zIndex = zidx;
if (body_shap && body_shap.getElement)
body_shap.getElement().style.zIndex = zidx;
if (body_shap_circle && body_shap_circle.getElement)
body_shap_circle.getElement().style.zIndex = zidx;
if (title_text_circle && title_text_circle.getElement())
title_text_circle.getElement().style.zIndex = zidx;
for (var i = 0; i < user_texts.length; i++) {
//if (user_texts[i].img && user_texts[i].img.getElement) {
// user_texts[i].img.getElement().style.zIndex = zidx;
//}
if (user_texts[i].txt && user_texts[i].txt.getElement) {
user_texts[i].txt.getElement().style.zIndex = zidx;
}
}
}
this.clearUser = function () {
for (var i = 0; i < user_texts.length; i++) {
//user_texts[i].img.remove();
user_texts[i].txt.remove();
}
user_texts = [];
};
this.x = function () {
return parseInt(data.left);
};
this.y = function () {
return parseInt(data.top);
};
this.w = function () {
return parseInt(data.width);
};
this.h = function () {
return parseInt(data.height);
};
this.setData = function (value) {
if (value) data = value;
this.draw();
};
this.draw = function () {
this.clearUser();
if (data.title)
title = data.title;
var x = 0;
if (data.left) x = parseInt(data.left);
var y = 0;
if (data.top) y = parseInt(data.top);
var w = 100;
if (data.width) w = parseInt(data.width);
var h = 150;
if (data.height) h = parseInt(data.height);
data.left = x;
data.top = y;
data.width = w;
data.height = h;
var pen = undefined;
if (this.isActive)
pen = pen_active;
else if ((data.stated) && (data.stated == 3)) { //1 待审批 2 当前 3 完成
pen = pen_flished
} else
pen = pen_nomal;
if (this.nodeType() == aowner.ntp_Normal) {//普通节点
if (title_shap) {
title_shap.point = new jxPoint(x, y);
title_shap.width = w;
title_shap.height = titleH;
title_shap.pen = pen;
} else {
title_shap = new jxRect(new jxPoint(x, y), w, titleH, pen, br_title);
var e = title_shap.getElement();
e.setAttribute("cursor", "move");
e.style.cursor = "move";
title_shap.node = this;
title_shap.addEventListener('mousedown', nodeMouseDown);
title_shap.addEventListener('mouseup', nodeMouseUp);
title_shap.addEventListener('dblclick', nodeMouseDBClick);
title_shap.addEventListener('mousemove', nodeMouseMove);
}
if (body_shap) {
body_shap.point = new jxPoint(x, y + titleH);
body_shap.width = w;
body_shap.height = h - titleH;
body_shap.pen = pen;
} else {
body_shap = new jxRect(new jxPoint(x, y + titleH), w, h - titleH, pen, br_body);
var e = body_shap.getElement();
body_shap.node = this;
body_shap.addEventListener('mousedown', nodeMouseDown);
body_shap.addEventListener('mouseup', nodeMouseUp);
body_shap.addEventListener('dblclick', nodeMouseDBClick);
body_shap.addEventListener('mousemove', nodeMouseMove);
}
var font = new jxFont('sans-serif');
font.size = 12;
font.weight = 'bold';
var wh = getTextLH(12, title);
var tx = x + w / 2 - wh.w / 2, ty = y + titleH / 2 + wh.h / 2;
if (tx < x) tx = x;
if (ty < y)ty = y;
var vpt = new jxPoint(tx, ty);
if (title_text) {
title_text.point = vpt;
title_text.text = title;
} else {
title_text = new jxText(vpt, title, font, null, new jxBrush(new jxColor()));
var e = title_text.getElement();
e.setAttribute("cursor", "move");
e.style.cursor = "move";
title_text.node = this;
title_text.addEventListener('mousedown', nodeMouseDown);
title_text.addEventListener('mouseup', nodeMouseUp);
title_text.addEventListener('dblclick', nodeMouseDBClick);
}
title_shap.draw(gr);
body_shap.draw(gr);
title_text.draw(gr);
var font = new jxFont('sans-serif');
font.size = 12;
var vptimg, vpttxt, u_img, u_text;
if (data.users) {
for (var i = 0; i < data.users.length; i++) {
/*vptimg = new jxPoint(x + 5, y + titleH + i * (16 + 2) + 2);
if ((user_texts[i]) && (user_texts[i].img)) {
u_img = user_texts[i].img;
u_img.point = vptimg;
}
else {
u_img = new jxImage(vptimg, wfOptions.icourl, 16, 16, 0);//
u_img.addEventListener('mousedown', nodeMouseDown);
u_img.addEventListener('mouseup', nodeMouseUp);
u_img.addEventListener('dblclick', nodeMouseDBClick);
u_img.node = this;
if (!user_texts[i]) user_texts[i] = {};
user_texts[i].img = u_img;
}
u_img.draw(gr);*/
if (!user_texts[i]) user_texts[i] = {};
//vpttxt = new jxPoint(x + 18 + 5, y + titleH + (i + 1) * (wh.h + 5.8) - 0.5);
vpttxt = new jxPoint(x + 5, y + titleH + (i + 1) * (wh.h + 5.8) - 0.5);
var user = data.users[i];
if (user_texts[i].txt) {
u_text = user_texts[i].txt;
u_text.point = vpttxt;
} else {
u_text = new jxText(vpttxt, user.username, font, null, new jxBrush(new jxColor()));
u_text.addEventListener('mousedown', nodeMouseDown);
u_text.addEventListener('mouseup', nodeMouseUp);
u_text.addEventListener('dblclick', nodeMouseDBClick);
u_text.node = this;
user_texts[i].txt = u_text;
}
u_text.draw(gr);
}
}
} else if ((this.nodeType() == aowner.ntp_Begin) || (this.nodeType() == aowner.ntp_End)) {//首尾节点
var txt = (this.nodeType() == aowner.ntp_Begin) ? "开始" : "结束";
var cpt = new jxPoint(x + (w / 2), y + (h / 2));
var rd = 80 / 2;
if (body_shap_circle) {
body_shap_circle.center = cpt;
body_shap_circle.radius = rd;
body_shap_circle.pen = pen;
} else {
body_shap_circle = new jxCircle(cpt, rd, pen, br_body);
body_shap_circle.node = this;
body_shap_circle.addEventListener('mousedown', nodeMouseDown);
body_shap_circle.addEventListener('mouseup', nodeMouseUp);
body_shap_circle.addEventListener('dblclick', nodeMouseDBClick);
body_shap_circle.addEventListener('mousemove', nodeMouseMove);
}
body_shap_circle.draw(gr);
var font = new jxFont('sans-serif');
font.size = 12;
font.weight = 'bold';
var cpt = new jxPoint(x + (w / 2) - 10, y + (h / 2) + 5);
if (title_text_circle) {
title_text_circle.point = cpt;
title_text_circle.text = txt;
} else {
title_text_circle = new jxText(cpt, txt, font, null, new jxBrush(new jxColor()));
title_text_circle.node = this;
title_text_circle.addEventListener('mousedown', nodeMouseDown);
title_text_circle.addEventListener('mouseup', nodeMouseUp);
title_text_circle.addEventListener('dblclick', nodeMouseDBClick);
title_text_circle.addEventListener('mousemove', nodeMouseMove);
}
title_text_circle.draw(gr);
}
};
this.draw();
this.remove = function () {
if (this.nodeType() != aowner.ntp_Normal) {
alert("首尾节点不允许删除");
return;
}
if (user_texts) {
for (var i = 0; i < user_texts.length; i++) {
//if (user_texts[i].img) {
// user_texts[i].img.remove();
//}
if (user_texts[i].txt) {
user_texts[i].txt.remove();
}
}
}
user_texts = null;
if (title_shap) title_shap.remove();
if (title_text) title_text.remove();
if (body_shap) body_shap.remove();
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i] == this) {
nodes.splice(i, 1);
break;
}
}
if (this == activeNode) {
activeNode = undefined;
}
var fl = this.getLineFromMe();
for (var i = fl.length - 1; i >= 0; i--) {
fl[i].remove();
}
var tl = this.getLineToMe();
for (var i = tl.length - 1; i >= 0; i--) {
tl[i].remove();
}
};
function nodeMouseDown(evt, obj) {
//
if (activeOnClick)
setActiveNode(obj.node);
if ((obj == title_shap) || (obj == title_text) || (obj == body_shap_circle)) {
draging = !owner.readonly;
} else
draging = false;
resizeing = ((resizeObj !== null) && (resizeObj == obj) && (resizetype != 0));
if (wfOptions.onNodeClick) {
wfOptions.onNodeClick(evt, obj.node);
}
}
function nodeMouseUp(evt, obj) {
draging = false;
resizeing = false;
}
function nodeMouseDBClick(evt, obj) {
if (wfOptions.onNodeDBClick) {
wfOptions.onNodeDBClick(evt, obj.node);
}
}
function nodeMouseMove(evt, obj) {
if ((obj == body_shap) & (!resizeing)) {
var xy = getMouseXy(evt);
var data = obj.node.getData();
obj.getElement().style.cursor = "default";
resizetype = 0;
if (data.left + data.width - xy.x <= 3) {
if ((data.top + 20 + data.height - xy.y) <= 3) {
obj.getElement().style.cursor = "nw-resize";
resizetype = 3;
} else {
obj.getElement().style.cursor = "e-resize";
resizetype = 1;
}
}
if (data.top + data.height - xy.y <= 3) {
if ((data.left + data.width - xy.x) <= 3) {
obj.getElement().style.cursor = "nw-resize";
resizetype = 3;
} else {
obj.getElement().style.cursor = "n-resize";
resizetype = 2;
}
}
if (resizetype != 0) {
resizeObj = obj;
} else resizeObj = null;
}
}
this.getLineFromMe = function () {
var rst = [];
for (var i = 0; i < lines.length; i++) {
if (lines[i].fnode == this) {
rst.push(lines[i]);
}
}
return rst;
};
this.getLineToMe = function () {
var rst = [];
for (var i = 0; i < lines.length; i++) {
if (lines[i].tnode == this) {
rst.push(lines[i]);
}
}
return rst;
};
this.getNextNodes = getNextNodes;
function getNextNodes() {
var rst = [];
var lines = this.getLineFromMe();
for (var i = 0; i < lines.length; i++) {
rst.push(lines[i].tnode);
}
return rst;
}
this.getPerNodes = getPerNodes;
function getPerNodes() {
var rst = [];
var lines = this.getLineToMe();
//alert("lines:" + lines.length);
for (var i = 0; i < lines.length; i++) {
rst.push(lines[i].fnode);
}
return rst;
}
}
////class line
function WFLine(aowner, adata, fNode, tNode) {
var line = getLine(fNode, tNode);
// if (line != null)
// return line;
var data = adata;
this.isActive = false;
this.getData = function () {
return data;
};
this.setData = function (adata) {
if (line_shap) {
line_shap.remove();
}
if (line_title) {
line_title.remove();
}
data = adata;
};
var owner = aowner;
this.owner = owner;
this.fnode = fNode;
this.tnode = tNode;
this.title = data.title;
var line_shap, line_title;
var ARROWLEN = 7;
this.sendTop = sendTop;
function sendTop() {
if (!jsDraw2DX._isVML) {
var svg = gr.getSVG();
if (line_title)
$(line_title.getElement()).appendTo(svg);
if (line_shap)
$(line_shap.getElement()).appendTo(svg);
} else {
var vml = gr.getVML();
if (line_title)
$(line_title.getElement()).appendTo(vml);
if (line_shap)
$(line_shap.getElement()).appendTo(vml);
}
}
this.setzIndex = setzIndex;
function setzIndex(zidx) {
if (line_shap)
line_shap.getElement().style.zIndex = zidx;
if (line_title)
line_title.getElement().style.zIndex = zidx;
}
//获取 默认 Y
function getDefaultY(x1, x4, fy, ty) {
var cy = fy + (ty - fy) / 2;
var ymin = cy;
var ymax = cy;
for (var i = 0; i < owner.nodes().length; i++) {
var node = owner.nodes()[i];
var data = node.getData();
if ((node != fNode) && (node != tNode)) {
if (((parseInt(data.left) + parseInt(data.width)) > x1) && (parseInt(data.left) < x4)) {
var top = parseInt(data.top);
ymin = (top < ymin) ? top : ymin;
var bt = parseInt(data.top) + parseInt(data.height);
ymax = (bt > ymax) ? bt : ymax;
}
}
}
if (ymin != cy) ymin = ymin - 50;
if (ymax != cy) ymax = ymax + 50;
if (ymin < 0) ymin = -99999;
return ( Math.abs(ymax - cy) > Math.abs(cy - ymin)) ? ymin : ymax;
}
function defPoints(fNode, tNode) {
var maxLiney = 0;
var fdata = fNode.getData(), tdata = tNode.getData();
var fPoint = new jxPoint(parseInt(fdata.left) + parseInt(fdata.width), parseInt(fdata.top) + parseInt(fdata.height) / 2);
var tPoint = new jxPoint(parseInt(tdata.left), parseInt(tdata.top) + parseInt(tdata.height) / 2);
var fl = (tPoint.x - fPoint.x) / 4;//from length
fl = (Math.abs(fl) > 20) ? 20 : Math.abs(fl);
var x1 = fPoint.x + fl;
var x4 = tPoint.x - fl;
var y2 = getDefaultY(x1, x4, parseInt(fdata.top), parseInt(tdata.top) + parseInt(tdata.height));
var Point1 = new jxPoint(x1, fPoint.y);
var Point2 = new jxPoint(x1, y2);
var Point3 = new jxPoint(x4, y2);
var Point4 = new jxPoint(x4, tPoint.y);
maxLiney = (fPoint.y > y2) ? fPoint.y : y2;
maxLiney = (maxLiney > tPoint.y) ? maxLiney : tPoint.y;
return {
p1: Point1,
p2: Point2,
p3: Point3,
p4: Point4,
mly: maxLiney
};
}
var lineMaxY = 0;
this.getLineMaxY = function () {
return lineMaxY;
}
this.draw = function () {
var fdata = fNode.getData(), tdata = tNode.getData();
var fPoint = new jxPoint(parseInt(fdata.left) + parseInt(fdata.width), parseInt(fdata.top) + parseInt(fdata.height) / 2);
var tPoint = new jxPoint(parseInt(tdata.left), parseInt(tdata.top) + parseInt(tdata.height) / 2);
var points = defPoints(fNode, tNode);
lineMaxY = points.mly;
//画箭头
var D = Math.sqrt((tPoint.y - points.p4.y) * (tPoint.y - points.p4.y) + (tPoint.x - points.p4.x) * (tPoint.x - points.p4.x));
if (D > 0) {
var xa = tPoint.x + ARROWLEN * ((points.p4.x - tPoint.x) + (points.p4.y - tPoint.y) / 2) / D;
var ya = tPoint.y + ARROWLEN * ((points.p4.y - tPoint.y) - (points.p4.x - tPoint.x) / 2) / D;
var xb = tPoint.x + ARROWLEN * ((points.p4.x - tPoint.x) - (points.p4.y - tPoint.y) / 2) / D;
var yb = tPoint.y + ARROWLEN * ((points.p4.y - tPoint.y) + (points.p4.x - tPoint.x) / 2) / D;
var aPoint = new jxPoint(xa, ya);
var bPoint = new jxPoint(xb, yb);
var pts = [];
pts.push(fPoint);
pts.push(points.p1);
pts.push(points.p2);
pts.push(points.p3);
pts.push(points.p4);
pts.push(tPoint);
pts.push(bPoint);
pts.push(tPoint);
pts.push(aPoint);
pts.push(tPoint);
pts.push(points.p4);
pts.push(points.p3);
pts.push(points.p2);
pts.push(points.p1);
var pen;
if (this.isActive)
pen = new jxPen(new jxColor(ActiveBorderColor), 2);
else
pen = new jxPen(new jxColor(nomalBorderColor), 2);
if (line_shap) {
line_shap.points = pts;
line_shap.pen = pen;
} else {
line_shap = new jxPolyline(pts, pen, new jxBrush(new jxColor("#FFFFFF")));//backColor
line_shap.line = this;
line_shap.addEventListener('mousedown', lineMouseDown);
line_shap.addEventListener('mouseup', lineMouseUp);
line_shap.addEventListener('dblclick', lineMouseDBClick);
}
line_shap.draw(gr);
if ((data.title) && (data.title.length > 0)) {
var wh = getTextLH(12, data.title);
//var ttpoint = new jxPoint(Point1.x + (Point2.x - Point1.x) / 2 - wh.w / 2, Point1.y + (Point2.y - Point1.y) / 2 + wh.h / 2);
var l1 = (points.p3.x - points.p2.x - wh.w) / 2;
var ttpoint = new jxPoint(points.p2.x + l1, points.p3.y - wh.h / 2);
var color = undefined;
if (this.isActive)
color = new jxColor(ActiveBorderColor);
else
color = new jxColor();
var bsh = new jxBrush(color);
if (line_title) {
line_title.point = ttpoint;
line_title.brush = bsh;
line_title.text = data.title;
} else {
var font = new jxFont('sans-serif');
font.size = 12;
line_title = new jxText(ttpoint, data.title, font, null, bsh);//new jxPen(new jxColor("#000000"), "0px")
line_title.addEventListener('mousedown', lineMouseDown);
line_title.addEventListener('mouseup', lineMouseUp);
line_title.addEventListener('dblclick', lineMouseDBClick);
line_title.line = this;
}
line_title.draw(gr);
}
}
};
this.draw();
this.remove = function () {
if (line_shap) {
line_shap.remove();
}
if (line_title) {
line_title.remove();
}
for (var i = 0; i < lines.length; i++) {
if (this == lines[i]) {
lines.splice(i, 1);
break;
}
}
if (this == activeLine) {
activeLine = undefined;
}
};
function lineMouseDown(evt, obj) {
if (activeOnClick)
setAciveLine(obj.line);
if (wfOptions.onLineClick) {
wfOptions.onLineClick(evt, obj.line);
}
}
function lineMouseUp(evt, obj) {
}
function lineMouseDBClick(evt, obj) {
if (wfOptions.onLineDBClick) {
wfOptions.onLineDBClick(evt, obj.line);
}
}
}
/////wf other functions
this.getHeadNode = getHeadNode;
function getHeadNode() {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType() == ntp_Begin)
return nodes[i];
}
return null;
}
this.getEndNode = getEndNode;
function getEndNode() {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType() == this.ntp_End)
return nodes[i];
}
return null;
}
function getLine(fNode, tNode) {
for (var i = 0; i < lines.length; i++) {
if ((lines[i].fnode == fNode) && (lines[i].fnode == tNode)) {
return lines[i];
}
}
return null;
}
function drowLinesAboutNode(node) {
var fl = node.getLineFromMe();
for (var i = 0; i < fl.length; i++) {
fl[i].draw();
}
var tl = node.getLineToMe();
for (var i = 0; i < tl.length; i++) {
tl[i].draw();
}
}
function onMouseMove(evt, obj) {
if (!activeOnClick) return;
var needReSize = false;
mousexy = getMouseXy(evt);
if (draging) {
if (activeNode) {
var dt = activeNode.getData();
dt.left = mousexy.x - dt.width / 2;
if (activeNode.nodeType() == 3) {//ntp_Normal
dt.top = mousexy.y - 30 / 2;
} else {
dt.top = mousexy.y - dt.height / 3;
}
if (dt.left < 0) dt.left = 0;
if (dt.top < 0) dt.top = 0;
needReSize = true;
drowLinesAboutNode(activeNode);
activeNode.draw();
}
}
if (resizeing & (activeNode != undefined) & (resizetype != 0)) {
var dt = activeNode.getData();
if (resizetype == 1) {
dt.width = mousexy.x - dt.left + 1;
}
if (resizetype == 2) {
dt.height = mousexy.y - dt.top + 1;
}
if (resizetype == 3) {
dt.width = mousexy.x - dt.left + 1;
dt.height = mousexy.y - dt.top + 1;
}
if (dt.width < 50)dt.width = 50;
if (dt.height < 80)dt.height = 80;
needReSize = true;
drowLinesAboutNode(activeNode);
activeNode.draw();
}
if (needReSize) {
reSetScroll();
}
}
this.checkWF = checkWF;
function checkWF() {
var isyxt = false;
var begct = 0, endct = 0;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var pct = node.getLineToMe().length;
var nct = node.getLineFromMe().length;
if (node.nodeType() == ntp_Begin) {
begct++;
if (pct !== 0) {
alert(node.title + "头节点有前置节点:" + pct);
return 0;
}
if (nct == 0) {
alert("头节点无后置节点");
return 0;
}
} else if (node.nodeType() == ntp_End) {
endct++;
if (nct !== 0) {
alert("尾节点有后置节点");
return 0;
}
if (pct == 0) {
alert("尾节点无前置节点");
return 0;
}
} else {
if ((pct == 0) || (nct == 0)) {
alert("无前置或后置结点");
return 0;
} else if ((nct > 1) && (nct > 1)) {
isyxt = true;
}
}
}
if ((begct != 1) || (endct != 1)) {
return 0;
}
if (isyxt) return 2; else return 1;
}
this.autoSortUI = autoSortUI;
function autoSortUI() {
var ckw = checkWF();
if (ckw == 0) {
return;
} else if (ckw == 2) {
alert("非链表流程不能自动排序");
return;
} else if (ckw == 1) {
var anode = getHeadNode();
if (anode == null) {
alert("未发现头结点");
return;
}
var pl = pw = 0;
while (1) {
var dt = anode.getData();
dt.left = pl + pw + 30;
dt.top = 50;
pl = anode.x();
pw = anode.w();
anode.draw();
var nns = anode.getNextNodes();
if (nns.length != 1)
break;
else
anode = nns[0];
}
for (var i = 0; i < lines.length; i++) {
lines[i].draw();
}
}
}
this.reSetScroll = reSetScroll;
function reSetScroll() {
var maxWH = getMaxWH();
if (maxWH.w < grMain.clientWidth)
graphicsDiv.style.width = grMain.clientWidth + "px";
else
graphicsDiv.style.width = maxWH.w + "px";
if (maxWH.h < grMain.clientHeight)
graphicsDiv.style.height = (parseInt(grMain.clientHeight) + 20) + "px";
else
graphicsDiv.style.height = (parseInt(maxWH.h) + 20) + "px";
if (!jsDraw2DX._isVML) {
var _svg = gr.getSVG();
_svg.style.width = graphicsDiv.style.width;
_svg.style.height = graphicsDiv.style.height;
}
if (activeNode) {
var aRight = activeNode.x() + activeNode.w();
var aButtom = activeNode.y() + activeNode.h();
var sRight = grMain.clientWidth;
var sButton = grMain.clientHeight;
if (aRight > sRight) {//左边被挡住
grMain.scrollLeft = aRight - sRight;
}
if (aButtom > sButton) {//左边被挡住
grMain.scrollTop = aButtom - sButton;
}
}
}
function getMaxWH() {
var mh = 0, mw = 0;
for (var i = 0; i < nodes.length; i++) {
var w = nodes[i].x() + nodes[i].w();
if (mw < w) mw = w;
var h = nodes[i].y() + nodes[i].h();
if (mh < h) mh = h;
}
for (var i = 0; i < lines.length; i++) {
var l = lines[i];
if (mh < l.getLineMaxY())mh = l.getLineMaxY();
}
return {w: mw, h: mh};
}
this.setActiveNode = setActiveNode;
function setActiveNode(node) {
if (activeNode) {
activeNode.isActive = false;
activeNode.draw();
//activeNode.setzIndex(0);
activeNode = undefined;
}
if (node) {
setAciveLine(undefined);
activeNode = node;
activeNode.isActive = true;
activeNode.draw();
//activeNode.setzIndex(999);
}
}
function setAciveLine(line) {
if (activeLine) {
activeLine.isActive = false;
activeLine.draw();
//activeLine.setzIndex(0);
activeLine = undefined;
}
if (line) {
setActiveNode(undefined);
activeLine = line;
activeLine.isActive = true;
activeLine.draw();
activeLine.sendTop();////////moyh
//activeLine.setzIndex(999);
}
}
function getMouseXy(evt) {
if (document.all) {//For IE
mouseX = event.clientX + grMain.scrollLeft + document.body.parentElement.scrollLeft;
mouseY = event.clientY + grMain.scrollTop + document.body.parentElement.scrollTop;
} else {
mouseX = evt.pageX + grMain.scrollLeft;
mouseY = evt.pageY + grMain.scrollTop;
}
if (mouseX < 0) {
mouseX = 0;
}
if (mouseY < 0) {
mouseY = 0;
}
mouseX = mouseX - grMain.getBoundingClientRect().left;
mouseY = mouseY - grMain.getBoundingClientRect().top;
return {x: mouseX, y: mouseY};
}
function getTextLH(size, str) {
if ($("#divctstrlh").length == 0)
$("<div id='divctstrlh' style='position:absolute;visibility:hidden;padding: 0px;margin: 0px'></div>").appendTo("body");
$("#divctstrlh").css({
"fontSize": size + "px",
"line-height": size + "px"
});
$("#divctstrlh").html(str);
var o = $("#divctstrlh")[0];
var h = o.offsetHeight;
var w = o.offsetWidth;
return {h: h, w: w};
}
}<file_sep>/src/com/hr/util/HRServletContextListener.java
package com.hr.util;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.listener.SWServletContextListener;
import com.corsair.server.retention.RContextInit;
import com.hr.attd.ctr.HrkqUtil;
import com.hr.attd.entity.Hrkq_swcdlst;
import com.hr.inface.ctr.TimerTaskHRAccessLog;
import com.hr.inface.ctr.TimerTaskHRAccessSum;
import com.hr.inface.entity.TXkqView_Hrms;
import com.hr.inface.entity.V_TrainRecord;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_trainwk;
import com.hr.timer.TaskCalcDepartDayReport;
import com.hr.timer.TaskKqSendWx;
import com.hr.timer.TaskPersonSendWx;
import com.hr.timer.TimerTaskMonthy;
@RContextInit()
public class HRServletContextListener implements SWServletContextListener {
private Timer timer_readswcard = new Timer(true);
private Timer timer_calckq = new Timer(true);
private Timer timer_trainwk = new Timer(true);
private Timer timer_syncmail = new Timer(true);
private Timer timer_synctxzm = new Timer(true);
private Timer timer_synctcrs = new Timer(true);
private Timer timer_synconcarts = new Timer(true);
private Timer timer_synoplog = new Timer(true);
private Timer timer_synaccesssum = new Timer(true);
private Timer timer_syntrans2ins = new Timer(true);
private Timer timer_checkDisableMail = new Timer(true);
private Timer timer_SYNEMPCARDNO = new Timer(true);
private Timer timer_AUTODELENTITY = new Timer(true);
private Timer timer_AUTOTRY = new Timer(true);// 试用期 考察期 过期处理
private Timer timerTaskHRCountRecords = new Timer(true);
private Timer TimerTaskAUTOSalary = new Timer(true);
private Timer TimerTaskAUTOSalaryHotSub = new Timer(true);
private Timer TimerTaskAUTOSetSalaryList = new Timer(true);
private Timer TimerTaskSendWxDepart = new Timer(true);
private Timer TimerTaskMonthly= new Timer(true);
private Timer TimerTaskSendPerson = new Timer(true);
private Timer TimerCalcDepartDayReport= new Timer(true);
private SendEmailDBThread sedbt = new SendEmailDBThread();
private AUTOSETSalaryListThread asslt = new AUTOSETSalaryListThread();
private AUTOCountRecords acrs = new AUTOCountRecords();
//private Scheduler scheduler;
@Override
public void contextInitialized(ServletContextEvent sContextE) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 1);
try {
if (ConstsSw.getAppParmBoolean("AUTOMONTHY")) {
System.out.println("月结【启用】");
long mit = 1 * 1 * 60 * 1000;
TimerTaskMonthly.schedule(new TimerTaskMonthy(), cal.getTime(), mit);
}
else{
System.out.println("月结【停用】");
}
if (ConstsSw.getAppParmBoolean("AUTOSENDWXMSGBYPERSON")) {
System.out.println("发送部门考勤数据【启用】");
long mit = 1 * 1 * 60 * 1000;
TimerTaskSendWxDepart.schedule(new TaskKqSendWx(), cal.getTime(), mit);
}
else{
System.out.println("发送部门考勤数据【停用】");
}
if (ConstsSw.getAppParmBoolean("AUTOSENDWXMSGBYPERSON")) {
System.out.println("发送个人考勤数据【启用】");
long mit = 1 * 1 * 60 * 1000;
TimerTaskSendPerson.schedule(new TaskPersonSendWx(), cal.getTime(), mit);
}
else{
System.out.println("发送个人考勤数据【停用】");
}
if (ConstsSw.getAppParmBoolean("AUTOCALCDAYDEPART")) {
System.out.println("自动统计各部门当天考勤【启用】");
long mit = 1 * 1 * 60 * 1000;// 一天一次
TimerCalcDepartDayReport.schedule(new TaskCalcDepartDayReport(), cal.getTime(), mit);
}
else{
System.out.println("自动统计各部门当天考勤【停用】");
}
// 同步打卡记录
if (ConstsSw.getAppParmBoolean("SYNTXCARDDATA")) {
int mit = Integer.valueOf(HrkqUtil.getParmValue("IMPORT_SWCARDINFO"));
if (mit != 0) {
System.out.println("同步打卡记录【启用】");
long spedt = mit * 60 * 1000;// mit 分钟运行一次
timer_readswcard.schedule(new TimerTaskHRSwcard(), cal.getTime(), spedt);
} else
System.out.println("同步打卡记录【停用】,系统参数SYNTXCARDDATA:false");
} else
System.out.println("同步打卡记录【停用】,应用参数IMPORT_SWCARDINFO:false");
if (ConstsSw.getAppParmBoolean("AUTOCALCKQ")) {
System.out.println("考勤计算【启用】");
long spedt = 1 * 60 * 60 * 1000;// 每小时运行一次
timer_calckq.schedule(new TimerTaskHRKQCalc(), cal.getTime(), spedt);
} else
System.out.println("考勤计算【停用】,应用参数AUTOCALCKQ:false");
// 在职培训
if (ConstsSw.getAppParmBoolean("SYNTEAINWK")) {
int mit = Integer.valueOf(HrkqUtil.getParmValue("SYNTEAINWK_TIME_SEP"));
if (mit != 0) {
System.out.println("在职培训【启用】");
long spedt = mit * 60 * 1000;// mit 分钟运行一次
timer_readswcard.schedule(new TimerTasTrainwk(), cal.getTime(), spedt);
} else
System.out.println("同步在职培训【停用】,系统参数SYNTEAINWK_TIME_SEP:0");
} else
System.out.println("同步在职培训【停用】,应用参数SYNTEAINWK:false");
// 同步邮件
if (ConstsSw.getAppParmBoolean("SYNUSERMAIL")) {
long mit = 24 * 60 * 60 * 1000;// 一天一次
System.out.println("同步邮件【启用】");
timer_syncmail.schedule(new TimerTasUserMail(), cal.getTime(), mit);
} else
System.out.println("同步用户邮件【停用】,应用参数SYNUSERMAIL:false");
// 同步招募系统资料
if (ConstsSw.getAppParmBoolean("SYNTXZMEMP")) {
System.out.println("同步招募系统资料【启用】");
long mit = 20 * 60 * 1000;// 20分钟一次
timer_synctxzm.schedule(new TimerTaskHRZM(), cal.getTime(), mit);
} else
System.out.println("同步招募系统资料【停用】,应用参数SYNTXZMEMP:false");
// 自动检测调动后生成购保单
if (ConstsSw.getAppParmBoolean("SYNTRANS2INSURANCE")) {
System.out.println("调动后生成购保单权限【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
timer_syntrans2ins.schedule(new TimerTaskHRTrans2Insurance(), cal.getTime(), mit);
}
// 同步饭堂消费记录
if (ConstsSw.getAppParmBoolean("SYNTXCOSTRECORD")) {
int mit = Integer.valueOf(HrkqUtil.getParmValue("IMPORT_CTCOSTRECORDS"));
if (mit != 0) {
System.out.println("同步饭堂消费记录【启用】");
long spedt = 24 * 60 * 60 * 1000;// 一天一次
timer_synctcrs.schedule(new TimerTaskHRCTCostRecords(), cal.getTime(), spedt);
} else
System.out.println("同步饭堂消费记录【停用】,考勤系统参数IMPORT_CTCOSTRECORDS:0");
} else
System.out.println("同步饭堂消费记录【停用】,应用参数SYNTXCOSTRECORD:false");
// 将过期合同状态修改为过期
if (ConstsSw.getAppParmBoolean("SYNCONSTAT")) {
System.out.println("更改过期合同状态【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
timer_synconcarts.schedule(new TimerTaskHRContract(), cal.getTime(), mit);
} else
System.out.println("更改过期合同状态【停用】,应用参数SYNCONSTAT:false");
// 同步开门日志
if (ConstsSw.getAppParmBoolean("SYNOPLOG")) {
System.out.println("同步开门日志【启用】");
long mit = 10 * 60 * 1000;// 10分钟一次
timer_synoplog.schedule(new TimerTaskHRAccessLog(), cal.getTime(), mit);
}
// 同步门禁权限
if (ConstsSw.getAppParmBoolean("SYNACCESSSUM")) {
System.out.println("同步门禁权限【启用】");
long mit = 10 * 60 * 1000;// 10分钟一次
timer_synaccesssum.schedule(new TimerTaskHRAccessSum(), cal.getTime(), mit);
}
// 检查无效通知
if (ConstsSw.getAppParmBoolean("CHECKDISABLENOTIFY")) {
sedbt.start();
// System.out.println("检查无效通知【启用】");
// long mit = 10 * 60 * 1000;// 10分钟一次
// timer_checkDisableMail.schedule(new TimerCheckDisableNotify(), cal.getTime(), mit);
} else
System.out.println("检查无效通知【停用】");
// 同步人事资料卡号
if (ConstsSw.getAppParmBoolean("SYNEMPCARDNO")) {
System.out.println("同步卡号【启用】");
long mit = 10 * 60 * 1000;// 10分钟一次
timer_SYNEMPCARDNO.schedule(new TimerTaskSYNEMPCARDNO(), cal.getTime(), mit);
} else
System.out.println("同步卡号【停用】");
// 自动清除实体资料
if (ConstsSw.getAppParmBoolean("AUTODELENTITY")) {
System.out.println("自动清除实体【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
timer_AUTODELENTITY.schedule(new TimerTaskAUTODELENTITY(), cal.getTime(), mit);
} else
System.out.println("自动清除实体【停用】");
if (ConstsSw.getAppParmBoolean("AUTOTRY")) {
System.out.println("自动处理考察期试用期过期【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
timer_AUTOTRY.schedule(new TimerTaskAUTOTRY(), cal.getTime(), mit);
} else
System.out.println("自动处理考察期试用期过期【停用】");
// 统计计算消费记录
if (ConstsSw.getAppParmBoolean("COUNTCOSTRECORDS")) {
System.out.println("统计计算消费记录【启用】");
acrs.start();
/*long spedt = 24 * 60 * 60 * 1000;// 一天一次
int countday = cal.get(Calendar.DAY_OF_MONTH);
if (countday == 5) {
//timerTaskHRCountRecords.schedule(new TimerTaskHRCountRecords(), cal.getTime(), spedt);
}*/
} else
System.out.println("统计计算消费记录【停用】,应用参数COUNTCOSTRECORDS:false");
if (ConstsSw.getAppParmBoolean("AUTOPOSTSUB")) {
System.out.println("自动处理岗位津贴过期调薪【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
TimerTaskAUTOSalary.schedule(new TimerTaskAUTOSalary(), cal.getTime(), mit);
} else
System.out.println("自动处理岗位津贴过期调薪【停用】");
// 月初自动从薪资异动记录生成薪资明细
if (ConstsSw.getAppParmBoolean("SETSALARYCHAGTOLIST")) {
System.out.println("自动生成薪资明细【启用】");
asslt.start();
/*long spedt = 24 * 60 * 60 * 1000;// 一天一次
int countday=cal.get(Calendar.DAY_OF_MONTH);
if(countday==1){//每月1号
TimerTaskAUTOSetSalaryList.schedule(new TimerTaskAUTOSetSalaryList(), cal.getTime(), spedt);
}*/
} else
System.out.println("自动生成薪资明细【停用】,应用参数SETSALARYCHAGTOLIST:false");
if (ConstsSw.getAppParmBoolean("AUTOHOTSUB")) {
System.out.println("自动处理高温津贴资格过期调薪【启用】");
long mit = 24 * 60 * 60 * 1000;// 一天一次
TimerTaskAUTOSalaryHotSub.schedule(new TimerTaskAUTOSalaryHotSub(), cal.getTime(), mit);
} else
System.out.println("自动处理高温津贴资格过期调薪【停用】");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent sContextE) {
// TODO Auto-generated method stub
asslt.stoped=true;
acrs.stoped=true;
sedbt.stoped = true;
TimerTaskSendWxDepart.cancel();
TimerTaskSendPerson.cancel();
TimerCalcDepartDayReport.cancel();
timer_readswcard.cancel();
timer_calckq.cancel();
timer_synctxzm.cancel();
// removeJob("jobName1","groupName1","triggerName1","groupName1");
// removeJob("jobName2","groupName2","triggerName2","groupName2");
// removeJob("jobName3","groupName3","triggerName3","groupName3");
// shutdownJobs();
}
//
public class TimerTasTrainwk extends TimerTask {
// private String bgdate = "2016-01-01";
private int syncrowno = 5000;
@Override
public void run() {
Logsw.debug("同步在职培训");
try {
String sqlstr = "SELECT MAX(odsno) mx FROM hr_employee_trainwk ";
Hr_employee_trainwk trs = new Hr_employee_trainwk();
List<HashMap<String, String>> sws = trs.pool.openSql2List(sqlstr);
long mx = ((sws.size() == 0) || (sws.get(0).get("mx") == null)) ? 0 : Long.valueOf(sws.get(0).get("mx"));
CJPALineData<V_TrainRecord> strds = new CJPALineData<V_TrainRecord>(V_TrainRecord.class);
sqlstr = "SELECT TOP " + syncrowno + " * from V_TrainRecord where fHours>0 and RowNo>" + mx + " order by RowNo";
strds.findDataBySQL(sqlstr, true, false);
CJPALineData<Hr_employee_trainwk> dtrds = new CJPALineData<Hr_employee_trainwk>(Hr_employee_trainwk.class);
Hr_employee emp = new Hr_employee();
String synctime = Systemdate.getStrDate();
for (CJPABase jpa : strds) {
V_TrainRecord strd = (V_TrainRecord) jpa;
emp.clear();
emp.findBySQL("select * from hr_employee where employee_code='" + strd.UserCode.getValue() + "'");
Hr_employee_trainwk dtrd = new Hr_employee_trainwk();
if (emp.isEmpty())
dtrd.er_id.setAsInt(0);
else
dtrd.er_id.setValue(emp.er_id.getValue());
dtrd.employee_code.setValue(strd.UserCode.getValue());
dtrd.twktype.setAsInt(1);
dtrd.twktitle.setValue(strd.CourseType.getValue() + "-" + strd.CourseName.getValue());
dtrd.begintime.setValue(strd.CardStartTime.getValue());
dtrd.endtime.setValue(strd.CardEndTime.getValue());
dtrd.classh.setAsInt(strd.fHours.getAsIntDefault(0));
if (strd.TeacherOrgName.isEmpty())
dtrd.schoolname.setValue("0");
else
dtrd.schoolname.setValue(strd.TeacherOrgName.getValue());
dtrd.lecturer.setValue(strd.TeacherStaffName.getValue());
dtrd.remark.setValue("系统自动导入:" + synctime);
dtrd.odsno.setValue(strd.RowNo.getValue());
dtrds.add(dtrd);
}
dtrds.saveBatchSimple();// 高速存储
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TimerTasUserMail extends TimerTask {
@Override
public void run() {
Logsw.debug("同步用户邮件");
try {
Shwuser user = new Shwuser();
String sqlstr = "UPDATE shwuser SET shwuser.email=("
+ " SELECT DISTINCT hr_interfacemail.mail FROM hr_interfacemail WHERE shwuser.username=hr_interfacemail.employee_code"
+ " )WHERE EXISTS("
+ " SELECT * FROM hr_interfacemail WHERE shwuser.username=hr_interfacemail.employee_code)";
user.pool.execsql(sqlstr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/src/com/corsair/dbpool/CDBPool.java
package com.corsair.dbpool;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.dbpool.CDBConnection.ConStat;
import com.corsair.dbpool.CDBConnection.DBType;
import com.corsair.dbpool.util.CResultSetMetaData;
import com.corsair.dbpool.util.CResultSetMetaDataItem;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
public class CDBPool {
private DBType dbtype = null;
public DBPoolParms pprm;
public List<CDBConnection> sessions = new ArrayList<CDBConnection>();
private Lock lock = new ReentrantLock();
private int reConnectTimes = 1;// 重连次数;
private long reConnectSptime = 1000;// 重连间隔;
private IDBContext ict;
/**
* @return 获取连接池信息
*/
public synchronized JSONArray getinfo() {
JSONArray rst = new JSONArray();
for (CDBConnection session : sessions) {
JSONObject s = new JSONObject();
s.put("key", session.getKey());
s.put("stat", session.getStat());
s.put("time", session.getTime());
s.put("isValid", !session.isValid());
s.put("inbs", session.isInTrans());
s.put("lastcmd", session.getLastcmd());
s.put("cmdsds", (System.currentTimeMillis() - session.getLastcmdstarttime()) / 1000);
if (session.getOwner() == null)
s.put("owner", null);
else
s.put("owner", session.getOwner().toString());
s.put("username", session.getCurUserName());
s.put("clientip", session.getClientIP());
rst.add(s);
}
return rst;
}
/**
* 构建连接池
*
* @param pprm
*/
public CDBPool(DBPoolParms pprm) {
this.pprm = pprm;
try {
// 数据库链接用到再初始化
// for (int i = 0; i < pprm.minsession; i++) {
// RstConMsg rcm = newconnecttodb();
// if (rcm.getCon() == null)
// throw new Exception(rcm.getErrmsg());
// }
} catch (Exception e) {
Logsw.error("为连接池【" + pprm.name + "】创建数据库连接错误");
e.printStackTrace();
}
checkthread cktd = new checkthread();
cktd.start();
}
/**
* 执行sql语句
*
* @param sqlstr
* @param dbginfo
* 是否打印日志
* @return 变更数据条数
* @throws Exception
*/
public int execsql(String sqlstr, boolean dbginfo) throws Exception {
CDBConnection con = getCon(this);
try {
return con.execsql(sqlstr, dbginfo);
} finally {
con.close();
}
}
/**
* 执行sql语句
*
* @param sqlstr
* @return 变更数据条数
* @throws Exception
*/
public int execsql(String sqlstr) throws Exception {
return execsql(sqlstr, false);
}
/**
* 指定连接执行一批sql语句
*
* @param con
* @param sqls
* @throws Exception
*/
public void execSqls(CDBConnection con, List<String> sqls) throws Exception {
con.execSqls(sqls);
}
/**
* 执行一批sql语句
*
* @param con
* @param sqls
* @throws Exception
*/
public void execSqls(List<String> sqls) throws Exception {
CDBConnection con = getCon(this);
con.startTrans();
try {
execSqls(con, sqls);
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组
*
* @param sqlstr
* @return
* @throws Exception
*/
public JSONArray opensql2json_O(String sqlstr) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json_o(sqlstr);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组
*
* @param psql
* @return
* @throws Exception
*/
public JSONArray opensql2json_O(PraperedSql psql) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json_o(psql);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON对象
*
* @param sqlstr
* @param page
* 页码
* @param pagesize
* 每页数量
* @return {page:page,total:total,rows:rows} total:总行数 rows:rows 数据的json数组
* @throws Exception
*/
public JSONObject opensql2json_O(String sqlstr, int page, int pagesize) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json_o(sqlstr, page, pagesize);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON对象
*
* @param sqlstr
* @param page
* 页码
* @param pagesize
* 每页数量
* @return {page:page,total:total,rows:rows} total:总行数 rows:rows 数据的json数组
* @throws Exception
*/
public JSONObject opensql2json_O(String sqlstr, int page, int pagesize, boolean withMetaData) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json_o(sqlstr, page, pagesize, withMetaData);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组
*
* @param sqlstr
* @param dbginfo
* 是否打印日志
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr, boolean dbginfo) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json(sqlstr, dbginfo);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组字符串
*
* @param sqlstr
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json(sqlstr);
} finally {
con.close();
}
}
public String openrowsql2json(String sqlstr) throws Exception {
CDBConnection con = getCon(this);
try {
return con.openrowsql2json(sqlstr);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组第一行字符串
*
* @param sqlstr
* @return
* @throws Exception
*/
public String openrowsql2json(PraperedSql psql) throws Exception {
CDBConnection con = getCon(this);
try {
return con.openrowsql2json(psql);
} finally {
con.close();
}
}
/**
* 执行查询sql语句,返回JSON数组字符串 分页
*
* @param sqlstr
* @return
* @throws Exception
*/
public String opensql2json(PraperedSql psql, int page, int pagesize) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json(psql, page, pagesize);
} finally {
con.close();
}
}
/**
* 执行查询,返回列表 参数如下 PraperedSql psql = new PraperedSql();
* psql.setSqlstr("select * from table where id=?"); psql.getParms().add(new
* PraperedValue(Types.INTEGER, id));
*
* @param psql
* @return
* @throws Exception
*/
public List<HashMap<String, String>> openSql2List(PraperedSql psql) throws Exception {
CDBConnection con = getCon(this);
try {
return con.openSql2List(psql);
} finally {
con.close();
}
}
/**
* 执行查询,返回JOSN字符串 参数如下 PraperedSql psql = new PraperedSql();
* psql.setSqlstr("select * from table where id=?"); psql.getParms().add(new
* PraperedValue(Types.INTEGER, id));
*
* @param psql
* @return
* @throws Exception
*/
public String opensql2json(PraperedSql psql) throws Exception {
return opensql2json(psql, true);
}
/**
* 执行查询,返回JOSN字符串 参数如下 PraperedSql psql = new PraperedSql();
* psql.setSqlstr("select * from table where id=?"); psql.getParms().add(new
* PraperedValue(Types.INTEGER, id));
*
* @param psql
* @param dbginfo
* 是否显示日志
* @return
* @throws Exception
*/
public String opensql2json(PraperedSql psql, boolean dbginfo) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json(psql, dbginfo);
} finally {
con.close();
}
}
/**
* 分页查询,返回JSON字符串
*
* @param sqlstr
* @param page
* @param pagesize
* @return
* @throws Exception
*/
public String opensql2json(String sqlstr, int page, int pagesize) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2json(sqlstr, page, pagesize);
} finally {
con.close();
}
}
/**
* 执行查询树结构JSON数组
*
* @param sqlstr
* @param idfd
* id字段名
* @param pidfd
* 父id字段名
* @param async
* 是否异步 false 将一次生成整个树结构,true:只生成第一级别
* @return [{fd:v,children:[{fd:v,children:[]},{}]}]
* @throws Exception
*/
public JSONArray opensql2jsontree_o(String sqlstr, String idfd, String pidfd, boolean async) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2jsontree_o(sqlstr, idfd, pidfd, async);
} finally {
con.close();
}
}
/**
* 执行查询树结构JSON数组字符串
*
* @param sqlstr
* @param idfd
* id字段名
* @param pidfd
* 父id字段名
* @param async
* 是否异步 false 将一次生成整个树结构,true:只生成第一级别
* @return [{fd:v,children:[{fd:v,children:[]},{}]}]
* @throws Exception
*/
public String opensql2jsontree(String sqlstr, String idfd, String pidfd, boolean async) throws Exception {
CDBConnection con = getCon(this);
try {
return con.opensql2jsontree(sqlstr, idfd, pidfd, async);
} finally {
con.close();
}
}
/**
* 执行查询返回列表
*
* @param sqlstr
* @return
* @throws Exception
*/
public List<HashMap<String, String>> openSql2List(String sqlstr) throws Exception {
CDBConnection con = getCon(this);
try {
return con.openSql2List(sqlstr);
} finally {
con.close();
}
}
/**
* 执行查询返回JPA对象列表(包含自关联数据)
*
* @param sqlstr
* @param cls
* @return
* @throws Exception
*/
public List<CJPABase> openSql2List(String sqlstr, Class<?> cls) throws Exception {
CDBConnection con = getCon(this);
try {
return con.openSql2List(sqlstr, cls);
} finally {
con.close();
}
}
public CResultSetMetaData<CResultSetMetaDataItem> getsqlMetadata(String sqlstr) throws Exception {
CDBConnection con = getCon(this);
try {
return con.getsqlMetadata(sqlstr);
} finally {
con.close();
}
}
class checkthread extends Thread {
public checkthread() {
}
public void run() {
while (true) {
// if (CDBPool.this == null)
// break;
CDBPool.this.checklinks();
try {
Thread.sleep(1000 * CDBPool.this.pprm.checkcontime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 从连接池中取出一个链接
private synchronized RstConMsg dogetcon(Object owner) {
for (CDBConnection conn : sessions) {
if (conn.getStat() == ConStat.ready) {
conn.open(owner);
return new RstConMsg(conn);
}
}
RstConMsg rcm = newconnecttodb();// 如果没有找到可用连接 就生成一个新的
if (rcm.getCon() != null) {
rcm.getCon().open(owner);
}
return rcm;
}
// 从连接池中取出一个链接
/**
* 从连接池获取一个连接,使用完毕需要close 或 提交 或回滚,否则连接将不能使用,直到超时
*
* @param owner
* 创建连接的对象,用来DEBUG
* @return 返回一个独用数据库连接
* @throws Exception
*/
public synchronized CDBConnection getCon(Object owner) throws Exception {
lock.lock();
try {
RstConMsg rcm = dogetcon(owner);
if (rcm.getCon() != null)
return rcm.getCon();
else
throw new Exception(rcm.getErrmsg());
} finally {
lock.unlock();
}
}
/**
* 关闭一个链接并放回连接池 并不断开数据库连接
*
* @param con
*/
// public synchronized void closeCon1(CDBConnection con) {
// con.close();
// }
/**
* 返回数据库类型 DBType.sqlserver, DBType.hsql, DBType.mysql, DBType.oracle,
* DBType.unknow
*
* @return
*/
public DBType getDbtype() {
if (dbtype == null) {
if (sessions.size() == 0) {
newconnecttodb();
}
System.out.println("sessions:" + sessions.size());
dbtype = sessions.get(0).getDBType();
}
return dbtype;
}
// 创建一个新的链接放入 连接池
private synchronized RstConMsg newconnecttodb() {
if (sessions.size() >= pprm.maxsession) {
return new RstConMsg(pprm.name + "数据库连接超过上限:" + pprm.maxsession);
}
try {
CDBConnection dbc = new CDBConnection(this, pprm);
if ((dbc == null) || (!dbc.isValid())) {
return new RstConMsg(pprm.name + "无法连接数据库!");
}
sessions.add(dbc);
return new RstConMsg(dbc);
} catch (Exception e) {
e.printStackTrace();
return new RstConMsg(pprm.name + "无法连接数据库:" + e.getMessage());
}
}
private void checklinks() {
lock.lock();
try {
Iterator<CDBConnection> iter = sessions.iterator();
while (iter.hasNext()) {
CDBConnection session = iter.next();
if (!session.isValid()) {
Logsw.error("异常中断的数据库连接,被干掉:" + session.getKey() + ":" + getObjectStr(session.getOwner()));
session.close();
iter.remove();
session = null;
continue;
}
if (session.isUsesTimeout()) {// 使用超时 关闭
Logsw.error("使用中的数据库连接超时,被连接池回收:" + session.getKey() + ":" + getObjectStr(session.getOwner()) + ":" + session.getLastcmd() + ":" + session.getCurUserName());
session.disConnect();
iter.remove();
session = null;
continue;
}
if ((session != null) && (!session.isInUse()) && (sessions.size() > pprm.minsession)) {// 检查是否连接数是否超初始化数量
// 超过就干掉
Logsw.error("未使用的链接超过初始化数量,被干掉:" + session.getKey() + ":" + getObjectStr(session.getOwner()));
session.disConnect();
iter.remove();
session = null;
continue;
}
}
} finally {
lock.unlock();
}
}
private String getObjectStr(Object o) {
if (o == null)
return null;
if ((o.getClass().getSimpleName().equalsIgnoreCase("String"))) {
return (String) o;
} else
return o.getClass().getName();
}
public IDBContext getIct() {
return ict;
}
public void setIct(IDBContext ict) {
this.ict = ict;
}
}
<file_sep>/src/com/hr/.svn/pristine/b3/b337330d3256d06453726f761732c7c7b761330b.svn-base
package com.hr.util;
import java.util.TimerTask;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.server.cjpa.CJPA;
import com.hr.base.entity.Hr_auto_delenty;
public class TimerTaskAUTODELENTITY extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
try {
CJPALineData<Hr_auto_delenty> ads = new CJPALineData<Hr_auto_delenty>(Hr_auto_delenty.class);
String sqlstr = "SELECT * FROM hr_auto_delenty WHERE useable=1";
ads.findDataBySQL(sqlstr);
for (CJPABase j : ads) {
Hr_auto_delenty ad = (Hr_auto_delenty) j;
if (ad.delwhere.isEmpty()) {
throw new Exception("自动删除【" + ad.adename.getValue() + "】条件不允许为空");
}
CJPA jpa = (CJPA) CjpaUtil.newJPAObjcet(ad.adeclass.getValue());
if (jpa != null) {
while (true) {
sqlstr = "select * from " + jpa.tablename + " where stat=1 and createtime is not null and createtime<DATE_ADD(NOW(), INTERVAL -" + ad.delwhere.getValue() + " DAY) ";
jpa.clear();
jpa.findBySQL(sqlstr);
if (jpa.isEmpty())
break;
else
jpa.delete();
}
}
}
} catch (Exception e) {
System.out.println("自动删除实体错误");
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/cjpa/util/CJPASqlUtil.java
package com.corsair.cjpa.util;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPASave;
import com.corsair.dbpool.CDBConnection.DBType;
import com.corsair.dbpool.util.CPoolSQLUtil;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.DBPools;
/**
* SQL创建工具
*
* @author Administrator
*
*/
public class CJPASqlUtil {
public static PraperedValue getSqlPValue(DBType dbtype, CField cf) {
PraperedValue rst = new PraperedValue();
rst.setFieldtype(cf.getFieldtype());
if (CPoolSQLUtil.eInArray(rst.getFieldtype(), CPoolSQLUtil.numFDType))
if ((cf.getValue() == null) || (cf.getValue().isEmpty()))
rst.setValue(null);
else
rst.setValue(cf.getValue());
if (CPoolSQLUtil.eInArray(cf.getFieldtype(), CPoolSQLUtil.strFDType)) {
if ((cf.getValue() == null) || (cf.getValue().isEmpty()))
rst.setValue(null);
else
rst.setValue(cf.getValue());
}
if (CPoolSQLUtil.eInArray(cf.getFieldtype(), CPoolSQLUtil.dateFDType)) {
if ((cf.getValue() == null) || (cf.getValue().isEmpty()))
rst.setValue(null);
else {
rst.setValue(cf.getAsDatetime());
}
}
return rst;
}
public static String getSqlValue(DBType dbtype, int datatype, String value) {
String result = "";
if ((value == null) || value.isEmpty())
return "null";
result = value;
if (CPoolSQLUtil.eInArray(datatype, CPoolSQLUtil.numFDType))
result = value;
if (CPoolSQLUtil.eInArray(datatype, CPoolSQLUtil.strFDType)) {
result = value.replaceAll("\\\\", "\\\\\\\\");
result = result.replaceAll("\'", "\\\\'");
result = "'" + result + "'";
}
if (CPoolSQLUtil.eInArray(datatype, CPoolSQLUtil.dateFDType)) {
if (dbtype == DBType.mysql)
result = "'" + value + "'";
if (dbtype == DBType.oracle)
result = "to_date('" + value + "','yyyy-mm-dd hh24:mi:ss')";
}
return result;
}
public static String getSqlTable(String tbname) {
return getSqlTable(DBPools.defaultPool().getDbtype(), tbname);
}
public static String getSqlTable(DBType dbtype, String tbname) {
String result = tbname;
if (dbtype == DBType.mysql)
if (!result.startsWith("`"))
result = "`" + result.toLowerCase() + "`";
if (dbtype == DBType.oracle)
result = result.toUpperCase();
return result;
}
public static String getSqlField(DBType dbtype, String parmname) {
int idx = parmname.lastIndexOf('.');
String tbname = null;
String fdname = parmname;
if (idx != -1) {
tbname = parmname.substring(0, idx);
fdname = parmname.substring(idx + 1);
}
String result = parmname;
if (dbtype == DBType.mysql)
result = (tbname == null) ? "`" + fdname + "`" : tbname + ".`" + fdname + "`";
if (dbtype == DBType.oracle)
result = (tbname == null) ? "" + fdname + "" : tbname + "." + fdname + "";
return result;
}
// 生成 某字段 更新SQL语句 如:fdname=value
public static String getFieldSQLUpdate(CJPASave cjpa, String fdname, String value) {
DBType dbtype = cjpa.pool.getDbtype();
return getSqlField(dbtype, fdname) + "=" + getSqlValue(dbtype, cjpa.cfield(fdname).getFieldtype(), value);
}
/**
* 生成 某些字段 更新SQL语句 如:fdname1=value1,fdname2=value2,fdname3=value3
*
* @param upjpa
* @param fdnames
* @param valjpa
* @return
*/
public static String getFieldSQLUpdate(CJPASave upjpa, String[] fdnames, CJPASave valjpa) {
DBType dbtype = upjpa.pool.getDbtype();
String rst = "";
for (String fdname : fdnames) {
rst = rst + getSqlField(dbtype, fdname) + "="
+ getSqlValue(dbtype, upjpa.cfield(fdname).getFieldtype(), valjpa.cfield(fdname).getValue()) + ",";
}
if (!rst.isEmpty())
rst = rst.substring(0, rst.length() - 1);
return rst;
}
public static int countStr(String str1, String str2) {
int counter = 0;
if (str1.indexOf(str2) == -1) {
return 0;
}
while (str1.indexOf(str2) != -1) {
counter++;
str1 = str1.substring(str1.indexOf(str2) + str2.length());
}
return counter;
}
}
<file_sep>/src/com/corsair/server/mail/CMailInfo.java
package com.corsair.server.mail;
import java.util.ArrayList;
import java.util.List;
public class CMailInfo {
private List<String> toMails = new ArrayList<String>();
private List<String> ccMails = new ArrayList<String>();
private List<String> bccMails = new ArrayList<String>();
private String subject;
private String content;
private String type = "text/html;charset=utf-8";
public List<String> getToMails() {
return toMails;
}
public List<String> getCcMails() {
return ccMails;
}
public List<String> getBccMails() {
return bccMails;
}
public String getType() {
return type;
}
public void setToMails(List<String> toMails) {
this.toMails = toMails;
}
public void setType(String type) {
this.type = type;
}
public void addToMail(String value) {
toMails.add(value);
}
public void addCCMail(String value) {
ccMails.add(value);
}
public void addBCCMail(String value) {
bccMails.add(value);
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
<file_sep>/src/com/hr/.svn/pristine/64/64ecda5f121204614d8e93a1eab6b7a5fc56c43d.svn-base
package com.hr.base.co;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.co.COPermRpt1;
import com.hr.util.HRUtil;
@ACO(coname = "web.hr.baserpt")
public class COBaseRpt {
// 组织机构列表
@ACOAction(eventname = "findOrgList", Authentication = true, notes = "组织机构列表报表")
public String findOrgList() throws Exception {
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(urlparms.get("parms"));
JSONParm jporgcode = CjpaUtil.getParm(jps, "orgcode");
if (jporgcode == null)
throw new Exception("需要参数【orgcode】");
JSONParm jpdqdate = CjpaUtil.getParm(jps, "yyyymm");
if (jpdqdate == null)
throw new Exception("需要参数【dqdate】");
String orgcode = jporgcode.getParmvalue();
String yyyymm = jpdqdate.getParmvalue();
String sqlstr = "select * from shworg where code='" + orgcode + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
JSONArray dws = HRUtil.getOrgsByPid(org.orgid.getValue());
dws.add(0, org.toJsonObj());
JSONArray footer = new JSONArray();
JSONObject srow = new JSONObject();
dofinddetail(dws, srow, yyyymm);
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = urlparms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private void dofinddetail(JSONArray datas, JSONObject srow, String yearmonth) throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String pyearmonth = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(Systemdate.getDateByStr(yearmonth), -1), "yyyy-MM");
int s_offquota = 0, s_not_offquota = 0, s_quota = 0, s_emnum = 0, s_emnumoff = 0, s_emnumnoff = 0;
for (int i = 0; i < datas.size(); i++) {
boolean includechld = (i != 0);
// boolean includechld = true;
JSONObject dw = datas.getJSONObject(i);
dw.put("yyyymm", yearmonth);
String orgid = dw.getString("orgid").toString();
// 机构脱产编制
String sqlstr = "SELECT IFNULL(SUM(op.quota),0) quota ";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_orgposition op,hr_standposition sp ";
else
sqlstr = sqlstr + " FROM hr_month_orgposition op,hr_standposition sp ";
sqlstr = sqlstr + " WHERE sp.usable=1 ";
if (!isnowmonth)
sqlstr = sqlstr + " and op.yearmonth=" + yearmonth + "";
if (includechld)
sqlstr = sqlstr + " AND op.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND op.orgid=" + dw.getString("orgid");
sqlstr = sqlstr + " AND op.sp_id=sp.sp_id AND op.isoffjob=1";
dw.put("offquota", DBPools.defaultPool().openSql2List(sqlstr).get(0).get("quota")); // 拖产编制
s_offquota = s_offquota + dw.getInt("offquota");
// 机构非脱产编制 可能要从 机构职类编制获取???????
sqlstr = "SELECT IFNULL(SUM(q.quota),0) quota FROM ";
if (isnowmonth)
sqlstr = sqlstr + " hr_quotaoc q, hr_wclass c,shworg o";
else
sqlstr = sqlstr + " hr_month_quotaoc q, hr_wclass c,shworg o";
sqlstr = sqlstr + " WHERE q.orgid=o.orgid AND q.classid=c.hwc_id AND c.isoffjob=2 and o.usable=1 and c.usable=1 ";
if (!isnowmonth)
sqlstr = sqlstr + " and q.yearmonth='" + yearmonth + "'";
if (includechld)
sqlstr = sqlstr + " AND o.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND o.orgid=" + dw.getString("orgid");
dw.put("not_offquota", DBPools.defaultPool().openSql2List(sqlstr).get(0).get("quota"));// 非拖产编制
s_not_offquota = s_not_offquota + dw.getInt("not_offquota");
dw.put("quota", dw.getInt("offquota") + dw.getInt("not_offquota"));// 总编制
s_quota = s_quota + dw.getInt("quota");
// 实际人数
HashMap<String, String> mp = COPermRpt1.getTrueEmpCts(dw, pyearmonth, yearmonth, 0, includechld);
dw.put("emnum", mp.get("emnum"));
dw.put("emnumoff", mp.get("emnumoff"));// 脱产人数
dw.put("emnumnoff", mp.get("emnumnoff"));//
s_emnum = s_emnum + dw.getInt("emnum");
s_emnumoff = s_emnumoff + dw.getInt("emnumoff");
s_emnumnoff = s_emnumnoff + dw.getInt("emnumnoff");
}
srow.put("offquota", s_offquota);
srow.put("not_offquota", s_not_offquota);
srow.put("quota", s_quota);
srow.put("emnum", s_emnum);
srow.put("emnumoff", s_emnumoff);
srow.put("emnumnoff", s_emnumnoff);
srow.put("orgname", "合计");
}
@ACOAction(eventname = "findopquota", Authentication = true, notes = "查询机构职位及编制")
public String findopquota() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String sqlstr = "SELECT op.*,IFNULL(COUNT(he.er_id),0) empct FROM hr_orgposition op,hr_employee he " +
"WHERE op.orgid=" + orgid + " AND op.ospid=he.ospid AND he.usable=1 " +
"AND EXISTS(SELECT 1 FROM hr_employeestat st WHERE he.empstatid=st.statvalue AND st.usable=1 AND st.isquota=1) " +
" GROUP BY op.ospid";
// String sqlstr = "select * from hr_orgposition where orgid=" + orgid;
Hr_orgposition hsp = new Hr_orgposition();
// JSONArray datas = hsp.pool.opensql2jsontree_o(sqlstr, "ospid", "pid", false);
JSONArray datas = hsp.pool.opensql2json_O(sqlstr);
for (int i = 0; i < datas.size(); i++) {
JSONObject dt = datas.getJSONObject(i);
int quota = (dt.has("quota")) ? Integer.valueOf(dt.getString("quota")) : 0;
int empct = Integer.valueOf(dt.getString("empct"));
int cbnum = empct - quota;
if (cbnum < 0)
cbnum = 0;
int qbnum = quota - empct;
if (qbnum < 0)
qbnum = 0;
dt.put("cbnum", cbnum);
dt.put("qbnum", qbnum);
}
// findENumOp(hsp, datas);
return datas.toString();
}
private void findENumOp(Hr_orgposition hsp, JSONArray dts) throws Exception {
for (int i = 0; i < dts.size(); i++) {
JSONObject dt = dts.getJSONObject(i);
String ospid = dt.getString("ospid");
String sqlstr = "SELECT COUNT(*) ct FROM hr_employee he " + " WHERE he.usable=1 AND he.ospid=" + ospid + " AND he.empstatid IN"
+ " (SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1)";
dt.put("empct", hsp.pool.openSql2List(sqlstr).get(0).get("ct"));
int quota = (dt.has("quota")) ? Integer.valueOf(dt.getString("quota")) : 0;
int empct = Integer.valueOf(dt.getString("empct"));
int cbnum = empct - quota;
if (cbnum < 0)
cbnum = 0;
int qbnum = quota - empct;
if (qbnum < 0)
qbnum = 0;
dt.put("cbnum", cbnum);
dt.put("qbnum", qbnum);
// if (dt.has("children")) {
// findENumOp(hsp, dt.getJSONArray("children"));
// }
}
}
@ACOAction(eventname = "findOrgEmployee", Authentication = true, notes = "机构包含员工")
public String findOrgEmployee() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String sqlstr = "SELECT * FROM hr_employee he WHERE he.empstatid IN(" + " SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1"
+ " ) AND he.orgid=" + orgid;
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "findOrgEmployeejz", Authentication = true, notes = "机构兼职员工")
public String findOrgEmployeejz() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String sqlstr = "SELECT eip.* " + " FROM hr_empptjob_info ji,hr_employee he,hr_empptjob_app eip "
+ " WHERE ji.er_id=he.er_id AND ji.enddate>=NOW() AND ji.startdate<=NOW() AND ji.sourceid=eip.ptjaid" + " AND eip.neworgid=" + orgid
+ " AND he.empstatid IN(" + " SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1)";
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "findOrgEmployeejr", Authentication = true, notes = "机构借入员工")
public String findOrgEmployeejr() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String sqlstr = "SELECT l.*,h.loandate,h.returndate,h.loanreason FROM hr_emploanbatch h,hr_emploanbatch_line l,hr_employee e"
+ " WHERE h.stat=9 AND h.loanid=l.loanid AND l.er_id=e.er_id AND h.returndate>=NOW() AND h.loandate<=NOW()"
+ " AND e.empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1)" + " AND l.neworgid=" + orgid;
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "findOrgEmployeejc", Authentication = true, notes = "机构借出员工")
public String findOrgEmployeejc() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid", "需要参数orgid");
String sqlstr = "SELECT l.*,h.loandate,h.returndate,h.loanreason FROM hr_emploanbatch h,hr_emploanbatch_line l,hr_employee e"
+ " WHERE h.stat=9 AND h.loanid=l.loanid AND l.er_id=e.er_id AND h.returndate>=NOW() AND h.loandate<=NOW()"
+ " AND e.empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1)" + " AND l.odorgid=" + orgid;
return DBPools.defaultPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "findEmployeeClassQuota", Authentication = true, notes = "机构职类编制")
public String findEmployeeClassQuota() throws Exception {
JSONArray dws = HRUtil.getOrgsByType("6");// 工厂
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
JSONArray cqs = getClassQuota(dw);
int emnum = getClassEmployees(dw);
if (cqs.size() > 0) {
JSONObject cq = cqs.getJSONObject(0);
dw.put("quota", cq.getString("quota"));
dw.put("emnum", emnum);
dw.put("hwc_id", cq.getString("hwc_id"));
dw.put("hw_code", cq.getString("hw_code"));
dw.put("hwc_name", cq.getString("hwc_name"));
} else {
dw.put("quota", 0);
dw.put("emnum", emnum);
}
int hwcquota = dw.getInt("quota");
if (hwcquota != 0) {
if (hwcquota > emnum) {
dw.put("overquota", hwcquota - emnum);
dw.put("lowquota", 0);
} else {
dw.put("overquota", 0);
dw.put("lowquota", emnum - hwcquota);
}
}
}
JSONArray temple = new JSONArray();
for (int j = 0; j < dws.size(); j++) {
JSONObject dw = dws.getJSONObject(j);
if (dw.getInt("quota") != 0) {
temple.add(dw);
}
}
return temple.toString();
}
private JSONArray getClassQuota(JSONObject dw) throws Exception {
String sqlstr = "SELECT hwc.hwc_id,hwc.hw_code,hwc.hwc_name, hqoc.quota,o.orgid,o.orgname,o.code FROM "
+ " hr_quotaoc hqoc,hr_wclass hwc,(SELECT * FROM shworg WHERE stat=1 AND entid=1 AND orgtype=6 AND idpath LIKE '" + dw.getString("idpath")
+ "%' ) o " + " WHERE hqoc.orgid=o.orgid AND hqoc.usable=1 AND hwc.hwc_id=hqoc.classid ORDER BY o.orgid";
return DBPools.defaultPool().opensql2json_O(sqlstr);
}
private int getClassEmployees(JSONObject dw) throws Exception {
String sqlstr = " SELECT COUNT(*) ct FROM hr_employee WHERE "
+ " usable=1 AND empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) " + " AND idpath = '"
+ dw.getString("idpath") + "'";
return Integer.valueOf(DBPools.defaultPool().opensql2json_O(sqlstr).getJSONObject(0).getString("ct"));
}
private JSONParm getParmByName(List<JSONParm> jps, String pname) {
for (JSONParm jp : jps) {
if (jp.getParmname().equals(pname))
return jp;
}
return null;
}
}
<file_sep>/src/com/hr/inface/entity/View_Hrms_TXJocatList.java
package com.hr.inface.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(dbpool = "oldtxmssql", tablename = "View_Hrms_TXJocatList")
public class View_Hrms_TXJocatList extends CJPA {
@CFieldinfo(fieldname="id",iskey=true,notnull=true,caption="id",datetype=Types.INTEGER)
public CField id; //id
@CFieldinfo(fieldname="rfkh",notnull=true,caption="卡号",datetype=Types.VARCHAR)
public CField rfkh; //卡号 关联员工工号
@CFieldinfo(fieldname="xfjh",notnull=true,caption="消费机编号",datetype=Types.VARCHAR)
public CField xfjh; //消费机编号
@CFieldinfo(fieldname="xfsj",caption="消费时间",datetype=Types.TIMESTAMP)
public CField xfsj; //消费时间
@CFieldinfo(fieldname="code",notnull=true,caption="工号",datetype=Types.VARCHAR)
public CField code; //工号
@CFieldinfo(fieldname="createTime",notnull=true,caption="创建时间",datetype=Types.TIMESTAMP)
public CField createTime; //创建时间
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public View_Hrms_TXJocatList() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/salary/ctr/CtrHr_salary_specchgsa.java
package com.hr.salary.ctr;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_entry_prob;
import com.hr.perm.entity.Hr_transfer_prob;
import com.hr.salary.co.Cosacommon;
import com.hr.salary.entity.Hr_salary_chgbill;
import com.hr.salary.entity.Hr_salary_orgminstandard;
import com.hr.salary.entity.Hr_salary_positionwage;
import com.hr.salary.entity.Hr_salary_specchgsa;
import com.hr.salary.entity.Hr_salary_structure;
import com.hr.util.HRUtil;
public class CtrHr_salary_specchgsa extends JPAController{
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf,
boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if(isFilished){
Hr_salary_specchgsa scs=(Hr_salary_specchgsa)jpa;
CtrSalaryCommon.newSalaryChangeLog(con,scs);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf,
Shwwfproc proc, Shwwfproc nxtproc, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
if(isFilished){
Hr_salary_specchgsa scs=(Hr_salary_specchgsa)jpa;
CtrSalaryCommon.newSalaryChangeLog(con,scs);
CtrSalaryCommon.updateWageState(scs.salary_quotacode.getValue(),scs.employee_code.getValue());
}
}
@Override
public String AfterCCoSave(CDBConnection con, CJPA jpa) throws Exception {
// TODO Auto-generated method stub
Hr_salary_specchgsa scs=(Hr_salary_specchgsa)jpa;
HashMap<String, String> pparms = CSContext.parPostDataParms();
String jpadata = pparms.get("jpadata");
if ((jpadata == null) || jpadata.isEmpty())
throw new Exception("需要jpadata参数");
JSONObject jo = JSONObject.fromObject(jpadata);
Cosacommon.save_salary_chgblill(con, scs, jo);
return null;
}
@Override
public void BeforeWFStart(CJPA jpa, String wftempid, CDBConnection con)
throws Exception {
// TODO Auto-generated method stub
Hr_salary_specchgsa scs=(Hr_salary_specchgsa)jpa;
Hr_employee emp = new Hr_employee();
Hr_salary_chgbill cb = new Hr_salary_chgbill();
emp.findByID(scs.er_id.getValue());
cb.findBySQL("SELECT * FROM `hr_salary_chgbill` WHERE stype=7 AND er_id="+emp.er_id.getValue()+" AND sid="+scs.scsid.getValue());
float np=cb.newposition_salary.getAsFloatDefault(0);
float op=cb.oldposition_salary.getAsFloatDefault(0);
float chgpos=np-op;
if(emp.emnature.getValue().equals("脱产")&&chgpos>0){
if(scs.salary_quotacode.isEmpty()){
throw new Exception("脱产人员调薪额度不为0时,额度编号不能为空");
}
}
HRUtil.issalary_quotacode_used(4, scs.salary_quotacode.getValue(), scs.scsid.getValue());
}
@Override
public void BeforeSave(CJPABase jpa, CDBConnection con, boolean selfLink)
throws Exception {
Hr_salary_specchgsa scs=(Hr_salary_specchgsa)jpa;
if((((scs.newposition_salary.getAsFloatDefault(0)>scs.oldposition_salary.getAsFloatDefault(0))
||(scs.newtech_allowance.getAsFloatDefault(0)>scs.oldtech_allowance.getAsFloatDefault(0)))
&&scs.pbtsarylev.getAsFloatDefault(0)==0)||
(((scs.newposition_salary.getAsFloatDefault(0)>scs.oldposition_salary.getAsFloatDefault(0)))
&&scs.overf_salary.getAsFloatDefault(0)==0)||((scs.newbase_salary.getAsFloatDefault(0)+
scs.newtech_salary.getAsFloatDefault(0)+scs.newachi_salary.getAsFloatDefault(0)+
scs.newotwage.getAsFloatDefault(0)-scs.newposition_salary.getAsFloatDefault(0))!=0)){
resetsalaryinfo(scs);
//throw new Exception("薪资有调整但调整额度为0,请检查单据或清理浏览器缓存后再制单。(清理浏览器缓存方法:同时按 ctr+shift+delete 即可弹出删除缓存对话框。)");
}
Hr_employee emp = new Hr_employee();
emp.findByID(scs.er_id.getValue());
//String sacra=jo.getString("sacrage");
System.out.println("----------保存前");
float sac=scs.pbtsarylev.getAsFloatDefault(0);
if(emp.emnature.getValue().equals("脱产")&&sac>0){
if(scs.salary_quotacode.isEmpty()){
throw new Exception("脱产人员调薪额度大于0,额度编号不能为空!");
}
}
if(!scs.salary_quotacode.isEmpty()){
if(scs.salary_quota_appy.getAsFloatDefault(0)==0){
throw new Exception("申请额度为0,请核查!");
}
}
scs.newcalsalarytype.setValue(emp.pay_way.getValue());
scs.salarydate.setValue(Systemdate.getStrDateyyyy_mm_01());
}
private void resetsalaryinfo(Hr_salary_specchgsa scs) throws Exception{
float np=scs.newposition_salary.getAsFloatDefault(0);
float op=scs.oldposition_salary.getAsFloatDefault(0);
if(((np>op)&scs.pbtsarylev.getAsFloatDefault(0)==0)||((scs.newbase_salary.getAsFloatDefault(0)+
scs.newtech_salary.getAsFloatDefault(0)+scs.newachi_salary.getAsFloatDefault(0)+
scs.newotwage.getAsFloatDefault(0)-np)!=0)){
Hr_salary_structure ss=new Hr_salary_structure();
ss.findByID(scs.newstru_id.getValue());
if(!ss.isEmpty()){
if(ss.strutype.getAsInt()==1){
float minstand=0;
String sqlstr="SELECT * FROM `hr_salary_orgminstandard` WHERE stat=9 AND usable=1 AND INSTR('"+scs.idpath.getValue()+"',idpath)=1 ORDER BY idpath DESC ";
Hr_salary_orgminstandard oms=new Hr_salary_orgminstandard();
oms.findBySQL(sqlstr);
if(oms.isEmpty()){
minstand=0;
}else{
minstand=oms.minstandard.getAsFloatDefault(0);
}
float bw=(np*ss.basewage.getAsFloatDefault(0))/100;
float bow=(np*ss.otwage.getAsFloatDefault(0))/100;
float sw=(np*ss.skillwage.getAsFloatDefault(0))/100;
float pw=(np*ss.meritwage.getAsFloatDefault(0))/100;
if(minstand>bw){
if((bw+bow)>minstand){
bow=bw+bow-minstand;
bw=minstand;
}else if((bw+bow+sw)>minstand){
sw=bw+bow+sw-minstand;
bow=0;
bw=minstand;
}else if((bw+bow+sw+pw)>minstand){
pw=bw+bow+sw+pw-minstand;
sw=0;
bow=0;
bw=minstand;
}else{
bw=np;
pw=0;
sw=0;
bow=0;
}
}
scs.newbase_salary.setAsFloat(bw);
scs.newtech_salary.setAsFloat(sw);
scs.newachi_salary.setAsFloat(pw);
scs.newotwage.setAsFloat(bow);
scs.chgbase_salary.setAsFloat(bw-scs.oldbase_salary.getAsFloatDefault(0));
scs.chgtech_salary.setAsFloat(sw-scs.oldtech_salary.getAsFloatDefault(0));
scs.chgachi_salary.setAsFloat(pw-scs.oldachi_salary.getAsFloatDefault(0));
scs.chgotwage.setAsFloat(bow-scs.oldotwage.getAsFloatDefault(0));
}else{
float newnp=scs.newbase_salary.getAsFloatDefault(0)+scs.newtech_salary.getAsFloatDefault(0)+scs.newachi_salary.getAsFloatDefault(0)+scs.newotwage.getAsFloatDefault(0);
scs.newposition_salary.setAsFloat(newnp);
}
scs.chgposition_salary.setAsFloat(np-scs.oldposition_salary.getAsFloatDefault(0));
scs.chgtech_allowance.setAsFloat(scs.newtech_allowance.getAsFloatDefault(0)-scs.oldtech_allowance.getAsFloatDefault(0));
scs.pbtsarylev.setAsFloat(np+scs.newtech_allowance.getAsFloatDefault(0)-scs.oldposition_salary.getAsFloatDefault(0)-scs.oldtech_allowance.getAsFloatDefault(0));
scs.sacrage.setAsFloat(np+scs.newtech_allowance.getAsFloatDefault(0)-scs.oldposition_salary.getAsFloatDefault(0)-scs.oldtech_allowance.getAsFloatDefault(0));
}
}
if(np>0){
Hr_salary_positionwage spw=new Hr_salary_positionwage();
spw.findBySQL("SELECT pw.* FROM `hr_salary_positionwage` pw,`hr_orgposition` op WHERE pw.stat=9 AND pw.usable=1 AND pw.ospid=op.sp_id AND op.ospid="+scs.ospid.getValue());
if(spw.isEmpty()){
scs.overf_salary.setValue(0);
scs.overf_salary_chgtech.setValue(0);
}else{
if(np>spw.psl5.getAsFloatDefault(0)){
float spwage=spw.psl5.getAsFloatDefault(0);
float chgspw=np-spwage;
scs.overf_salary.setAsFloat(chgspw);
float chgper=(chgspw/spwage)*100;
scs.overf_salary_chgtech.setAsFloat(chgper);
}
}
}
}
}
<file_sep>/src/com/hr/asset/entity/Hr_asset_reject_d.java
package com.hr.asset.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_asset_reject_d extends CJPA {
@CFieldinfo(fieldname="asset_reject_line_id",iskey=true,notnull=true,caption="报废单行ID",datetype=Types.INTEGER)
public CField asset_reject_line_id; //asset_reject_line_id
@CFieldinfo(fieldname="asset_reject_id",caption="报废单ID",datetype=Types.INTEGER)
public CField asset_reject_id; //asset_reject_id
@CFieldinfo(fieldname="asset_item_id",caption="物料ID",datetype=Types.INTEGER)
public CField asset_item_id; //asset_item_id
@CFieldinfo(fieldname="asset_item_code",caption="物料编码",datetype=Types.VARCHAR)
public CField asset_item_code; //asset_item_code
@CFieldinfo(fieldname="asset_item_name",caption="物料名称",datetype=Types.VARCHAR)
public CField asset_item_name; //asset_item_name
@CFieldinfo(fieldname="asset_type_id",caption="类型ID",datetype=Types.INTEGER)
public CField asset_type_id; //asset_type_id
@CFieldinfo(fieldname="asset_type_code",caption="类型编码",datetype=Types.VARCHAR)
public CField asset_type_code; //asset_type_code
@CFieldinfo(fieldname="asset_type_name",caption="类型名称",datetype=Types.VARCHAR)
public CField asset_type_name; //asset_type_name
@CFieldinfo(fieldname="uom",caption="单位",datetype=Types.VARCHAR)
public CField uom; //uom
@CFieldinfo(fieldname="asset_register_id",caption="登记号ID",datetype=Types.INTEGER)
public CField asset_register_id; //asset_register_id
@CFieldinfo(fieldname="asset_register_num",codeid=94,caption="登记号",datetype=Types.VARCHAR)
public CField asset_register_num; //asset_register_num
@CFieldinfo(fieldname="original_value",caption="原值",datetype=Types.VARCHAR)
public CField original_value; //original_value
@CFieldinfo(fieldname="net_value",caption="净值",datetype=Types.VARCHAR)
public CField net_value; //net_value
@CFieldinfo(fieldname="service_life",caption="报废年限",datetype=Types.INTEGER)
public CField service_life; //service_life
@CFieldinfo(fieldname="acquired_date",caption="购置日期",datetype=Types.TIMESTAMP)
public CField acquired_date; //acquired_date
@CFieldinfo(fieldname="deploy_qty",caption="配置数量",datetype=Types.INTEGER)
public CField deploy_qty; //deploy_qty
@CFieldinfo(fieldname="deploy_area",caption="配置区域",datetype=Types.VARCHAR)
public CField deploy_area; //deploy_area
@CFieldinfo(fieldname="deploy_restaurant",caption="配置餐厅",datetype=Types.VARCHAR)
public CField deploy_restaurant; //deploy_restaurant
@CFieldinfo(fieldname="deploy_restaurant_id",caption="配置餐厅id",datetype=Types.INTEGER)
public CField deploy_restaurant_id; //deploy_restaurant_id
@CFieldinfo(fieldname="keep_own",caption="保管人",datetype=Types.VARCHAR)
public CField keep_own; //keep_own
@CFieldinfo(fieldname="reject_qty",caption="报废数量",datetype=Types.INTEGER)
public CField reject_qty; //reject_qty
@CFieldinfo(fieldname="reject_date",caption="报废日期",datetype=Types.TIMESTAMP)
public CField reject_date; //reject_date
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //remark
@CFieldinfo(fieldname="creator",caption="创建人",datetype=Types.VARCHAR)
public CField creator; //creator
@CFieldinfo(fieldname="createtime",caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //createtime
@CFieldinfo(fieldname="updator",caption="更新人",datetype=Types.VARCHAR)
public CField updator; //updator
@CFieldinfo(fieldname="updatetime",caption="更新时间",datetype=Types.TIMESTAMP)
public CField updatetime; //updatetime
@CFieldinfo(fieldname="attribute1",caption="attribute1",datetype=Types.VARCHAR)
public CField attribute1; //attribute1
@CFieldinfo(fieldname="attribute2",caption="attribute2",datetype=Types.TIMESTAMP)
public CField attribute2; //attribute2
@CFieldinfo(fieldname="attribute3",caption="attribute3",datetype=Types.VARCHAR)
public CField attribute3; //attribute3
@CFieldinfo(fieldname="attribute4",caption="attribute4",datetype=Types.VARCHAR)
public CField attribute4; //attribute4
@CFieldinfo(fieldname="attribute5",caption="attribute5",datetype=Types.VARCHAR)
public CField attribute5; //attribute5
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_asset_reject_d() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/attd/co/COHrkq_workschmonthlist.java
package com.hr.attd.co;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.attd.entity.Hrkq_leave_blance;
import com.hr.attd.entity.Hrkq_sched;
import com.hr.attd.entity.Hrkq_workschmonthline;
import com.hr.attd.entity.Hrkq_workschmonthlist;
import com.hr.perm.entity.Hr_employee;
@ACO(coname = "web.hrkq.wscm")
public class COHrkq_workschmonthlist {
@ACOAction(eventname = "findwscm", Authentication = true, notes = "查询某人某月排班")
public String findsched() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
String yearmonth = CorUtil.hashMap2Str(parms, "yearmonth");
String sqlstr = "select * from hrkq_workschmonthlist where er_id=" + er_id;
if ((yearmonth != null) && (!yearmonth.isEmpty()))
sqlstr = sqlstr + " and yearmonth='" + yearmonth + "'";
Hrkq_workschmonthlist wscl = new Hrkq_workschmonthlist();
return wscl.pool.opensql2json(sqlstr);
}
@ACOAction(eventname = "findschedline", Authentication = true, notes = "查询某人某月某日排班明细")
public String findschedline() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String er_id = CorUtil.hashMap2Str(parms, "er_id", "需要参数er_id");
String resdate = CorUtil.hashMap2Str(parms, "resdate", "需要参数resdate");
Date dt = Systemdate.getDateByStr(resdate);
String yearmonth = Systemdate.getStrDateByFmt(dt, "yyyy-MM");
String sqlstr = "select * from hrkq_workschmonthlist where er_id=" + er_id;
sqlstr = sqlstr + " and yearmonth='" + yearmonth + "'";
Hrkq_workschmonthlist wscl = new Hrkq_workschmonthlist();
wscl.findBySQL(sqlstr);
if (wscl.isEmpty())
throw new Exception("没有发现该员工选定月份排班记录");
int d = Integer.valueOf(Systemdate.getStrDateByFmt(dt, "dd"));
// System.out.println("d:" + d);
String scid = wscl.cfield("scid" + d).getValue();
// System.out.println("scid" + scid);
if ((scid == null) || (scid.isEmpty()))
throw new Exception("没有发现该员工选定日期排班记录");
Hrkq_sched sc = new Hrkq_sched();
sc.findByID(scid);
if (sc.isEmpty())
throw new Exception("没有发现该员工选定日期排班记录");
return sc.tojson();
}
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "导入排班信息")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
CJPALineData<Hrkq_workschmonthline> rst = new CJPALineData<Hrkq_workschmonthline>(Hrkq_workschmonthline.class);
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
return rst.tojson();
}
private CJPALineData<Hrkq_workschmonthline> parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
@SuppressWarnings("resource")
// Workbook workbook = CExcelUtil.isExcel2003(fullname) ? new HSSFWorkbook(new FileInputStream(fullname))
// : new XSSFWorkbook(new FileInputStream(fullname));
Workbook workbook = WorkbookFactory.create(file);
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
Sheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private CJPALineData<Hrkq_workschmonthline> parserExcelSheet(Sheet aSheet, String batchno) throws Exception {
CJPALineData<Hrkq_workschmonthline> rst = new CJPALineData<Hrkq_workschmonthline>(Hrkq_workschmonthline.class);
if (aSheet.getLastRowNum() == 0) {
return rst;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Shworg org = new Shworg();
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
for (Map<String, String> v : values) {
Hrkq_workschmonthline wml = new Hrkq_workschmonthline();
String tcode = v.get("tcode");
String sstype = dictemp.getVbCE("919", v.get("ttype"), false, "类型【" + v.get("ttype") + "】不存在");
int stype = Integer.valueOf(sstype);
wml.ttype.setAsInt(stype);
if (stype == 2) {// 机构
org.clear();
String sqlstr = "select * from shworg where code='" + tcode + "'";
org.findBySQL(sqlstr, false);
if (org.isEmpty())
throw new Exception("编号为【" + tcode + "】的机构不存在");
wml.tid.setValue(org.orgid.getValue());
wml.tcode.setValue(org.code.getValue());
wml.tname.setValue(org.extorgname.getValue());
} else if (stype == 3) {// 个人
emp.clear();
String sqlstr = "select * from hr_employee where employee_code='" + tcode + "'";
emp.findBySQL(sqlstr, false);
if (emp.isEmpty())
throw new Exception("工号为【" + tcode + "】的人事资料不存在");
wml.tid.setValue(emp.er_id.getValue());
wml.tcode.setValue(emp.employee_code.getValue());
wml.tname.setValue(emp.employee_name.getValue());
} else {
throw new Exception("类型【" + v.get("ttype") + "】不存在");
}
rst.add(wml);
}
// throw new Exception("不给通过");
return rst;
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("编码", "tcode", true));
efields.add(new CExcelField("类型", "ttype", true));
return efields;
}
}
<file_sep>/WebContent/webapp/js/common/creport.js
/**
* Created by Administrator on 2015-01-07.
*/
var creport = undefined;
$(document).ready(function () {
creport = new TCreport(prtOptions);
}
);
function TCreport(prtOptions) {
var finddlg = undefined;//查询窗口对象
var prtOptions = prtOptions;
var gdListColumns = undefined;
var defaultListGridColumsn = undefined;//默认的
var showChartChoicetor = false;
this.prtOptions = prtOptions;
var pagination = (prtOptions.pagination == undefined) ? true : prtOptions.pagination;
var allow_colfilter = (prtOptions.allow_colfilter == undefined) ? true : prtOptions.allow_colfilter;
if (prtOptions.comUrls)
$C.grid.initComFormaters({
comUrls: prtOptions.comUrls, onOK: function () {
getHtmTemp();
}
});
else
getHtmTemp();
function getHtmTemp() {
if (prtOptions.beforeInitUI) {
var newOptions = prtOptions.beforeInitUI();
if (newOptions)
prtOptions = $.extend(prtOptions, newOptions);
}
//alert(prtOptions.istree);
if (prtOptions.istree) {
var url = (prtOptions.htmlTempt && (prtOptions.htmlTempt.length > 0)) ? prtOptions.htmlTempt : "../templet/default/reporttree.html";
}
else {
var url = (prtOptions.htmlTempt && (prtOptions.htmlTempt.length > 0)) ? prtOptions.htmlTempt : "../templet/default/report.html";
}
$.ajax({
url: url,
type: 'get',
dataType: 'text',
cache: false,
async: true,
contentType: "text/HTML; charset=utf-8",
success: function (data) {
$(data).appendTo("body");
if (prtOptions.afterLoadModel) {
prtOptions.afterLoadModel(); //加载完模板,没有渲染
}
$.parser.parse();
initUI();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$.messager.alert('错误', '获取模板文件错误!', 'error');
}
});
}
this.extendOptions = extendOptions;
function extendOptions(newOptions) {
prtOptions = $.extend(prtOptions, newOptions);
initgrid();
}
function initgrid() {
if (!prtOptions.gdListColumns) {
$.messager.alert('错误', '没有设置列表页字段!', 'error');
}
if (typeof prtOptions.gdListColumns == 'function') {
gdListColumns = prtOptions.gdListColumns();
} else {
gdListColumns = prtOptions.gdListColumns;
}
if (gdListColumns) {//兼容两种列定义方式
var col1 = gdListColumns[0];
gdListColumns = ($.isArray(col1)) ? gdListColumns : [gdListColumns];
}
defaultListGridColumsn = $.extend(true, [], gdListColumns);//复制一个默认的
gdListColumns = $InitGridColFields(gdListColumns, "dg_datalist_id");
var showFooter = (prtOptions.showFooter == undefined) ? false : prtOptions.showFooter;
if (prtOptions.istree) {
$("#dg_datalist_id").treegrid({
border: false,
showFooter: showFooter,
fitColumns: (prtOptions.fitColumns == undefined) ? false : prtOptions.fitColumns,
idField: prtOptions.idField,
treeField: prtOptions.treeField,
columns: gdListColumns
});
} else {
$("#dg_datalist_id").datagrid({
columns: [[]]
});
$("#dg_datalist_id").datagrid({
border: false,
showFooter: showFooter,
fitColumns: (prtOptions.fitColumns == undefined) ? false : prtOptions.fitColumns,
columns: gdListColumns
});
if (pagination)
inipageins("#dg_datalist_id");
}
if (prtOptions.afterInitGrid) {
prtOptions.afterInitGrid();
}
}
function initUI() {
$("#id_bt_exit").remove();
if (!allow_colfilter)
$("#id_bt_gridcolfilter").remove();
initgrid();
if ("function" != typeof TFindDialog) {
alert("需要引入cFindDlg.min.js文件");
return;
}
finddlg = new TFindDialog({
width: prtOptions.findwidth,
height: prtOptions.findheight,
findeditable: false,
findFields: prtOptions.findExtParms,
onOK: function (parms) {
return onFindWindowOK(parms);
}
});
if (prtOptions.findOptionsFilter) {
if ($(prtOptions.findOptionsFilter).length > 0) {
var panel = finddlg.getDlgLayout().layout("panel", "center");
panel.panel({
title: false,
content: $(prtOptions.findOptionsFilter).html()
});
} else
throw new error("【" + prtOptions.findOptionsFilter + "】没有元素");
}
var extButtons = (prtOptions.extButtons != undefined) ? prtOptions.extButtons : [];
for (var i = 0; i < extButtons.length; i++) {
var ebt = extButtons[i];
var id = (ebt.id) ? ebt.id : "ebt" + $generateUUID();
ebt.id = id;
var hs = "<a id='" + id + "' href='javascript:void(0)' class='easyui-linkbutton' data-options=\"plain:true,iconCls:'" + ebt.iconCls + "'\">" + ebt.text + "</a>";
if (ebt.posion) {
$(hs).insertBefore($(ebt.posion));
} else {
//$("#id_bt_new").parent().append(hs);
$(hs).insertAfter($("#id_bt_expt"));
}
$("#" + id).bind('click', ebt.handler);
}
if (extButtons.length > 0) {
$.parser.parse($("#id_bt_expt").parent());
// $.parser.parse($("#id_bt_save").parent());
}
$("#id_bt_find").linkbutton({
onClick: function () {
onClick($C.action.Find);
}
});
$("#id_bt_expt").linkbutton({
onClick: function () {
onClick($C.action.Export);
}
});
$("#id_bt_exptchart").linkbutton({
onClick: function () {
onClick($C.action.ExportChart);
}
});
$("#id_bt_exit").linkbutton({
onClick: function () {
onClick($C.action.Exit);
}
});
$("#id_bt_gridcolfilter").linkbutton({
onClick: function () {
onClick($C.action.ColsFilter);
}
});
if (!prtOptions.allowChart || prtOptions.istree) {
$("#main_tabs_id").tabs("hideHeader");
$("#main_tabs_id").tabs("close", 1);
$("#id_bt_exptchart").remove();
}
$("#find_window_id").find(".easyui-linkbutton[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
$(this).click(function () {
find_window_ok_click();
});
} else if (co.caction == "act_cancel") {
$(this).click(function () {
$('#find_window_id').window('close');
});
}
});
showChartChoicetor = (prtOptions.showChartChoicetor == undefined) ? false : prtOptions.showChartChoicetor;
if (!showChartChoicetor) {
$("#chart_layout").layout("remove", "east");
}
if (prtOptions.afterInitUI) {
var newOptions = prtOptions.afterInitUI();
if (newOptions)
prtOptions = $.extend(prtOptions, newOptions);
}
if (prtOptions.autoFind)
do_find([]);
}
function inipageins(gdfilter) {
var gd = $(gdfilter);
if (prtOptions.pageList == undefined)
prtOptions.pageList = [30, 50, 100, 300];
gd.datagrid({
// pageNumber: 1,
pagination: true,
rownumbers: true,
pageSize: prtOptions.pageList[0],
pageList: prtOptions.pageList
});
var p = gd.datagrid('getPager');
p.pagination({
beforePageText: '第',//页数文本框前显示的汉字
afterPageText: '页 共 {pages} 页',
displayMsg: '共{total}条数据'
});
}
function onClick(action) {
if (action == $C.action.Find) {
doFind();
}
if (action == $C.action.Export) {
doExport();
}
if (action == $C.action.Exit) {
//alert("Exit");
}
if (action == $C.action.ExportChart) {
doExportChart();
}
if (action == $C.action.ColsFilter) {
setColFilter();
}
}
function setColFilter() {
var grd = $("#dg_datalist_id");
$showGridColFilter(grd, defaultListGridColumsn, gdListColumns, "dg_datalist_id", function (colparms) {
grd.datagrid({data: grd.datagrid("getRows")});
}, function () {
});
}
function doExportChart() {
if ($("#placeholder").html() == "") {
alert("没有图表数据");
return;
}
$("#main_tabs_id").tabs("select", 1);
var placeholder = document.getElementById("main_tab_chart_id");
if (placeholder) {
html2canvas(placeholder, {
onrendered: function (canvas) {
var dataURL = canvas.toDataURL("image/jpeg");
console.error(dataURL);
var jsdata = {data: dataURL};
var url = _serUrl + "/web/common/getDataURLImg.co";
var wd = $("#downloadfile_form");
if (wd.length <= 0) {
$("<form id='downloadfile_form' style='display:none'><input type='hidden' name='_pjdata'/></form>").appendTo("#common_divs_id");
var wd = $("#downloadfile_form");
}
$("#downloadfile_form input").val(JSON.stringify(jsdata));
wd.attr("target", "");
wd.attr("action", url);
wd.attr("method", "post");
wd.submit();
}
});
} else {
}
}
function doFind() {
//var parms = (prtOptions.findExtParms) ? prtOptions.findExtParms.concat(prtOptions.gdListColumns()) : prtOptions.gdListColumns();
if (prtOptions.findOptionsFilter) {
finddlg.show();
//$("#find_window_id").window("open");
} else {
var parms = (prtOptions.findExtParms);
if ((parms != null) && (parms != undefined) && (parms.length > 0)) {
finddlg.show();
} else {
do_find([]);
}
}
}
function onFindWindowOK(parms) {
if (prtOptions.findOptionsFilter) {
if (prtOptions.onGetFindParms) {
var parms = prtOptions.onGetFindParms();
do_find(parms);
return true;
} else
throw new error("设置了【findOptionsFilter】属性,也必须设置【onGetFindParms】属性");
} else {
if (parms != undefined) {
if (prtOptions.onFind)
prtOptions.onFind(parms);
do_find(parms);
return true;
} else
return false;
}
}
/*
function find_window_ok_click() {
if (prtOptions.findOptionsFilter) {
if (prtOptions.onGetFindParms) {
var parms = prtOptions.onGetFindParms();
do_find(parms);
} else
throw new error("设置了【findOptionsFilter】属性,也必须设置【onGetFindParms】属性");
} else {
$C.grid.accept("dg_find_window_parms_id");
var parms = $("#dg_find_window_parms_id").datagrid("getData").rows;
do_find(parms);
}
}
*/
var extParms = {};
var perurl = undefined;
this.do_find = do_find;
function do_find(parms) {
for (var i = parms.length - 1; i >= 0; i--) {
if ((!parms[i].parmname) || (parms[i].parmname.length == 0)) {
parms.splice(i, 1);
}
}
if (!prtOptions.coURL) {
$.messager.alert('错误', '没有设置查询URL!', 'error');
return;
}
var url = (prtOptions.coURL.indexOf("?") >= 0) ? prtOptions.coURL : prtOptions.coURL + "?1=1";
if (parms.length > 0)
url = url + "&parms=" + JSON.stringify(parms);
url = url + "&dt=" + (new Date()).valueOf();
url = encodeURI(url);
_perparms = parms;
if (prtOptions.istree) {
do_getTreeData(url);
} else {
extParms.totals = getTotalInfos();
//alert(JSON.stringify(extParms.totals));
var gd = $("#dg_datalist_id");
if (pagination) {
var p = gd.datagrid("getPager");
setOnListselectPage(url);
var option = p.pagination("options");
do_getdata(url, option.pageNumber, option.pageSize);
} else {
do_getdata(url, 1, 10000);
}
}
}
function getTotalInfos() {
var totles = [];
var fcls = gdListColumns;
for (var i = 0; i < fcls.length; i++) {
var col = fcls[i];
if (col) {
if ($.isArray(col)) {
for (var j = 0; j < col.length; j++) {
var coll = col[j];
if (coll && coll.field) {
getTotlInfoCol(coll, totles);
}
}
} else {
if (col.field) {
getTotlInfoCol(col, totles);
}
}
}
}
return totles;
}
function getTotlInfoCol(col, totles) {
if (col.total_title || col.total_type) {
var t = {};
t.field = col.field;
if (col.total_title)
t.total_title = col.total_title;
if (col.total_type)
t.total_type = col.total_type;
totles.push(t);
}
}
this.setOnListselectPage = setOnListselectPage;
function setOnListselectPage(url) {
var gd = $("#dg_datalist_id");
var p = gd.datagrid("getPager");
p.pagination({
onSelectPage: function (pageNumber, pageSize) {
do_getdata(url, pageNumber, pageSize);
}
});
}
function do_getTreeData(url) {
perurl = url;
$ajaxjsonget(url, function (jsdata) {
lastLoadedData = jsdata;
if (prtOptions.beforeLoadData) {
prtOptions.beforeLoadData(jsdata);
}
$("#dg_datalist_id").treegrid("loadData", jsdata);
if (prtOptions.afterLoadData) {
prtOptions.afterLoadData(jsdata);
}
$("#find_window_id").window("close");
}, function (err) {
alert(err.errmsg);
});
}
var lastLoadedData = undefined;
this.getData = function () {
return lastLoadedData;
};
function do_getdata(url, page, pageSize) {
perurl = url;
if (!extParms)extParms = {};
$ajaxjsonpost(url + "&page=" + page + "&rows=" + pageSize, JSON.stringify(extParms),
function (jsdata) {
lastLoadedData = jsdata;
if (prtOptions.beforeLoadData) {
prtOptions.beforeLoadData(jsdata, page, pageSize, url);
}
$("#dg_datalist_id").datagrid({pageNumber: page, pageSize: pageSize});
setOnListselectPage(url);
$("#dg_datalist_id").datagrid("loadData", jsdata);
if (prtOptions.afterLoadData) {
prtOptions.afterLoadData(jsdata, page, pageSize, url);
}
if (prtOptions.allowChart && (!prtOptions.istree)) {
do_loadchart(jsdata);
}
$("#find_window_id").window("close");
}, function (err) {
alert(err.errmsg);
});
}
var allChartData = undefined, checkedChartData = undefined, loadedChartOptions = undefined;
this.getCheckedChartData = function () {
return checkedChartData;
};
this.getChartOptions = function () {
return loadedChartOptions;
};
function do_loadchart(jsdata) {
$("#main_tabs_id").tabs("select", 1);
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickDecimals: 0,
tickSize: 1
}
};
if (prtOptions.onLoadChartOptions) {
var uoptions = prtOptions.onLoadChartOptions(jsdata);
if (uoptions) {
options = uoptions;// $.extend(options, uoptions);
}
}
var data = [];
if (prtOptions.onLoadChartData) {
data = prtOptions.onLoadChartData(jsdata);
} else {
alert("显示图表需要设置【onLoadChartData】方法");
return;
}
allChartData = data;
if (showChartChoicetor)
buildChecker(allChartData);
showChart(allChartData, options);
$("#main_tabs_id").tabs("select", 0);
}
function showChart(sdata, options) {
$.plot("#placeholder", sdata, options);
checkedChartData = sdata;
loadedChartOptions = options;
if (prtOptions.afterShowChart) {
prtOptions.afterShowChart();
}
}
function buildChecker(data) {
var choiceContainer = $("#chart_choices");
choiceContainer.html("");
$.each(data, function (key, val) {
var id = "chart_choices_id_" + key;
choiceContainer.append("<br/><input type='checkbox' name='" + key +
"' checked='checked' id='" + id + "'/>" +
"<label for='" + id + "'>" + val.label + "</label>");
});
choiceContainer.find("input").click(plotAccordingToChoices);
function plotAccordingToChoices() {
var ckeddata = [];
var choiceContainer = $("#chart_choices");
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && allChartData[key]) {
ckeddata.push(allChartData[key]);
}
});
showChart(ckeddata, loadedChartOptions);
}
}
function doExport() {
if (!perurl) {
$.messager.alert('错误', '请先查询数据!', 'error');
return;
}
var fcls = gdListColumns;
for (var i = 0; i < fcls.length; i++) {
var col = fcls[i];
if (col) {
if ($.isArray(col)) {
for (var j = 0; j < col.length; j++) {
var coll = col[j];
if (coll && (coll.field)) {
parsetcolfrmatparms(coll);
}
}
} else {
if (col.field) {
parsetcolfrmatparms(col);
}
}
}
}
var _perparms = {};
_perparms.cols = fcls;
if (extParms && extParms.totals)
_perparms.totals = extParms.totals;
if (prtOptions.onExport) {
if (!prtOptions.onExport(_perparms)) return;
}
var url = perurl;
var wd = $("#downloadfile_form");
if (wd.length <= 0) {
$("<form id='downloadfile_form' style='display:none'><input type='hidden' name='_pjdata'/></form>").appendTo("#common_divs_id");
var wd = $("#downloadfile_form");
}
$("#downloadfile_form input").val(JSON.stringify(_perparms));
wd.attr("target", "");
wd.attr("action", url);
wd.attr("method", "post");
wd.submit();
}
function parsetcolfrmatparms(col) {
if (col.formatter) {
var comurl = col.formatter("get_com_url");
if (comurl) {
var multiple = (comurl["multiple"] == undefined) ? false : comurl["multiple"];
col.formatparms = {
valueField: comurl["valueField"],
textField: comurl["textField"],
jsondata: comurl["jsondata"],
multiple: multiple
};
}
if (col.formatter == $fieldDateFormatorYYYY_MM_DD) {
col.formatparms = {
fttype: "date"
}
}
}
}
this.get_finddlg = get_finddlg;
function get_finddlg() {
return finddlg;
}
}<file_sep>/src/com/corsair/server/generic/Shwnotice.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwnotice extends CJPA {
@CFieldinfo(fieldname = "noticeid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField noticeid; // ID
@CFieldinfo(fieldname = "noticecode", codeid = 29, notnull = true, caption = "通知编号", datetype = Types.VARCHAR)
public CField noticecode; // 通知编号
@CFieldinfo(fieldname = "noticetype", caption = "类别", datetype = Types.INTEGER)
public CField noticetype; // 类别
@CFieldinfo(fieldname = "title", notnull = true, caption = "标题", datetype = Types.VARCHAR)
public CField title; // 标题
@CFieldinfo(fieldname = "note", caption = "备注", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "fpname", caption = "通知文件名称", datetype = Types.VARCHAR)
public CField fpname; // 通知文件名称
@CFieldinfo(fieldname = "pfid", caption = "物理文件ID", datetype = Types.FLOAT)
public CField pfid; // 物理文件ID
@CFieldinfo(fieldname = "usable", caption = "可用", datetype = Types.FLOAT)
public CField usable; // 可用
@CFieldinfo(fieldname = "attid", caption = "附件ID", datetype = Types.INTEGER)
public CField attid; // 附件ID
@CFieldinfo(fieldname = "stat", caption = "状态", datetype = Types.INTEGER)
public CField stat; // 状态
@CFieldinfo(fieldname = "wfid", caption = "", datetype = Types.INTEGER)
public CField wfid; //
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "create_time", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField create_time; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "update_time", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField update_time; // 更新时间
@CFieldinfo(fieldname = "entid", notnull = true, caption = "组织ID", datetype = Types.FLOAT)
public CField entid; // 组织ID
@CFieldinfo(fieldname = "entname", caption = "组织名称", datetype = Types.VARCHAR)
public CField entname; // 组织名称
@CFieldinfo(fieldname = "property1", caption = "", datetype = Types.FLOAT)
public CField property1; //
@CFieldinfo(fieldname = "property2", caption = "", datetype = Types.FLOAT)
public CField property2; //
@CFieldinfo(fieldname = "property3", caption = "", datetype = Types.FLOAT)
public CField property3; //
@CFieldinfo(fieldname = "property4", caption = "", datetype = Types.FLOAT)
public CField property4; //
@CFieldinfo(fieldname = "property5", caption = "", datetype = Types.FLOAT)
public CField property5; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public CJPALineData<Shw_attach> shw_attachs;
public Shwnotice() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
shw_attachs.addLinkField("attid", "attid");
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/sms/Sms_receive.java
package com.corsair.server.sms;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Sms_receive extends CJPA {
@CFieldinfo(fieldname = "rid", iskey = true, notnull = true, datetype = Types.FLOAT)
public CField rid; // 短信ID
@CFieldinfo(fieldname = "smstype", datetype = Types.INTEGER)
public CField smstype; // 短信类型
@CFieldinfo(fieldname = "mobile", datetype = Types.VARCHAR)
public CField mobile; // 手机号
@CFieldinfo(fieldname = "content", datetype = Types.VARCHAR)
public CField content; // 短信内容
@CFieldinfo(fieldname = "flag", datetype = Types.INTEGER)
public CField flag; // 状态
@CFieldinfo(fieldname = "receivetime", datetype = Types.TIMESTAMP)
public CField receivetime; // 接收时间
@CFieldinfo(fieldname = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "creator", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "entid", notnull = true, datetype = Types.FLOAT)
public CField entid; // 组织ID
@CFieldinfo(fieldname = "entname", datetype = Types.VARCHAR)
public CField entname; // 组织名称
@CFieldinfo(fieldname = "idpath", datetype = Types.VARCHAR)
public CField idpath; // 路径
@CFieldinfo(fieldname = "property1", datetype = Types.VARCHAR)
public CField property1; //
@CFieldinfo(fieldname = "property2", datetype = Types.VARCHAR)
public CField property2; //
@CFieldinfo(fieldname = "property3", datetype = Types.VARCHAR)
public CField property3; //
@CFieldinfo(fieldname = "property4", datetype = Types.VARCHAR)
public CField property4; //
@CFieldinfo(fieldname = "property5", datetype = Types.VARCHAR)
public CField property5; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Sms_receive() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/hr/util/TimerTaskAUTOSalaryHotSub.java
package com.hr.util;
import java.util.TimerTask;
import com.corsair.dbpool.util.Logsw;
import com.hr.salary.ctr.CtrHr_salary_hotsub_qual;
import com.hr.salary.ctr.CtrHr_salary_postsub;
public class TimerTaskAUTOSalaryHotSub extends TimerTask{
@Override
public void run() {
Logsw.debug("薪资高温津贴资格到期");
try{
CtrHr_salary_hotsub_qual.scanOutTimeHotSubQual();//高温补贴资格过期
}catch(Exception e){
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/server/generic/Shwsessionct.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "记录访问量,每次启动读取,关闭保存")
public class Shwsessionct extends CJPA {
@CFieldinfo(fieldname = "scid", iskey = true, notnull = true, precision = 10, scale = 0, caption = "ID", defvalue = "1", datetype = Types.INTEGER)
public CField scid; // ID
@CFieldinfo(fieldname = "ymhh", precision = 15, scale = 0, caption = "yyyy-MM-dd HH 每个小时访问量", datetype = Types.VARCHAR)
public CField ymhh; // yyyy-MM-dd HH 每个小时访问量
@CFieldinfo(fieldname = "scnum", precision = 10, scale = 0, caption = "访问人次", defvalue = "0", datetype = Types.INTEGER)
public CField scnum; // 访问人次
@CFieldinfo(fieldname = "acactive", precision = 10, scale = 0, caption = "在线数", defvalue = "0", datetype = Types.INTEGER)
public CField acactive; // 在线数
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwsessionct() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/eai/EAIMapField.java
package com.corsair.server.eai;
public class EAIMapField {
private String s_field;
private String d_field;
private int s_fieldtype = -999;
private int d_fieldtype = -999;
public String getS_field() {
return s_field;
}
public String getD_field() {
return d_field;
}
public int getS_fieldtype() {
return s_fieldtype;
}
public int getD_fieldtype() {
return d_fieldtype;
}
public void setS_field(String s_field) {
this.s_field = s_field;
}
public void setD_field(String d_field) {
this.d_field = d_field;
}
public void setS_fieldtype(int s_fieldtype) {
this.s_fieldtype = s_fieldtype;
}
public void setD_fieldtype(int d_fieldtype) {
this.d_fieldtype = d_fieldtype;
}
}
<file_sep>/src/com/hr/.svn/pristine/9a/9a29765955bb5404378d48e22afafd83da915a36.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.hr.perm.ctr.CtrHr_emploanbatch;
import java.sql.Types;
@CEntity(controller = CtrHr_emploanbatch.class)
public class Hr_emploanbatch extends CJPA {
@CFieldinfo(fieldname = "loanid", iskey = true, notnull = true, caption = "借调单ID", datetype = Types.INTEGER)
public CField loanid; // 借调单ID
@CFieldinfo(fieldname = "loancode", codeid = 59, notnull = true, caption = "借调编码", datetype = Types.VARCHAR)
public CField loancode; // 借调编码
@CFieldinfo(fieldname = "applaydate", notnull = true, caption = "申请时间", datetype = Types.TIMESTAMP)
public CField applaydate; // 申请时间
@CFieldinfo(fieldname = "loandate", notnull = true, caption = "开始时间", datetype = Types.TIMESTAMP)
public CField loandate; // 开始时间
@CFieldinfo(fieldname = "returndate", notnull = true, caption = "归还时间", datetype = Types.TIMESTAMP)
public CField returndate; // 归还时间
@CFieldinfo(fieldname = "odorgid", caption = "借调前部门ID", datetype = Types.INTEGER)
public CField odorgid; // 借调前部门ID
@CFieldinfo(fieldname = "odorgcode", caption = "借调前部门编码", datetype = Types.VARCHAR)
public CField odorgcode; // 借调前部门编码
@CFieldinfo(fieldname = "odorgname", caption = "借调前部门名称", datetype = Types.VARCHAR)
public CField odorgname; // 借调前部门名称
@CFieldinfo(fieldname = "neworgid", caption = "借调后部门ID", datetype = Types.INTEGER)
public CField neworgid; // 借调后部门ID
@CFieldinfo(fieldname = "neworgcode", caption = "借调后部门编码", datetype = Types.VARCHAR)
public CField neworgcode; // 借调后部门编码
@CFieldinfo(fieldname = "neworgname", caption = "借调后部门名称", datetype = Types.VARCHAR)
public CField neworgname; // 借调后部门名称
@CFieldinfo(fieldname = "loanreason", caption = "借调原因", datetype = Types.VARCHAR)
public CField loanreason; // 借调原因
@CFieldinfo(fieldname = "loantype", caption = "调动范围", datetype = Types.INTEGER)
public CField loantype; // 调动范围 1内部调用 2 跨单位 3 跨模块/制造群
@CFieldinfo(fieldname = "empnum", caption = "人数", datetype = Types.INTEGER)
public CField empnum; // 人数
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", notnull = true, caption = "流程状态", datetype = Types.INTEGER)
public CField stat; // 流程状态
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Hr_emploanbatch_line.class, linkFields = { @LinkFieldItem(lfield = "loanid", mfield = "loanid") })
public CJPALineData<Hr_emploanbatch_line> hr_emploanbatch_lines;
public Hr_emploanbatch() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/eai/CEAIParamXMLFile.java
package com.corsair.server.eai;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class CEAIParamXMLFile extends CEAIParamBase {
public CEAIParamXMLFile(String xmlfname) throws Exception {
try {
loadFromXMLFile(xmlfname);
} catch (Exception e1) {
throw new Exception("初始化EAI参数文件<" + xmlfname + ">错误:" + e1.getMessage());
}
}
private void loadFromXMLFile(String xmlfname) throws Exception {
SAXReader saxReader = new SAXReader();
Document document = null;
document = saxReader.read(new File(xmlfname));
Element root = document.getRootElement();
Element name = root.element("name");
if (name == null)
throw new Exception("EAI配置文件缺少name");
this.setName(root.element("name").getText());
Element eaiclass = root.element("eaiclass");
if (eaiclass == null)
throw new Exception("EAI配置文件缺少eaiclass");
this.setEaicalss(root.element("eaiclass").getText());
Element enable = root.element("enable");
if (enable == null)
throw new Exception("EAI配置文件缺少enable");
this.setEnable(Boolean.valueOf(root.element("enable").getText()));
Element trans_type = root.element("trans_type");
if (trans_type == null)
throw new Exception("EAI配置文件缺少trans_type");
String tratstr = trans_type.getText();
if (tratstr.equalsIgnoreCase("row"))
this.setTrans_type(TRANASTYPE.row);
else if (tratstr.equalsIgnoreCase("disp"))
this.setTrans_type(TRANASTYPE.disp);
else if (tratstr.equalsIgnoreCase("none"))
this.setTrans_type(TRANASTYPE.none);
else
throw new Exception("EAI配置文件trans_type" + tratstr + "未定义");
Element eaitype = root.element("eaitype");
if (eaitype == null)
throw new Exception("EAI配置文件缺少eaitype");
String eaitypestr = eaitype.getText();
if (eaitypestr.equalsIgnoreCase("NoticePoll"))
this.setEaitype(EAITYPE.NoticePoll);
else if (eaitypestr.equalsIgnoreCase("Poll"))
this.setEaitype(EAITYPE.Poll);
else if (eaitypestr.equalsIgnoreCase("ParEAI"))
this.setEaitype(EAITYPE.ParEAI);
else
throw new Exception("EAI配置文件eaitype" + eaitypestr + "未定义");
Element frequency = root.element("frequency");
if (frequency == null)
throw new Exception("EAI配置文件缺少frequency");
this.setFrequency(Integer.valueOf(frequency.getText()));
Element dbpool_source = root.element("source");
if (dbpool_source == null)
throw new Exception("EAI配置文件缺少source");
this.setDbpool_source(dbpool_source.getText());
Element dbpool_target = root.element("target");
if (dbpool_target == null)
throw new Exception("EAI配置文件缺少target");
this.setDbpool_target(dbpool_target.getText());
Element s_tablename = root.element("s_tablename");
if (s_tablename == null)
throw new Exception("EAI配置文件缺少s_tablename");
this.setS_tablename(s_tablename.getText());
Element t_tablename = root.element("t_tablename");
if (t_tablename == null)
throw new Exception("EAI配置文件缺少t_tablename");
this.setT_tablename(t_tablename.getText());
Element lastupdatefield = root.element("lastupdatefield");
if (lastupdatefield != null)
setLastupdatefield(lastupdatefield.getText());
else
setLastupdatefield(null);
Element allow_insert = root.element("allow_insert");
if (allow_insert == null)
throw new Exception("EAI配置文件缺少allow_insert");
this.setAllow_insert(Boolean.valueOf(allow_insert.getText()));
Element childeais = root.element("childeais");
if (childeais != null) {
initChildEais(childeais);
}
Element eaimap = root.element("eaimap");
if (eaimap == null)
throw new Exception("EAI配置文件缺少eaimap");
Element keyfields = eaimap.element("keyfields");
if (keyfields == null)
throw new Exception("EAI配置文件缺少keyfields");
Element mapfields = eaimap.element("fields");
if (mapfields == null)
throw new Exception("EAI配置文件缺少fields");
Element condts = root.element("condts");
if (condts == null)
throw new Exception("EAI配置文件缺少condts");
initkeyfields(keyfields);
initmapfields(mapfields);
initcondts(condts);
}
private void initkeyfields(Element keyfields) throws Exception {
@SuppressWarnings("unchecked")
List<Element> kfds = keyfields.elements("keyfield");
if ((kfds == null) || (kfds.isEmpty())) {
throw new Exception("EAI配置文件至少需要一项keyfield");
}
for (Element kfd : kfds) {
EAIMapField ekf = new EAIMapField();
ekf.setS_field(kfd.element("s_keyfield").getText());
ekf.setD_field(kfd.element("d_keyfield").getText());
if ((ekf.getS_field() == null) || (ekf.getS_field().isEmpty())) {
throw new Exception("EAI配置文件缺少s_keyfield为空!");
}
if ((ekf.getD_field() == null) || (ekf.getD_field().isEmpty())) {
throw new Exception("EAI配置文件缺少d_keyfield为空!");
}
this.getKeyfieds().add(ekf);
}
}
private void initmapfields(Element mapfields) throws Exception {
@SuppressWarnings("unchecked")
List<Element> mfds = mapfields.elements("field");
if ((mfds == null) || (mfds.isEmpty())) {
throw new Exception("EAI配置文件至少需要一项mapfield");
}
for (Element mfd : mfds) {
EAIMapField emf = new EAIMapField();
emf.setS_field(mfd.element("s_fieldname").getText());
emf.setD_field(mfd.element("d_fieldname").getText());
if ((emf.getS_field() == null) || (emf.getS_field().isEmpty())) {
throw new Exception("EAI配置文件缺少s_fieldname为空!");
}
if ((emf.getD_field() == null) || (emf.getD_field().isEmpty())) {
throw new Exception("EAI配置文件缺少d_fieldname为空!");
}
this.getMapfields().add(emf);
}
// System.out.println("init eaimat:" + getMapfields().size());
}
@SuppressWarnings("unchecked")
private void initcondts(Element condts) throws Exception {
List<Element> econdts = condts.elements("condt");
for (Element econdt : econdts) {
CEAICondt cdt = new CEAICondt();
cdt.setField(econdt.element("field").getText());
cdt.setOper(econdt.element("oper").getText());
cdt.setValue(econdt.element("value").getText());
getCondts().add(cdt);
}
}
@SuppressWarnings("unchecked")
private void initChildEais(Element childeais) throws Exception {
List<Element> eceais = childeais.elements("childeai");
for (Element eceai : eceais) {
CChildEAIParm ceai = new CChildEAIParm();
ceai.setCldEaiName(eceai.element("name").getText());
if ((ceai.getCldEaiName() == null) || (ceai.getCldEaiName().isEmpty())) {
throw new Exception("EAI配置文件childeai 没有指定 名称");
}
List<Element> elinkfields = eceai.element("linkfields").elements("linkfield");
if (elinkfields.size() <= 0) {
throw new Exception("EAI配置文件childeai至少需要一个linkfield项目");
}
// System.out.println("fdsa");
for (Element elinkfield : elinkfields) {
EAIMapField mf = new EAIMapField();
mf.setS_field(elinkfield.element("fieldname").getText());
mf.setD_field(elinkfield.element("cfieldname").getText());
if ((mf.getS_field() == null) || mf.getS_field().isEmpty()) {
throw new Exception("EAI配置文件childeai中cfieldname不能为空!");
}
if ((mf.getD_field() == null) || mf.getD_field().isEmpty()) {
throw new Exception("EAI配置文件childeai中fieldname不能为空!");
}
ceai.getLinkfields().add(mf);
}
getChildeais().add(ceai);
}
// System.out.println(this.getName() + " " + getChildeais().size());
}
}
<file_sep>/src/com/hr/.svn/pristine/86/86c2a8ed98d657ca4f4b1fec0fe2802847dc3963.svn-base
package com.hr.base.entity;
import java.sql.Types;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import com.hr.base.ctr.CtrHr_relative;
@CEntity(controller = CtrHr_relative.class)
public class Hr_relative extends CJPA {
@CFieldinfo(fieldname = "hrvid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField hrvid; // ID
@CFieldinfo(fieldname = "hrvcode", codeid = 49, notnull = true, caption = "类型编码", datetype = Types.VARCHAR)
public CField hrvcode; // 类型编码
@CFieldinfo(fieldname = "hrvname", notnull = true, caption = "类型名称", datetype = Types.VARCHAR)
public CField hrvname; // 类型名称
@CFieldinfo(fieldname = "pid", notnull = true, caption = "上级ID", datetype = Types.INTEGER)
public CField pid; // 上级ID
@CFieldinfo(fieldname = "hrvlevel", notnull = true, caption = "分级", datetype = Types.INTEGER)
public CField hrvlevel; // 分级
@CFieldinfo(fieldname = "usable", caption = "有效状态", datetype = Types.INTEGER)
public CField usable; // 有效状态
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_relative() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/util/GetNewSEQID.java
package com.corsair.server.util;
import java.util.HashMap;
import java.util.List;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.CDBConnection.DBType;
import com.corsair.dbpool.DBPools;
public class GetNewSEQID {
public static String dogetnewid1(String tbname, int num) throws Exception {
String a[] = tbname.split("\\.");
String tablename = null;
String poolname = null;
if (a.length == 1) {
tablename = a[0];
}
if (a.length >= 2) {
poolname = a[0];
tablename = a[1];
}
if (poolname != null)
poolname = poolname.toLowerCase();
CDBConnection con = DBPools.poolByName(poolname).getCon(GetNewSEQID.class.getName());
con.startTrans();
try {
String idx = doCreateNewID(con, tablename, num);
con.submit();
return idx;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
public static String doCreateNewID(CDBConnection con, String tbname, int num) throws Exception {
String tablename = getTrueTablename(tbname);
String sqlstr = "select * from seq_all where tbname='" + tablename + "' for update";// 试着锁定行
List<HashMap<String, String>> rows = con.openSql2List(sqlstr);
if (rows.size() == 0) { // 第一次插入行
// con.openSql2List("select * from seq_all for update");// 锁表 貌似不用锁表
long idx = num + 1;
if (!tbname.equalsIgnoreCase("seq_all")) {
String sid = doCreateNewID(con, "seq_all", 1);
sqlstr = "insert into seq_all(sid,tbname,idx) values(" + sid + ",'" + tablename + "'," + idx + ")";
} else {
sqlstr = "insert into seq_all(sid,tbname,idx) values(0,'seq_all'," + idx + ")";
}
con.execsql(sqlstr);
return "1";
} else if (rows.size() == 1) {// 已经有行
HashMap<String, String> row = rows.get(0);
long idx = Long.valueOf(row.get("idx"));
long newidx = idx + num;
sqlstr = "update seq_all set idx=" + newidx + " where tbname='" + tablename + "'";
con.execsql(sqlstr);
return String.valueOf(idx);
} else if (rows.size() > 1) {
throw new Exception("序列表【" + tablename + "】发现多行数据!");
} else
throw new Exception("序列表【" + tablename + "】返回负数行,数据库连接错误?");
}
private static String getTrueTablename(String tbname) {
String a[] = tbname.split("\\.");
String tablename = (a.length == 2) ? a[1] : a[0];
tablename = tablename.toLowerCase();
if (tablename.startsWith("`"))
tablename = tablename.substring(1);
if (tablename.endsWith("`"))
tablename = tablename.substring(0, tablename.length() - 1);
return tablename;
}
public static String dogetnewid_old(CDBConnection con, String tbname, int num) throws Exception {
String a[] = tbname.split("\\.");
String tablename = (a.length == 2) ? a[1] : a[0];
tablename = tablename.toLowerCase();
if (tablename.startsWith("`"))
tablename = tablename.substring(1);
if (tablename.endsWith("`"))
tablename = tablename.substring(0, tablename.length() - 1);
String sid = getrowid_old(con, tablename);
List<HashMap<String, String>> rows = con.openSql2List("select * from seq_all where sid=" + sid + " for update");
if (rows.size() != 1) {
throw new Exception("序列表【" + tablename + "】无数据!");
}
long idx = Long.valueOf(rows.get(0).get("idx"));
long newidx = idx + num;
String sqlstr = "update seq_all set idx=" + newidx + " where sid=" + sid;
con.execsql(sqlstr);
return String.valueOf(idx);
}
private static String getrowid_old(CDBConnection con, String tablename) throws Exception {
List<HashMap<String, String>> rows = con.openSql2List("select * from seq_all where tbname='" + tablename + "'");
if (rows.size() > 1)
throw new Exception("序列表【" + tablename + "】发现多行数据!");
if (rows.size() == 0) {// 没有找到
String sqlstr = "";
if (!tablename.equalsIgnoreCase("seq_all")) {
String sid = dogetnewid_old(con, "seq_all", 1);
sqlstr = "insert into seq_all(sid,tbname,idx) values(" + sid + ",'" + tablename + "',1)";
} else {
sqlstr = "insert into seq_all(sid,tbname,idx) values(0,'seq_all',1)";
}
con.execsql(sqlstr);
rows = con.openSql2List("select * from seq_all where tbname='" + tablename + "'");
}
return rows.get(0).get("sid").toString();
}
// //reset seq
public static void resetSeq(String poolname) throws Exception {
CDBPool pool = DBPools.poolByName(poolname);
CDBConnection con = pool.getCon(GetNewSEQID.class.getName());
con.startTrans();
try {
String schema = pool.pprm.schema;
con.openSql2List("select * from seq_all for update");// 锁表
String sqlstr = null;
if (con.getDBType() == DBType.mysql)
sqlstr = "select TABLE_NAME,COLUMN_NAME from information_schema.KEY_COLUMN_USAGE where TABLE_NAME not like '_seq_%'"
+ " and CONSTRAINT_NAME='PRIMARY' and ORDINAL_POSITION=1 and TABLE_SCHEMA='" + schema + "'";
if (con.getDBType() == DBType.oracle)
sqlstr = "select cc.TABLE_NAME,cc.COLUMN_NAME from all_cons_columns cc, all_constraints ac "
+ " where cc.OWNER=ac.OWNER and cc.TABLE_NAME=ac.TABLE_NAME and ac.CONSTRAINT_NAME=cc.CONSTRAINT_NAME "
+ " and ac.CONSTRAINT_TYPE='P'and cc.CONSTRAINT_NAME not like 'BIN%' and cc.OWNER='" + schema.toUpperCase() + "'";
List<HashMap<String, String>> rows = con.openSql2List(sqlstr);
for (HashMap<String, String> row : rows) {
String tbname = row.get("TABLE_NAME").toString().toLowerCase();
String fdname = row.get("COLUMN_NAME").toString().toLowerCase();
sqlstr = "select max(" + fdname + ") mx from " + tbname;
List<HashMap<String, String>> mrows = con.openSql2List(sqlstr);
Object o = mrows.get(0).get("mx");
long idx = 0;
try {
if (o == null) {
idx = 1;
} else {
idx = Long.valueOf(o.toString()) + 1;
}
if (con.openSql2List("select * from seq_all where tbname='" + tbname + "'").size() == 0) {
String sid = doCreateNewID(con, "seq_all", 1);
con.execsql("insert into seq_all(sid,tbname,idx) values(" + sid + ",'" + tbname + "'," + idx + ")");
} else
con.execsql("update seq_all set idx=" + idx + " where tbname='" + tbname + "'");
System.out.println("reset seq table 【" + tbname + "】 Ok,idx is " + idx);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("reset seq table 【" + tbname + "】错误,略过");
}
}
con.submit();
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
// 检查 seq_all 是否存在 存在则新建
// 循环所有 非 _seq 开头的表 检索每个表主键 当前值
// 更新 seq_all表
}
}
<file_sep>/src/com/corsair/server/retention/ACO.java
package com.corsair.server.retention;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ACO {
String coname();
}
<file_sep>/src/com/hr/attd/entity/Hrkq_overtime_list.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrkq_overtime_list extends CJPA {
@CFieldinfo(fieldname = "otlistid", iskey = true, notnull = true, caption = "加班列表ID", datetype = Types.INTEGER)
public CField otlistid; // 加班列表ID
@CFieldinfo(fieldname = "oth_id", caption = "加班时间明细ID/班次ID", datetype = Types.INTEGER)
public CField oth_id; // 加班时间明细ID/班次ID
@CFieldinfo(fieldname = "otl_id", caption = "加班申请明细ID/班制ID", datetype = Types.INTEGER)
public CField otl_id; // 加班申请明细ID/班制ID
@CFieldinfo(fieldname = "otltype", notnull = true, caption = "源单类型 1 批量申请单", datetype = Types.INTEGER)
public CField otltype; // 源单类型 1 批量申请单 2 单独申请 3 班次固定加班 4上班加班 5 下班加班
@CFieldinfo(fieldname = "ot_id", notnull = true, caption = "加班申请ID", datetype = Types.INTEGER)
public CField ot_id; // 加班申请ID
@CFieldinfo(fieldname = "ot_code", notnull = true, caption = "加班申请编码", datetype = Types.VARCHAR)
public CField ot_code; // 加班申请编码
@CFieldinfo(fieldname = "kqdate", caption = "考勤日期", datetype = Types.TIMESTAMP)
public CField kqdate; // 考勤日期 针对考勤计算自动生成的加班信息
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "申请人档案ID", datetype = Types.INTEGER)
public CField er_id; // 申请人档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "申请人工号", datetype = Types.VARCHAR)
public CField employee_code; // 申请人工号
@CFieldinfo(fieldname = "employee_name", notnull = true, caption = "申请人姓名", datetype = Types.VARCHAR)
public CField employee_name; // 申请人姓名
@CFieldinfo(fieldname = "dealtype", notnull = true, caption = "加班处理 1 调休 2 计加班费", datetype = Types.INTEGER)
public CField dealtype; // 加班处理 1 调休 2 计加班费
@CFieldinfo(fieldname = "over_type", caption = "加班类型", datetype = Types.INTEGER)
public CField over_type; // 加班类型
@CFieldinfo(fieldname = "needchedksb", precision = 1, scale = 0, caption = "上班需要打卡", defvalue = "1", datetype = Types.INTEGER)
public CField needchedksb; // 上班需要打卡
@CFieldinfo(fieldname = "needchedkxb", precision = 1, scale = 0, caption = "下班需要打卡", defvalue = "1", datetype = Types.INTEGER)
public CField needchedkxb; // 下班需要打卡
@CFieldinfo(fieldname = "bgtime", notnull = false, caption = "上班时间", datetype = Types.TIMESTAMP)
public CField bgtime; // 上班时间 当otltype 为3,4,5 时候可能为空
@CFieldinfo(fieldname = "edtime", notnull = false, caption = "下班时间", datetype = Types.TIMESTAMP)
public CField edtime; // 上班时间 当otltype 为3,4,5 时候可能为空
@CFieldinfo(fieldname = "bgpktime", caption = "上班打卡时间", datetype = Types.TIMESTAMP)
public CField bgpktime; // 上班打卡时间
@CFieldinfo(fieldname = "edpktime", caption = "下班打卡时间", datetype = Types.TIMESTAMP)
public CField edpktime; // 下班打卡时间
@CFieldinfo(fieldname = "frst", caption = "上班考勤结果 1 正常 2 迟到 3早退 4未打卡", datetype = Types.INTEGER)
public CField frst; // 上班考勤结果 1 正常 2 迟到 3早退 4未打卡
@CFieldinfo(fieldname = "trst", caption = "下班考勤结果 1 正常 2 迟到 3早退 4未打卡", datetype = Types.INTEGER)
public CField trst; // 下班考勤结果 1 正常 2 迟到 3早退 4未打卡
@CFieldinfo(fieldname = "applyhours", caption = "申请时数", datetype = Types.DECIMAL)
public CField applyhours; // 申请时数
@CFieldinfo(fieldname = "otrate", notnull = true, caption = "加班倍率", datetype = Types.DECIMAL)
public CField otrate; // 加班倍率
@CFieldinfo(fieldname = "othours", caption = "加班时数", datetype = Types.DECIMAL)
public CField othours; // 加班时数
@CFieldinfo(fieldname = "deductoff", caption = "扣休息时数", datetype = Types.DECIMAL)
public CField deductoff; // 扣休息时数
@CFieldinfo(fieldname = "allfreetime", caption = "调休时长小时", datetype = Types.DECIMAL)
public CField allfreetime; // 调休时长小时
@CFieldinfo(fieldname = "freeedtime", caption = "已休息时间小时", datetype = Types.DECIMAL)
public CField freeedtime; // 已休息时间小时
@CFieldinfo(fieldname = "allotamont", caption = "加班费", datetype = Types.DECIMAL)
public CField allotamont; // 加班费
@CFieldinfo(fieldname = "payedotamont", caption = "已发放加班费", datetype = Types.DECIMAL)
public CField payedotamont; // 已发放加班费
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_overtime_list() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/cjpa/util/CLinkFieldInfo.java
package com.corsair.cjpa.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 关联注解
*
* @author Administrator
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CLinkFieldInfo {
Class<?> jpaclass();
LinkFieldItem[] linkFields();// [mfd,lfd,]
}
<file_sep>/WebContent/webapp/js/common/submainpage.js
/**
* Created by Administrator on 2014-09-19.
*/
var _menus;
$(document).ready(function () {
//gemenus();
}
);
function gemenus() {
var modid = $getPageParms().modid;
$ajaxjsonget($C.cos.getmenusbymod() + "?modid=" + modid, function (data) {
_menus = data;
buildmenus(_menus);
}, function (XMLHttpRequest, textStatus, errorThrown) {
alert("获取菜单错误!");
});
}
function haschildmenu(menuid) {
for (var i = 0; i < _menus.length; i++) {
var menu = _menus[i];
if (menu.menupid == menuid) {
return true;
break;
}
}
return false;
}
function buildmenus(menus) {
for (var i = 0; i < menus.length; i++) {
var menu = menus[i];
if ((menu.isitem == "2") && (menu.clas == "1")) {
var menubt = $("<a href='#' class='easyui-menubutton'>" + menu.language1 + "</a>").appendTo($("#menudiv_id"));
if (haschildmenu(menu.menuid)) {
menubt.attr("data-options", "menu:'#mm" + menu.menuid + "',iconCls:'" + menu.menuidpath + "'");
//创建子菜单
var submeus = $("<div id='mm" + menu.menuid + "' style='width:100px;'></div>").appendTo(menubt);
for (var j = 0; j < menus.length; j++) {
var submenu = menus[j];
if (submenu.menupid == menu.menuid) {
if (submenu.clas == "1") {
var menuiten = $("<div onclick='menuonclick(\"" + submenu.menuid + "\")'>" + submenu.language1 + "</div>").appendTo(submeus);
if (submenu.menuidpath != "") {
menuiten.attr("data-options", "iconCls:'" + submenu.menuidpath + "'");
}
} else {
$("<div class='menu-sep'></div>").appendTo(submeus);
}
}
}
}
}
}
$.parser.parse($("#menudiv_id").parent());
}
function menuonclick(menuid) {
var menu = undefined;
for (var i in _menus) {
if (_menus[i].menuid == menuid) {
menu = _menus[i];
break;
}
}
if (!menu) return false;
var title = menu.language1;
var maintab = $('#sub_main_tabs_id');
maintab.css("display", "block");
if (maintab.tabs('exists', title)) {
maintab.tabs('select', title);
} else {
var url = menu.weburl;
if ((!url) || (url.length == 0)) {
$.messager.alert('错误', '菜单没有指定URL!', 'error');
return false;
}
//console.log(url + "?menu=" + JSON.stringify(menu));
var ifid = "ifid_" + menu.menuid;
var content = "<iframe id='" + ifid + "' scrolling='no' frameborder='0' src='../" + url + "' style='width:100%;height:100%;'></iframe>";
maintab.tabs('add', {
id: 'tab' + menu.menuid,
title: title,
content: content,
iconCls: menu.menuidpath,
fit: true,
closable: true
}
);
var tab = maintab.tabs("getSelected");
tab.css("overflow", "hidden");
$("#" + ifid)[0].contentWindow._menu = menu;
}
}
<file_sep>/src/com/corsair/server/task/TaskCDay.java
package com.corsair.server.task;
import java.util.TimerTask;
import com.corsair.server.weixin.WXMsgSend;
/**
* @author Administrator
* 每天执行一次的任务
*/
public class TaskCDay extends TimerTask {
@Override
public void run() {
try {
// WXMsgSend.upDateTempleMsgList();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/src/com/corsair/server/weixin/WXTemplateMsg.java
package com.corsair.server.weixin;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
public class WXTemplateMsg {
private String touser;
private String template_id;
private String url;
private String topcolor;
private List<MsgParm> datas = new ArrayList<MsgParm>();
public class MsgParm {
private String parmname;
private String value;
private String color;
public MsgParm(String parmname, String value, String color) {
this.parmname = parmname;
this.value = value;
this.color = color;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getParmname() {
return parmname;
}
public void setParmname(String parmname) {
this.parmname = parmname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public WXTemplateMsg(String touser, String template_id, String url, String topcolor) {
this.touser = touser;
this.template_id = template_id;
this.url = url;
this.topcolor = topcolor;
}
public String getTouser() {
return touser;
}
public String getTemplate_id() {
return template_id;
}
public String getUrl() {
return url;
}
public String getTopcolor() {
return topcolor;
}
public void setTouser(String touser) {
this.touser = touser;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public void setUrl(String url) {
this.url = url;
}
public void setTopcolor(String topcolor) {
this.topcolor = topcolor;
}
public List<MsgParm> getDatas() {
return datas;
}
public String toWXJson() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartObject();
jg.writeStringField("touser", getTouser());
jg.writeStringField("template_id", getTemplate_id());
jg.writeStringField("url", getUrl());
jg.writeStringField("topcolor", getTopcolor());
jg.writeFieldName("data");
jg.writeStartObject();
for (MsgParm parm : getDatas()) {
jg.writeFieldName(parm.getParmname());
jg.writeStartObject();
jg.writeStringField("value", parm.getValue());
jg.writeStringField("color", parm.getColor());
jg.writeEndObject();
}
jg.writeEndObject();
jg.writeEndObject();
jg.close();
return baos.toString("utf-8");
}
}
<file_sep>/src/com/hr/attd/entity/Hrkq_ohyear.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrkq_ohyear extends CJPA {
@CFieldinfo(fieldname="ohid",iskey=true,notnull=true,caption="ID",datetype=Types.INTEGER)
public CField ohid; //ID
@CFieldinfo(fieldname="ohyear",notnull=true,caption="年度",datetype=Types.VARCHAR)
public CField ohyear; //年度
@CFieldinfo(fieldname="ohdate",notnull=true,caption="日期",datetype=Types.DATE)
public CField ohdate; //日期
@CFieldinfo(fieldname="iswork",caption="工作",datetype=Types.INTEGER)
public CField iswork; //工作
@CFieldinfo(fieldname="daydis",caption="显示",datetype=Types.VARCHAR)
public CField daydis; //显示
@CFieldinfo(fieldname="daymeo",caption="备注",datetype=Types.VARCHAR)
public CField daymeo; //备注
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hrkq_ohyear() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/generic/Shwuser_wf_agent.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwuser_wf_agent extends CJPA {
@CFieldinfo(fieldname = "wfagentid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField wfagentid; // ID
@CFieldinfo(fieldname = "userid", notnull = true, caption = "出差用户ID", datetype = Types.INTEGER)
public CField userid; // 出差用户ID
@CFieldinfo(fieldname = "wftempid", notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField wftempid; // ID
@CFieldinfo(fieldname = "wftempname", caption = "", datetype = Types.VARCHAR)
public CField wftempname; //
@CFieldinfo(fieldname = "auserid", notnull = true, caption = "代理用户ID", datetype = Types.INTEGER)
public CField auserid; // 代理用户ID
@CFieldinfo(fieldname = "ausername", notnull = true, caption = "代理用户名", datetype = Types.VARCHAR)
public CField ausername; // 代理用户名
@CFieldinfo(fieldname = "adisplayname", caption = "", datetype = Types.VARCHAR)
public CField adisplayname; //
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwuser_wf_agent() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/corsair/server/wordflow/Shwwftemplinkline.java
package com.corsair.server.wordflow;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwwftemplinkline extends CJPA {
@CFieldinfo(fieldname = "wftemllid", iskey = true, notnull = true, caption = "连线ID", datetype = Types.INTEGER)
public CField wftemllid; // 连线ID
@CFieldinfo(fieldname = "wftempid", notnull = true, caption = "流程模板ID", datetype = Types.INTEGER)
public CField wftempid; // 流程模板ID
@CFieldinfo(fieldname = "fromproctempid", notnull = true, caption = "源节点", datetype = Types.INTEGER)
public CField fromproctempid; // 源节点
@CFieldinfo(fieldname = "toproctempid", notnull = true, caption = "目标节点", datetype = Types.INTEGER)
public CField toproctempid; // 目标节点
@CFieldinfo(fieldname = "lltitle", caption = "标题", datetype = Types.VARCHAR)
public CField lltitle; // 标题
@CFieldinfo(fieldname = "idx", notnull = true, caption = "优先级别", datetype = Types.INTEGER)
public CField idx; // 优先级别
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
@CLinkFieldInfo(jpaclass = Shwwftemplinklinecondition.class, linkFields = { @LinkFieldItem(lfield = "wftemllid", mfield = "wftemllid") })
public CJPALineData<Shwwftemplinklinecondition> shwwftemplinklineconditions; // 条件明细
// 自关联数据定义
public Shwwftemplinkline() throws Exception {
}
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
// shwwftemplinklineconditions.addLinkField("wftemllid", "wftemllid");
return true;
}
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/test/TestThreadRunable2.java
package com.corsair.server.test;
public class TestThreadRunable2 implements Runnable {
private int thid;
private ThreadCallSourse tcs;
public TestThreadRunable2(int thid) {
this.thid = thid;
}
public TestThreadRunable2(ThreadCallSourse tcs, int thid) {
this.thid = thid;
this.tcs = tcs;
}
@Override
public void run() {
// TODO Auto-generated method stub
// (new ThreadCallSourse()).procedure(thid);
tcs.procedure2(thid);
}
}
<file_sep>/src/com/hr/.svn/pristine/31/310cb2d86613685d8d92acb0c5131ad4b63dfe8b.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_entry_try extends CJPA {
@CFieldinfo(fieldname = "entrytry_id", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField entrytry_id; // ID
@CFieldinfo(fieldname = "entry_id", notnull = true, caption = "入职单ID", datetype = Types.INTEGER)
public CField entry_id; // 入职单ID
@CFieldinfo(fieldname = "entry_code", notnull = true, caption = "入职表单编码", datetype = Types.VARCHAR)
public CField entry_code; // 入职表单编码
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "人事档案ID", datetype = Types.INTEGER)
public CField er_id; // 人事档案ID
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "employee_name", notnull = true, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "degree", caption = "学历", datetype = Types.INTEGER)
public CField degree; // 学历
@CFieldinfo(fieldname="id_number",notnull=true,caption="身份证号",defvalue="0",datetype=Types.VARCHAR)
public CField id_number; //身份证号
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "部门名称", datetype = Types.VARCHAR)
public CField orgname; // 部门名称
@CFieldinfo(fieldname = "ospid", notnull = true, caption = "职位ID", datetype = Types.INTEGER)
public CField ospid; // 职位ID
@CFieldinfo(fieldname = "ospcode", notnull = true, caption = "职位编码", datetype = Types.VARCHAR)
public CField ospcode; // 职位编码
@CFieldinfo(fieldname = "sp_name", notnull = true, caption = "职位名称", datetype = Types.VARCHAR)
public CField sp_name; // 职位名称
@CFieldinfo(fieldname = "hwc_namezl", caption = "职类", datetype = Types.VARCHAR)
public CField hwc_namezl; // 职类
@CFieldinfo(fieldname = "hg_name", caption = "职等名称", datetype = Types.VARCHAR)
public CField hg_name; // 职等名称
@CFieldinfo(fieldname = "lv_num", caption = "职级", datetype = Types.DECIMAL)
public CField lv_num; // 职级
@CFieldinfo(fieldname = "entrydate", notnull = true, caption = "入职日期", datetype = Types.TIMESTAMP)
public CField entrydate; // 入职日期
@CFieldinfo(fieldname = "probation", notnull = true, caption = "试用期", datetype = Types.INTEGER)
public CField probation; // 试用期
@CFieldinfo(fieldname = "promotionday", notnull = true, caption = "转正日期 第一次约定的试用期", datetype = Types.TIMESTAMP)
public CField promotionday; // 转正日期 第一次约定的试用期
@CFieldinfo(fieldname = "promotiondaytrue", caption = "实际转正日期 根据转正评审结果确定 如延长试用期则为空", datetype = Types.TIMESTAMP)
public CField promotiondaytrue; // 实际转正日期 根据转正评审结果确定 如延长试用期则为空
@CFieldinfo(fieldname = "wfresult", caption = "评审结果 1 同意转正 2 延长试用 3 试用不合格", datetype = Types.INTEGER)
public CField wfresult; // 评审结果 1 同意转正 2 延长试用 3 试用不合格
@CFieldinfo(fieldname = "delayprobation", caption = "延长试用期", datetype = Types.INTEGER)
public CField delayprobation; // 延长试用期
@CFieldinfo(fieldname = "delaypromotionday", caption = "延期待转正时间 根据延长试用期自动计算,多次延期累计计算", datetype = Types.TIMESTAMP)
public CField delaypromotionday; // 延期待转正时间 根据延长试用期自动计算,多次延期累计计算
@CFieldinfo(fieldname = "delaypromotiondaytrue", caption = "延期实际转正时间", datetype = Types.TIMESTAMP)
public CField delaypromotiondaytrue; // 延期实际转正时间
@CFieldinfo(fieldname = "delaywfresult", caption = "评审结果 1 同意转正 2 延长试用 3 试用不合格", datetype = Types.INTEGER)
public CField delaywfresult; // 评审结果 1 同意转正 2 延长试用 3 试用不合格
@CFieldinfo(fieldname = "delaytimes", caption = "延期次数", datetype = Types.INTEGER)
public CField delaytimes; // 延期次数
@CFieldinfo(fieldname = "trystat", notnull = true, caption = "试用期人事状态 试用期中、试用过期、试用延期、己转正、试用不合格", datetype = Types.INTEGER)
public CField trystat; // 试用期人事状态 试用期中、试用过期、试用延期、己转正、试用不合格
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1 调动自动转正
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
@CFieldinfo(fieldname = "pay_way", caption = "计薪方式", datetype = Types.VARCHAR)
public CField pay_way; // 计薪方式
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_entry_try() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/attd/entity/Hrkq_overtime_qual_line.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrkq_overtime_qual_line extends CJPA {
@CFieldinfo(fieldname="oql_id",iskey=true,notnull=true,caption="加班资格行ID",datetype=Types.INTEGER)
public CField oql_id; //加班资格行ID
@CFieldinfo(fieldname="oq_id",notnull=true,caption="加班资格申请ID",datetype=Types.INTEGER)
public CField oq_id; //加班资格申请ID
@CFieldinfo(fieldname="breaked",caption="已终止",defvalue="2",datetype=Types.INTEGER)
public CField breaked; //已终止
@CFieldinfo(fieldname="er_id",notnull=true,caption="员工档案ID",datetype=Types.INTEGER)
public CField er_id; //员工档案ID
@CFieldinfo(fieldname="employee_code",notnull=true,caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname="employee_name",notnull=true,caption="姓名",datetype=Types.VARCHAR)
public CField employee_name; //姓名
@CFieldinfo(fieldname="orgid",notnull=true,caption="部门ID",datetype=Types.INTEGER)
public CField orgid; //部门ID
@CFieldinfo(fieldname="orgcode",notnull=true,caption="部门编码",datetype=Types.VARCHAR)
public CField orgcode; //部门编码
@CFieldinfo(fieldname="orgname",notnull=true,caption="部门名称",datetype=Types.VARCHAR)
public CField orgname; //部门名称
@CFieldinfo(fieldname="lv_id",caption="职级ID",datetype=Types.INTEGER)
public CField lv_id; //职级ID
@CFieldinfo(fieldname="lv_num",caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="ospid",caption="职位ID",datetype=Types.INTEGER)
public CField ospid; //职位ID
@CFieldinfo(fieldname="ospcode",caption="职位编码",datetype=Types.VARCHAR)
public CField ospcode; //职位编码
@CFieldinfo(fieldname="sp_name",caption="职位名称",datetype=Types.VARCHAR)
public CField sp_name; //职位名称
@CFieldinfo(fieldname = "orghrlev", caption = "机构人事层级", datetype = Types.INTEGER)
public CField orghrlev; // 机构人事层级
@CFieldinfo(fieldname = "emplev", caption = "人事层级", datetype = Types.INTEGER)
public CField emplev; // 人事层级
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hrkq_overtime_qual_line() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/WebContent/webapp/js/common/shwmodmenu.js
/**
* Created by Administrator on 2014-10-15.
*/
$(document).ready(function () {
getAllMods();
$("#mod_form").c_initDictionary();
$("#menu_form").c_initDictionary();
testcss();
});
function setNodeIco(t, node) {
if (t == "MOD") {
node.usesable = node.state;
node.iconCls = node.modidpath;
}
if (t == "MENU") {
node.usesable = node.state;
if (node.clas == 1) {
if (node.isitem == 1) {
node.iconCls = "icon-text_ab";
}
if (node.isitem == 2) {
node.iconCls = "icon-folder";
}
}
if (node.clas == 2) {
node.iconCls = "icon-text_horizontalrule";
}
}
}
function setNodesIco(t, nodes) {
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
setNodeIco(t, node);
if (node.children) {
setNodesIco(t, node.children);
}
}
}
function getAllMods() {
var url = $C.cos.getModTree + "?roleid=-1";//-1 获取所有模块 不设置checkbox
$ajaxjsonget(url, function (jsondata) {
setNodesIco("MOD", jsondata);
$("#modtree").tree({data: jsondata});
}, function () {
alert("错误");
});
}
function modclick() {
var node = $("#modtree").tree("getSelected");
if (!node) return;
$ajaxjsonget($C.cos.getModMenuTree + "?roleid=-1&modid=" + node.id + "&type=all",
function (jsondata) {
setNodesIco("MENU", jsondata);
for (var i = 0; i < jsondata.length; i++) {
jsondata[i].state = "closed";
}
$("#menutree").tree("loadData", jsondata);
},
function () {
});
}
function modDClick() {
modmenu_action(1, $C.action.Edit);
}
function menuDClick() {
modmenu_action(2, $C.action.Edit)
}
function modmenu_action(t, act) {
if (t == 1) {
modaction(act);
}
if (t == 2) {
menuaction(act);
}
}
function modaction(act) {
var isnew, jsondata;
var otb = $('#modtree');
var node = otb.tree('getSelected');
var popw = $("#mod_info_w");
if (act == $C.action.New) {
isnew = true;
jsondata = {};
jsondata.modpid = 53;
jsondata.isitem = 2;
jsondata.usesable = 1;
jsondata.issystem = 2;
}
if (act == $C.action.New2) {
if (!node) {
$.messager.alert('错误', '没选定的模块!', 'error');
return;
}
isnew = true;
jsondata = {};
jsondata.usesable = 1;
jsondata.issystem = 2;
jsondata.isitem = 1;
if (node.isitem == 1) {
jsondata.modpid = node.modpid;
}
if (node.isitem == 2) {
jsondata.modpid = node.modid;
}
} else if (act == $C.action.Edit) {
if (!node) {
$.messager.alert('错误', '没选定的模块!', 'error');
return;
}
isnew = false;
jsondata = node;
} else if (act == $C.action.Del) {
if (!node) {
$.messager.alert('错误', '没选定的角色!', 'error');
return;
}
//do del
$.messager.confirm('提醒', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delMod + "?modid=" + node.modid, function (jsondata) {
if (jsondata.result == "OK")
otb.tree("remove", node.target);
}, function () {
$.messager.alert('错误', '删除模块错误!', 'error');
});
}
});
return;
}
popw.c_popInfo({
isNew: isnew,
jsonData: jsondata,
onOK: function (jsondata) {
jsondata.state = jsondata.usesable;//冲突
$ajaxjsonpost($C.cos.saveMod, JSON.stringify(jsondata), function (reData) {
jsondata.id = jsondata.modid;
jsondata.usesable = jsondata.state;
jsondata.text = jsondata.modname;
jsondata.iconCls = jsondata.modidpath;
if (isnew) {
if (jsondata.isitem == 2) {
otb.tree("append", {data: [jsondata]});
} else {
otb.tree("append", {parent: otb.tree("find", jsondata.modpid).target, data: [jsondata]});
}
} else {
jsondata.target = node.target;
otb.tree("update", jsondata);
}
}, function () {
alert("保存错误!");
});
return true;
}
});
}
function testcss() {
var ics = "easyui/themes/icon.css";
var ss = undefined;
for (var i = 0; i < document.styleSheets.length; i++) {
ss = document.styleSheets[i];
var href = ss.href;
if (href.substr(href.length - ics.length, ics.length) == ics)
break;
}
if (!ss) return;
var rus = ss.cssRules || ss.rules;
var icons = [];
for (var i = 0; i < rus.length; i++) {
var s = rus[i].selectorText;
s = s.substr(1, s.length - 1);
icons.push({id: s, text: s});
}
$("#modidpath_id").combobox({
data: icons,
valueField: 'id',
textField: 'text',
formatter: function (row) {
return "<span class=" + row.text + " style='width:50px'>      </span>";
}
});
$("#menuidpath_id").combobox({
data: icons,
valueField: 'id',
textField: 'text',
formatter: function (row) {
return "<span class=" + row.text + " style='width:50px'>      </span>";
}
});
}
function menuaction(act) {
var isnew, jsondata;
var otb = $('#menutree');
var node = otb.tree('getSelected');
var popw = $("#menu_info_w");
if (act == $C.action.New) {
isnew = true;
jsondata = {};
jsondata.menupid = 21;
jsondata.isitem = 2;
jsondata.usesable = 1;
jsondata.issystem = 2;
jsondata.clas = 1;
jsondata.modid = $('#modtree').tree('getSelected').modid;
}
if (act == $C.action.New2) {
if (!node) {
$.messager.alert('错误', '没选定的菜单!', 'error');
return;
}
isnew = true;
jsondata = {};
jsondata.usesable = 1;
jsondata.issystem = 2;
jsondata.isitem = 1;
jsondata.clas = 1;
jsondata.modid = $('#modtree').tree('getSelected').modid;
if (node.isitem == 1) {
jsondata.menupid = node.menupid;
}
if (node.isitem == 2) {
jsondata.menupid = node.menuid;
}
} else if (act == $C.action.Edit) {
if (!node) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
isnew = false;
jsondata = node;
} else if (act == $C.action.Del) {
if (!node) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
//do del
$.messager.confirm('提醒', '确认删除?', function (r) {
if (r) {
$ajaxjsonget($C.cos.delMenu + "?menuid=" + node.menuid, function (jsondata) {
if (jsondata.result == "OK")
otb.tree("remove", node.target);
}, function () {
$.messager.alert('错误', '删除菜单错误!', 'error');
});
}
});
return;
}
loadMenuCosTree(jsondata.menuid);
popw.c_popInfo({
isNew: isnew,
jsonData: jsondata,
onOK: function (jsondata) {
jsondata.state = jsondata.usesable;//冲突
jsondata.cos = getCheckedCos();
//console.error(JSON.stringify(jsondata));
$ajaxjsonpost($C.cos.saveMenu, JSON.stringify(jsondata), function (jsondata) {
jsondata.id = jsondata.menuid;
jsondata.usesable = jsondata.state;
jsondata.text = jsondata.menuname;
setNodeIco("MENU", jsondata);
if (isnew) {
if (jsondata.isitem == 2) {
otb.tree("append", {data: [jsondata]});
} else {
otb.tree("append", {parent: otb.tree("find", jsondata.menupid).target, data: [jsondata]});
}
} else {
jsondata.target = node.target;
otb.tree("update", jsondata);
}
}, function () {
alert("保存错误!");
});
return true;
}
});
}
function loadMenuCosTree(menuid) {
if ($isEmpty(menuid))
menuid = -1;
var url = _serUrl + "/web/common/getCoTreeMenu.co?menuid=" + menuid;
$ajaxjsonget(url, function (jsdata) {
$("#cotreeid").tree("loadData", jsdata);
}, function (msg) {
alert("获取菜单CO错误:" + msg);
});
}
function onCoTreeSelect(node) {
if (!node) return;
if (node.method)
$("#methodid").html(node.method);
else
$("#methodid").html("");
if (node.auth != undefined)
$("#authid").html(node.auth);
else
$("#authid").html("");
if (node.note)
$("#noteid").html(node.note);
else
$("#noteid").html("");
}
function getCheckedCos() {
var nodes = $("#cotreeid").tree("getChecked");
var cos = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.name) {
cos.push({name: node.name});
}
}
return cos;
}
var copyedMenuCos = undefined;
function onmenutreemenushow() {
var item = $('#menutree_menu').menu('findItem', '粘贴CO权限');
if (copyedMenuCos == undefined)
$('#menutree_menu').menu('disableItem', item.target);
else
$('#menutree_menu').menu('enableItem', item.target);
}
function copyMCos() {
var node = $('#menutree').tree('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
var menuid = node.menuid;
if ($isEmpty(menuid)) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
var url = _serUrl + "/web/common/getCosByMenu.co?menuid=" + menuid;
$ajaxjsonget(url, function (jsdata) {
copyedMenuCos = undefined;
copyedMenuCos = jsdata;
$.messager.alert('提示', '已复制【' + jsdata.length + '】条CO!');
}, function (msg) {
alert("获取菜单CO错误:" + msg);
});
}
function pastMCos() {
if (copyedMenuCos == undefined) {
$.messager.alert('错误', '请先复制菜单CO!', 'error');
return;
}
var node = $('#menutree').tree('getSelected');
if (!node) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
var menuid = node.menuid;
if ($isEmpty(menuid)) {
$.messager.alert('错误', '没选定的数据!', 'error');
return;
}
$.messager.confirm('确认', '粘贴后将会覆盖菜单【' + node.menuname + '】CO权限,确认继续?', function (r) {
if (r) {
var postdata = {mueuid: menuid, conames: copyedMenuCos};
var url = _serUrl + "/web/menu/saveMenuCos.co";
$ajaxjsonpost(url, JSON.stringify(postdata), function (jsondata) {
copyedMenuCos = undefined;
$.messager.alert('提示', '完成粘贴!');
}, function (msg) {
$.messager.alert('错误', '粘贴数据错误:' + msg, 'error');
});
}
});
}
<file_sep>/src/com/hr/.svn/pristine/63/636a12e079776eec5535a50f5ce2e3d079c954ad.svn-base
package com.hr.pm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hrpm_rstmonthex extends CJPA {
@CFieldinfo(fieldname="pmmrid",iskey=true,notnull=true,caption="ID",datetype=Types.INTEGER)
public CField pmmrid; //ID
@CFieldinfo(fieldname="er_id",caption="人事ID",datetype=Types.INTEGER)
public CField er_id; //人事ID
@CFieldinfo(fieldname="employee_code",caption="工号",datetype=Types.VARCHAR)
public CField employee_code; //工号
@CFieldinfo(fieldname="employee_name",caption="姓名",datetype=Types.VARCHAR)
public CField employee_name; //姓名
@CFieldinfo(fieldname="pmtype",caption="1 主职 2 兼职",defvalue="1",datetype=Types.INTEGER)
public CField pmtype; //1 主职 2 兼职
@CFieldinfo(fieldname="orgname",caption="机构",datetype=Types.VARCHAR)
public CField orgname; //机构
@CFieldinfo(fieldname="sp_name",caption="职位",datetype=Types.VARCHAR)
public CField sp_name; //职位
@CFieldinfo(fieldname="lv_num",caption="职级",datetype=Types.DECIMAL)
public CField lv_num; //职级
@CFieldinfo(fieldname="pmyear",caption="年",datetype=Types.INTEGER)
public CField pmyear; //年
@CFieldinfo(fieldname="pmonth",caption="月",datetype=Types.INTEGER)
public CField pmonth; //月
@CFieldinfo(fieldname="qrst",caption="绩效",datetype=Types.DECIMAL)
public CField qrst; //绩效
@CFieldinfo(fieldname="createtime",caption="创建时间",datetype=Types.TIMESTAMP)
public CField createtime; //创建时间
@CFieldinfo(fieldname="remark",caption="备注",datetype=Types.VARCHAR)
public CField remark; //备注
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hrpm_rstmonthex() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/inface/entity/View_ICCO_AssignEmp.java
package com.hr.inface.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(dbpool = "oldtxmssql", tablename = "dbo.view_ICCO_AssignEmp")
public class View_ICCO_AssignEmp extends CJPA {
@CFieldinfo(fieldname="card_id",notnull=true,caption="card_id",datetype=Types.NVARCHAR)
public CField card_id; //card_id
@CFieldinfo(fieldname="clock_id",notnull=true,caption="clock_id",datetype=Types.INTEGER)
public CField clock_id; //clock_id
@CFieldinfo(fieldname="opDate",caption="opDate",datetype=Types.TIMESTAMP)
public CField opDate; //opDate
@CFieldinfo(fieldname="join_id",caption="join_id",datetype=Types.INTEGER)
public CField join_id; //join_id
@CFieldinfo(fieldname="card_sn",caption="card_sn",datetype=Types.NVARCHAR)
public CField card_sn; //card_sn
@CFieldinfo(fieldname="depart_id",caption="depart_id",datetype=Types.VARCHAR)
public CField depart_id; //depart_id
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public View_ICCO_AssignEmp() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/01/01eedc3f0e246bdd31a619f0a957ad30f52d8e24.svn-base
package com.hr.inface.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(dbpool = "oldtxmssql", tablename = "View_Hrms_TXJocatConfig")
public class View_Hrms_TXJocatConfig extends CJPA {
@CFieldinfo(fieldname="id",iskey=true,notnull=true,caption="id",datetype=Types.INTEGER)
public CField id; //id
@CFieldinfo(fieldname="jh",notnull=true,caption="消费机编号",datetype=Types.INTEGER)
public CField jh; //消费机编号
@CFieldinfo(fieldname="lx",notnull=true,caption="名称",datetype=Types.VARCHAR)
public CField lx; //名称
@CFieldinfo(fieldname="ip",notnull=true,caption="消费机ip",datetype=Types.VARCHAR)
public CField ip; //消费机ip
@CFieldinfo(fieldname="bz",notnull=true,caption="消费机地址",datetype=Types.VARCHAR)
public CField bz; //消费机地址
@CFieldinfo(fieldname="zt",notnull=true,caption="状态 1可用,0不可用",datetype=Types.INTEGER)
public CField zt; //状态 1可用,0不可用
@CFieldinfo(fieldname="sd1",notnull=true,caption="早餐",datetype=Types.VARCHAR)
public CField sd1; //早餐
@CFieldinfo(fieldname="sd2",notnull=true,caption="早餐",datetype=Types.VARCHAR)
public CField sd2; //早餐
@CFieldinfo(fieldname="sd3",notnull=true,caption="中餐",datetype=Types.VARCHAR)
public CField sd3; //中餐
@CFieldinfo(fieldname="sd4",notnull=true,caption="中餐",datetype=Types.VARCHAR)
public CField sd4; //中餐
@CFieldinfo(fieldname="sd5",notnull=true,caption="晚餐",datetype=Types.VARCHAR)
public CField sd5; //晚餐
@CFieldinfo(fieldname="sd6",notnull=true,caption="晚餐",datetype=Types.VARCHAR)
public CField sd6; //晚餐
@CFieldinfo(fieldname="sd7",notnull=true,caption="夜宵",datetype=Types.VARCHAR)
public CField sd7; //夜宵
@CFieldinfo(fieldname="sd8",notnull=true,caption="夜宵",datetype=Types.VARCHAR)
public CField sd8; //夜宵
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public View_Hrms_TXJocatConfig() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/card/co/COHr_ykt_card_loss.java
package com.hr.card.co;
import java.util.Date;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.access.co.COHr_access_emauthority_list;
import com.hr.access.ctr.UtilAccess;
import com.hr.asset.entity.Hr_asset_reject_h;
import com.hr.card.entity.Hr_ykt_card;
import com.hr.card.entity.Hr_ykt_card_clean;
import com.hr.card.entity.Hr_ykt_card_loss;
import com.hr.card.entity.Hr_ykt_card_publish;
import com.hr.perm.entity.Hr_employee;
import com.hr.card.co.COHr_ykt_card_clean;
@ACO(coname = "web.hr.Card")
public class COHr_ykt_card_loss extends JPAController {
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doupcardloss(jpa, con);
doUpdateAcS(con, jpa);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc,
Shwwfproc nxtproc, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doupcardloss(jpa, con);
doUpdateAcS(con, jpa);
}
}
/**
* 离职自动挂失
*
* @param con
* @param er_id
* @throws Exception
*/
public static void doLeaveLoss(CDBConnection con, String er_id, String remark) throws Exception {
Hr_ykt_card_loss ycl = new Hr_ykt_card_loss();
String sqlstr = "SELECT * FROM hr_ykt_card WHERE card_stat=1 AND er_id=" + er_id;
Hr_ykt_card card = new Hr_ykt_card();
card.findBySQL(con, sqlstr, false);
if (card.isEmpty()) {
return;// throw new Exception("无正在使用的卡,无法挂失");
}
Hr_employee he = new Hr_employee();
he.findByID(con, er_id);
if (he.isEmpty())
return;
ycl.employee_code.setValue(he.employee_code.getValue());
ycl.employee_name.setValue(he.employee_name.getValue());
ycl.card_number.setValue(he.card_number.getValue());
ycl.er_id.setValue(he.er_id.getValue());
ycl.er_code.setValue(he.er_code.getValue());
ycl.orgid.setValue(he.orgid.getValue());
ycl.orgcode.setValue(he.orgcode.getValue());
ycl.orgname.setValue(he.orgname.getValue());
ycl.sp_name.setValue(he.sp_name.getValue());
ycl.hwc_namezl.setValue(he.hwc_namezl.getValue());
ycl.hwc_namezq.setValue(he.hwc_namezq.getValue());
ycl.hwc_namezz.setValue(he.hwc_namezz.getValue());
ycl.hg_name.setValue(he.hg_name.getValue());
ycl.lv_num.setValue(he.lv_num.getValue());
ycl.idpath.setValue(he.idpath.getValue());
ycl.card_id.setValue(card.card_id.getValue());
ycl.card_sn.setValue(card.card_sn.getValue());
ycl.card_number.setValue(card.card_number.getValue());
ycl.card_stat.setValue(card.card_stat.getValue());
ycl.remark.setValue(remark);
ycl.save(con);
ycl.wfcreate(null, con);// 自动提交
}
// 更新门禁权限列表
public static void doUpdateAcS(CDBConnection con, CJPA jpa) throws Exception {
Hr_ykt_card_loss ycl = new Hr_ykt_card_loss();
String sqlstr = "UPDATE hr_access_emauthority_sum t" +
" SET t.access_status = '2'," +
" t.accrediter = 'SYSTEM'," +
" t.accredit_date = NOW()," +
" t.attribute1 = 'Y'," +
" t.remarks = '清卡关闭'" +
" WHERE t.employee_code = '" + ycl.employee_code.getValue() + "'" +
" AND t.access_card_number = '" + ycl.card_number.getValue() + "' and t.access_status=1 ";
con.execsql(sqlstr);
}
// 更新卡档案数据
private void doupcardloss(CJPA jpa, CDBConnection con) throws Exception {
Hr_employee he = new Hr_employee();
Hr_ykt_card_loss ycl = (Hr_ykt_card_loss) jpa;
Hr_ykt_card yc = new Hr_ykt_card();
// Hr_employee he = new Hr_employee();
String sqlstr = "SELECT * FROM hr_ykt_card WHERE card_id= " + ycl.card_id.getValue();
yc.findBySQL(con, sqlstr, false);
yc.card_number.setValue(ycl.card_number.getValue());
yc.card_stat.setValue("2");
yc.er_id.setValue(ycl.er_id.getValue());
yc.er_code.setValue(ycl.er_code.getValue());
yc.employee_code.setValue(ycl.employee_code.getValue());
yc.employee_name.setValue(ycl.employee_name.getValue());
yc.orgid.setValue(ycl.orgid.getValue());
yc.orgcode.setValue(ycl.orgcode.getValue());
yc.orgname.setValue(ycl.orgname.getValue());
yc.sp_name.setValue(ycl.sp_name.getValue());
yc.hwc_namezl.setValue(ycl.hwc_namezl.getValue());
yc.hwc_namezq.setValue(ycl.hwc_namezq.getValue());
yc.hwc_namezz.setValue(ycl.hwc_namezz.getValue());
yc.hg_name.setValue(ycl.hg_name.getValue());
yc.lv_num.setValue(ycl.lv_num.getValue());
yc.disable_date.setAsDatetime(new Date());
yc.save(con, false);
// 清空人事档案中的卡信息
String sqlstr1 = "SELECT * FROM hr_employee WHERE er_id = " + ycl.er_id.getValue();
he.findBySQL(con, sqlstr1, false);
he.card_number.setValue("");
he.save(con, false);
// COHr_access_emauthority_list.doUpdateAccessList(con, yc.employee_code.getValue(), 8, ycl.card_loss_no.getValue(), "卡挂失");
UtilAccess.disableAllAccessByEmpid(con, he.er_id.getAsInt(), "挂失禁用权限");
}
@ACOAction(eventname = "saveloss", Authentication = true, notes = "自定义保存")
public String saveloss() throws Exception {
Hr_ykt_card_loss ycl = new Hr_ykt_card_loss();
ycl.fromjson(CSContext.getPostdata());
if (ycl.card_id.isEmpty()) {
String sqlstr = "SELECT * FROM hr_ykt_card WHERE card_stat=1 AND er_id=" + ycl.er_id.getValue();
Hr_ykt_card card = new Hr_ykt_card();
card.findBySQL(sqlstr);
if (card.isEmpty()) {
throw new Exception("无正在使用的卡,无法挂失");
}
ycl.card_id.setValue(card.card_id.getValue());
ycl.card_sn.setValue(card.card_sn.getValue());
ycl.card_number.setValue(card.card_number.getValue());
ycl.card_stat.setValue(card.card_stat.getValue());
}
ycl.save();
ycl.wfcreate(null);// 自动提交
return ycl.tojson();
}
@ACOAction(eventname = "findemp4loss", Authentication = true, notes = "查找可以挂失的人事资料")
public String findemp4loss() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String eparms = parms.get("parms");
List<JSONParm> jps = CJSON.getParms(eparms);
Hr_employee he = new Hr_employee();
String where = CjpaUtil.buildFindSqlByJsonParms(he, jps);
String orgid = CorUtil.hashMap2Str(parms, "orgid");
String sqlstr = "SELECT * FROM hr_employee "
+ " WHERE EXISTS( "
+ " SELECT 1 FROM hr_ykt_card WHERE hr_employee.er_id=hr_ykt_card.er_id AND hr_ykt_card.card_stat=1 "
+ " )";
if ((orgid != null) && (!orgid.isEmpty())) {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("没发现ID为【" + orgid + "】的机构");
where = where + " and idpath like '" + org.idpath.getValue() + "%'";
}
String smax = parms.get("max");
int max = (smax == null) ? 300 : Integer.valueOf(smax);
sqlstr = sqlstr + CSContext.getIdpathwhere() + where + " limit 0," + max;
return DBPools.defaultPool().opensql2json(sqlstr);
}
}
<file_sep>/src/com/hr/canteen/ctr/CtrHr_canteen_mealsystem.java
package com.hr.canteen.ctr;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.hr.canteen.entity.Hr_canteen_mealsystem;
public class CtrHr_canteen_mealsystem extends JPAController{
@Override
public String OnCCoVoid(CDBConnection con, CJPA jpa) throws Exception {
// TODO Auto-generated method stub
Hr_canteen_mealsystem ms=(Hr_canteen_mealsystem)jpa;
ms.usable.setAsInt(2);
ms.save(con);
return null;
}
}
<file_sep>/src/com/hr/util/HRUtil.java
package com.hr.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.mail.CMailInfo;
import com.corsair.server.util.HttpTookit;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.corsair.server.wordflow.Shwwfprocuser;
import com.hr.perm.entity.Hr_employee_transfer;
import com.hr.perm.entity.Hr_entry_prob;
import com.hr.perm.entity.Hr_transfer_prob;
import com.hr.salary.entity.Hr_salary_specchgsa;
import com.hr.util.hrmail.DLHRMailCenterWS;
import com.hr.util.hrmail.Hr_emailsend_log;
public class HRUtil {
public static boolean RunSendWxflag=true;//微信推送变量
public static boolean RunSendWxPersonflag=true;//推送人员考勤数据
public static boolean RunCalcKqDepartFlag=true;//运算部门考勤数据
public static CDBPool getReadPool() {
return DBPools.poolByName("dlhrread");
}
// 机构人事层级
public static int getOrgHrLev(String orgid) throws Exception {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty()) {
throw new Exception("ID为【" + orgid + "】的机构不存在");
}
if (org.idpath.isEmpty())
throw new Exception("机构【" + org.code.getValue() + "】的IDPATH为空");
String idps = org.idpath.getValue();
idps = idps.substring(0, idps.length() - 1);
String sqlstr = "select * from shworg where orgid in(" + idps + ")";
CJPALineData<Shworg> orgs = new CJPALineData<Shworg>(Shworg.class);
orgs.findDataBySQL(sqlstr, true, false);
int hrlev = 1;
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (o.orgtype.getAsIntDefault(0) == 6) {
hrlev = 3;
break;
}
}
if (hrlev == 1) {
for (CJPABase jpa : orgs) {
Shworg o = (Shworg) jpa;
if (o.orgtype.getAsIntDefault(0) == 4) {
hrlev = 2;
break;
}
}
}
return hrlev;
}
public static JSONArray getOrgsByType(String orgtypes) throws Exception {
String sqlstr = "SELECT * FROM shworg WHERE usable=1 " + CSContext.getIdpathwhere()
+ "AND orgtype IN (" + orgtypes + ") ORDER BY orgid ";
Shworg org = new Shworg();
return org.pool.opensql2json_O(sqlstr);
}
/**
* @param orgid
* @param includechild //是否包含子机构
* @return 获取机构数组
* @throws Exception
*/
public static JSONArray getOrgsByOrgid(String orgid, boolean includechild, List<String> yearmonths) throws Exception {
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
JSONArray orgs = new JSONArray();
if (includechild) {
String sqlstr = "SELECT * FROM shworg WHERE usable=1 " + CSContext.getIdpathwhere()
+ "AND superid=" + orgid + " ORDER BY orgid ";
JSONArray orgjos = org.pool.opensql2json_O(sqlstr);
for (int i = 0; i < orgjos.size(); i++) {
orgjos.getJSONObject(i).put("_incc", 1);
}
orgs = orgjos;
}
JSONObject orgjo = org.toJsonObj();
if (includechild) {
orgjo.put("_incc", 2);
} else {
orgjo.put("_incc", 1);
}
orgs.add(0, orgjo);
JSONArray rst = new JSONArray();
for (String yearmonth : yearmonths) {
for (int i = 0; i < orgs.size(); i++) {
orgs.getJSONObject(i).put("yearmonth", yearmonth);
}
rst.addAll(orgs);
}
return rst;
}
public static List<String> buildYeatMonths(String yearmonth_begin, String yearmonth_end, int maxm) throws Exception {
Date bgdate = Systemdate.getDateByStr(yearmonth_begin);
Date eddate = Systemdate.getDateByStr(yearmonth_end);
if (eddate.getTime() < bgdate.getTime())
throw new Exception("开始月度大于截止月度");
List<String> rst = new ArrayList<String>();
Date tempDate = bgdate;
while (tempDate.getTime() <= eddate.getTime()) {
System.out.println("yearmonths:" + Systemdate.getStrDateByFmt(tempDate, "yyyy-MM"));
rst.add(Systemdate.getStrDateByFmt(tempDate, "yyyy-MM"));
tempDate = Systemdate.dateMonthAdd(tempDate, 1);
}
if (rst.size() > maxm)
throw new Exception("不能超过" + maxm + "个月");
return rst;
}
public static JSONArray getOrgsByPid(String superid) throws Exception {
String sqlstr = "SELECT * FROM shworg WHERE usable=1 " + CSContext.getIdpathwhere()
+ "AND superid=" + superid + " ORDER BY orgid ";
Shworg org = new Shworg();
return org.pool.opensql2json_O(sqlstr);
}
public static void OnArriveProcSendMail(Shwwf wf, Shwwfproc proc) {
}
public static void sendProcBrockMail(Shwwf wf) throws Exception {
String sqlstr = "SELECT DISTINCT * FROM( SELECT l.* FROM hr_emailsend_log l, shwwfprocuser u WHERE l.extid=u.procid AND u.wfid=" + wf.wfid.getValue() + ") tb";
CJPALineData<Hr_emailsend_log> els = new CJPALineData<Hr_emailsend_log>(Hr_emailsend_log.class);
els.findDataBySQL(sqlstr);
for (CJPABase jpa : els) {
Hr_emailsend_log el = (Hr_emailsend_log) jpa;
System.out.println("delMail:" + el.aynemid.getValue() + " sqlstr:" + sqlstr);
DLHRMailCenterWS.delMail(el.aynemid.getValue());
el.removed.setAsInt(1);
el.save();
}
}
private static void sendMail(CMailInfo minfo) {
HttpTookit ht = new HttpTookit();
String url = "http://192.168.117.65:5556/InterFaces/SendEmail";
// ht.doPost(url, params)
}
/**
* 设置系统流程代理 如果原没有开始时间或原开始时间大于需要的设置的开始时间:设置开始时间 如果原没有截止时间或原截止时间小于需要设置的截止时间:设置截止时间;
*
* @param con
* @param empcode
* @param bgdate
* @param eddate
*/
public static void setWFAgend(CDBConnection con, String empcode, Date bgdate, Date eddate) {
try {
Shwuser user = new Shwuser();
String sqlstr = "select * from shwuser where username='" + empcode + "'";
user.findBySQL(con, sqlstr, false);
if (user.isEmpty())
return;
Date gst = user.gooutstarttime.getAsDatetime();
Date ged = user.gooutendtime.getAsDatetime();
if ((gst == null) || (gst.getTime() > bgdate.getTime()))
user.gooutstarttime.setAsDatetime(bgdate);
if ((ged == null) || (ged.getTime() < eddate.getTime()))
user.gooutendtime.setAsDatetime(eddate);
user.goout.setAsInt(1);
user.save(con, false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 检查无效的流程通知
*/
public static void delMailByProceUser(Shwwfprocuser puser) {
try {
String sqlstr = "SELECT * FROM hr_emailsend_log WHERE extid=" + puser.wfprocuserid.getValue();
CJPALineData<Hr_emailsend_log> els = new CJPALineData<Hr_emailsend_log>(Hr_emailsend_log.class);
els.findDataBySQL(sqlstr);
for (CJPABase jpa : els) {
Hr_emailsend_log el = (Hr_emailsend_log) jpa;
System.out.println("delMail:" + el.aynemid.getValue() + " sqlstr:" + sqlstr);
DLHRMailCenterWS.delMail(el.aynemid.getValue());
el.removed.setAsInt(1);
el.save();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param roleids 角色ID 用逗号分隔
* @return 登录用户是否包含角色;管理员包含任何角色
* @throws Exception
*/
public static boolean hasRoles(String roleids) throws Exception {
String userid = CSContext.getUserIDNoErr();
if ((userid == null) || (userid.isEmpty()))
return false;
Shwuser user = new Shwuser();
user.findByID(userid, false);
if (user.isEmpty())
throw new Exception("获取当前登录用户错误!");
if (user.usertype.getAsIntDefault(0) != 1) {// 不是管理员
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM shwroleuser where roleid in (" + roleids + ") AND userid=" + userid; //
return (Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr).get(0).get("ct")) > 0);
} else
return true;
}
/**
* @param roleids 岗位ID 用逗号分隔
* @return 登录用户是否包含岗位;
* @throws Exception
*/
public static boolean hasPostions(String positionids) throws Exception {
String userid = CSContext.getUserIDNoErr();
if ((userid == null) || (userid.isEmpty()))
return false;
Shwuser user = new Shwuser();
user.findByID(userid, false);
if (user.isEmpty())
throw new Exception("获取当前登录用户错误!");
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM shwpositionuser WHERE userid=" + userid + " AND positionid IN(" + positionids + ")"; //
return (Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr).get(0).get("ct")) > 0);
}
/**
* @param tp 1 试用转正 2 调动 3调动转正
* @param salary_quotacode
* @param id
* @return
* @throws Exception
*/
public static void issalary_quotacode_used(int tp, String salary_quotacode, String id) throws Exception {
if ((salary_quotacode == null) || salary_quotacode.trim().isEmpty())
return;
String sqlstr = null;
sqlstr = "SELECT * FROM hr_entry_prob WHERE stat>1 AND stat<=9 AND salary_quotacode='" + salary_quotacode + "'";
if (tp == 1)
sqlstr = sqlstr + " and pbtid<>" + id;
Hr_entry_prob jpa = new Hr_entry_prob();
jpa.findBySQL(sqlstr);
if (!jpa.isEmpty())
throw new Exception("可用工资额度编号【" + salary_quotacode + "】已经被编号为【" + jpa.pbtcode.getValue() + "】的【入职转正】表单使用");
sqlstr = "SELECT * FROM hr_employee_transfer WHERE stat>1 AND stat<=9 AND salary_quotacode='" + salary_quotacode + "'";
if (tp == 2)
sqlstr = sqlstr + " and emptranf_id<>" + id;
Hr_employee_transfer jpa1 = new Hr_employee_transfer();
jpa1.findBySQL(sqlstr);
if (!jpa1.isEmpty())
throw new Exception("可用工资额度编号【" + salary_quotacode + "】已经被编号为【" + jpa1.emptranfcode.getValue() + "】的【调动】表单使用");
sqlstr = "SELECT * FROM hr_transfer_prob WHERE stat>1 AND stat<=9 AND salary_quotacode='" + salary_quotacode + "'";
if (tp == 3)
sqlstr = sqlstr + " and pbtid<>" + id;
Hr_transfer_prob jpa2 = new Hr_transfer_prob();
jpa2.findBySQL(sqlstr);
if (!jpa2.isEmpty())
throw new Exception("可用工资额度编号【" + salary_quotacode + "】已经被编号为【" + jpa2.pbtcode.getValue() + "】的【调动转正】表单使用");
sqlstr = "SELECT * FROM Hr_salary_specchgsa WHERE stat>1 AND stat<=9 AND salary_quotacode='" + salary_quotacode + "'";
if(tp==4)
sqlstr = sqlstr + " and scsid<>" + id;
Hr_salary_specchgsa jpa3=new Hr_salary_specchgsa();
jpa3.findBySQL(sqlstr);
if (!jpa3.isEmpty())
throw new Exception("可用工资额度编号【" + salary_quotacode + "】已经被编号为【" + jpa3.scscode.getValue() + "】的【特殊调薪】表单使用");
}
/**
* 获取年龄 精确到日
*
* @param birthday
* @return
* @throws Exception
* @throws NumberFormatException
*/
public static float getAgeByBirth(Date birthday) throws Exception {
String sqlstr = "SELECT TIMESTAMPDIFF(YEAR, '" + Systemdate.getStrDateyyyy_mm_dd(birthday) + "', CURDATE()) age";
return Integer.valueOf(DBPools.defaultPool().openSql2List(sqlstr).get(0).get("age").toString());
// int age = 0;
// try {
// Calendar now = Calendar.getInstance();
// now.setTime(new Date());// 当前时间
// Calendar birth = Calendar.getInstance();
// birth.setTime(birthday);
// if (birth.after(now)) {// 如果传入的时间,在当前时间的后面,返回0岁
// age = 0;
// } else {
// age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);// - 1;
// System.out.println("now.get(Calendar.MONTH):" + now.get(Calendar.MONTH));
// System.out.println("now.get(Calendar.MONTH):" + birth.get(Calendar.MONTH));
// if (now.get(Calendar.MONTH) >= birth.get(Calendar.MONTH)) {
// System.out.println("now.get(Calendar.DAY_OF_MONTH):" + now.get(Calendar.DAY_OF_MONTH));
// System.out.println("now.get(Calendar.DAY_OF_MONTH):" + birth.get(Calendar.DAY_OF_MONTH));
// if (now.get(Calendar.DAY_OF_MONTH) >= birth.get(Calendar.DAY_OF_MONTH)) {
// age += 1;
// }
// }
// }
// if (age < 0)
// age = 0;
// return age;
// } catch (Exception e) {// 兼容性更强,异常后返回数据
// return 0;
// }
}
/*
* 转换成SQL IN
*/
public static String tranInSql(List<String>ids){
StringBuffer idsStr = new StringBuffer();
for (int i = 0; i < ids.size(); i++) {
if (i > 0) {
idsStr.append(",");
}
idsStr.append("'").append(ids.get(i)).append("'");
}
//System.out.print(idsStr.toString());
return idsStr.toString();
}
/**
* 获取子级
* @param orgid 机构id
* @param level 下级层数
* @return
* @throws Exception
*/
public static List<Shworg> getChildByOrg(Shworg orgHead,int level) throws Exception{
List<Shworg>orglist=new ArrayList<Shworg>();
orglist.add(orgHead);
String sqlstr = "select * from shworg where usable='1' and superid='" + orgHead.orgid.getValue() + "'";
List<HashMap<String, String>> oneList = HRUtil.getReadPool().openSql2List(sqlstr);
System.out.print("level="+level);
if(level>0){
for(HashMap<String, String>entity : oneList){
Shworg org = new Shworg();
org.extorgname.setValue(entity.get("extorgname"));
org.idpath.setValue(entity.get("idpath"));
org.orgid.setValue(entity.get("orgid"));
org.code.setValue(entity.get("code"));
orglist.add(org);
//System.out.print("orgname="+org.extorgname.getValue());
if(level>1){
String twosqlstr = "select * from shworg where usable='1' and superid='" + org.orgid.getValue() + "'";
List<HashMap<String, String>> twoList = HRUtil.getReadPool().openSql2List(twosqlstr);
for(HashMap<String, String>entity2 : twoList){
Shworg org2 = new Shworg();
org2.extorgname.setValue(entity2.get("extorgname"));
org2.idpath.setValue(entity2.get("idpath"));
org2.orgid.setValue(entity2.get("orgid"));
org2.code.setValue(entity2.get("code"));
orglist.add(org2);
//System.out.print("orgname="+org2.extorgname.getValue());
}
}
}
}
return orglist;
}
}
<file_sep>/src/com/corsair/server/base/Login.java
package com.corsair.server.base;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CJPASqlUtil;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.server.csession.CSession;
import com.corsair.server.csession.CToken;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shworguser;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.generic.Shwuserexeclog;
import com.corsair.server.generic.Shwusertoken;
import com.corsair.server.util.DesSw;
/**
* 登录的类
*
* @author Administrator
*
*/
public class Login {
// public void dologinex(String UserName, String UserPWD, Double Vession) throws Exception {
// HttpSession session = CSContext.getSession();// request.getSession();
// Shwuser user = new Shwuser();
// dologininsession(session, UserName, UserPWD, Vession, CSContext.getRequest().getRemoteHost(), user, null);
// }
/**
* 网页登录
*
* @param UserName
* @param UserPWD
* @param Vession
* @param atoken
* @return 成功登录返回token 字符串 登录失败 直接报错
* @throws Exception
*/
public String dologinweb(String UserName, String UserPWD, Double Vession, Shwusertoken atoken) throws Exception {
// System.out.println("dologinweb!!!!!!!!!!!!!!!!!!!!");
HttpSession session = CSContext.getSession();
Shwuser user = new Shwuser();
dologininsession(session, UserName, UserPWD, Vession, CSContext.getRequest().getRemoteHost(), user, atoken);
String sessionid = (CSContext.getSession() == null) ? "" : CSContext.getSession().getId();
Shwusertoken tk = CToken.createToken(user, atoken, sessionid, 0);
return tk.token.getValue();
}
// ///web login end///////////
private void dologininsession(HttpSession session, String UserName, String UserPWD, Double Vession, String remotehost,
Shwuser user, Shwusertoken token)
throws Exception {
Logsw.debug("用户登录:" + UserName);
try {
String sqlstr = "SELECT * FROM shwuser WHERE username=?";
PraperedSql psql = new PraperedSql();
psql.setSqlstr(sqlstr);
psql.getParms().add(new PraperedValue(java.sql.Types.VARCHAR, UserName.trim()));// UserName.trim().toUpperCase()
user.findByPSQL(psql);
if (user.isEmpty())
throw new Exception("用户名不存在!");
if (user.actived.getAsIntDefault(0) != 1)
throw new Exception("用户已禁用!");
if ((user.userpass.isEmpty() && UserPWD.isEmpty()) || (token != null) || user.userpass.getValue().equals(UserPWD)) {
// 登录成功
CSession.putvalue(session.getId(), "sessionid", session.getId());
CSession.putvalue(session.getId(), "remotehost", remotehost);
CSession.putvalue(session.getId(), "userid", user.userid.getValue());
CSession.putvalue(session.getId(), "displayname", user.displayname.getValue());
CSession.putvalue(session.getId(), "username", user.username.getValue());
CSession.putvalue(session.getId(), "usertype", user.usertype.getAsIntDefault(0));
CSession.putvalue(session.getId(), ConstsSw.session_userpwd, UserPWD);
CSession.putvalue(session.getId(), ConstsSw.session_logined, true);
CSession.putvalue(session.getId(), ConstsSw.session_logintime, System.currentTimeMillis());
setLoginedParms(session, user);
} else {
throw new Exception("密码错误");
}
} catch (Exception e) {
String[] fields = { "sessionid", "remotehost", "userid", "displayname", "username", "usertype", ConstsSw.session_username,
ConstsSw.session_logined,
ConstsSw.session_logintime };
CSession.removeValue(session.getId(), fields);
throw e;
}
}
// /////用户参数///////////////////////
// //根据参数名验证设置的值是否合法
protected boolean onSetUserParmValue(String parmname, String value) {
// System.out.println("onSetUserParmValue:" + parmname + " " + value);
return true;
}
// public String setUserParmValue(String xmlstr) throws Exception {
// return CodeXML.AddCodeStr(ConstsSw.code_of_setUserParmValue, "OK");
// }
private void setLoginedParms(HttpSession session, Shwuser user) throws Exception {
defaultorgid(session, user);
Object o = CSession.getvalue(session.getId(), "curentid");
if (o == null) {
throw new Exception("登录用户【" + user.username.getValue() + "】没有默认组织");
}
setIdpathlike(o.toString(), user.userid.getValue(), session);
}
// 需要包含不可用机构的权限
private void defaultorgid(HttpSession session, Shwuser user) throws Exception {
CJPALineData<Shworguser> ous = new CJPALineData<Shworguser>(Shworguser.class);
ous.setPool(user.pool);
String sqlstr = "select * from shworguser where userid=" + user.userid.getValue();
ous.findDataBySQL(sqlstr, true, true);
for (CJPABase oub : ous) {
Shworguser ou = (Shworguser) oub;
if (ou.isdefault.getAsIntDefault(0) == 1) {
Shworg org = new Shworg();
org.findByID(ou.orgid.getValue());
// if (org.usable.getAsInt() == 1) {
CSession.putvalue(session.getId(), "defaultorgid", ou.orgid.getValue());
CSession.putvalue(session.getId(), "curentid", org.entid.getValue());
break;
// }
}
}
}
//
/**
* 登录成功后,给session设置机构,idpath ,idpathwhere 等信息
* 需要包含不可用机构的权限
*
* @param entid
* @param userid
* @param session
* @throws Exception
*/
private void setIdpathlike(String entid, String userid, HttpSession session) throws Exception {
CJPALineData<Shworg> userorgs = new CJPALineData<Shworg>(Shworg.class);
String sqlstr = "select a.* from shworg a,shworguser b where a.orgid=b.orgid and a.entid=" + entid + " and b.userid=" + userid;
userorgs.findDataBySQL(sqlstr, true, true);
List<String> allidpaths = new ArrayList<String>();
List<String> allorgids = new ArrayList<String>();
for (CJPABase cjpa : userorgs) {
Shworg borg = (Shworg) cjpa;
allidpaths.add(borg.idpath.getValue());
allorgids.add(borg.orgid.getValue());
}
sqlstr = "SELECT fidpath,forgid FROM shworg_find WHERE orgid=" + CSession.getvalue(session.getId(), "defaultorgid");// session.getAttribute("");
List<HashMap<String, String>> idps = DBPools.defaultPool().openSql2List(sqlstr);
for (HashMap<String, String> idp : idps) {
allidpaths.add(idp.get("fidpath"));
allorgids.add(idp.get("forgid"));
}
// 去掉子 idpath 及重复 idpath
List<String> ridps = new ArrayList<String>();
for (String idp : allidpaths) {
if (isNeedAppIdpath(ridps, idp)) {
ridps.add(idp);
}
}
String oidstr = "";
List<String> orgids = new ArrayList<String>();
for (String orgid : allorgids) {
if (!orgids.contains(orgid)) {
orgids.add(orgid);
oidstr = oidstr + orgid + ",";
}
}
String fdips = "";
String idpwhr = "";
for (String idp : ridps) {
idpwhr = idpwhr + "( idpath like '" + idp + "%') or ";
fdips = fdips + idp + "#";
}
if (fdips.length() > 0) {
fdips = fdips.substring(0, fdips.length() - 1);
CSession.putvalue(session.getId(), "idpaths", fdips);
}
if (idpwhr.length() > 0) {
idpwhr = idpwhr.substring(0, idpwhr.length() - 3);
idpwhr = " and (" + idpwhr + ")";
CSession.putvalue(session.getId(), "idpathwhere", idpwhr);
}
if (oidstr.length() > 0) {
oidstr = oidstr.substring(0, oidstr.length() - 1);
CSession.putvalue(session.getId(), "curorgids", oidstr);
}
}
/**
* 是否需要添加IDPATH
*
* @param ridps
* @param idp
* @return
*/
private boolean isNeedAppIdpath(List<String> ridps, String idp) {
if (idp == null)
return false;// 不给加入,标识为存在
// System.out.println("isNeedAppIdpath:" + idp);
Iterator<String> it = ridps.iterator();
while (it.hasNext()) {
String ridp = it.next();
// System.out.println(idp + ":" + ridp);
if (idp.equalsIgnoreCase(ridp))
return false;
if ((idp.length() > ridp.length()) && (idp.substring(0, ridp.length()).equals(ridp))) {
return false;
}
if ((idp.length() < ridp.length()) && (ridp.substring(0, idp.length()).equals(idp))) {
it.remove();
return true;
}
}
return true;
}
// ///////用户参数 end//////////////////
// ////////////////////
/**
* 用户登出
*
* @throws Exception
*/
public static void dologinout() throws Exception {
HttpSession session = CSContext.getSession();
if (session == null)
return;
String userid = null;
Object o = CSession.getvalue(session.getId(), "userid");// session.getAttribute("userid");
if (o != null)
userid = o.toString();
String username = null;
o = CSession.getvalue(session.getId(), "username");// session.getAttribute("username");
if (o != null)
username = o.toString();
String remotehost = null;
o = CSession.getvalue(session.getId(), "remotehost");// session.getAttribute("");
if (o != null)
remotehost = o.toString();
String sqlstr = "DELETE FROM shwusertoken WHERE sessionid='" + session.getId() + "'";
DBPools.defaultPool().execsql(sqlstr);
Shwuserexeclog ec = new Shwuserexeclog();
ec.userid.setValue(userid);
ec.username.setValue(username);
ec.exectype.setAsInt(4);// 登出
ec.execname.setValue("登出系统");
ec.exectime.setAsDatetime(new Date());
ec.remoteip.setValue(remotehost);
ec.sessionid.setValue(session.getId());
try {
ec.save();
} catch (Exception e) {
e.printStackTrace();
}
//
String[] fields = { "sessionid", "remotehost", "userid", "displayname", "username", "usertype", ConstsSw.session_username,
ConstsSw.session_logined,
ConstsSw.session_logintime };
CSession.removeValue(session.getId(), fields);
}
//
/**
* 获取一个可用管理员用户 解密登录密码
*
* @return
* @throws Exception
*/
public static Shwuser getAdminUser() throws Exception {
String sqlstr = "SELECT * FROM shwuser WHERE actived=1 AND usertype=1";
Shwuser user = new Shwuser();
user.findBySQL(sqlstr);
if (user.isEmpty())
throw new Exception("无可用系统管理员!");
if (!user.userpass.isEmpty()) {
user.userpass.setValue(DesSw.DESryStrHex(user.userpass.getValue(), ConstsSw._userkey));
}
return user;
}
/**
* 获取用户密码
*
* @param username
* @return
* @throws Exception
*/
public static String getUserPass(String username) throws Exception {
String sqlstr = "select * from shwuser where username='" + username.trim().toUpperCase() + "'";
Shwuser user = new Shwuser();
user.findBySQL(sqlstr);
if (user.isEmpty())
throw new Exception("用户名不存在!");
if (user.userpass.isEmpty())
return "";
return DesSw.DESryStrHex(user.userpass.getValue(), ConstsSw._userkey);
}
}
<file_sep>/src/com/hr/attd/entity/Hrkq_holidaytype.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import com.hr.attd.ctr.CtrHrkq_holidaytype;
import java.sql.Types;
@CEntity(controller = CtrHrkq_holidaytype.class)
public class Hrkq_holidaytype extends CJPA {
@CFieldinfo(fieldname = "htid", iskey = true, notnull = true, caption = "类型ID", datetype = Types.INTEGER)
public CField htid; // 类型ID
@CFieldinfo(fieldname = "htname", notnull = true, caption = "类型名称", datetype = Types.VARCHAR)
public CField htname; // 类型名称
@CFieldinfo(fieldname="bhtype",notnull=true,caption="假期大类",defvalue="1",datetype=Types.INTEGER)
public CField bhtype; //假期大类
@CFieldinfo(fieldname = "daymin", notnull = true, caption = "最小天数", datetype = Types.DECIMAL)
public CField daymin; // 最小天数
@CFieldinfo(fieldname = "daymax", notnull = true, caption = "最大天数", datetype = Types.DECIMAL)
public CField daymax; // 最大天数
@CFieldinfo(fieldname = "dayymax", notnull = true, caption = "年度最大天数", datetype = Types.DECIMAL)
public CField dayymax; // 年度最大天数
@CFieldinfo(fieldname = "daymmax", notnull = true, caption = "月度最大天数", datetype = Types.DECIMAL)
public CField daymmax; // 月度最大天数
@CFieldinfo(fieldname = "daywmax", notnull = true, caption = "周度最大天数", datetype = Types.DECIMAL)
public CField daywmax; // 周度最大天数
@CFieldinfo(fieldname = "insaray", notnull = true, caption = "带薪假期", datetype = Types.INTEGER)
public CField insaray; // 带薪假期
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname="isbuildin",caption="系统内置",defvalue="1",datetype=Types.INTEGER)
public CField isbuildin; //系统内置
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hrkq_holidaytype() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/perm/ctr/CtrHr_employee_transfer.java
package com.hr.perm.ctr;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.generic.Shworg;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.access.ctr.UtilAccess;
import com.hr.attd.entity.Hrkqtransfer2insurancetimer;
import com.hr.base.entity.Hr_employeestat;
import com.hr.base.entity.Hr_orgposition;
import com.hr.base.entity.Hrrl_declare;
import com.hr.insurance.co.COHr_ins_insurance;
import com.hr.insurance.entity.Hr_ins_buyinsurance;
import com.hr.insurance.entity.Hr_ins_insurancetype;
import com.hr.insurance.entity.Hr_ins_prebuyins;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_contract;
import com.hr.perm.entity.Hr_employee_transfer;
import com.hr.perm.entity.Hr_employee_transfer_rl;
import com.hr.perm.entity.Hr_entry_prob;
import com.hr.perm.entity.Hr_transfer_salarycode_parms;
import com.hr.perm.entity.Hr_transfer_try;
import com.hr.salary.co.Cosacommon;
import com.hr.salary.ctr.CtrSalaryCommon;
import com.hr.salary.entity.Hr_salary_chgbill;
import com.hr.salary.entity.Hr_salary_orgminstandard;
import com.hr.salary.entity.Hr_salary_structure;
import com.hr.util.HRUtil;
import com.hr.util.HTQuotaUtil;
import net.sf.json.JSONObject;
public class CtrHr_employee_transfer extends JPAController {
/**
* 通用保存后,提交事务前触发
*
* @param con
* @param jpa
* @return 不为空的返回值,将作为查询结果返回给前台
* @throws Exception
*/
@Override
public String AfterCCoSave(CDBConnection con, CJPA jpa) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
HashMap<String, String> pparms = CSContext.parPostDataParms();
String jpadata = pparms.get("jpadata");
if ((jpadata == null) || jpadata.isEmpty())
throw new Exception("需要jpadata参数");
JSONObject jo = JSONObject.fromObject(jpadata);
Cosacommon.save_salary_chgblill(con, ep, jo);
return null;
}
@Override
public void AfterSave(CJPABase jpa, CDBConnection con, boolean selfLink)
throws Exception {
// TODO Auto-generated method stub
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
String sqlstr = "SELECT * FROM hr_salary_chgbill WHERE scatype=2 AND stype=4 AND sid=" + ep.emptranf_id.getValue();
Hr_salary_chgbill cb = new Hr_salary_chgbill();
cb.findBySQL(con, sqlstr, false);
if(!cb.isEmpty()){
cb.newstru_id.setValue(ep.newstru_id.getValue()); // 调薪后工资结构ID
cb.newstru_name.setValue(ep.newstru_name.getValue()); // 调薪后工资结构名
cb.newchecklev.setValue(ep.newchecklev.getValue()); // 调薪后绩效考核层级
cb.newattendtype.setValue(ep.newattendtype.getValue()); // 调薪后出勤类别
cb.newcalsalarytype.setValue(ep.newcalsalarytype.getValue()); // 调薪后计薪方式
cb.newposition_salary.setValue(ep.newposition_salary.getValue()); // 调薪后职位工资
cb.newbase_salary.setValue(ep.newbase_salary.getValue()); // 调薪后基本工资
cb.newtech_salary.setValue(ep.newtech_salary.getValue()); // 调薪后技能工资
cb.newachi_salary.setValue(ep.newachi_salary.getValue()); // 调薪后绩效工资
cb.newotwage.setValue(ep.newotwage.getValue()); // 调薪后固定加班工资
cb.newtech_allowance.setValue(ep.newtech_allowance.getValue()); // 调薪后技术津贴
cb.newovt_salary.setValue(ep.newovt_salary.getValue()); // 调薪后加班工资
cb.newavg_salary.setValue(ep.newavg_salary.getValue()); // 调薪后平均工资
cb.sacrage.setValue(ep.newposition_salary.getAsFloat(0)-ep.oldposition_salary.getAsFloat(0)); // 调薪幅度
cb.save(con);
}
}
@Override
public void BeforeWFStartSave(CJPA jpa, Shwwf wf, CDBConnection con, boolean isFilished) throws Exception {
wf.subject.setValue(((Hr_employee_transfer) jpa).emptranfcode.getValue());
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
if ((ep.attribute1.getAsIntDefault(0) != 1) && (ep.attribute1.getAsIntDefault(0) != 2)) {// 组织机构调整的调动
int bt = isneedsarryqcode(ep.odospid.getValue(), ep.newospid.getValue(), ep.tranftype3.getAsIntDefault(0));
ep.salary_qcnotnull.setValue(bt);
if (bt == 1) {
if (ep.salary_quotacode.isEmpty())
throw new Exception("工资额度不允许为空");
}
}
}
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
if ((ep.attribute1.getAsIntDefault(0) != 1) && (ep.attribute1.getAsIntDefault(0) != 2)) {// 组织机构调整的调动
// 和
// 批量导入的调动
// 不检查
HRUtil.issalary_quotacode_used(2, ep.salary_quotacode.getValue(), ep.emptranf_id.getValue());
String sqlstr = "SELECT * FROM hr_salary_chgbill WHERE scatype=2 AND stype=4 AND sid="
+ ep.emptranf_id.getValue();
Hr_salary_chgbill cb = new Hr_salary_chgbill();
cb.findBySQL(con, sqlstr, false);
if (cb.isEmpty())
throw new Exception("薪资结构不能为空");
}
checkquota(jpa, con);
// checkUnregzed(jpa, con);
if (isFilished) {
calcdates(jpa, con);
setEmploestat(jpa, con);
prebuyinsurances(jpa, con);
doresigncontract(jpa, con);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc, Shwwfproc arg3, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
calcdates(jpa, con);
setEmploestat(jpa, con);
prebuyinsurances(jpa, con);
doresigncontract(jpa, con);
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
CtrSalaryCommon.updateWageState(ep.salary_quotacode.getValue(),ep.employee_code.getValue());
}
}
@Override
public void BeforeSave(CJPABase jpa, CDBConnection con, boolean selfLink) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
ep.odorgid.getValue();// 转出部门
ep.neworgid.getValue();// 转入部门
String sqlstr = "select * from shworg where orgid='" + ep.odorgid.getValue() + "'";
String sqlstr2 = "select * from shworg where orgid='" + ep.neworgid.getValue() + "'";
Shworg org = new Shworg();
org.findBySQL(sqlstr);
String oldidpath = org.idpath.getValue();
Shworg org2 = new Shworg();
org2.findBySQL(sqlstr2);
String newidpath = org2.idpath.getValue();
if(newidpath.contains("1,") && oldidpath.contains("1,")){//非新宝的不限制调动
String[] oldidpaths = oldidpath.split(",");
String[] newidpaths = newidpath.split(",");
// if (oldidpaths.length == 2 || newidpaths.length == 2) {
// throw new Exception("调出机构或调入机构不允许选择整个制造群");
// }
boolean flag = true;
// 调动范围 1跨部门2 跨单位 3 跨模块/制造群 4部门内部
Logsw.dblog(oldidpaths[1] + "*******" + newidpaths[1] + "*******" + ep.tranftype3.getValue());
if (oldidpaths.length >= 2 && newidpaths.length >= 2) {
if (!oldidpaths[1].equals(newidpaths[1])) {
if (!ep.tranftype3.getValue().equals("3")) {
throw new Exception("调动范围只能选择跨模块/制造群");
} else {
flag = false;
}
}
}
if (oldidpaths.length >= 3 && newidpaths.length >= 3 && flag) {
Logsw.dblog(oldidpaths[2] + "*******" + newidpaths[2] + "*******" + ep.tranftype3.getValue());
if (oldidpaths[1].equals(newidpaths[1]) && !oldidpaths[2].equals(newidpaths[2])) {
if (ep.tranftype3.getValue().equals("2") || ep.tranftype3.getValue().equals("1")) {
flag = false;
} else {
throw new Exception("调动范围只能选择跨单位、跨部门");
}
}
}
if (oldidpaths.length >= 3 && newidpaths.length >= 3 && flag) {
if (oldidpaths[1].equals(newidpaths[1]) && oldidpaths[2].equals(newidpaths[2])) {
if (ep.tranftype3.getValue().equals("2") || ep.tranftype3.getValue().equals("3")) {
throw new Exception("调动范围只能选择跨部门/部门内部");
}
}
}
}
if (ep.appdate.isEmpty())
ep.appdate.setValue(ep.createtime.getValue());
checkNotMonthAVGSalary(ep, con);
if (((ep.newposition_salary.getAsFloatDefault(0) > ep.oldposition_salary.getAsFloatDefault(0)) && ep.chgposition_salary.getAsFloatDefault(0) == 0) ||
((ep.newtech_allowance.getAsFloatDefault(0) > ep.oldtech_allowance.getAsFloatDefault(0)) && ep.chgtech_allowance.getAsFloatDefault(0) == 0)) {
resetsalaryinfo(ep);
}
if ((!ep.oldcalsalarytype.isEmpty()) && (ep.oldcalsalarytype.getValue().equals("月薪"))) {
ep.oldavg_salary.setAsFloat(ep.oldposition_salary.getAsFloatDefault(0) + ep.oldovt_salary.getAsFloatDefault(0));
}
ep.newavg_salary.setAsFloat(ep.newposition_salary.getAsFloatDefault(0) + ep.newovt_salary.getAsFloatDefault(0));
checkOrgSp(ep, con);
}
private void checkOrgSp(Hr_employee_transfer ep, CDBConnection con) throws Exception {
Shworg org = new Shworg();
org.findByID(con, ep.neworgid.getValue());
if (org.isEmpty())
throw new Exception("没有找到ID为【" + ep.neworgid.getValue() + "】的机构");
String sqlstr = "SELECT * FROM `hr_orgposition` WHERE idpath LIKE '" + org.idpath.getValue() + "%' AND ospid=" + ep.newospid.getValue();
Hr_orgposition op = new Hr_orgposition();
op.findBySQL(con, sqlstr, false);
if (op.isEmpty()) {
throw new Exception("在机构【" + org.extorgname.getValue() + "】里没有找到ID为【" + ep.newospid.getValue() + "】的机构职位");
}
}
private void checkNotMonthAVGSalary(Hr_employee_transfer ep, CDBConnection con) throws Exception {
if ((!ep.oldcalsalarytype.isEmpty()) && (!ep.oldcalsalarytype.getValue().equals("月薪"))) {
String sqlstr = "SELECT IFNULL(ROUND(AVG(paynosubs),2),0) AS avgpaysubs FROM (SELECT * FROM " +
" hr_salary_list WHERE wagetype=2 AND isfullattend=1 AND er_id=" + ep.er_id.getValue() + " ORDER BY yearmonth DESC LIMIT 0,3) tt";
float oldavg = Float.valueOf(con.openSql2List(sqlstr).get(0).get("avgpaysubs").toString());
ep.oldavg_salary.setAsFloat(oldavg);
}
}
private void resetsalaryinfo(Hr_employee_transfer ep) throws Exception {
float np = ep.newposition_salary.getAsFloatDefault(0);
float op = ep.oldposition_salary.getAsFloatDefault(0);
if ((np > op) & ep.chgposition_salary.getAsFloatDefault(0) == 0) {
Hr_salary_structure ss = new Hr_salary_structure();
ss.findByID(ep.newstru_id.getValue());
if (!ss.isEmpty()) {
if (ss.strutype.getAsInt() == 1) {
float minstand = 0;
String sqlstr = "SELECT * FROM `hr_salary_orgminstandard` WHERE stat=9 AND usable=1 AND INSTR('" + ep.idpath.getValue() + "',idpath)=1 ORDER BY idpath DESC ";
Hr_salary_orgminstandard oms = new Hr_salary_orgminstandard();
oms.findBySQL(sqlstr);
if (oms.isEmpty()) {
minstand = 0;
} else {
minstand = oms.minstandard.getAsFloatDefault(0);
}
float bw = (np * ss.basewage.getAsFloatDefault(0)) / 100;
float bow = (np * ss.otwage.getAsFloatDefault(0)) / 100;
float sw = (np * ss.skillwage.getAsFloatDefault(0)) / 100;
float pw = (np * ss.meritwage.getAsFloatDefault(0)) / 100;
if (minstand > bw) {
if ((bw + bow) > minstand) {
bow = bw + bow - minstand;
bw = minstand;
} else if ((bw + bow + sw) > minstand) {
sw = bw + bow + sw - minstand;
bow = 0;
bw = minstand;
} else if ((bw + bow + sw + pw) > minstand) {
pw = bw + bow + sw + pw - minstand;
sw = 0;
bow = 0;
bw = minstand;
} else {
bw = np;
pw = 0;
sw = 0;
bow = 0;
}
}
ep.newbase_salary.setAsFloat(bw);
ep.newtech_salary.setAsFloat(sw);
ep.newachi_salary.setAsFloat(pw);
ep.newotwage.setAsFloat(bow);
ep.chgbase_salary.setAsFloat(bw - ep.oldbase_salary.getAsFloatDefault(0));
ep.chgtech_salary.setAsFloat(sw - ep.oldtech_salary.getAsFloatDefault(0));
ep.chgachi_salary.setAsFloat(pw - ep.oldachi_salary.getAsFloatDefault(0));
ep.chgotwage.setAsFloat(bow - ep.oldotwage.getAsFloatDefault(0));
} else {
ep.chgbase_salary.setAsFloat(ep.newbase_salary.getAsFloatDefault(0) - ep.oldbase_salary.getAsFloatDefault(0));
ep.chgtech_salary.setAsFloat(ep.newtech_salary.getAsFloatDefault(0) - ep.oldtech_salary.getAsFloatDefault(0));
ep.chgachi_salary.setAsFloat(ep.newachi_salary.getAsFloatDefault(0) - ep.oldachi_salary.getAsFloatDefault(0));
ep.chgotwage.setAsFloat(ep.newotwage.getAsFloatDefault(0) - ep.oldotwage.getAsFloatDefault(0));
}
ep.chgposition_salary.setAsFloat(np - ep.oldposition_salary.getAsFloatDefault(0));
ep.chgtech_allowance.setAsFloat(ep.newtech_allowance.getAsFloatDefault(0) - ep.oldtech_allowance.getAsFloatDefault(0));
}
}
}
/**
* 调动生效日期按审批通过时间
*
* @param jpa
* @param con
* @throws Exception
*/
// 调动单据的 待转正日期=调动生效日期+考察期。调动生效日期为15日之前(包含15号),待转正日期为当月1号+考察期;
// 调动生效日期为15日之后(不包含15号),待转正日期为次月1号+考察期
private void calcdates(CJPABase jpa, CDBConnection con) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
Date tranfcmpdate = Systemdate.getDateYYYYMMDD(new Date());
ep.tranfcmpdate.setAsDatetime(tranfcmpdate);
int probation = ep.probation.getAsIntDefault(0);
if (probation > 0) {
Date probationdate = Systemdate.dateMonthAdd(tranfcmpdate, probation);
Calendar ca = Calendar.getInstance();
ca.setTime(probationdate);
if (ca.get(Calendar.DAY_OF_MONTH) <= 15)
ep.probationdate.setValue(Systemdate.getStrDateByFmt(probationdate, "yyyy-MM") + "-01");
else
ep.probationdate.setValue(
Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(probationdate, 1), "yyyy-MM") + "-01");
} else {
ep.probationdate.setAsDatetime(tranfcmpdate);
}
calcsalarydate(jpa, con);
ep.save(con);
}
/*
* 调动单据的 核薪生效日期,按调动生效日期自动更新。调动生效日期为15日之前(包含15号),核薪生效日期为当月1号;
* 调动生效日期为15日之后(不包含15号),核薪生效日期为次月1号;
*/
private void calcsalarydate(CJPABase jpa, CDBConnection con) {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
if (ep.salarydate.isEmpty()) {
Date tranfcmpdate = ep.tranfcmpdate.getAsDate();
Calendar ca = Calendar.getInstance();
ca.setTime(tranfcmpdate);
if (ca.get(Calendar.DAY_OF_MONTH) <= 15)
ep.salarydate.setValue(Systemdate.getStrDateByFmt(tranfcmpdate, "yyyy-MM") + "-01");
else
ep.salarydate.setValue(
Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(tranfcmpdate, 1), "yyyy-MM") + "-01");
}
}
/**
* 检查工资额度编码占用情况
*
* @param jpa
* @param con
* @throws Exception
*/
private void checkUnregzed(CJPABase jpa, CDBConnection con) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
if ((ep.attribute1.getAsIntDefault(0) == 1) || (ep.attribute1.getAsIntDefault(0) == 2))// 组织机构调整的调动
// 和
// 批量导入的调动
// 不检查
return;
if (ep.salary_quotacode.isEmpty())
return;
if (ep.salary_quotacode.getAsIntDefault(1) == 0)
return;
String sqlstr = "SELECT * FROM hr_employee_transfer WHERE stat>1 AND stat<=9 AND salary_quotacode='"
+ ep.salary_quotacode.getValue() + "'";
if (!ep.empstatid.isEmpty())
sqlstr = sqlstr + " AND emptranf_id<>" + ep.emptranf_id.getValue();
Hr_employee_transfer nep = new Hr_employee_transfer();
nep.findBySQL(sqlstr, false);
if (!nep.isEmpty())
throw new Exception(
"工资额度编码【" + ep.salary_quotacode.getValue() + "】已经被调动单【" + nep.emptranfcode.getValue() + "】占用");
}
private void setEmploestat(CJPA jpa, CDBConnection con) throws Exception {
// 根据评审结果 修改人事资料
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
Hr_employee emp = new Hr_employee();
emp.findByID4Update(con, ep.er_id.getValue(), false);
if (emp.isEmpty()) {
throw new Exception("ID为【" + ep.er_id.getValue() + "】的人事档案不存在");
}
Hr_employeestat estat = new Hr_employeestat();
estat.findBySQL("select * from hr_employeestat where statvalue=" + emp.empstatid.getValue());
if (estat.allowtransfer.getAsInt() != 1) {
throw new Exception("状态为【" + estat.language1.getValue() + "】的人事档案不允许调动");
}
if (ep.quota_over.getAsIntDefault(2) == 1) {// 超编
if (ep.quota_over_rst.isEmpty())
throw new Exception("超编的调动需要评审超编处理方式");
int quota_over_rst = ep.quota_over_rst.getAsInt(); // 1 允许增加编制调动 2
// 超编调动 3不允许调动
if (quota_over_rst == 1) {
doaddquota(con, ep);// 增加编制
dotranfer(ep, emp, estat, con);// 调动
} else if (quota_over_rst == 2) {
dotranfer(ep, emp, estat, con);// 调动
} else if (quota_over_rst == 3) {
// 不处理资料
}
} else
dotranfer(ep, emp, estat, con);// 调动
}
private void dotranfer(Hr_employee_transfer ep, Hr_employee emp, Hr_employeestat estat, CDBConnection con)
throws Exception {
if ((ep.attribute1.getAsIntDefault(0) != 1) && (ep.attribute1.getAsIntDefault(0) != 2)) {// 组织机构调整的调动
// 和
// 批量导入的调动
// 不检查
// HRUtil.issalary_quotacode_used(2, ep.salary_quotacode.getValue(),
// ep.emptranf_id.getValue());
}
int needtry = CtrHr_employee_transferUtil.setEmpState(con, ep, emp);// 设置人事状态
Shworg org = new Shworg();
org.findByID(con, ep.neworgid.getValue());
if (org.isEmpty())
throw new Exception("没有找到ID为【" + ep.neworgid.getValue() + "】的机构");
Hr_orgposition op = new Hr_orgposition();
op.findByID(con, ep.newospid.getValue());
if (op.isEmpty())
throw new Exception("没有找到ID为【" + ep.newospid.getValue() + "】的机构职位");
emp.orgid.setValue(org.orgid.getValue()); // 部门ID
emp.orgcode.setValue(org.code.getValue()); // 部门编码
emp.orgname.setValue(org.extorgname.getValue()); // 部门名称
emp.lv_id.setValue(ep.newlv_id.getValue()); // 职级ID
emp.lv_num.setValue(ep.newlv_num.getValue()); // 职级
emp.hg_id.setValue(ep.newhg_id.getValue()); // 职等ID
emp.hg_code.setValue(ep.newhg_code.getValue()); // 职等编码
emp.hg_name.setValue(ep.newhg_name.getValue()); // 职等名称
emp.ospid.setValue(ep.newospid.getValue()); // 职位ID
emp.ospcode.setValue(ep.newospcode.getValue()); // 职位编码
emp.idpath.setValue(org.idpath.getValue());
emp.ospid.setValue(ep.newospid.getValue());
emp.ospcode.setValue(ep.newospcode.getValue());
emp.sp_name.setValue(ep.newsp_name.getValue());
emp.atdtype.setValue(ep.newattendtype.getValue());
emp.hwc_namezl.setValue(op.hwc_namezl.getValue());
emp.hwc_namezq.setValue(op.hwc_namezq.getValue());
emp.hwc_namezz.setValue(op.hwc_namezz.getValue());
emp.hg_remark.setValue(ep.newhg_remark.getValue());
if (op.isoffjob.getAsIntDefault(0) == 1) {
emp.emnature.setValue("脱产");
} else {
emp.emnature.setValue("非脱产");
}
emp.pay_way.setValue(ep.newcalsalarytype.getValue());
emp.uorgid.setValue(null);
emp.uorgcode.setValue(null);
emp.uorgname.setValue(null);
emp.uidpath.setValue(null);
emp.save(con);// 保存人事信息
// dosetSACHGLog(ep, con);// 薪资变动记录
CtrSalaryCommon.newSalaryChangeLog(con, ep);// 薪资变动记录
if (needtry == 1)
createTransferTryInfo(ep, emp, con);// 考察期记录
doUpdateRlDeclare(ep, emp, con);// 关联关系变动
// CtrHrkq_workschmonth.putEmDdtWeekPB(con, emp,
// ep.tranfcmpdate.getAsDatetime());// 生成默认排班
updateExtInfo(con, emp);// 更新扩展信息
UtilAccess.disableAllAccessByEmpid(con, emp.er_id.getAsInt(), "调出关闭权限");
UtilAccess.appendAccessListByOrg(con, emp.er_id.getAsInt(), ep.neworgid.getValue(), 2,
ep.emptranf_id.getValue(), ep.emptranfcode.getValue(), "调入新增权限");
// COHr_access_emauthority_list.doUpdateAccessList(con,
// emp.employee_code.getValue(), "3",
// ep.emptranf_id.getValue(), "员工调动", ep.odorgid.getValue(),
// ep.neworgid.getValue());
}
/**
* 更新扩展信息
*
* @param con
* @param emp
* @throws Exception
*/
public static void updateExtInfo(CDBConnection con, Hr_employee emp) throws Exception {
String sqlstr = "UPDATE hrkq_leave_blance SET orgid=" + emp.orgid.getValue() + " ,orgcode='"
+ emp.orgcode.getValue() + "',orgname='"
+ emp.orgname.getValue() + "',idpath='" + emp.idpath.getValue() + "' WHERE er_id="
+ emp.er_id.getValue();
con.execsql(sqlstr);
sqlstr = "UPDATE hr_ykt_card SET orgid=" + emp.orgid.getValue() + ", orgcode='" + emp.orgcode.getValue()
+ "',orgname='" + emp.orgname.getValue() + "',"
+ "sp_name='" + emp.sp_name.getValue() + "',hwc_namezl='" + emp.hwc_namezl.getValue() + "',hwc_namezq='"
+ emp.hwc_namezq.getValue() + "',"
+ "hwc_namezz='" + emp.hwc_namezz.getValue() + "',hg_name='" + emp.hg_name.getValue() + "',lv_num='"
+ emp.lv_num.getValue() + "'," + "idpath='"
+ emp.idpath.getValue() + "' WHERE er_id=" + emp.er_id.getValue();
con.execsql(sqlstr);
}
private void doaddquota(CDBConnection con, Hr_employee_transfer ep) throws Exception {
Hr_orgposition hop = new Hr_orgposition();
hop.findByID4Update(con, ep.newospid.getValue(), false);
CtrHr_quota_release.dochgquota(con, hop, 1, ep.emptranf_id.getValue(), "0", ep.emptranfcode.getValue(), "4");
}
private void checkquota(CJPA jpa, CDBConnection con) throws Exception {
Hr_employee_transfer ep = (Hr_employee_transfer) jpa;
// 调动单提交时候 检查编制
Hr_employee emp = new Hr_employee();
emp.findByID4Update(con, ep.er_id.getValue(), false);
if (emp.isEmpty()) {
throw new Exception("ID为【" + ep.er_id.getValue() + "】的人事档案不存在");
}
Hr_orgposition op = new Hr_orgposition();
op.findByID(emp.ospid.getValue());
if (op.isEmpty())
throw new Exception("ID为【" + emp.ospid.getValue() + "】的机构职位不存在");
// String sqlstr = "SELECT * FROM hr_systemparms WHERE usable=1 AND
// parmcode='BATCH_QUATA_CLASS' AND parmvalue='" +
// op.hwc_idzl.getValue() + "'";
// Hr_systemparms hs = new Hr_systemparms(sqlstr);
// if (!hs.isEmpty())
// throw new Exception("员工对应的职类标记为【批量编制控制】不允许单个调动");
if (HTQuotaUtil.checkOrgPositionQuota(con, ep.newospid.getValue(), 1)) {
ep.quota_over.setAsInt(2);
} else {
ep.quota_over.setAsInt(1);
ep.quota_over_rst.setAsInt(2);
}
ep.save(con);// 基类已经保存过,需要重新保存
// System.out.println("ep.quota_over:" + ep.quota_over.getAsInt());
}
private void createTransferTryInfo(Hr_employee_transfer ep, Hr_employee emp, CDBConnection con) throws Exception {
if (ep.probation.getAsIntDefault(0) == 0)// 无考察期 不需要保存
return;
Hr_transfer_try tt = new Hr_transfer_try();
tt.emptranf_id.setValue(ep.emptranf_id.getValue()); // 调动单ID
tt.emptranfcode.setValue(ep.emptranfcode.getValue()); // 调动表单编码
tt.er_id.setValue(emp.er_id.getValue()); // 人事档案ID
tt.employee_code.setValue(emp.employee_code.getValue()); // 工号
tt.employee_name.setValue(emp.employee_name.getValue()); // 姓名
tt.id_number.setValue(emp.id_number.getValue());// 身份证号码
tt.degree.setValue(emp.degree.getValue()); // 学历
tt.orgid.setValue(emp.orgid.getValue()); // 部门ID
tt.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
tt.orgname.setValue(emp.orgname.getValue()); // 部门名称
tt.ospid.setValue(emp.ospid.getValue()); // 职位ID
tt.ospcode.setValue(emp.ospcode.getValue()); // 职位编码
tt.sp_name.setValue(emp.sp_name.getValue()); // 职位名称
tt.hwc_namezl.setValue(emp.hwc_namezl.getValue()); // 职类
tt.hg_name.setValue(emp.hg_name.getValue()); // 职等名称
tt.lv_num.setValue(emp.lv_num.getValue()); // 职级
tt.entrydate.setValue(emp.hiredday.getValue()); // 入职日期
tt.tranfcmpdate.setValue(ep.tranfcmpdate.getValue());// 调动日期
tt.probation.setValue(ep.probation.getValue()); // 考察期
tt.probationdate.setValue(ep.probationdate.getValue()); // 转正日期
// 第一次约定的考察期
tt.probationdatetrue.setValue(null); // 实际转正日期 根据转正评审结果确定 如延长考察期则为空
tt.wfresult.setValue(null); // 评审结果 1 同意转正 2 延长考察 3 考察不合格
tt.delayprobation.setValue(null); // 延长考察期
tt.delaypromotionday.setValue(null); // 延期待转正时间 根据延长考察期自动计算,多次延期累计计算
tt.delaypromotiondaytrue.setValue(null); // 延期实际转正时间
tt.delaywfresult.setValue(null); // 评审结果 1 同意转正 2 延长考察 3 考察不合格
tt.delaytimes.setValue("0"); // 延期次数
tt.trystat.setValue("1"); // 考察期人事状态 考察期中、考察过期、考察延期、己转正、考察不合格
tt.remark.setValue(null); // 备注
tt.idpath.setValue(emp.idpath.getValue()); // idpath
tt.entid.setValue(emp.entid.getValue()); // entid
tt.creator.setValue("SYSTEM"); // 创建人
tt.createtime.setAsDatetime(new Date()); // 创建时间
tt.save(con);
}
// private void dosetSACHGLog(Hr_employee_transfer ep, CDBConnection con)
// throws Exception {
// Hrsa_chglg sac = new Hrsa_chglg();
// sac.er_id.setValue(ep.er_id.getValue()); // 人事ID
// sac.scatype.setValue("2"); // 入职定薪、调薪核薪、转正调薪、年度调薪、特殊调薪
// sac.stype.setValue("4"); // 来源类别 历史数据、实习登记、入职表单、调动表单、入职转正、调动转正....
// sac.sid.setValue(ep.emptranf_id.getValue()); // 来源ID
// sac.scode.setValue(ep.emptranfcode.getValue()); // 来源单号
// sac.oldattendtype.setValue(ep.odattendtype.getValue()); // 调薪前出勤类别
// sac.oldcalsalarytype.setValue(ep.oldcalsalarytype.getValue()); // 调薪前计薪方式
// sac.oldposition_salary.setValue(ep.oldposition_salary.getValue()); //
// 调薪前职位工资
// sac.oldbase_salary.setValue(ep.oldbase_salary.getValue()); // 调薪前基本工资
// sac.oldtech_salary.setValue(ep.oldtech_salary.getValue()); // 调薪前技能工资
// sac.oldachi_salary.setValue(ep.oldachi_salary.getValue()); // 调薪前技能工资
// sac.oldtech_allowance.setValue(ep.oldtech_salary.getValue()); // 调薪前技术津贴
// sac.oldavg_salary.setValue(ep.oldavg_salary.getValue()); // 调薪前平均工资
// sac.newattendtype.setValue(ep.newattendtype.getValue()); // 调薪后出勤类别
// sac.newcalsalarytype.setValue(ep.newcalsalarytype.getValue()); // 调薪后计薪方式
// sac.newposition_salary.setValue(ep.newposition_salary.getValue()); //
// 调薪前职位工资
// sac.newbase_salary.setValue(ep.newbase_salary.getValue()); // 调薪后基本工资
// sac.newtech_salary.setValue(ep.newtech_salary.getValue()); // 调薪后技能工资
// sac.newachi_salary.setValue(ep.newachi_salary.getValue()); // 调薪后技能工资
// sac.newtech_allowance.setValue(ep.newtech_salary.getValue()); // 调薪后技术津贴
// sac.sacrage.setAsFloat(sac.newposition_salary.getAsFloatDefault(0) -
// sac.oldposition_salary.getAsFloatDefault(0)); // 调薪幅度
// sac.chgdate.setValue(ep.tranfcmpdate.getValue()); // 调薪日期
// sac.chgreason.setValue(""); // 调薪原因
// sac.remark.setValue(""); // 备注
// sac.createtime.setAsDatetime(new Date()); // 创建时间
// sac.save(con);
// }
private void doUpdateRlDeclare(Hr_employee_transfer ep, Hr_employee emp, CDBConnection con) throws Exception {
Hrrl_declare rldcold = new Hrrl_declare();
Hrrl_declare rldcnew1 = new Hrrl_declare();
Hrrl_declare rldcnew2 = new Hrrl_declare();
Hr_employee remp = new Hr_employee();
CJPALineData<Hr_employee_transfer_rl> rls = ep.hr_employee_transfer_rls;
for (CJPABase jpa : rls) {
Hr_employee_transfer_rl rl = (Hr_employee_transfer_rl) jpa;
rldcold.clear();
rldcnew1.clear();
rldcnew2.clear();
remp.clear();
rldcold.findByID(con, rl.ldid.getValue());
if (rldcold.isEmpty())
throw new Exception("ID为【" + rl.ldid.getValue() + "】的申报单不存在");
rldcnew1.assignfield(rldcold, true);
rldcold.useable.setAsInt(2);
rldcold.disusetime.setAsDatetime(new Date());
rldcold.disuseremark.setValue("人事调动表单【" + ep.emptranfcode.getValue() + "】审批通过禁用");
rldcold.save(con);
String sqlstr = "SELECT * FROM Hrrl_declare WHERE er_id=" + rldcold.rer_id.getValue() + " AND rer_id="
+ emp.er_id.getValue()
+ " AND ldtype=1 AND useable=1";
rldcnew2.findBySQL(con, sqlstr, false);
if (!rldcnew2.isEmpty()) {
rldcnew2.useable.setAsInt(2);
rldcnew2.disusetime.setAsDatetime(new Date());
rldcnew2.disuseremark.setValue("人事调动表单【" + ep.emptranfcode.getValue() + "】审批通过禁用");
rldcnew2.save(con);
}
rldcnew2.clear();
rldcnew1.ldid.setValue(null);
rldcnew1.ldcode.setValue(null);
rldcnew1.dcldate.setAsDatetime(new Date());
rldcnew1.ljdate.setValue(emp.ljdate.getValue());
rldcnew1.orgid.setValue(emp.orgid.getValue());
rldcnew1.orgcode.setValue(emp.orgcode.getValue());
rldcnew1.orgname.setValue(emp.orgname.getValue());
rldcnew1.ospid.setValue(emp.ospid.getValue());
rldcnew1.ospcode.setValue(emp.ospcode.getValue());
rldcnew1.sp_name.setValue(emp.sp_name.getValue());
rldcnew1.hwc_namezl.setValue(emp.hwc_namezl.getValue());
rldcnew1.hg_name.setValue(emp.hg_name.getValue());
rldcnew1.lv_num.setValue(emp.lv_num.getValue());
rldcnew1.rbusiness.setValue(rl.newrbusiness.getValue());
rldcnew1.rlmanagetype.setValue(rl.newrlmanagetype.getValue());
rldcnew1.rctrms.setValue(rl.newrctrms.getValue());
rldcnew1.rccode.setValue(rl.newrccode.getValue());
rldcnew1.useable.setAsInt(1);
rldcnew1.disusetime.setValue(null);
rldcnew1.disuseremark.setValue(null);
rldcnew1.remark.setValue(rl.remark.getValue());
rldcnew1.creator.setValue(null);
rldcnew1.createtime.setValue(null);
rldcnew1.updator.setValue(null);
rldcnew1.updatetime.setValue(null);
rldcnew1.clearAllId();
remp.findByID(con, rldcnew1.rer_id.getValue());
if (!remp.isEmpty()) {
rldcnew2.clear();
rldcnew2.assignfield(rldcnew1, true);
rldcnew2.ldid.setValue(null);
rldcnew2.ldcode.setValue(null);
rldcnew2.er_id.setValue(remp.er_id.getValue()); // 档案ID
rldcnew2.employee_code.setValue(remp.employee_code.getValue()); // 工号
rldcnew2.employee_name.setValue(remp.employee_name.getValue()); // 姓名
rldcnew2.sex.setValue(remp.sex.getValue()); // 性别
rldcnew2.hiredday.setValue(remp.hiredday.getValue());
rldcnew2.ljdate.setValue(remp.ljdate.getValue());
rldcnew2.orgid.setValue(remp.orgid.getValue());
rldcnew2.orgcode.setValue(remp.orgcode.getValue());
rldcnew2.orgname.setValue(remp.orgname.getValue());
rldcnew2.ospid.setValue(remp.ospid.getValue());
rldcnew2.ospcode.setValue(remp.ospcode.getValue());
rldcnew2.sp_name.setValue(remp.sp_name.getValue());
rldcnew2.hwc_namezl.setValue(remp.hwc_namezl.getValue());
rldcnew2.hg_name.setValue(remp.hg_name.getValue());
rldcnew2.lv_num.setValue(remp.lv_num.getValue());
rldcnew2.emplev.setValue("0");
rldcnew2.idpath.setValue(remp.idpath.getValue());
rldcnew2.rer_id.setValue(emp.er_id.getValue()); // 关联档案ID
rldcnew2.remployee_code.setValue(emp.employee_code.getValue()); // 关联工号
rldcnew2.remployee_name.setValue(emp.employee_name.getValue()); // 关联姓名/推荐人姓名
rldcnew2.rsex.setValue(emp.sex.getValue()); // 关联性别
rldcnew2.rhiredday.setValue(emp.hiredday.getValue()); // 关联入职日期
rldcnew2.rljdate.setValue(emp.ljdate.getValue()); // 关联离职日期
rldcnew2.rorgid.setValue(emp.orgid.getValue()); // 关联部门ID
rldcnew2.rorgcode.setValue(emp.orgcode.getValue()); // 关联部门编码
rldcnew2.rorgname.setValue(emp.orgname.getValue()); // 关联部门名称/推荐人工作单位
rldcnew2.rospid.setValue(emp.ospid.getValue()); // 关联职位ID
rldcnew2.rospcode.setValue(emp.ospcode.getValue()); // 关联职位编码
rldcnew2.rsp_name.setValue(emp.sp_name.getValue()); // 关联职位/推荐人职务
rldcnew2.rhwc_namezl.setValue(emp.hwc_namezl.getValue()); // 关联职类
rldcnew2.rhg_name.setValue(emp.hg_name.getValue()); // 关联职等
rldcnew2.rlv_num.setValue(emp.lv_num.getValue()); // 关联职级
rldcnew2.clearAllId();
rldcnew1.save(con);
rldcnew2.save(con);
} else
rldcnew1.save(con);
}
}
private void dobuyinsurance(CJPA jpa, CDBConnection con) throws Exception {
Hr_employee_transfer trans = (Hr_employee_transfer) jpa;
Hr_employee emp = new Hr_employee();
emp.findByID4Update(con, trans.er_id.getValue(), false);
if (emp.isEmpty()) {
throw new Exception("ID为【" + trans.er_id.getValue() + "】的人事档案不存在");
}
if (emp.empstatid.getAsInt() >= 12) {
throw new Exception("工号为【" + trans.employee_code.getValue() + "】的人员状态不是在职或其他可购保的状态");
}
Hr_ins_buyinsurance oldbi = new Hr_ins_buyinsurance();
oldbi.findBySQL(
"SELECT * FROM `hr_ins_buyinsurance` WHERE stat=9 AND CURDATE()>=buydday AND CURDATE()<=LAST_DAY(buydday) AND er_id="
+ emp.er_id.getValue());
if (!oldbi.isEmpty()) {
setinsrancetimer(trans, con);// 插入调度列表等待自动生成购保单
return;
}
Hr_ins_buyinsurance bi = new Hr_ins_buyinsurance();
// Hr_ins_buyins_line buyinsline = new Hr_ins_buyins_line();
Hr_ins_insurancetype it = new Hr_ins_insurancetype();
String buydate = Systemdate.getStrDateyyyy_mm_dd(new Date());
it.findBySQL("SELECT * FROM hr_ins_insurancetype WHERE ins_type=1 AND '" + buydate
+ "'>=buydate ORDER BY buydate DESC ");
if (it.isEmpty()) {
throw new Exception("购保时间为【" + buydate + "】时无可用的险种");
}
bi.insurance_number.setValue(emp.employee_code.getValue());
bi.orgid.setValue(emp.orgid.getValue()); // 部门ID
bi.orgcode.setValue(emp.orgcode.getValue()); // 部门编码
bi.orgname.setValue(emp.orgname.getValue()); // 部门名称
bi.buydday.setValue(buydate);
bi.insit_id.setValue(it.insit_id.getValue());
bi.insit_code.setValue(it.insit_code.getValue());
bi.insname.setValue(it.insname.getValue());
bi.ins_type.setAsInt(1);
bi.payment.setValue(it.payment.getValue());
bi.tselfpay.setValue(it.selfpay.getValue());
bi.tcompay.setValue(it.compay.getValue());
bi.er_id.setValue(emp.er_id.getValue());
bi.employee_code.setValue(emp.employee_code.getValue());
bi.employee_name.setValue(emp.employee_name.getValue());
bi.ospid.setValue(emp.ospid.getValue());
bi.ospcode.setValue(emp.ospcode.getValue());
bi.sp_name.setValue(emp.sp_name.getValue());
bi.lv_id.setValue(emp.lv_id.getValue());
bi.lv_num.setValue(emp.lv_num.getValue());
bi.hiredday.setValue(emp.hiredday.getValue());
bi.orgid.setValue(emp.orgid.getValue());
bi.orgcode.setValue(emp.orgcode.getValue());
bi.orgname.setValue(emp.orgname.getValue());
bi.degree.setValue(emp.degree.getValue());
bi.sex.setValue(emp.sex.getValue());
bi.telphone.setValue(emp.telphone.getValue());
bi.nativeplace.setValue(emp.nativeplace.getValue());
bi.registertype.setValue(emp.registertype.getValue());
bi.pay_type.setValue(emp.pay_way.getValue());
bi.id_number.setValue(emp.id_number.getValue());
bi.sign_org.setValue(emp.sign_org.getValue());
bi.sign_date.setValue(emp.sign_date.getValue());
bi.expired_date.setValue(emp.expired_date.getValue());
bi.birthday.setValue(emp.birthday.getValue());
int age = getAgeByBirth(emp.birthday.getValue());
bi.age.setAsInt(age);
bi.sptype.setValue(emp.emnature.getValue());
bi.isnew.setAsInt(1);
bi.reg_type.setAsInt(1);
String nowtime = "";
Calendar hday = Calendar.getInstance();
Date hd = Systemdate.getDateByStr(emp.hiredday.getValue());
hday.setTime(hd);
int inday = hday.get(Calendar.DATE);
if (inday < 21) {
nowtime = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd");
} else {
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd"));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
nowtime = Systemdate.getStrDateyyyy_mm_dd(eddate);
}
bi.buydday.setValue(nowtime);
bi.ins_type.setValue(it.ins_type.getValue());
bi.selfratio.setValue(it.selfratio.getValue());
bi.selfpay.setValue(it.selfpay.getValue());
bi.comratio.setValue(it.comratio.getValue());
bi.compay.setValue(it.compay.getValue());
bi.insurancebase.setValue(it.insurancebase.getValue());
// bi.hr_ins_buyins_lines.add(buyinsline);
bi.remark.setValue("调动单【" + trans.emptranfcode.getValue() + "】自动生成购保");
bi.save(con);
}
private static int getAgeByBirth(String birthday) {
int age = 0;
try {
Calendar now = Calendar.getInstance();
now.setTime(new Date());// 当前时间
Calendar birth = Calendar.getInstance();
Date bd = Systemdate.getDateByStr(birthday);
birth.setTime(bd);
if (birth.after(now)) {// 如果传入的时间,在当前时间的后面,返回0岁
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {// 兼容性更强,异常后返回数据
return 0;
}
}
private void doresigncontract(CJPA jpa, CDBConnection con) throws Exception {// 调动后更新原有合同
Hr_employee_transfer trans = (Hr_employee_transfer) jpa;
Hr_employee_contract hrecon = new Hr_employee_contract();
Hr_employee emp = new Hr_employee();
emp.findByID(trans.er_id.getValue());
if (emp.isEmpty()) {
throw new Exception("ID为【" + trans.er_id.getValue() + "】的人事档案不存在");
}
Shworg org = new Shworg();
org.findByID(con, trans.neworgid.getValue());
if (org.isEmpty())
throw new Exception("没有找到ID为【" + trans.neworgid.getValue() + "】的机构");
Hr_orgposition op = new Hr_orgposition();
op.findByID(con, trans.newospid.getValue());
if (op.isEmpty())
throw new Exception("没有找到ID为【" + trans.newospid.getValue() + "】的机构职位");
hrecon.findBySQL(
"SELECT * FROM `hr_employee_contract` WHERE stat=9 AND contractstat=1 AND contract_type=1 AND er_id="
+ emp.er_id.getValue());
if (hrecon.isEmpty())
return;
// throw new Exception("没有找到员工【" + emp.employee_name.getValue() +
// "】的有效合同资料"); //要求取消限制 17-12-27
hrecon.orgid.setValue(org.orgid.getValue()); // 部门ID
hrecon.orgcode.setValue(org.code.getValue()); // 部门编码
hrecon.orgname.setValue(org.extorgname.getValue()); // 部门名称
hrecon.lv_id.setValue(trans.newlv_id.getValue()); // 职级ID
hrecon.lv_num.setValue(trans.newlv_num.getValue()); // 职级
hrecon.ospid.setValue(trans.newospid.getValue()); // 职位ID
hrecon.ospcode.setValue(trans.newospcode.getValue()); // 职位编码
hrecon.idpath.setValue(org.idpath.getValue());
hrecon.ospid.setValue(trans.newospid.getValue());
hrecon.ospcode.setValue(trans.newospcode.getValue());
hrecon.sp_name.setValue(trans.newsp_name.getValue());
hrecon.remark.setValue("调动单【" + trans.emptranfcode.getValue() + "】自动更新合同!"); // 备注
hrecon.save(con);
}
private void setinsrancetimer(Hr_employee_transfer trans, CDBConnection con) throws Exception {// 插入待调度列表,等待调度生成购保单
Hrkqtransfer2insurancetimer instimer = new Hrkqtransfer2insurancetimer();
instimer.er_id.setValue(trans.er_id.getValue());
instimer.employee_code.setValue(trans.employee_code.getValue());
instimer.employee_name.setValue(trans.employee_name.getValue());
instimer.tranfcmpdate.setValue(trans.tranfcmpdate.getValue());
String tranmount = Systemdate.getStrDateByFmt(instimer.tranfcmpdate.getAsDatetime(), "yyyy-MM");
tranmount = tranmount + "-01";
Date buydate = Systemdate.dateMonthAdd(Systemdate.getDateByyyyy_mm_dd(tranmount), 1);
instimer.dobuyinsdate.setAsDatetime(buydate);
instimer.isbuyins.setAsInt(2);
instimer.sourceid.setValue(trans.emptranf_id.getValue());
instimer.sourcecode.setValue(trans.emptranfcode.getValue());
instimer.save(con);
}
private void prebuyinsurances(CJPA jpa, CDBConnection con) throws Exception {
Hr_employee_transfer trans = (Hr_employee_transfer) jpa;
Hr_employee emp = new Hr_employee();
emp.findByID4Update(con, trans.er_id.getValue(), false);
if (emp.isEmpty()) {
throw new Exception("ID为【" + trans.er_id.getValue() + "】的人事档案不存在");
}
Hr_ins_buyinsurance oldbi = new Hr_ins_buyinsurance();
oldbi.findBySQL("SELECT * FROM `hr_ins_buyinsurance` WHERE stat=9 AND '" + trans.tranfcmpdate.getValue()
+ "'>=buydday AND '"
+ trans.tranfcmpdate.getValue() + "'<=LAST_DAY(buydday) AND er_id=" + emp.er_id.getValue());
if (!oldbi.isEmpty()) {
return;
}
boolean islocal = false;
boolean levcheck = false;
if (emp.registertype.isEmpty())
throw new Exception("工号【" + emp.employee_code.getValue() + "】未维护户籍类型,购保单生成失败");
if ((emp.registertype.getAsInt() == 1) || (emp.registertype.getAsInt() == 2)) {// 户籍类型是本地的
islocal = true;
}
if (trans.newlv_num.getAsFloat() <= 6.3) {// 调动后职级<=6.3的
levcheck = true;
}
if (islocal || levcheck) {
Hr_ins_prebuyins pbi = new Hr_ins_prebuyins();
pbi.er_id.setValue(emp.er_id.getValue());
pbi.employee_code.setValue(emp.employee_code.getValue());
pbi.employee_name.setValue(emp.employee_name.getValue());
pbi.ospid.setValue(emp.ospid.getValue());
pbi.ospcode.setValue(emp.ospcode.getValue());
pbi.sp_name.setValue(emp.sp_name.getValue());
pbi.lv_id.setValue(emp.lv_id.getValue());
pbi.lv_num.setValue(emp.lv_num.getValue());
pbi.hiredday.setValue(emp.hiredday.getValue());
pbi.orgid.setValue(emp.orgid.getValue());
pbi.orgcode.setValue(emp.orgcode.getValue());
pbi.orgname.setValue(emp.orgname.getValue());
pbi.sex.setValue(emp.sex.getValue());
pbi.birthday.setValue(emp.birthday.getValue());
pbi.registertype.setValue(emp.registertype.getValue());
pbi.idpath.setValue(emp.idpath.getValue());
pbi.degree.setValue(emp.degree.getValue());
pbi.nativeplace.setValue(emp.nativeplace.getValue());
pbi.id_number.setValue(emp.id_number.getValue());
pbi.registeraddress.setValue(emp.registeraddress.getValue());
pbi.telphone.setValue(emp.telphone.getValue());
pbi.transorg.setValue(emp.transorg.getValue());
pbi.dispunit.setValue(emp.dispunit.getValue());
int age = COHr_ins_insurance.getAgeByBirth(emp.birthday.getValue());
pbi.age.setAsInt(age);
pbi.tranfcmpdate.setValue(trans.tranfcmpdate.getValue());
pbi.isbuyins.setAsInt(2);
pbi.sourceid.setValue(trans.emptranf_id.getValue());
pbi.sourcecode.setValue(trans.emptranfcode.getValue());
pbi.prebuytype.setAsInt(2);
Calendar hday = Calendar.getInstance();
Date hd = Systemdate.getDateByStr(trans.tranfcmpdate.getValue());
hday.setTime(hd);
String nowtime = "";
// Date nowdate =
// Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd());
int inday = hday.get(Calendar.DATE);
if (inday <= 25) {
Date firstdate = Systemdate.getFirstAndLastOfMonth(hd).date1;
nowtime = Systemdate.getStrDateyyyy_mm_dd(firstdate);
} else {
Date bgdate = Systemdate.getFirstAndLastOfMonth(hd).date2;// 取最后一天的日期
Date eddate = Systemdate.dateDayAdd(bgdate, 1);// 加一天获取下月一号的日期
nowtime = Systemdate.getStrDateyyyy_mm_dd(eddate);
}
pbi.dobuyinsdate.setValue(nowtime);
pbi.save(con);
}
}
/**
*
* 算法逻辑: 调入非脱产的:都不需要填写; 调入为脱产的:不是“同部门内部”和“特殊部门”调动都需要填
* 是“同部门内部”和“特殊部门”的,调动前为非脱产需要填写,为脱产不需要填写;
*
*
* @param orgid
* @return 1 必填 2 非必填
* @throws Exception
*/
public static int isneedsarryqcode(String odospid, String newospid, int tranftype3) throws Exception {
Hr_orgposition oldosp = new Hr_orgposition();
oldosp.findByID(odospid);
if (oldosp.isEmpty())
throw new Exception("ID为【" + odospid + "】的机构职位ID不存在");
Hr_orgposition newosp = new Hr_orgposition();
newosp.findByID(newospid);
if (newosp.isEmpty())
throw new Exception("ID为【" + newospid + "】的机构职位ID不存在");
if(newosp.idpath.getValue().startsWith("11293,")){//调出到集团的都不需要填写
System.out.println("调出到集团的都不需要填写");
return 2;
}
if (newosp.isoffjob.getAsIntDefault(0) == 2) {// 调入非脱产的:都不需要填写;
System.out.println("调入非脱产的:都不需要填写;");
return 2;
} else { // 调入是脱产
boolean flag=false;
boolean isspecnew = isSpecOrg(newosp.orgid.getValue());// 调入部门是否特殊部门
boolean isspecold=isSpecOrg(oldosp.orgid.getValue());//调出部门是否特殊部门
if(isspecnew && isspecold ){
if(isSameChildOrg(newosp.idpath.getValue(),oldosp.idpath.getValue())){
flag=true;
}
}
if ((tranftype3 != 4) && (!flag)) {// 不是“内部”且不是跨部门且不是“特殊部门”调动都需要填2
// //&& (tranftype3 != 1)又取消了
System.out.println("不是“同部门内部”且不是“特殊部门”调动都需要填");
return 1;
} else {// 是“同部门内部”或“特殊部门”的,
if (oldosp.isoffjob.getAsIntDefault(0) == 1) {// 调动前为非脱产需要填写,;
System.out.println("调动前为脱产不需要填写");
return 2;
} else {
System.out.println("调动前为非脱产需要填写");
return 1;
}
}
}
}
/**
* @param orgid
* @return 是否特殊部门
* @throws Exception
*/
private static boolean isSpecOrg(String orgid) throws Exception {
Shworg org = new Shworg();
org.findByID(orgid);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String orgids = org.idpath.getValue();
String[] ids = orgids.split(",");
orgids = "";
for (String id : ids) {
if ((id != null) && (!id.isEmpty())) {
orgids = orgids + "'" + id + "',";
}
}
orgids = orgids.substring(0, orgids.length() - 1);
String sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_transfer_salarycode_parms WHERE useable=1 AND includchild=1 AND orgid IN("
+ orgids + ")";
if (Integer.valueOf(org.pool.openSql2List(sqlstr).get(0).get("ct").toString()) > 0)// 需要
return true;
sqlstr = "SELECT IFNULL(COUNT(*),0) ct FROM hr_transfer_salarycode_parms WHERE useable=1 and includchild=2 AND orgid="+ orgid;
if (Integer.valueOf(org.pool.openSql2List(sqlstr).get(0).get("ct").toString()) > 0)// 需要
return true;
return false;
}
/**
* 判断是否同属一个特殊组织下面
* @return
*/
private static boolean isSameChildOrg(String oldOrgIdpath,String newOrgIdpath)throws Exception{
//Hr_transfer_salarycode_parms specorg=new Hr_transfer_salarycode_parms();
//specorg.fin.findBySQL(sqlstr)
boolean flag=false;
String sqlstr = "select * from Hr_transfer_salarycode_parms WHERE useable=1 AND includchild=1";
CJPALineData<Hr_transfer_salarycode_parms> cas = new CJPALineData<Hr_transfer_salarycode_parms>(Hr_transfer_salarycode_parms.class);
cas.findDataBySQL(sqlstr);
for (CJPABase jpa : cas) {
Hr_transfer_salarycode_parms ca = (Hr_transfer_salarycode_parms) jpa;
if(oldOrgIdpath.startsWith(ca.idpath.getValue()) && newOrgIdpath.startsWith(ca.idpath.getValue()))
{
flag=true;
}
}
return flag;
}
}
<file_sep>/src/com/corsair/server/generic/Shwarea.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwarea extends CJPA {
@CFieldinfo(fieldname = "areaid", iskey = true, notnull = true, caption = "", datetype = Types.INTEGER)
public CField areaid; //
@CFieldinfo(fieldname = "areacode", caption = "", datetype = Types.VARCHAR)
public CField areacode; //
@CFieldinfo(fieldname = "areaname", caption = "", datetype = Types.VARCHAR)
public CField areaname; //
@CFieldinfo(fieldname = "assistcode", caption = "", datetype = Types.VARCHAR)
public CField assistcode; //
@CFieldinfo(fieldname = "telzone", caption = "", datetype = Types.VARCHAR)
public CField telzone; //
@CFieldinfo(fieldname = "postcode", caption = "", datetype = Types.VARCHAR)
public CField postcode; //
@CFieldinfo(fieldname = "superid", caption = "", datetype = Types.INTEGER)
public CField superid; //
@CFieldinfo(fieldname = "carmark", caption = "", datetype = Types.VARCHAR)
public CField carmark; //
@CFieldinfo(fieldname = "note", caption = "", datetype = Types.VARCHAR)
public CField note; //
@CFieldinfo(fieldname = "lvidx", precision = 1, scale = 0, caption = "lvidx", datetype = Types.INTEGER)
public CField lvidx; // lvidx
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwarea() throws Exception {
}
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/corsair/server/genco/COWebSocket.java
package com.corsair.server.genco;
import java.util.HashMap;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.csession.CSession;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CorUtil;
import com.corsair.server.websocket.COnSendJSON;
import com.corsair.server.websocket.CWebSocket;
@ACO(coname = "web.socket")
public class COWebSocket {
private String sendstr = null;
private boolean issended = false;
private final int timeout = 5;// 5分钟
private final int timestop = 5;// 5秒
@ACOAction(eventname = "connect", Authentication = false, notes = "长连接", ispublic = true)
public String connect() throws Exception {
if (!ConstsSw.getAppParmBoolean("websocket")) {
throw new Exception("产品配置不支持websocket");
}
issended = false;
HashMap<String, String> urlparms = CSContext.get_pjdataparms();
String vport = CorUtil.hashMap2Str(urlparms, "vport", "需要参数vport");
String sid = CSContext.getSession().getId();
String userid = CSession.getvalue(sid, "userid");
CWebSocket socket = CSContext.wbsktpool.addSocket(vport, sid);
COnSendJSON onsend = new COnSendJSON() {
@Override
public void onsend(String jsonstr) {
// TODO Auto-generated method stub
sendstr = jsonstr;
issended = true;
}
};
socket.setOnsend(onsend);
socket.setUserid(userid);
socket.OnConnected();
int i = 0;
while (true) {
Thread.sleep(timestop * 1000);
if (issended) {
break;
}
// 超时处理
i++;
if ((i * timestop) > (timeout * 60)) {
socket.OnClose(2);
return null;
}
}
socket.OnClose(1);
CSContext.wbsktpool.removeSocket(sid, vport);
return sendstr;
}
}
<file_sep>/src/com/corsair/server/base/CorsairwebCommon.java
package com.corsair.server.base;
/**
* 远程方法调用测试
*
* @author Administrator
*
*/
public class CorsairwebCommon {
public String rpc_proc0(String Input) {
//System.out.println("请求:" + Input);
return "操蛋" + Input;
}
}
<file_sep>/src/com/hr/perm/ctr/CtrHr_transfer_prob.java
package com.hr.perm.ctr;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import com.corsair.cjpa.CJPABase;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.base.entity.Hr_employeestat;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_employee_transfer;
import com.hr.perm.entity.Hr_entry_prob;
import com.hr.perm.entity.Hr_transfer_prob;
import com.hr.perm.entity.Hr_transfer_try;
import com.hr.salary.co.Cosacommon;
import com.hr.salary.ctr.CtrSalaryCommon;
import com.hr.salary.entity.Hr_salary_chgbill;
import com.hr.salary.entity.Hr_salary_orgminstandard;
import com.hr.salary.entity.Hr_salary_positionwage;
import com.hr.salary.entity.Hr_salary_structure;
import com.hr.util.HRUtil;
import net.sf.json.JSONObject;
public class CtrHr_transfer_prob extends JPAController {
/**
* 保存前
*
* @param jpa里面有值
* ,还没检测数据完整性,没生成ID CODE 设置默认值
* @param con
* @param selfLink
* @throws Exception
*/
@Override
public void BeforeSave(CJPABase jpa, CDBConnection con, boolean selfLink) throws Exception {
Hr_transfer_prob tp = (Hr_transfer_prob) jpa;
// Hr_employee_transfer tr = new Hr_employee_transfer();
// tr.findByID(tp.sourceid.getValue(), false);
// if (tr.isEmpty())
// return;
// if (tr.salary_qcnotnull.getAsIntDefault(0) == 1) {
// if (tp.salary_quotacode.isEmpty())
// throw new Exception("工资额度编号不允许为空");
// }
Hr_orgposition osp = new Hr_orgposition();
osp.findByID(tp.newospid.getValue(), false);
if (!osp.isEmpty()) {
if ((osp.isoffjob.getAsIntDefault(0) == 1) && (tp.pbtsarylev.getAsFloatDefault(0) > 0))
if (tp.salary_quotacode.isEmpty())
throw new Exception("工资额度编号不允许为空");
}
if ((((tp.newposition_salary.getAsFloatDefault(0) > tp.oldposition_salary.getAsFloatDefault(0)) || (tp.newtech_allowance.getAsFloatDefault(0) > tp.oldtech_allowance.getAsFloatDefault(0))) && tp.pbtsarylev.getAsFloatDefault(0) == 0)||
(((tp.newposition_salary.getAsFloatDefault(0)>tp.oldposition_salary.getAsFloatDefault(0)))
&&tp.overf_salary.getAsFloatDefault(0)==0)) {
resetsalaryinfo(tp);
//throw new Exception("薪资有调整但调整额度为0,请检查单据或清理浏览器缓存后再制单。(清理浏览器缓存方法:同时按 ctr+shift+delete 即可弹出删除缓存对话框。)");
}
Logsw.dblog("重新计算薪资生效日期");
Date pbtdate=Systemdate.getDateByyyyy_mm_dd(tp.pbtdate.getValue());
Calendar ca = Calendar.getInstance();
ca.setTime(pbtdate);
int pbmonth=ca.get(Calendar.MONTH);
int pbyear=ca.get(Calendar.YEAR);
Calendar now = Calendar.getInstance();
int nowmonth=now.get(Calendar.MONTH);
int nowyear=now.get(Calendar.YEAR);
if(pbyear>nowyear){
tp.salarydate.setValue(tp.pbtdate.getValue());
}else if(pbyear<nowyear){
tp.salarydate.setValue(Systemdate.getStrDateyyyy_mm_01());
}
else if(pbmonth>=nowmonth){
tp.salarydate.setValue(tp.pbtdate.getValue());
}else if(pbmonth<nowmonth){
tp.salarydate.setValue(Systemdate.getStrDateyyyy_mm_01());
}
Logsw.dblog("实际调薪日期:"+tp.salarydate.getValue());
}
private void resetsalaryinfo(Hr_transfer_prob scs) throws Exception{
System.out.println("-----------重新核算薪资各项");
float np=scs.newposition_salary.getAsFloatDefault(0);
float op=scs.oldposition_salary.getAsFloatDefault(0);
if((np>op)&scs.pbtsarylev.getAsFloatDefault(0)==0){
Hr_salary_structure ss=new Hr_salary_structure();
ss.findByID(scs.newstru_id.getValue());
if(!ss.isEmpty()){
if(ss.strutype.getAsInt()==1){
float minstand=0;
String sqlstr="SELECT * FROM `hr_salary_orgminstandard` WHERE stat=9 AND usable=1 AND INSTR('"+scs.idpath.getValue()+"',idpath)=1 ORDER BY idpath DESC ";
Hr_salary_orgminstandard oms=new Hr_salary_orgminstandard();
oms.findBySQL(sqlstr);
if(oms.isEmpty()){
minstand=0;
}else{
minstand=oms.minstandard.getAsFloatDefault(0);
}
float bw=(np*ss.basewage.getAsFloatDefault(0))/100;
float bow=(np*ss.otwage.getAsFloatDefault(0))/100;
float sw=(np*ss.skillwage.getAsFloatDefault(0))/100;
float pw=(np*ss.meritwage.getAsFloatDefault(0))/100;
if(minstand>bw){
if((bw+bow)>minstand){
bow=bw+bow-minstand;
bw=minstand;
}else if((bw+bow+sw)>minstand){
sw=bw+bow+sw-minstand;
bow=0;
bw=minstand;
}else if((bw+bow+sw+pw)>minstand){
pw=bw+bow+sw+pw-minstand;
sw=0;
bow=0;
bw=minstand;
}else{
bw=np;
pw=0;
sw=0;
bow=0;
}
}
scs.newbase_salary.setAsFloat(bw);
scs.newtech_salary.setAsFloat(sw);
scs.newachi_salary.setAsFloat(pw);
scs.newotwage.setAsFloat(bow);
scs.chgbase_salary.setAsFloat(bw-scs.oldbase_salary.getAsFloatDefault(0));
scs.chgtech_salary.setAsFloat(sw-scs.oldtech_salary.getAsFloatDefault(0));
scs.chgachi_salary.setAsFloat(pw-scs.oldachi_salary.getAsFloatDefault(0));
scs.chgotwage.setAsFloat(bow-scs.oldotwage.getAsFloatDefault(0));
}else{
scs.chgbase_salary.setAsFloat(scs.newbase_salary.getAsFloatDefault(0)-scs.oldbase_salary.getAsFloatDefault(0));
scs.chgtech_salary.setAsFloat(scs.newtech_salary.getAsFloatDefault(0)-scs.oldtech_salary.getAsFloatDefault(0));
scs.chgachi_salary.setAsFloat(scs.newachi_salary.getAsFloatDefault(0)-scs.oldachi_salary.getAsFloatDefault(0));
scs.chgotwage.setAsFloat(scs.newotwage.getAsFloatDefault(0)-scs.oldotwage.getAsFloatDefault(0));
}
scs.chgposition_salary.setAsFloat(np-scs.oldposition_salary.getAsFloatDefault(0));
scs.chgtech_allowance.setAsFloat(scs.newtech_allowance.getAsFloatDefault(0)-scs.oldtech_allowance.getAsFloatDefault(0));
scs.pbtsarylev.setAsFloat(np+scs.newtech_allowance.getAsFloatDefault(0)-scs.oldposition_salary.getAsFloatDefault(0)-scs.oldtech_allowance.getAsFloatDefault(0));
}
}
if(np>0){
Hr_salary_positionwage spw=new Hr_salary_positionwage();
spw.findBySQL("SELECT pw.* FROM `hr_salary_positionwage` pw,`hr_orgposition` op WHERE pw.stat=9 AND pw.usable=1 AND pw.ospid=op.sp_id AND op.ospid="+scs.newospid.getValue());
if(spw.isEmpty()){
scs.overf_salary.setValue(0);
scs.overf_salary_chgtech.setValue(0);
}else{
if(np>spw.psl5.getAsFloatDefault(0)){
float spwage=spw.psl5.getAsFloatDefault(0);
float chgspw=np-spwage;
scs.overf_salary.setAsFloat(chgspw);
float chgper=(chgspw/spwage)*100;
scs.overf_salary_chgtech.setAsFloat(chgper);
}
}
}
}
/**
* 通用保存后,提交事务前触发
*
* @param con
* @param jpa
* @return 不为空的返回值,将作为查询结果返回给前台
* @throws Exception
*/
@Override
public String AfterCCoSave(CDBConnection con, CJPA jpa) throws Exception {
Hr_transfer_prob ep = (Hr_transfer_prob) jpa;
HashMap<String, String> pparms = CSContext.parPostDataParms();
String jpadata = pparms.get("jpadata");
if ((jpadata == null) || jpadata.isEmpty())
throw new Exception("需要jpadata参数");
JSONObject jo = JSONObject.fromObject(jpadata);
Logsw.dblog("流程AfterCCoSave:"+ep.salarydate.getValue());
Cosacommon.save_salary_chgblill(con, ep, jo);//保存薪资异动记录
return null;
}
@Override
public void BeforeWFStartSave(CJPA jpa, Shwwf wf, CDBConnection con, boolean isFilished) throws Exception {
Hr_transfer_prob tp = (Hr_transfer_prob) jpa;
wf.subject.setValue(tp.pbtcode.getValue());
if ((tp.shw_attachs == null) || (tp.shw_attachs.size() == 0)) {
throw new Exception("需要上传附件");
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc,
Shwwfproc arg3, boolean arg4) throws Exception {
// TODO Auto-generated method stub
if (arg4)
doepend(jpa, con);
Hr_transfer_prob prob=(Hr_transfer_prob) jpa;
CtrSalaryCommon.updateWageState(prob.salary_quotacode.getValue(),prob.employee_code.getValue());
}
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
HRUtil.issalary_quotacode_used(3, ((Hr_transfer_prob) jpa).salary_quotacode.getValue(), ((Hr_transfer_prob) jpa).pbtid.getValue());
String sqlstr = "SELECT * FROM hr_salary_chgbill WHERE scatype=3 AND stype=6 AND sid=" + ((Hr_transfer_prob) jpa).pbtid.getValue();
Hr_salary_chgbill cb = new Hr_salary_chgbill();
cb.findBySQL(con, sqlstr, false);
if (cb.isEmpty())
throw new Exception("薪资结构不能为空");
if (isFilished){
doepend(jpa, con);
//updateSalarydate(jpa, con);//更新调薪生效月份
}
}
/*
* 更新调薪生效月份
*/
private void doepend(CJPA jpa, CDBConnection con) throws Exception {
Hr_transfer_prob tp = (Hr_transfer_prob) jpa;
Hr_employee emp = new Hr_employee();
Hr_employeestat estat = new Hr_employeestat();
Hr_employee_transfer tsf = new Hr_employee_transfer();
Hr_transfer_try tt = new Hr_transfer_try();
emp.findByID4Update(con, tp.er_id.getValue(), false);
if (emp.isEmpty())
throw new Exception("没有找到id为【】的员工资料");
tsf.findByID4Update(con, tp.sourceid.getValue(), false);
estat.findBySQL("select * from hr_employeestat where statvalue=" + emp.empstatid.getValue());
tt.findBySQL("select * from hr_transfer_try where emptranf_id=" + tsf.emptranf_id.getValue());
int pbttype1 = tp.pbttype1.getAsInt();// 转正类型 实习转正 入职转正 调动转正
if (pbttype1 == 1) {
if (estat.issxenprob.getAsInt() != 1) {
throw new Exception("状态为【" + estat.language1.getValue() + "】的员工不允许【实习生转正操作】");
}
} else if (pbttype1 == 2) {
if (estat.isptemprob.getAsInt() != 1) {
throw new Exception("状态为【" + estat.language1.getValue() + "】的员工不允许【转正操作】");
}
} else if (pbttype1 == 3) {
if (estat.isjxprob.getAsInt() != 1) {
throw new Exception("状态为【" + estat.language1.getValue() + "】的员工不允许【考察期转正操作】");
}
} else
throw new Exception("转正类型错误【" + pbttype1 + "】");
int wfresult = tp.wfresult.getAsInt(); // 1 同意转正 2 延长考察 3 降职 4 其它
if (wfresult == 1) {// 1 同意转正
emp.empstatid.setAsInt(4);// 正式
tsf.ispromotioned.setAsInt(1);// 已经转正
// dosetSACHGLog(tp, con);
CtrSalaryCommon.newSalaryChangeLog(con, tp);//保存薪资记录
if (!tt.isEmpty()) {
if (tt.delaytimes.getAsIntDefault(0) > 0) {
tt.delaypromotiondaytrue.setAsDatetime(new Date());// 延长过考察期转正时间
} else {
tt.probationdatetrue.setAsDatetime(new Date());// 没延长过考察期转正时间
}
tt.trystat.setAsInt(4);// 1考察期中、2考察过期、3考察延期、4己转正、5考察不合格
tt.save(con);
}
} else if (wfresult == 2) {// 2 延长考察
tsf.probationdate.setValue(tp.wfpbtdate.getValue());
if (!tt.isEmpty()) {
tt.delaypromotionday.setValue(tp.wfpbtdate.getValue());
tt.delaytimes.setAsInt(tt.delaytimes.getAsIntDefault(0) + 1);
tt.trystat.setAsInt(3);// 1考察期中、2考察过期、3考察延期、4己转正、5考察不合格
tt.delayprobation.setAsInt(tt.delayprobation.getAsIntDefault(0) + tp.wfpbprobation.getAsIntDefault(0));
tt.save(con);
}
} else if (wfresult == 3) {
// 建议降职
} else if (wfresult == 4) {
// 其它建议
} else
throw new Exception("评审结果错误");
emp.save(con, false);
tsf.save(con, false);
};
// private void dosetSACHGLog(Hr_transfer_prob tp, CDBConnection con) throws Exception {
// Hrsa_chglg sac = new Hrsa_chglg();
// sac.er_id.setValue(tp.er_id.getValue()); // 人事ID
// sac.scatype.setValue("3"); // 入职定薪、调薪核薪、转正调薪、年度调薪、特殊调薪
// sac.stype.setValue("6"); // 来源类别 历史数据、实习登记、入职表单、调动表单、入职转正、调动转正....
// sac.sid.setValue(tp.pbtid.getValue()); // 来源ID
// sac.scode.setValue(tp.pbtcode.getValue()); // 来源单号
// sac.oldattendtype.setValue(tp.odattendtype.getValue()); // 调薪前出勤类别
// sac.oldcalsalarytype.setValue(tp.oldcalsalarytype.getValue()); // 调薪前计薪方式
// sac.oldposition_salary.setValue(tp.oldposition_salary.getValue()); // 调薪前职位工资
// sac.oldbase_salary.setValue(tp.oldbase_salary.getValue()); // 调薪前基本工资
// sac.oldtech_salary.setValue(tp.oldtech_salary.getValue()); // 调薪前技能工资
// sac.oldachi_salary.setValue(tp.oldachi_salary.getValue()); // 调薪前技能工资
// sac.oldtech_allowance.setValue(tp.oldtech_salary.getValue()); // 调薪前技术津贴
// sac.oldavg_salary.setValue("0"); // 调薪前平均工资
// sac.newattendtype.setValue(tp.newattendtype.getValue()); // 调薪后出勤类别
// sac.newcalsalarytype.setValue(tp.newcalsalarytype.getValue()); // 调薪后计薪方式
// sac.newposition_salary.setValue(tp.newposition_salary.getValue()); // 调薪前职位工资
// sac.newbase_salary.setValue(tp.newbase_salary.getValue()); // 调薪后基本工资
// sac.newtech_salary.setValue(tp.newtech_salary.getValue()); // 调薪后技能工资
// sac.newachi_salary.setValue(tp.newachi_salary.getValue()); // 调薪后技能工资
// sac.newtech_allowance.setValue(tp.newtech_salary.getValue()); // 调薪后技术津贴
// sac.sacrage.setAsFloat(sac.newposition_salary.getAsFloatDefault(0) - sac.oldposition_salary.getAsFloatDefault(0)); // 调薪幅度
// sac.chgdate.setValue(tp.pbtdate.getValue()); // 调薪日期
// sac.chgreason.setValue(""); // 调薪原因
// sac.remark.setValue(""); // 备注
// sac.createtime.setAsDatetime(new Date()); // 创建时间
// sac.save(con);
// }
}
<file_sep>/src/com/hr/perm/entity/Hr_train_regex.java
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_train_regex extends CJPA {
@CFieldinfo(fieldname = "treg_id", notnull = true, caption = "treg_id", datetype = Types.INTEGER)
public CField treg_id; // treg_id
@CFieldinfo(fieldname = "treg_code", notnull = true, caption = "treg_code", datetype = Types.VARCHAR)
public CField treg_code; // treg_code
@CFieldinfo(fieldname = "er_id", notnull = true, caption = "er_id", datetype = Types.INTEGER)
public CField er_id; // er_id
@CFieldinfo(fieldname = "employee_code", notnull = true, caption = "employee_code", datetype = Types.VARCHAR)
public CField employee_code; // employee_code
@CFieldinfo(fieldname = "regtype", notnull = true, caption = "regtype", datetype = Types.INTEGER)
public CField regtype; // regtype
@CFieldinfo(fieldname = "regdate", caption = "登记日期", datetype = Types.TIMESTAMP)
public CField regdate; // 登记日期
@CFieldinfo(fieldname = "nationality", caption = "国籍", datetype = Types.VARCHAR)
public CField nationality; // 国籍
@CFieldinfo(fieldname = "bwday", caption = "参加工作时间", datetype = Types.TIMESTAMP)
public CField bwday; // 参加工作时间
@CFieldinfo(fieldname = "enddatetrain", caption = "enddatetrain", datetype = Types.TIMESTAMP)
public CField enddatetrain; // enddatetrain
@CFieldinfo(fieldname = "enddatetry", caption = "enddatetry", datetype = Types.TIMESTAMP)
public CField enddatetry; // enddatetry
@CFieldinfo(fieldname = "jxdatetry", caption = "jxdatetry", datetype = Types.TIMESTAMP)
public CField jxdatetry; // jxdatetry
@CFieldinfo(fieldname = "isfrainflish", caption = "isfrainflish", datetype = Types.INTEGER)
public CField isfrainflish; // isfrainflish
@CFieldinfo(fieldname = "norgid", caption = "norgid", datetype = Types.INTEGER)
public CField norgid; // norgid
@CFieldinfo(fieldname = "norgname", caption = "norgname", datetype = Types.VARCHAR)
public CField norgname; // norgname
@CFieldinfo(fieldname = "nospid", caption = "nospid", datetype = Types.INTEGER)
public CField nospid; // nospid
@CFieldinfo(fieldname = "nsp_name", caption = "nsp_name", datetype = Types.VARCHAR)
public CField nsp_name; // nsp_name
@CFieldinfo(fieldname = "remark", caption = "remark", datetype = Types.VARCHAR)
public CField remark; // remark
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "stat", notnull = true, caption = "stat", datetype = Types.INTEGER)
public CField stat; // stat
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "creator", notnull = true, caption = "creator", datetype = Types.VARCHAR)
public CField creator; // creator
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "createtime", datetype = Types.TIMESTAMP)
public CField createtime; // createtime
@CFieldinfo(fieldname = "updator", caption = "updator", datetype = Types.VARCHAR)
public CField updator; // updator
@CFieldinfo(fieldname = "updatetime", caption = "updatetime", datetype = Types.TIMESTAMP)
public CField updatetime; // updatetime
@CFieldinfo(fieldname = "attribute1", caption = "attribute1", datetype = Types.VARCHAR)
public CField attribute1; // attribute1
@CFieldinfo(fieldname = "attribute2", caption = "attribute2", datetype = Types.VARCHAR)
public CField attribute2; // attribute2
@CFieldinfo(fieldname = "attribute3", caption = "attribute3", datetype = Types.VARCHAR)
public CField attribute3; // attribute3
@CFieldinfo(fieldname = "attribute4", caption = "attribute4", datetype = Types.VARCHAR)
public CField attribute4; // attribute4
@CFieldinfo(fieldname = "attribute5", caption = "attribute5", datetype = Types.VARCHAR)
public CField attribute5; // attribute5
@CFieldinfo(fieldname = "id_number", notnull = true, caption = "id_number", datetype = Types.VARCHAR)
public CField id_number; // id_number
@CFieldinfo(fieldname = "card_number", caption = "card_number", datetype = Types.VARCHAR)
public CField card_number; // card_number
@CFieldinfo(fieldname = "employee_name", notnull = true, caption = "employee_name", datetype = Types.VARCHAR)
public CField employee_name; // employee_name
@CFieldinfo(fieldname = "mnemonic_code", caption = "mnemonic_code", datetype = Types.VARCHAR)
public CField mnemonic_code; // mnemonic_code
@CFieldinfo(fieldname = "english_name", caption = "english_name", datetype = Types.VARCHAR)
public CField english_name; // english_name
@CFieldinfo(fieldname = "avatar_id1", caption = "身份证头像", datetype = Types.INTEGER)
public CField avatar_id1; // 身份证头像
@CFieldinfo(fieldname = "avatar_id2", caption = "拍照头像", datetype = Types.INTEGER)
public CField avatar_id2; // 拍照头像
@CFieldinfo(fieldname = "birthday", notnull = true, caption = "birthday", datetype = Types.TIMESTAMP)
public CField birthday; // birthday
@CFieldinfo(fieldname = "sex", caption = "sex", datetype = Types.INTEGER)
public CField sex; // sex
@CFieldinfo(fieldname = "hiredday", caption = "hiredday", datetype = Types.TIMESTAMP)
public CField hiredday; // hiredday
@CFieldinfo(fieldname = "degree", caption = "degree", datetype = Types.INTEGER)
public CField degree; // degree
@CFieldinfo(fieldname = "married", caption = "married", datetype = Types.INTEGER)
public CField married; // married
@CFieldinfo(fieldname = "nativeplace", caption = "nativeplace", datetype = Types.VARCHAR)
public CField nativeplace; // nativeplace
@CFieldinfo(fieldname = "address", caption = "address", datetype = Types.VARCHAR)
public CField address; // address
@CFieldinfo(fieldname = "nation", caption = "nation", datetype = Types.VARCHAR)
public CField nation; // nation
@CFieldinfo(fieldname = "email", caption = "email", datetype = Types.VARCHAR)
public CField email; // email
@CFieldinfo(fieldname = "empstatid", notnull = true, caption = "empstatid", datetype = Types.INTEGER)
public CField empstatid; // empstatid
@CFieldinfo(fieldname = "modify", caption = "modify", datetype = Types.VARCHAR)
public CField modify; // modify
@CFieldinfo(fieldname = "usedname", caption = "usedname", datetype = Types.VARCHAR)
public CField usedname; // usedname
@CFieldinfo(fieldname = "pldcp", caption = "pldcp", datetype = Types.INTEGER)
public CField pldcp; // pldcp
@CFieldinfo(fieldname = "major", caption = "major", datetype = Types.VARCHAR)
public CField major; // major
@CFieldinfo(fieldname = "registertype", caption = "registertype", datetype = Types.INTEGER)
public CField registertype; // registertype
@CFieldinfo(fieldname = "registeraddress", caption = "registeraddress", datetype = Types.VARCHAR)
public CField registeraddress; // registeraddress
@CFieldinfo(fieldname = "health", caption = "health", datetype = Types.VARCHAR)
public CField health; // health
@CFieldinfo(fieldname = "medicalhistory", caption = "medicalhistory", datetype = Types.VARCHAR)
public CField medicalhistory; // medicalhistory
@CFieldinfo(fieldname = "bloodtype", caption = "bloodtype", datetype = Types.VARCHAR)
public CField bloodtype; // bloodtype
@CFieldinfo(fieldname = "height", caption = "height", datetype = Types.VARCHAR)
public CField height; // height
@CFieldinfo(fieldname = "importway", caption = "importway", datetype = Types.INTEGER)
public CField importway; // importway
@CFieldinfo(fieldname = "importor", caption = "importor", datetype = Types.VARCHAR)
public CField importor; // importor
@CFieldinfo(fieldname = "cellphone", caption = "cellphone", datetype = Types.VARCHAR)
public CField cellphone; // cellphone
@CFieldinfo(fieldname = "urgencycontact", caption = "urgencycontact", datetype = Types.VARCHAR)
public CField urgencycontact; // urgencycontact
@CFieldinfo(fieldname = "telphone", caption = "telphone", datetype = Types.VARCHAR)
public CField telphone; // telphone
@CFieldinfo(fieldname = "introducer", caption = "introducer", datetype = Types.VARCHAR)
public CField introducer; // introducer
@CFieldinfo(fieldname = "guarantor", caption = "guarantor", datetype = Types.VARCHAR)
public CField guarantor; // guarantor
@CFieldinfo(fieldname = "skill", caption = "skill", datetype = Types.VARCHAR)
public CField skill; // skill
@CFieldinfo(fieldname = "skillfullanguage", caption = "skillfullanguage", datetype = Types.VARCHAR)
public CField skillfullanguage; // skillfullanguage
@CFieldinfo(fieldname = "speciality", caption = "speciality", datetype = Types.VARCHAR)
public CField speciality; // speciality
@CFieldinfo(fieldname = "welfare", caption = "welfare", datetype = Types.VARCHAR)
public CField welfare; // welfare
@CFieldinfo(fieldname = "talentstype", caption = "talentstype", datetype = Types.INTEGER)
public CField talentstype; // talentstype
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "orgid", datetype = Types.INTEGER)
public CField orgid; // orgid
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "orgcode", datetype = Types.VARCHAR)
public CField orgcode; // orgcode
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "orgname", datetype = Types.VARCHAR)
public CField orgname; // orgname
@CFieldinfo(fieldname = "lv_id", caption = "lv_id", datetype = Types.INTEGER)
public CField lv_id; // lv_id
@CFieldinfo(fieldname = "lv_num", caption = "lv_num", datetype = Types.DECIMAL)
public CField lv_num; // lv_num
@CFieldinfo(fieldname = "hg_id", caption = "hg_id", datetype = Types.INTEGER)
public CField hg_id; // hg_id
@CFieldinfo(fieldname = "hg_code", caption = "hg_code", datetype = Types.VARCHAR)
public CField hg_code; // hg_code
@CFieldinfo(fieldname = "hg_name", caption = "hg_name", datetype = Types.VARCHAR)
public CField hg_name; // hg_name
@CFieldinfo(fieldname = "ospid", notnull = true, caption = "ospid", datetype = Types.INTEGER)
public CField ospid; // ospid
@CFieldinfo(fieldname = "ospcode", caption = "ospcode", datetype = Types.VARCHAR)
public CField ospcode; // ospcode
@CFieldinfo(fieldname = "sp_name", caption = "sp_name", datetype = Types.VARCHAR)
public CField sp_name; // sp_name
@CFieldinfo(fieldname = "iskey", caption = "关键岗位", datetype = Types.INTEGER)
public CField iskey; // 关键岗位
@CFieldinfo(fieldname = "hwc_namezq", caption = "职群", datetype = Types.VARCHAR)
public CField hwc_namezq; // 职群
@CFieldinfo(fieldname = "hwc_namezz", caption = "职种", datetype = Types.VARCHAR)
public CField hwc_namezz; // 职种
@CFieldinfo(fieldname = "usable", notnull = true, caption = "usable", datetype = Types.INTEGER)
public CField usable; // usable
@CFieldinfo(fieldname = "sscurty_addr", caption = "sscurty_addr", datetype = Types.VARCHAR)
public CField sscurty_addr; // sscurty_addr
@CFieldinfo(fieldname = "sscurty_startdate", caption = "sscurty_startdate", datetype = Types.TIMESTAMP)
public CField sscurty_startdate; // sscurty_startdate
@CFieldinfo(fieldname = "shoesize", caption = "shoesize", datetype = Types.VARCHAR)
public CField shoesize; // shoesize
@CFieldinfo(fieldname = "pants_code", caption = "pants_code", datetype = Types.VARCHAR)
public CField pants_code; // pants_code
@CFieldinfo(fieldname = "coat_code", caption = "coat_code", datetype = Types.VARCHAR)
public CField coat_code; // coat_code
@CFieldinfo(fieldname = "dorm_bed", caption = "dorm_bed", datetype = Types.VARCHAR)
public CField dorm_bed; // dorm_bed
@CFieldinfo(fieldname = "pay_way", caption = "pay_way", datetype = Types.VARCHAR)
public CField pay_way; // pay_way
@CFieldinfo(fieldname = "schedtype", caption = "schedtype", datetype = Types.VARCHAR)
public CField schedtype; // schedtype
@CFieldinfo(fieldname = "note", caption = "note", datetype = Types.VARCHAR)
public CField note; // note
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "rectname", caption = "招聘人", datetype = Types.VARCHAR)
public CField rectname; // 招聘人
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_train_regex() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/.svn/pristine/5e/5ec4f4574c6638ad0d7009409458c55223fd4cdf.svn-base
package com.hr.perm.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Hr_employee_contract_line extends CJPA {
@CFieldinfo(fieldname="conlineid",iskey=true,notnull=true,caption="明细行ID",datetype=Types.INTEGER)
public CField conlineid; //明细行ID
@CFieldinfo(fieldname="con_id",notnull=true,caption="合同ID",datetype=Types.INTEGER)
public CField con_id; //合同ID
@CFieldinfo(fieldname="changetype",caption="异动类型。1、终止;2解除;3变更",datetype=Types.INTEGER)
public CField changetype; //异动类型。1、终止;2解除;3变更
@CFieldinfo(fieldname="description",notnull=true,caption="异动说明",datetype=Types.VARCHAR)
public CField description; //异动说明
@CFieldinfo(fieldname="changetime",caption="异动时间",datetype=Types.TIMESTAMP)
public CField changetime; //异动时间
@CFieldinfo(fieldname="note",caption="备注",datetype=Types.VARCHAR)
public CField note; //备注
public String SqlWhere; //查询附加条件
public int MaxCount; //查询最大数量
//自关联数据定义
public Hr_employee_contract_line() throws Exception {
}
@Override
public boolean InitObject() {//类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { //类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/hr/asset/co/COHr_asset_reject.java
package com.hr.asset.co;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.cjpa.util.CjpaUtil;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CJPA;
import com.corsair.server.cjpa.JPAController;
import com.corsair.server.genco.COShwUser;
import com.corsair.server.generic.Shw_attach;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.CSearchForm;
import com.corsair.server.util.CorUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.corsair.server.wordflow.Shwwf;
import com.corsair.server.wordflow.Shwwfproc;
import com.hr.base.entity.Hr_grade;
import com.hr.base.entity.Hr_orgposition;
import com.hr.base.entity.Hr_orgpositionkpi;
import com.hr.base.entity.Hr_standposition;
import com.hr.base.entity.Hr_wclass;
import com.hr.asset.entity.Hr_asset_allot_h;
import com.hr.asset.entity.Hr_asset_allot_d;
import com.hr.asset.entity.Hr_asset_item;
import com.hr.asset.entity.Hr_asset_register;
import com.hr.asset.entity.Hr_asset_statement;
import com.hr.asset.entity.Hr_asset_reject_h;
import com.hr.asset.entity.Hr_asset_reject_d;
@ACO(coname = "web.hr.Asset")
public class COHr_asset_reject extends JPAController{
@Override
public void AfterWFStart(CJPA jpa, CDBConnection con, Shwwf wf, boolean isFilished)
throws Exception {
// TODO Auto-generated method stub
checkQty((Hr_asset_reject_h)jpa,con);
if (isFilished) {
doUpdateAssetList(jpa, con);
}
}
@Override
public void OnWfSubmit(CJPA jpa, CDBConnection con, Shwwf wf, Shwwfproc proc,
Shwwfproc nxtproc, boolean isFilished) throws Exception {
// TODO Auto-generated method stub
if (isFilished) {
doUpdateAssetList(jpa, con);
}
}
@Override
public void OnSave(CJPABase jpa, CDBConnection con, ArrayList<PraperedSql> sqllist, boolean selfLink) throws Exception{
checkQty((Hr_asset_reject_h)jpa,con);
}
//流程完成时数据插入流水表
private void doUpdateAssetList(CJPA jpa, CDBConnection con) throws Exception {
Hr_asset_reject_h ar = (Hr_asset_reject_h) jpa;
Hr_asset_statement as = new Hr_asset_statement();
for (CJPABase jpa1:ar.hr_asset_reject_ds){
Hr_asset_reject_d ard = (Hr_asset_reject_d) jpa1;
Float qty = 0-ard.reject_qty.getAsFloat();
as.clear();
//插入报废数据
as.source.setValue("asset_reject");
as.source_id.setValue(ar.asset_reject_id.getValue());
as.source_num.setValue(ar.asset_reject_num.getValue());
as.asset_item_id.setValue(ard.asset_item_id.getValue());
as.asset_item_code.setValue(ard.asset_item_code.getValue());
as.asset_item_name.setValue(ard.asset_item_name.getValue());
as.asset_type_id.setValue(ard.asset_type_id.getValue());
as.asset_type_code.setValue(ard.asset_type_code.getValue());
as.asset_type_name.setValue(ard.asset_type_name.getValue());
//as.brand.setValue(ard.brand.getValue());
//as.model.setValue(ard.model.getValue());
//as.original_value.setValue(ard.original_value.getValue());
//as.net_value.setValue(ard.net_value.getValue());
as.uom.setValue(ard.uom.getValue());
//as.service_life.setValue(ard.service_life.getValue());
//as.acquired_date.setValue(ard.acquired_date.getValue());
as.deploy_area.setValue(ar.deploy_area.getValue());
as.deploy_restaurant_id.setValue(ar.deploy_restaurant_id.getValue());
as.deploy_restaurant.setValue(ar.deploy_restaurant.getValue());
//as.keep_own.setValue(ard.keep_own.getValue());
as.adjust_qty.setAsFloat(qty);
as.adjust_date.setValue(ard.reject_date.getValue());
as.save(con);
}
}
//直接查询物料数据(暂停使用)
@ACOAction(eventname = "finditemlist", Authentication = true, ispublic = false, notes = "物料查询")
public String finditemlist() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String pctid = CorUtil.hashMap2Str(parms, "ctid","需要参数ctid");
Hr_asset_item ai = new Hr_asset_item();
String sqlstr = "SELECT * "+
"FROM hr_asset_item t "+
"WHERE EXISTS (SELECT * "+
"FROM hr_asset_sum s "+
"WHERE s.deploy_restaurant_id = "+pctid+
" AND s.sum_qty > 0)";
return ai.pool.opensql2json(sqlstr);
}
//检查调出数量是否超出该餐厅下的余额数量
private void checkQty(Hr_asset_reject_h ar,CDBConnection con) throws Exception{
for(CJPABase jpa:ar.hr_asset_reject_ds){
Hr_asset_reject_d ard=(Hr_asset_reject_d) jpa;
String restaurantid = ar.deploy_restaurant_id.getValue();
String itemid = ard.asset_item_id.getValue();
String sqlstr = "SELECT t.sum_qty "+
" FROM hr_asset_sum t "+
" WHERE t.deploy_restaurant_id = "+restaurantid+
" AND t.asset_item_id = " +itemid;
JSONArray result = con.opensql2json_o(sqlstr);
if (!result.isEmpty()){
int qty = result.getJSONObject(0).getInt("sum_qty");
if(qty<ard.reject_qty.getAsInt()){
throw new Exception("报废数量超过该餐厅可用余额数量("+qty+"),不允许保存和提交");
}
}else{
throw new Exception("该资产在调出餐厅下没有配置,不允许报废");
}
}
}
//查询资产登记数据
@ACOAction(eventname = "findAssetregisterlist", Authentication = true, ispublic = false, notes = "登记信息查询")
public String findAssetregisterlist() throws Exception {
HashMap<String, String> parms = CSContext.getParms();
String pctid = CorUtil.hashMap2Str(parms, "pctid","需要参数pctid");
Hr_asset_register ar = new Hr_asset_register();
String sqlstr = "SELECT t.*"+
" FROM hr_asset_register t"+
" WHERE t.stat = 9"+
" AND EXISTS (SELECT 1"+
" FROM hr_asset_sum a"+
" WHERE a.asset_item_id = t.asset_item_id"+
" AND a.deploy_restaurant_id = "+pctid+
" AND a.sum_qty > 0)";
return ar.pool.opensql2json(sqlstr);
}
}
<file_sep>/src/com/corsair/server/generic/Shworg.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shworg extends CJPA {
@CFieldinfo(fieldname = "orgid", iskey = true, notnull = true, caption = "ID", datetype = Types.INTEGER)
public CField orgid; // ID
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "名称", datetype = Types.VARCHAR)
public CField orgname; // 名称
@CFieldinfo(fieldname = "code", codeid = 15, caption = "编码", datetype = Types.VARCHAR)
public CField code; // 编码
@CFieldinfo(fieldname = "superid", notnull = true, caption = "父ID", datetype = Types.DECIMAL)
public CField superid; // 父ID
@CFieldinfo(fieldname = "extorgname", caption = "全路径名称", datetype = Types.VARCHAR)
public CField extorgname; // 全路径名称
@CFieldinfo(fieldname = "manager", caption = "第一负责人", datetype = Types.VARCHAR)
public CField manager; // 第一负责人
@CFieldinfo(fieldname = "vicemanager", caption = "第二负责人", datetype = Types.VARCHAR)
public CField vicemanager; // 第二负责人
@CFieldinfo(fieldname = "managerpos", caption = "第一负责人岗位", datetype = Types.VARCHAR)
public CField managerpos; // 第一负责人岗位
@CFieldinfo(fieldname = "vicemanagerpos", caption = "第二负责人岗位", datetype = Types.VARCHAR)
public CField vicemanagerpos; // 第二负责人岗位
@CFieldinfo(fieldname = "emailmanager", caption = "邮件管理员", datetype = Types.VARCHAR)
public CField emailmanager; // 邮件管理员
@CFieldinfo(fieldname = "emailuser", caption = "emailuser", datetype = Types.VARCHAR)
public CField emailuser; // emailuser
// @CFieldinfo(fieldname = "stat", caption = "状态", datetype = Types.INTEGER)
// public CField stat; // 状态
@CFieldinfo(fieldname = "usable", caption = "可用", defvalue = "1", datetype = Types.INTEGER)
public CField usable; // 可用
@CFieldinfo(fieldname = "orgtype", notnull = true, caption = "类型", datetype = Types.INTEGER)
public CField orgtype; // 类型数据字典
@CFieldinfo(fieldname = "pubfdrid", caption = "pubfdrid", datetype = Types.INTEGER)
public CField pubfdrid; // pubfdrid
@CFieldinfo(fieldname = "focusfdrid1", caption = "焦点文件", datetype = Types.INTEGER)
public CField focusfdrid1; // 焦点文件
@CFieldinfo(fieldname = "focusfdrid2", caption = "焦点文件", datetype = Types.INTEGER)
public CField focusfdrid2; // 焦点文件
@CFieldinfo(fieldname = "mrporgid", caption = "计划部门", datetype = Types.VARCHAR)
public CField mrporgid; // 计划部门
@CFieldinfo(fieldname = "areaid", caption = "区域ID", datetype = Types.INTEGER)
public CField areaid; // 区域ID
@CFieldinfo(fieldname = "idpath", caption = "路径", datetype = Types.VARCHAR)
public CField idpath; // 路径
@CFieldinfo(fieldname = "typepath", caption = "typepath", datetype = Types.VARCHAR)
public CField typepath; // typepath
@CFieldinfo(fieldname = "creator", caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "showinposition", caption = "showinposition", datetype = Types.INTEGER)
public CField showinposition; // showinposition
@CFieldinfo(fieldname = "note", caption = "备注", datetype = Types.VARCHAR)
public CField note; // 备注
@CFieldinfo(fieldname = "width", caption = "width", datetype = Types.INTEGER)
public CField width; // width
@CFieldinfo(fieldname = "height", caption = "height", datetype = Types.INTEGER)
public CField height; // height
@CFieldinfo(fieldname = "isfeecenter", caption = "isfeecenter", datetype = Types.INTEGER)
public CField isfeecenter; // isfeecenter
@CFieldinfo(fieldname = "sfeecenter", caption = "费用中心", datetype = Types.INTEGER)
public CField sfeecenter; // 费用中心
@CFieldinfo(fieldname = "isbc", caption = "isbc", datetype = Types.INTEGER)
public CField isbc; // isbc
@CFieldinfo(fieldname = "orguserid", caption = "机构管理员", datetype = Types.VARCHAR)
public CField orguserid; // 机构管理员
@CFieldinfo(fieldname = "orginvid", caption = "库存中心", datetype = Types.INTEGER)
public CField orginvid; // 库存中心
@CFieldinfo(fieldname = "entid", caption = "组织ID", datetype = Types.INTEGER)
public CField entid; // 组织ID
@CFieldinfo(fieldname = "visituser", caption = "visituser", datetype = Types.VARCHAR)
public CField visituser; // visituser
@CFieldinfo(fieldname = "orglevel", caption = "部门层级", datetype = Types.INTEGER)
public CField orglevel; // 部门层级
@CFieldinfo(fieldname = "orgmail", caption = "机构邮件", datetype = Types.VARCHAR)
public CField orgmail; // 机构邮件
@CFieldinfo(fieldname = "orgaddr", caption = "机构地址", datetype = Types.VARCHAR)
public CField orgaddr; // 机构地址
@CFieldinfo(fieldname = "webset", caption = "网址", datetype = Types.VARCHAR)
public CField webset; // 网址
@CFieldinfo(fieldname = "orgfrof", caption = "部门简介", datetype = Types.VARCHAR)
public CField orgfrof; // 部门简介
@CFieldinfo(fieldname = "orgduty", caption = "部门职责", datetype = Types.VARCHAR)
public CField orgduty; // 部门职责
@CFieldinfo(fieldname = "attribute1", precision = 32, scale = 0, caption = "扩展属性1", datetype = Types.VARCHAR)
public CField attribute1; // 扩展属性1
@CFieldinfo(fieldname = "attribute2", precision = 32, scale = 0, caption = "扩展属性2", datetype = Types.VARCHAR)
public CField attribute2; // 扩展属性2
@CFieldinfo(fieldname = "attribute3", precision = 32, scale = 0, caption = "扩展属性3", datetype = Types.VARCHAR)
public CField attribute3; // 扩展属性3
@CFieldinfo(fieldname = "attribute4", precision = 32, scale = 0, caption = "扩展属性4", datetype = Types.VARCHAR)
public CField attribute4; // 扩展属性4
@CFieldinfo(fieldname = "attribute5", precision = 32, scale = 0, caption = "扩展属性5", datetype = Types.VARCHAR)
public CField attribute5; // 扩展属性5
@CFieldinfo(fieldname = "attribute6", precision = 32, scale = 0, caption = "扩展属性6", datetype = Types.VARCHAR)
public CField attribute6; // 扩展属性6
@CFieldinfo(fieldname = "attribute7", precision = 32, scale = 0, caption = "扩展属性7", datetype = Types.VARCHAR)
public CField attribute7; // 扩展属性7
@CFieldinfo(fieldname = "attribute8", precision = 32, scale = 0, caption = "扩展属性8", datetype = Types.VARCHAR)
public CField attribute8; // 扩展属性8
@CFieldinfo(fieldname = "attribute9", precision = 32, scale = 0, caption = "扩展属性9", datetype = Types.VARCHAR)
public CField attribute9; // 扩展属性9
@CFieldinfo(fieldname = "attribute10", precision = 32, scale = 0, caption = "扩展属性10", datetype = Types.VARCHAR)
public CField attribute10; // 扩展属性10
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public CJPALineData<Shworg_find> shworg_finds;
public Shworg() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
shworg_finds.addLinkField("orgid", "orgid");
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}<file_sep>/src/com/hr/.svn/pristine/6d/6d1ee3f06babca8b3e4ee60b89bd771a665b99cc.svn-base
package com.hr.perm.co;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.dbpool.util.JSONParm;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shworg;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CReport;
import com.corsair.server.util.CorUtil;
import com.hr.base.co.COBaseRpt;
import com.hr.perm.entity.Hr_employee;
import com.hr.util.HRUtil;
/**
* @author Administrator
*
*/
@ACO(coname = "web.hr.permrpt1")
public class COPermRpt1 {
private static String empstids = "1,2,3,4,5,7,8";// 需要计算编制的人事状态 "2,3,4,5";
/**
* 添加扩展的条件,职类 职群 职种 职级
*
* @param tbaname
* @param sqlstr
* @return
* @throws Exception
*/
public static String parExtSQL(String tbaname, String sqlstr) throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String hwc_namezl = CorUtil.getJSONParmValue(jps, "hwc_namezl");
if ((hwc_namezl != null) && (!hwc_namezl.isEmpty())) {
if (tbaname == null)
sqlstr = sqlstr + " and hwc_namezl like '%" + hwc_namezl + "%'";
else
sqlstr = sqlstr + " and " + tbaname + ".hwc_namezl like '%" + hwc_namezl + "%'";
}
String hwc_namezq = CorUtil.getJSONParmValue(jps, "hwc_namezq");
if ((hwc_namezq != null) && (!hwc_namezq.isEmpty())) {
if (tbaname == null)
sqlstr = sqlstr + " and hwc_namezq like '%" + hwc_namezq + "%'";
else
sqlstr = sqlstr + " and " + tbaname + ".hwc_namezq like '%" + hwc_namezq + "%'";
}
String hwc_namezz = CorUtil.getJSONParmValue(jps, "hwc_namezz");
if ((hwc_namezz != null) && (!hwc_namezz.isEmpty())) {
if (tbaname == null)
sqlstr = sqlstr + " and hwc_namezz like '%" + hwc_namezz + "%'";
else
sqlstr = sqlstr + " and " + tbaname + ".hwc_namezz like '%" + hwc_namezz + "%'";
}
String lv_num_sql = CorUtil.getJSONParmValue(jps, "lv_num_sql");
if ((lv_num_sql != null) && (!lv_num_sql.isEmpty())) {
lv_num_sql = (tbaname == null) ? lv_num_sql : lv_num_sql.replace("lv_num", tbaname + ".lv_num");
sqlstr = sqlstr + " " + lv_num_sql;
}
return sqlstr;
}
@ACOAction(eventname = "findEmployeeZWXZPotal", Authentication = true, notes = "人事职位性质分析-门户")
public String findEmployeeZWXZPotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
orgid = (orgid == null) ? CSContext.getDefaultOrgID() : orgid;
String strempclass = CorUtil.hashMap2Str(parms, "empclass");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String sqlstr = "select SUM(1) sumpeo," + " IFNULL(SUM(CASE WHEN e.emnature='脱产' THEN 1 ELSE 0 END),0) ow,"
+ " IFNULL(SUM(CASE WHEN e.emnature='非脱产' THEN 1 ELSE 0 END),0) notow " + " FROM hr_employee e WHERE e.empstatid IN (" + empstids + ") "
+ " AND e.idpath LIKE '" + org.idpath.getValue() + "%'";
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
JSONArray rows = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("org", org.extorgname.getValue());
return rst.toString();
}
// /////////////////学历开始///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeXL", Authentication = true, notes = "人事学历分析")
public String findEmployeeXL() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return findEmployeeXLAndQS(dws, orgid, yearmonths, empclass, includechild, parms).toString();
}
@ACOAction(eventname = "findEmployeeXLPotal", Authentication = true, notes = "人事学历分析-门户")
public String findEmployeeXLPotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
orgid = (orgid == null) ? CSContext.getDefaultOrgID() : orgid;
String strempclass = CorUtil.hashMap2Str(parms, "empclass");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String sqlstr = "select SUM(1) sumpeo," + " SUM(CASE WHEN degree IN (1,2) THEN 1 ELSE 0 END) ss," + " SUM(CASE WHEN degree =3 THEN 1 ELSE 0 END) bk,"
+ " SUM(CASE WHEN degree =4 THEN 1 ELSE 0 END) dz," + " SUM(CASE WHEN degree =5 THEN 1 ELSE 0 END) gz,"
+ " SUM(CASE WHEN degree =6 or degree =7 THEN 1 ELSE 0 END) zzzj," + " SUM(CASE WHEN degree IN(8,9,10,0) THEN 1 ELSE 0 END) cz,"
+ " SUM(CASE WHEN degree IS NULL THEN 1 ELSE 0 END) qt " + " FROM hr_employee e WHERE e.empstatid IN (2, 3, 4, 5) " + " AND e.idpath LIKE '"
+ org.idpath.getValue() + "%'";
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
JSONArray rows = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("org", org.extorgname.getValue());
return rst.toString();
}
@ACOAction(eventname = "findEmployeeXL_QS", Authentication = true, notes = "人事学历趋势分析")
public String findEmployeeXL_QS() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findEmployeeXLAndQS(dws, orgid, yearmonths, empclass, includechild, parms);
dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
JSONArray chartdata = buildXLChartData(findEmployeeXLAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONArray buildXLChartData(JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildYearChartDateRow(rows, "ss", "硕士及以上"));
rst.add(buildYearChartDateRow(rows, "bk", "本科"));
rst.add(buildYearChartDateRow(rows, "dz", "大专"));
rst.add(buildYearChartDateRow(rows, "gz", "高中"));
rst.add(buildYearChartDateRow(rows, "zz", "中专"));
rst.add(buildYearChartDateRow(rows, "zj", "中技"));
rst.add(buildYearChartDateRow(rows, "cz", "初中及以下"));
return rst;
}
private JSONObject buildYearChartDateRow(JSONArray rows, String fdname, String lable) {
JSONObject ss = new JSONObject();
ss.put("label", lable);
JSONArray ssArray = new JSONArray();
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
JSONArray cd = new JSONArray();
String yearmonth = row.getString("yearmonth");
// yearmonth = yearmonth.replace("-", "");
// cd.add(Integer.valueOf(yearmonth));
Date dt = Systemdate.getDateByStr(yearmonth + "-01");
dt = Systemdate.dateMonthAdd(dt, 1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
cd.add(calendar.getTimeInMillis());
if (row.has(fdname))
cd.add(row.getInt(fdname));
else
cd.add(0);
ssArray.add(cd);
}
ss.put("data", ssArray);
return ss;
}
/**
* 学历及趋势分析
*
* @param dws
* @param yearmonths
* @param includechild
* @param parms
* @return
* @throws Exception
*/
private JSONObject findEmployeeXLAndQS(JSONArray dws, String orgid, List<String> yearmonths, int empclass, boolean includechild,
HashMap<String, String> parms) throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0, s_ss = 0, s_bk = 0, s_dz = 0, s_gz = 0, s_zz = 0, s_zj = 0, s_cz = 0, s_qt = 0, s_zzzj = 0;
float bs_ss = 0, bs_bk = 0, bs_dz = 0, bs_gz = 0, bs_zz = 0, bs_zj = 0, bs_cz = 0, bs_qt = 0, bs_zzzj = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
List<String> yms = new ArrayList<String>();
yms.add(dw.getString("yearmonth"));
JSONArray cts = getDegreeEmoloyCts(he, dw, yms, empclass, spname, findtype, includechld);
for (int j = 0; j < cts.size(); j++) {
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("sumpeo");// getDegreeEmoloyssct(he, dw,
// null, yearmonth,
// includechld);// 总人数
s_sumpeo += sumpeo;
int ss = ct.getInt("ss");// getDegreeEmoloyssct(he, dw, "1,2",
// yearmonth, includechld);// 硕士及以上
s_ss += ss;
int bk = ct.getInt("bk");// getDegreeEmoloyssct(he, dw, "3",
// yearmonth, includechld);// 本科
s_bk += bk;
int dz = ct.getInt("dz");// getDegreeEmoloyssct(he, dw, "4",
// yearmonth, includechld);// 大专
s_dz += dz;
int gz = ct.getInt("gz");// getDegreeEmoloyssct(he, dw, "5",
// yearmonth, includechld);// 高中
s_gz += gz;
int zz = ct.getInt("zz");// getDegreeEmoloyssct(he, dw, "6",
// yearmonth, includechld);// 中专
s_zz += zz;
int zj = ct.getInt("zj");// getDegreeEmoloyssct(he, dw, "7",
// yearmonth, includechld);// 中技
s_zj += zj;
int zzzj = ct.getInt("zz") + ct.getInt("zj");
s_zzzj += zzzj;
int cz = ct.getInt("cz");// getDegreeEmoloyssct(he, dw,
// "8,9,10,0", yearmonth,
// includechld);// 高中
s_cz += cz;
int qt = ct.getInt("qt");// getDegreeEmoloyssct(he, dw, "0",
// yearmonth, includechld);// 其他
s_qt += qt;
dw.put("sumpeo", sumpeo);
dw.put("ss", ss);
dw.put("bk", bk);
dw.put("dz", dz);
dw.put("gz", gz);
dw.put("zz", zz);
dw.put("zj", zj);
dw.put("zzzj", zzzj);
dw.put("cz", cz);
dw.put("qt", qt);
dw.put("bss", ((sumpeo > 0) ? (dec.format((float) ss / sumpeo)) : "0.000"));
dw.put("bbk", ((sumpeo > 0) ? (dec.format((float) bk / sumpeo)) : "0.000"));
dw.put("bdz", ((sumpeo > 0) ? (dec.format((float) dz / sumpeo)) : "0.000"));
dw.put("bgz", ((sumpeo > 0) ? (dec.format((float) gz / sumpeo)) : "0.000"));
dw.put("bcz", ((sumpeo > 0) ? (dec.format((float) cz / sumpeo)) : "0.000"));
dw.put("bzz", ((sumpeo > 0) ? (dec.format((float) zz / sumpeo)) : "0.000"));
dw.put("bzj", ((sumpeo > 0) ? (dec.format((float) zj / sumpeo)) : "0.000"));
dw.put("bzzzj", ((sumpeo > 0) ? (dec.format((float) zzzj / sumpeo)) : "0.000"));
dw.put("bqt", ((sumpeo > 0) ? (dec.format((float) qt / sumpeo)) : "0.000"));
}
}
bs_ss = (s_sumpeo == 0) ? 0 : ((float) s_ss / s_sumpeo);
bs_bk = (s_sumpeo == 0) ? 0 : ((float) s_bk / s_sumpeo);
bs_gz = (s_sumpeo == 0) ? 0 : ((float) s_gz / s_sumpeo);
bs_cz = (s_sumpeo == 0) ? 0 : ((float) s_cz / s_sumpeo);
bs_zz = (s_sumpeo == 0) ? 0 : ((float) s_zz / s_sumpeo);
bs_zj = (s_sumpeo == 0) ? 0 : ((float) s_zj / s_sumpeo);
bs_zzzj = (s_sumpeo == 0) ? 0 : ((float) s_zzzj / s_sumpeo);
bs_dz = (s_sumpeo == 0) ? 0 : ((float) s_dz / s_sumpeo);
bs_qt = (s_sumpeo == 0) ? 0 : ((float) s_qt / s_sumpeo);
JSONObject srow = new JSONObject();
srow.put("sumpeo", s_sumpeo);
srow.put("bss", bs_ss);
srow.put("bbk", bs_bk);
srow.put("bgz", bs_gz);
srow.put("bcz", bs_cz);
srow.put("bzz", bs_zz);
srow.put("bzj", bs_zj);
srow.put("bzzzj", bs_zzzj);
srow.put("bdz", bs_dz);
srow.put("bqt", bs_qt);
srow.put("ss", s_ss);
srow.put("bk", s_bk);
srow.put("dz", s_dz);
srow.put("gz", s_gz);
srow.put("zz", s_zz);
srow.put("zj", s_zj);
srow.put("zzzj", s_zzzj);
srow.put("cz", s_cz);
srow.put("qt", s_qt);
srow.put("orgname", "合计");
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
/**
* 学历Ex
*
* @param he
* @param dw
* @param yms
* 月度列表
* @param includchd
* @return
* @throws Exception
*/
private JSONArray getDegreeEmoloyCts(Hr_employee he, JSONObject dw, List<String> yms, int empclass, String spname, int findtype, boolean includchd) throws Exception {
String yearmonths = "";
for (String ym : yms) {
yearmonths += "'" + ym + "',";
}
if (yearmonths.length() > 0)
yearmonths = yearmonths.substring(0, yearmonths.length() - 1);
boolean isnowmonth = (yms.size() == 1) && isNowMonth(yearmonths);
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + " '" + yms.get(0) + "' yearmonth,";
else
sqlstr = sqlstr + " yearmonth,";
sqlstr = sqlstr + " SUM(1) sumpeo," + " SUM(CASE WHEN degree IN (1,2) THEN 1 ELSE 0 END) ss," + " SUM(CASE WHEN degree =3 THEN 1 ELSE 0 END) bk,"
+ " SUM(CASE WHEN degree =4 THEN 1 ELSE 0 END) dz," + " SUM(CASE WHEN degree =5 THEN 1 ELSE 0 END) gz,"
+ " SUM(CASE WHEN degree =6 THEN 1 ELSE 0 END) zz," + " SUM(CASE WHEN degree =7 THEN 1 ELSE 0 END) zj,"
+ " SUM(CASE WHEN degree IN(8,9,10,0) THEN 1 ELSE 0 END) cz," + " SUM(CASE WHEN degree IS NULL THEN 1 ELSE 0 END) qt";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_employee e";
else
sqlstr = sqlstr + " FROM hr_month_employee e";
sqlstr = sqlstr + " WHERE e.`empstatid` IN(" + empstids + ") ";
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and e.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and e.sp_name like '%" + spname + "%'";
}
if (yms.size() == 1) {
if (!isnowmonth)
sqlstr = sqlstr + " and yearmonth=" + yearmonths + "";
} else if (yms.size() > 1)
sqlstr = sqlstr + "AND yearmonth IN (" + yearmonths + ") ";
else
throw new Exception("月度长度不能为0");
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
sqlstr = parExtSQL("e", sqlstr);
sqlstr = sqlstr + " GROUP BY yearmonth";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
/**
* 学历
*
* @param he
* @param dw
* @param degree
* @param yearmonth
* @param includchd
* @return
* @throws Exception
*/
// private int getDegreeEmoloyssct(Hr_employee he, JSONObject dw, String
// degree, String yearmonth, boolean includchd) throws Exception {
// String sqlstr = "SELECT count(*) ct FROM hr_month_employee WHERE
// yearmonth='" + yearmonth + "' ";
// if ("0".equals(degree))
// sqlstr = sqlstr + " AND degree is null ";
// else if (degree != null)
// sqlstr = sqlstr + " AND degree in(" + degree + ") ";
//
// sqlstr = sqlstr + " AND empstatid IN(SELECT statvalue FROM
// hr_employeestat WHERE usable=1 AND isquota=1) ";
// if (includchd)
// sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
// else
// sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
// return Integer.valueOf(he.pool.openSql2List(sqlstr).get(0).get("ct"));
// }
// /////////////////学历结束///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeAge", Authentication = true, notes = "人事年龄分析")
public String findEmployeeAge() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return findEmployeeAgeAndQS(dws, orgid, yearmonths, empclass, includechild, parms).toString();
}
@ACOAction(eventname = "findEmployeeAgePotal", Authentication = true, notes = "人事年龄分析门户")
public String findEmployeeAgePotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
orgid = (orgid == null) ? CSContext.getDefaultOrgID() : orgid;
String strempclass = CorUtil.hashMap2Str(parms, "empclass");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String nowdatestr = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM");
String sqlstr = "select IFNULL(SUM(1),0) sumpeo," + " IFNULL(SUM(CASE WHEN age>=50 THEN 1 ELSE 0 END),0) f50,"
+ " IFNULL(SUM(CASE WHEN age>=40 AND age<50 THEN 1 ELSE 0 END),0) f40,"
+ " IFNULL(SUM(CASE WHEN age>=30 AND age<40 THEN 1 ELSE 0 END),0) f30,"
+ " IFNULL(SUM(CASE WHEN age>=18 AND age<30 THEN 1 ELSE 0 END),0) f20," + " IFNULL(SUM(CASE WHEN age<18 THEN 1 ELSE 0 END),0) f00 "
+ " FROM (" + " SELECT he.*, (DATE_FORMAT(FROM_DAYS(TO_DAYS(CONCAT('" + nowdatestr + "','-01')) - TO_DAYS(birthday)),'%Y') + 0) AS age "
+ " FROM hr_employee he where `empstatid` IN(" + empstids + ") ";
if (empclass == 2)
sqlstr = sqlstr + " and he.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and he.emnature='非脱产'";
sqlstr = sqlstr + " AND he.idpath LIKE '" + org.idpath.getValue() + "%') tb ";
JSONArray rows = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("org", org.extorgname.getValue());
return rst.toString();
}
@ACOAction(eventname = "findEmployeeAge_QS", Authentication = true, notes = "人事年龄趋势分析")
public String findEmployeeAge_QS() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findEmployeeAgeAndQS(dws, orgid, yearmonths, empclass, includechild, parms);
dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
JSONArray chartdata = buildAgeChartData(findEmployeeAgeAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONObject findEmployeeAgeAndQS(JSONArray dws, String orgid, List<String> yearmonths, int empclass, boolean includechild,
HashMap<String, String> parms) throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0, s_f50 = 0, s_f40 = 0, s_f30 = 0, s_f20 = 0, s_f00 = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
List<String> yms = new ArrayList<String>();
yms.add(dw.getString("yearmonth"));
JSONArray cts = getAgetEmpCts(he, dw, yms, empclass, spname, findtype, includechld);
for (int j = 0; j < cts.size(); j++) {
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("sumpeo");// getAgeEmoloyct(he, dw, -1,
// -1, yearmonth,
// includechld);// 总人数
s_sumpeo += sumpeo;
int f50 = ct.getInt("f50");// getAgeEmoloyct(he, dw, 50, -1,
// yearmonth, includechld);// 50岁及以上
s_f50 += f50;
int f40 = ct.getInt("f40");// getAgeEmoloyct(he, dw, 40, 50,
// yearmonth, includechld);//
// 40(含)-50岁
s_f40 += f40;
int f30 = ct.getInt("f30");// getAgeEmoloyct(he, dw, 30, 40,
// yearmonth, includechld);//
// 30(含)-40岁
s_f30 += f30;
int f20 = ct.getInt("f20");// getAgeEmoloyct(he, dw, 18, 30,
// yearmonth, includechld);//
// 18(含)-30岁
s_f20 += f20;
int f00 = ct.getInt("f00");// getAgeEmoloyct(he, dw, -1, 18,
// yearmonth, includechld);// 18岁以下
s_f00 += f00;
dw.put("sumpeo", sumpeo);
dw.put("f50", f50);
dw.put("f40", f40);
dw.put("f30", f30);
dw.put("f20", f20);
dw.put("f00", f00);
dw.put("bf50", ((sumpeo > 0) ? (dec.format((float) f50 / sumpeo)) : "0.000"));
dw.put("bf40", ((sumpeo > 0) ? (dec.format((float) f40 / sumpeo)) : "0.000"));
dw.put("bf30", ((sumpeo > 0) ? (dec.format((float) f30 / sumpeo)) : "0.000"));
dw.put("bf20", ((sumpeo > 0) ? (dec.format((float) f20 / sumpeo)) : "0.000"));
dw.put("bf00", ((sumpeo > 0) ? (dec.format((float) f00 / sumpeo)) : "0.000"));
}
}
JSONObject srow = new JSONObject();
srow.put("sumpeo", s_sumpeo);
srow.put("f50", s_f50);
srow.put("f40", s_f40);
srow.put("f30", s_f30);
srow.put("f20", s_f20);
srow.put("f00", s_f00);
srow.put("bf50", ((s_sumpeo > 0) ? (dec.format((float) s_f50 / s_sumpeo)) : "0.000"));
srow.put("bf40", ((s_sumpeo > 0) ? (dec.format((float) s_f40 / s_sumpeo)) : "0.000"));
srow.put("bf30", ((s_sumpeo > 0) ? (dec.format((float) s_f30 / s_sumpeo)) : "0.000"));
srow.put("bf20", ((s_sumpeo > 0) ? (dec.format((float) s_f20 / s_sumpeo)) : "0.000"));
srow.put("bf00", ((s_sumpeo > 0) ? (dec.format((float) s_f00 / s_sumpeo)) : "0.000"));
srow.put("orgname", "合计");
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONArray buildAgeChartData(JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildYearChartDateRow(rows, "f50", "50岁及以上"));
rst.add(buildYearChartDateRow(rows, "f40", "40(含)-50岁"));
rst.add(buildYearChartDateRow(rows, "f30", "30(含)-40岁"));
rst.add(buildYearChartDateRow(rows, "f20", "18(含)-30岁"));
rst.add(buildYearChartDateRow(rows, "f00", "18岁以下"));
return rst;
}
private JSONArray getAgetEmpCts(Hr_employee he, JSONObject dw, List<String> yms, int empclass, String spname, int findtype, boolean includchd) throws Exception {
String yearmonths = "";
for (String ym : yms) {
yearmonths += "'" + ym + "',";
}
if (yearmonths.length() > 0)
yearmonths = yearmonths.substring(0, yearmonths.length() - 1);
boolean isnowmonth = false;
if (yms.size() == 1) {
isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yms.get(0));
}
String nowdatestr = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM");
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + " '" + yms.get(0) + "' yearmonth,";
else
sqlstr = sqlstr + " yearmonth,";
sqlstr = sqlstr + " IFNULL(SUM(1),0) sumpeo," + " IFNULL(SUM(CASE WHEN age>=50 THEN 1 ELSE 0 END),0) f50,"
+ " IFNULL(SUM(CASE WHEN age>=40 AND age<50 THEN 1 ELSE 0 END),0) f40,"
+ " IFNULL(SUM(CASE WHEN age>=30 AND age<40 THEN 1 ELSE 0 END),0) f30,"
+ " IFNULL(SUM(CASE WHEN age>=18 AND age<30 THEN 1 ELSE 0 END),0) f20," + " IFNULL(SUM(CASE WHEN age<18 THEN 1 ELSE 0 END),0) f00 ";
if (isnowmonth) {
sqlstr = sqlstr + " FROM (" + " SELECT he.*, (DATE_FORMAT(FROM_DAYS(TO_DAYS(CONCAT('" + nowdatestr
+ "','-01')) - TO_DAYS(birthday)),'%Y') + 0) AS age " + " FROM hr_employee he where `empstatid` IN(" + empstids + ") ";
} else
sqlstr = sqlstr + " FROM (" + " SELECT he.*, (DATE_FORMAT(FROM_DAYS(TO_DAYS(CONCAT(yearmonth,'-01')) - TO_DAYS(birthday)),'%Y') + 0) AS age "
+ " FROM hr_month_employee he where `empstatid` IN(" + empstids + ") ";
if (yms.size() == 1) {
if (!isnowmonth)
sqlstr = sqlstr + " and yearmonth=" + yearmonths + "";
} else if (yms.size() > 1)
sqlstr = sqlstr + "AND yearmonth IN (" + yearmonths + ") ";
else
throw new Exception("月度长度不能为0");
if (empclass == 2)
sqlstr = sqlstr + " and emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
sqlstr = parExtSQL("he", sqlstr);
sqlstr = sqlstr + " ) tb ";
if (!isnowmonth)
sqlstr = sqlstr + " GROUP BY tb.yearmonth";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
// // -1 作为条件 包含minAge
// private int getAgeEmoloyct(Hr_employee he, JSONObject dw, int minAge, int
// MaxAge, String yearmonth, boolean includchd) throws Exception {
// String sqlstr = "SELECT COUNT(*) ct FROM ("
// + " SELECT he.*, (DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW()) -
// TO_DAYS(birthday)),'%Y') + 0) AS age "
// + " FROM hr_month_employee he WHERE yearmonth='" + yearmonth +
// "' AND empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1
// AND isquota=1 ) ";
// if (includchd)
// sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%' ";
// else
// sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
// sqlstr = sqlstr + ") tb where 1=1 ";
// if (minAge != -1)
// sqlstr = sqlstr + " and tb.age>=" + minAge;
// if (MaxAge != -1)
// sqlstr = sqlstr + " and tb.age<" + MaxAge;
// return Integer.valueOf(he.pool.openSql2List(sqlstr).get(0).get("ct"));
// }
// /////////////////年龄结束///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeSex", Authentication = true, notes = "人事性别分析")
public String findEmployeeSex() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return findEmployeeSexAndQS(dws, orgid, yearmonths, empclass, includechild, parms).toString();
}
@ACOAction(eventname = "findEmployeeSexPotal", Authentication = true, notes = "人事性别分析门户")
public String findEmployeeSexPotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
orgid = (orgid == null) ? CSContext.getDefaultOrgID() : orgid;
String strempclass = CorUtil.hashMap2Str(parms, "empclass");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String sqlstr = "SELECT IFNULL(SUM(1), 0) sumpeo, " + " IFNULL(SUM(1),0) sumpeo," + " IFNULL(SUM(CASE WHEN sex=1 THEN 1 ELSE 0 END),0) nv,"
+ " IFNULL(SUM(CASE WHEN sex =2 THEN 1 ELSE 0 END),0) nan" + " FROM hr_employee e " + " WHERE e.`empstatid` IN(" + empstids + ") ";
sqlstr = sqlstr + " AND idpath LIKE '" + org.idpath.getValue() + "%'";
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
JSONArray rows = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("org", org.extorgname.getValue());
return rst.toString();
}
@ACOAction(eventname = "findEmployeeSex_QS", Authentication = true, notes = "人事性别趋势分析")
public String findEmployeeSex_QS() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findEmployeeSexAndQS(dws, orgid, yearmonths, empclass, includechild, parms);
dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
JSONArray chartdata = buildSexChartData(findEmployeeSexAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONArray buildSexChartData(JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildYearChartDateRow(rows, "nan", "男"));
rst.add(buildYearChartDateRow(rows, "nv", "女"));
return rst;
}
private JSONObject findEmployeeSexAndQS(JSONArray dws, String orgid, List<String> yearmonths, int empclass, boolean includechild,
HashMap<String, String> parms) throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0, s_nan = 0, s_nv = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
List<String> yms = new ArrayList<String>();
yms.add(dw.getString("yearmonth"));
JSONArray cts = getSexEmpCts(he, dw, yms, empclass, spname, findtype, includechld);
for (int j = 0; j < cts.size(); j++) {
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("sumpeo");// 总人数
s_sumpeo += sumpeo;
int nan = ct.getInt("nan");
s_nan += nan;
int nv = ct.getInt("nv");
s_nv += nv;
dw.put("sumpeo", sumpeo);
dw.put("nan", nan);
dw.put("nv", nv);
dw.put("bnan", ((sumpeo > 0) ? (dec.format((float) nan / sumpeo)) : "0.000"));
dw.put("bnv", ((sumpeo > 0) ? (dec.format((float) nv / sumpeo)) : "0.000"));
}
}
JSONObject srow = new JSONObject();
srow.put("sumpeo", s_sumpeo);
srow.put("nan", s_nan);
srow.put("nv", s_nv);
srow.put("orgname", "合计");
srow.put("bnan", ((s_sumpeo > 0) ? (dec.format((float) s_nan / s_sumpeo)) : "0.000"));
srow.put("bnv", ((s_sumpeo > 0) ? (dec.format((float) s_nv / s_sumpeo)) : "0.000"));
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONArray getSexEmpCts(Hr_employee he, JSONObject dw, List<String> yms, int empclass, String spname, int findtype, boolean includchd) throws Exception {
String yearmonths = "";
for (String ym : yms) {
yearmonths += "'" + ym + "',";
}
if (yearmonths.length() > 0)
yearmonths = yearmonths.substring(0, yearmonths.length() - 1);
boolean isnowmonth = false;
if (yms.size() == 1) {
isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yms.get(0));
}
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + "'" + Systemdate.getStrDateByFmt(new Date(), "yyyy-MM") + "' yearmonth, ";
else
sqlstr = sqlstr + " yearmonth,";
sqlstr = sqlstr + " IFNULL(SUM(1),0) sumpeo," + " IFNULL(SUM(CASE WHEN sex=1 THEN 1 ELSE 0 END),0) nv,"
+ " IFNULL(SUM(CASE WHEN sex =2 THEN 1 ELSE 0 END),0) nan";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_employee e ";
else
sqlstr = sqlstr + " FROM hr_month_employee e ";
sqlstr = sqlstr + " WHERE e.`empstatid` IN(" + empstids + ") ";
if (isnowmonth) {
} else {
if (yms.size() == 1)
sqlstr = sqlstr + " and yearmonth=" + yearmonths + "";
else if (yms.size() > 1)
sqlstr = sqlstr + "AND yearmonth IN (" + yearmonths + ") ";
else
throw new Exception("月度长度不能为0");
}
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
sqlstr = parExtSQL("e", sqlstr);
if (!isnowmonth)
sqlstr = sqlstr + " GROUP BY yearmonth";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
// // sex -1 所有
// private int getDegreeEmoloySexct(Hr_employee he, JSONObject dw, int sex,
// String yearmonth, boolean includchd) throws Exception {
// String sqlstr = "SELECT count(*) ct FROM hr_month_employee WHERE
// yearmonth='" + yearmonth + "'";
// if (sex != -1)
// sqlstr = sqlstr + " AND sex =" + sex + " ";
// sqlstr = sqlstr + " AND empstatid IN(SELECT statvalue FROM
// hr_employeestat WHERE usable=1 AND isquota=1) ";
// if (includchd)
// sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
// else
// sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
// return Integer.valueOf(he.pool.openSql2List(sqlstr).get(0).get("ct"));
// }
// /////////////////性别结束///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeMZ", Authentication = true, notes = "员工民族分析")
public String findEmployeeMZ() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths); // 第一个为当前机构
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0;
JSONObject srow = new JSONObject();
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
boolean includechld = dw.getInt("_incc") == 1;// (!includechild || (i != 0));// 包含子机构 且 为自身机构时候
// 不查询子机构数据
String yearmonth = dw.getString("yearmonth");
JSONArray mzs = getEmployeeMZ(he, dw, yearmonth, spname, findtype, includechld);
int sumpeo = 0;
for (int j = 0; j < mzs.size(); j++) {
JSONObject mz = mzs.getJSONObject(j);
int ct = mz.getInt("ct");
sumpeo = sumpeo + ct;
String fdname = "f" + mz.getString("dictvalue");
dw.put(fdname, ct);
if (srow.has(fdname))
srow.put(fdname, srow.getInt(fdname) + ct);
else
srow.put(fdname, ct);
}
dw.put("sumpeo", sumpeo);
s_sumpeo += sumpeo;
for (int j = 0; j < mzs.size(); j++) {
JSONObject mz = mzs.getJSONObject(j);
if (sumpeo != 0) {
int ct = mz.getInt("ct");
dw.put("bf" + mz.getString("dictvalue"), dec.format((float) ct / sumpeo));
} else {
dw.put("bf" + mz.getString("dictvalue"), 0);
}
}
}
srow.put("orgname", "合计");
srow.put("sumpeo", s_sumpeo);
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONArray getEmployeeMZ(Hr_employee he, JSONObject dw, String yearmonth, String spname, int findtype, boolean includchd) throws Exception {
boolean isnowmonth = isNowMonth("'" + yearmonth + "'");
String sqlstr = "SELECT d.dictvalue,IFNULL(ct,0) ct FROM shwdict d LEFT JOIN " + " (SELECT anation,COUNT(*) ct FROM ("
+ " SELECT IF(e.`nation` IS NULL,57,e.`nation`) anation, " +
" e.* FROM ";
if (isnowmonth) {
sqlstr = sqlstr + "hr_employee e WHERE ";
} else {
sqlstr = sqlstr + "hr_month_employee e WHERE yearmonth='" + yearmonth + "' AND ";
}
sqlstr = sqlstr + " empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) ";
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL(null, sqlstr);
sqlstr = sqlstr + " ) tb" + " GROUP BY anation) tb1 ON d.dictvalue=tb1.anation" + " WHERE d.pid=797" + " ORDER BY (d.dictvalue+0)";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
// /////////////////名族结束///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeLev", Authentication = true, notes = "员工职级分布分析")
public String findEmployeeLev() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return findEmployeeLevAndQS(dws, orgid, yearmonths, empclass, includechild, parms).toString();
}
@ACOAction(eventname = "findEmployeeLev_QS", Authentication = true, notes = "员工职级趋势分析")
public String findEmployeeLev_QS() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findEmployeeLevAndQS(dws, orgid, yearmonths, empclass, includechild, parms);
dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
JSONArray chartdata = buildLevChartData(findEmployeeLevAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONArray buildLevChartData(JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildYearChartDateRow(rows, "f1", "1.1-1.3"));
rst.add(buildYearChartDateRow(rows, "f2", "2.0"));
rst.add(buildYearChartDateRow(rows, "f21", "2.1-2.3"));
rst.add(buildYearChartDateRow(rows, "f3", "3.0"));
rst.add(buildYearChartDateRow(rows, "f31", "3.1-3.3"));
rst.add(buildYearChartDateRow(rows, "f4", "4.0"));
rst.add(buildYearChartDateRow(rows, "f41", "4.1-4.3"));
rst.add(buildYearChartDateRow(rows, "f51", "5.1-5.2"));
rst.add(buildYearChartDateRow(rows, "f61", "6.1-6.3"));
rst.add(buildYearChartDateRow(rows, "f71", "7.1-7.2"));
rst.add(buildYearChartDateRow(rows, "f8", "8.0"));
return rst;
}
private JSONObject findEmployeeLevAndQS(JSONArray dws, String orgid, List<String> yearmonths, int empclass, boolean includechild,
HashMap<String, String> parms) throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0, s_f1 = 0, s_f2 = 0, s_f21 = 0, s_f3 = 0, s_f31 = 0, s_f4 = 0, s_f41 = 0, s_f51 = 0, s_f61 = 0, s_f71 = 0, s_f8 = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
List<String> yms = new ArrayList<String>();
yms.add(dw.getString("yearmonth"));
JSONArray cts = getEmployeeLevcts(he, dw, yms, empclass, spname, findtype, includechld);
for (int j = 0; j < cts.size(); j++) {
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("sumpeo");// 总人数
s_sumpeo += sumpeo;
int f1 = ct.getInt("f1");//
s_f1 += f1;
int f2 = ct.getInt("f2");//
s_f2 += f2;
int f21 = ct.getInt("f21");//
s_f21 += f21;
int f3 = ct.getInt("f3");//
s_f3 += f3;
int f31 = ct.getInt("f31");//
s_f31 += f31;
int f4 = ct.getInt("f4");//
s_f4 += f4;
int f41 = ct.getInt("f41");//
s_f41 += f41;
int f51 = ct.getInt("f51");//
s_f51 += f51;
int f61 = ct.getInt("f61");//
s_f61 += f61;
int f71 = ct.getInt("f71");//
s_f71 += f71;
int f8 = ct.getInt("f8");//
s_f8 += f8;
dw.put("sumpeo", sumpeo);
dw.put("f1", f1);
dw.put("f2", f2);
dw.put("f21", f21);
dw.put("f3", f3);
dw.put("f31", f31);
dw.put("f4", f4);
dw.put("f41", f41);
dw.put("f51", f51);
dw.put("f61", f61);
dw.put("f71", f71);
dw.put("f8", f8);
dw.put("bf1", ((sumpeo > 0) ? (dec.format((float) f1 / sumpeo)) : "0.000"));
dw.put("bf2", ((sumpeo > 0) ? (dec.format((float) f2 / sumpeo)) : "0.000"));
dw.put("bf21", ((sumpeo > 0) ? (dec.format((float) f21 / sumpeo)) : "0.000"));
dw.put("bf3", ((sumpeo > 0) ? (dec.format((float) f3 / sumpeo)) : "0.000"));
dw.put("bf31", ((sumpeo > 0) ? (dec.format((float) f31 / sumpeo)) : "0.000"));
dw.put("bf4", ((sumpeo > 0) ? (dec.format((float) f4 / sumpeo)) : "0.000"));
dw.put("bf41", ((sumpeo > 0) ? (dec.format((float) f41 / sumpeo)) : "0.000"));
dw.put("bf51", ((sumpeo > 0) ? (dec.format((float) f51 / sumpeo)) : "0.000"));
dw.put("bf61", ((sumpeo > 0) ? (dec.format((float) f61 / sumpeo)) : "0.000"));
dw.put("bf71", ((sumpeo > 0) ? (dec.format((float) f71 / sumpeo)) : "0.000"));
dw.put("bf8", ((sumpeo > 0) ? (dec.format((float) f8 / sumpeo)) : "0.000"));
}
}
JSONObject srow = new JSONObject();
srow.put("sumpeo", s_sumpeo);
srow.put("f1", s_f1);
srow.put("f2", s_f2);
srow.put("f21", s_f21);
srow.put("f3", s_f3);
srow.put("f31", s_f31);
srow.put("f4", s_f4);
srow.put("f41", s_f41);
srow.put("f51", s_f51);
srow.put("f61", s_f61);
srow.put("f71", s_f71);
srow.put("f8", s_f8);
srow.put("orgname", "合计");
srow.put("bf1", ((s_sumpeo > 0) ? (dec.format((float) s_f1 / s_sumpeo)) : "0.000"));
srow.put("bf2", ((s_sumpeo > 0) ? (dec.format((float) s_f2 / s_sumpeo)) : "0.000"));
srow.put("bf21", ((s_sumpeo > 0) ? (dec.format((float) s_f21 / s_sumpeo)) : "0.000"));
srow.put("bf3", ((s_sumpeo > 0) ? (dec.format((float) s_f3 / s_sumpeo)) : "0.000"));
srow.put("bf31", ((s_sumpeo > 0) ? (dec.format((float) s_f31 / s_sumpeo)) : "0.000"));
srow.put("bf4", ((s_sumpeo > 0) ? (dec.format((float) s_f4 / s_sumpeo)) : "0.000"));
srow.put("bf41", ((s_sumpeo > 0) ? (dec.format((float) s_f41 / s_sumpeo)) : "0.000"));
srow.put("bf51", ((s_sumpeo > 0) ? (dec.format((float) s_f51 / s_sumpeo)) : "0.000"));
srow.put("bf61", ((s_sumpeo > 0) ? (dec.format((float) s_f61 / s_sumpeo)) : "0.000"));
srow.put("bf71", ((s_sumpeo > 0) ? (dec.format((float) s_f71 / s_sumpeo)) : "0.000"));
srow.put("bf8", ((s_sumpeo > 0) ? (dec.format((float) s_f8 / s_sumpeo)) : "0.000"));
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONArray getEmployeeLevcts(Hr_employee he, JSONObject dw, List<String> yms, int empclass, String spname, int findtype, boolean includchd) throws Exception {
String yearmonths = "";
for (String ym : yms) {
yearmonths += "'" + ym + "',";
}
if (yearmonths.length() > 0)
yearmonths = yearmonths.substring(0, yearmonths.length() - 1);
boolean isnowmonth = (yms.size() == 1) && isNowMonth(yearmonths);
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + " '" + yms.get(0) + "' yearmonth,";
else
sqlstr = sqlstr + " yearmonth,";
sqlstr = sqlstr + " SUM(1) sumpeo," + " SUM(CASE WHEN lv_num>=1.1 AND lv_num<=1.9 THEN 1 ELSE 0 END) f1,"
+ " SUM(CASE WHEN lv_num=2.0 THEN 1 ELSE 0 END) f2," + " SUM(CASE WHEN lv_num>=2.1 AND lv_num<=2.9 THEN 1 ELSE 0 END) f21,"
+ " SUM(CASE WHEN lv_num=3.0 THEN 1 ELSE 0 END) f3," + " SUM(CASE WHEN lv_num>=3.1 AND lv_num<=3.9 THEN 1 ELSE 0 END) f31,"
+ " SUM(CASE WHEN lv_num=4.0 THEN 1 ELSE 0 END) f4," + " SUM(CASE WHEN lv_num>=4.1 AND lv_num<=4.9 THEN 1 ELSE 0 END) f41,"
+ " SUM(CASE WHEN lv_num>=5.1 AND lv_num<=5.9 THEN 1 ELSE 0 END) f51,"
+ " SUM(CASE WHEN lv_num>=6.1 AND lv_num<=6.9 THEN 1 ELSE 0 END) f61,"
+ " SUM(CASE WHEN lv_num>=7.1 AND lv_num<=7.9 THEN 1 ELSE 0 END) f71," + " SUM(CASE WHEN lv_num=8 THEN 1 ELSE 0 END) f8";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_employee e";
else
sqlstr = sqlstr + " FROM hr_month_employee e";
sqlstr = sqlstr + " WHERE e.`empstatid` IN(" + empstids + ") ";
if (yms.size() == 1) {
if (!isnowmonth)
sqlstr = sqlstr + " and yearmonth=" + yearmonths + "";
} else if (yms.size() > 1)
sqlstr = sqlstr + "AND yearmonth IN (" + yearmonths + ") ";
else
throw new Exception("月度长度不能为0");
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and e.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and e.sp_name like '%" + spname + "%'";
}
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
sqlstr = parExtSQL("e", sqlstr);
sqlstr = sqlstr + " GROUP BY yearmonth";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
// // minlev maxLev -1 略过
// /**
// * 职级
// *
// * @param he
// * @param dw
// * @param minlev
// * @param maxLev
// * @param yearmonth
// * @param includchd
// * @return
// * @throws Exception
// */
// private int getEmployeeLevct(Hr_employee he, JSONObject dw, double
// minlev, double maxLev, String yearmonth, boolean includchd) throws
// Exception {
// String sqlstr = "SELECT count(*) ct FROM hr_month_employee WHERE
// yearmonth='" + yearmonth + "' ";
// if (minlev != -1)
// sqlstr = sqlstr + " AND lv_num >=" + minlev + " ";
// if (maxLev != -1)
// sqlstr = sqlstr + " AND lv_num <=" + maxLev + " ";
// sqlstr = sqlstr + " AND empstatid IN(SELECT statvalue FROM
// hr_employeestat WHERE usable=1 AND isquota=1) ";
// if (includchd)
// sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
// else
// sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
// return Integer.valueOf(he.pool.openSql2List(sqlstr).get(0).get("ct"));
// }
// /////////////////职级结束///////////////////////////////////////////
@ACOAction(eventname = "findEmpoyeeOrg", Authentication = true, notes = "员工机构分析")
public String findEmpoyeeOrg() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String ap = CorUtil.hashMap2Str(parms, "allowemptparm");
boolean allowemptparm = (ap == null) ? false : Boolean.valueOf(ap);
String orgid = null, yearmonth_begin = null, yearmonth_end = null;
boolean includechild = false;
int empclass = 1;
if (!allowemptparm) {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
} else {
orgid = CSContext.getDefaultOrgID();
yearmonth_begin = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM");
yearmonth_end = yearmonth_begin;
includechild = true;
}
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
// int ct0 = getOrgEmpctSum(he, org, false);// 自己的总数
// JSONObject dw0 = org.toJsonObj();
// dw0.put("ct", ct0);
// if (sumpeo == 0)
// dw0.put("bct", "0.0000");
// else
// dw0.put("bct", dec.format((float) ct0 / sumpeo));
for (String yearmonth : yearmonths) {
int sumpeo = getOrgEmpctSum(he, org, yearmonth, empclass, spname, findtype, true);// 包括子机构的合计
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
String eyearmonth = dw.getString("yearmonth");
if (yearmonth.equalsIgnoreCase(eyearmonth)) {
boolean includechld = dw.getInt("_incc") == 1;
// 不查询子机构数据
if (sumpeo != 0) {
int ct = getOrgEmpct(he, dw, yearmonth, empclass, spname, findtype, includechld);
dw.put("ct", ct);
dw.put("bct", dec.format((float) ct / sumpeo));
} else {
dw.put("ct", 0);
dw.put("bct", "0.0000");
}
}
}
}
// JSONObject srow = new JSONObject();
// srow.put("ct", sumpeo);
// srow.put("orgname", "合计");
// JSONArray footer = new JSONArray();
// footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
// rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONParm getParmByName(List<JSONParm> jps, String pname) {
for (JSONParm jp : jps) {
if (jp.getParmname().equals(pname))
return jp;
}
return null;
}
private int getOrgEmpctSum(Hr_employee he, Shworg org, String yearmonth, int empclass, String spname, int findtype, boolean includechilds) throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String sqlstr = "SELECT count(*) ct FROM ";
if (isnowmonth)
sqlstr = sqlstr + "hr_employee WHERE 1=1 ";
else
sqlstr = sqlstr + "hr_month_employee WHERE yearmonth='" + yearmonth + "'";
sqlstr = sqlstr + " and usable=1 AND empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) AND idpath LIKE '"
+ org.idpath.getValue() + "%'";
if (empclass == 2)
sqlstr = sqlstr + " and emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL(null, sqlstr);
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("ct"));
}
private int getOrgEmpct(Hr_employee he, JSONObject dw, String yearmonth, int empclass, String spname, int findtype, boolean includchd) throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String sqlstr = "SELECT count(*) ct FROM ";
if (isnowmonth)
sqlstr = sqlstr + "hr_employee WHERE 1=1 ";
else
sqlstr = sqlstr + "hr_month_employee WHERE yearmonth='" + yearmonth + "'";
sqlstr = sqlstr + " AND empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) ";
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
if (empclass == 2)
sqlstr = sqlstr + " and emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL(null, sqlstr);
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("ct"));
}
// /////////////////机构分析结束///////////////////////////////////////////
@ACOAction(eventname = "findEmployeeClass", Authentication = true, notes = "员工职类分析")
public String findEmployeeClass() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return findEmployeeClsAndQS(dws, orgid, yearmonths, empclass, includechild, parms).toString();
}
@ACOAction(eventname = "findEmployeeClassPotal", Authentication = true, notes = "员工职类分析-门户")
public String findEmployeeClassPotal() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String orgid = CorUtil.hashMap2Str(parms, "orgid");
orgid = (orgid == null) ? CSContext.getDefaultOrgID() : orgid;
String strempclass = CorUtil.hashMap2Str(parms, "empclass");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
String sqlstr = "SELECT IFNULL(SUM(1), 0) sumpeo, " + "IFNULL(SUM(CASE WHEN hwc_namezl = 'M类' THEN 1 ELSE 0 END),0) M, "
+ "IFNULL(SUM(CASE WHEN hwc_namezl = 'P类' THEN 1 ELSE 0 END),0) P, " + "IFNULL(SUM(CASE WHEN hwc_namezl = 'A类' THEN 1 ELSE 0 END),0) A, "
+ "IFNULL(SUM(CASE WHEN (hwc_namezl = 'OA' OR hwc_namezl = 'OM' OR hwc_namezl = 'OO' OR hwc_namezl = 'OP') THEN 1 ELSE 0 END),0) O "
+ "FROM hr_employee e WHERE e.empstatid IN (2, 3, 4, 5) " + "AND e.idpath LIKE '" + org.idpath.getValue() + "%'";
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
JSONArray rows = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("org", org.extorgname.getValue());
return rst.toString();
}
@ACOAction(eventname = "findEmployeeClass_QS", Authentication = true, notes = "员工职类趋势分析")
public String findEmployeeClass_QS() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findEmployeeClsAndQS(dws, orgid, yearmonths, empclass, includechild, parms);
dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
JSONArray chartdata = buildClsChartData(findEmployeeClsAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONArray buildClsChartData(JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildYearChartDateRow(rows, "M", "M类"));
rst.add(buildYearChartDateRow(rows, "P", "P类"));
rst.add(buildYearChartDateRow(rows, "A", "A类"));
rst.add(buildYearChartDateRow(rows, "OM", "OM"));
rst.add(buildYearChartDateRow(rows, "OP", "OP"));
rst.add(buildYearChartDateRow(rows, "OA", "OA"));
rst.add(buildYearChartDateRow(rows, "OO", "OO"));
return rst;
}
private JSONObject findEmployeeClsAndQS(JSONArray dws, String orgid, List<String> yearmonths, int empclass, boolean includechild,
HashMap<String, String> parms) throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int s_sumpeo = 0, s_M = 0, s_P = 0, s_A = 0, s_OM = 0, s_OP = 0, s_OA = 0, s_OO = 0, s_SO = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
List<String> yms = new ArrayList<String>();
yms.add(dw.getString("yearmonth"));
JSONArray cts = getEmployeeClsCts(he, dw, yms, empclass, spname, findtype, includechld);
for (int j = 0; j < cts.size(); j++) {
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("sumpeo");// 总人数
s_sumpeo += sumpeo;
int M = ct.getInt("M");//
s_M += M;
int P = ct.getInt("P");//
s_P += P;
int A = ct.getInt("A");//
s_A += A;
int OM = ct.getInt("OM");//
s_OM += OM;
int OP = ct.getInt("OP");//
s_OP += OP;
int OA = ct.getInt("OA");//
s_OA += OA;
int OO = ct.getInt("OO");//
s_OO += OO;
int SO = OM + OP + OA + OO;//
s_SO += SO;
dw.put("sumpeo", sumpeo);
dw.put("M", M);
dw.put("P", P);
dw.put("A", A);
dw.put("OM", OM);
dw.put("OP", OP);
dw.put("OA", OA);
dw.put("OO", OO);
dw.put("SO", SO);
dw.put("bM", ((sumpeo > 0) ? (dec.format((float) M / sumpeo)) : "0.000"));
dw.put("bP", ((sumpeo > 0) ? (dec.format((float) P / sumpeo)) : "0.000"));
dw.put("bA", ((sumpeo > 0) ? (dec.format((float) A / sumpeo)) : "0.000"));
dw.put("bOM", ((sumpeo > 0) ? (dec.format((float) OM / sumpeo)) : "0.000"));
dw.put("bOP", ((sumpeo > 0) ? (dec.format((float) OP / sumpeo)) : "0.000"));
dw.put("bOA", ((sumpeo > 0) ? (dec.format((float) OA / sumpeo)) : "0.000"));
dw.put("bOO", ((sumpeo > 0) ? (dec.format((float) OO / sumpeo)) : "0.000"));
dw.put("bSO", ((sumpeo > 0) ? (dec.format((float) SO / sumpeo)) : "0.000"));
}
}
JSONObject srow = new JSONObject();
srow.put("sumpeo", s_sumpeo);
srow.put("M", s_M);
srow.put("P", s_P);
srow.put("A", s_A);
srow.put("OM", s_OM);
srow.put("OP", s_OP);
srow.put("OA", s_OA);
srow.put("OO", s_OO);
srow.put("SO", s_SO);
srow.put("orgname", "合计");
srow.put("bM", ((s_sumpeo > 0) ? (dec.format((float) s_M / s_sumpeo)) : "0.000"));
srow.put("bP", ((s_sumpeo > 0) ? (dec.format((float) s_P / s_sumpeo)) : "0.000"));
srow.put("bA", ((s_sumpeo > 0) ? (dec.format((float) s_A / s_sumpeo)) : "0.000"));
srow.put("bOM", ((s_sumpeo > 0) ? (dec.format((float) s_OM / s_sumpeo)) : "0.000"));
srow.put("bOP", ((s_sumpeo > 0) ? (dec.format((float) s_OP / s_sumpeo)) : "0.000"));
srow.put("bOA", ((s_sumpeo > 0) ? (dec.format((float) s_OA / s_sumpeo)) : "0.000"));
srow.put("bOO", ((s_sumpeo > 0) ? (dec.format((float) s_OO / s_sumpeo)) : "0.000"));
srow.put("bSO", ((s_sumpeo > 0) ? (dec.format((float) s_SO / s_sumpeo)) : "0.000"));
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private JSONArray getEmployeeClsCts(Hr_employee he, JSONObject dw, List<String> yms, int empclass, String spname, int findtype, boolean includchd) throws Exception {
String yearmonths = "";
for (String ym : yms) {
yearmonths += "'" + ym + "',";
}
if (yearmonths.length() > 0)
yearmonths = yearmonths.substring(0, yearmonths.length() - 1);
boolean isnowmonth = false;
if (yms.size() == 1) {
isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yms.get(0));
}
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + "'" + Systemdate.getStrDateByFmt(new Date(), "yyyy-MM") + "' yearmonth, ";
else
sqlstr = sqlstr + " yearmonth,";
sqlstr = sqlstr + " IFNULL(SUM(1),0) sumpeo," + " IFNULL(SUM(CASE WHEN hwc_namezl='M类' THEN 1 ELSE 0 END),0) M,"
+ " IFNULL(SUM(CASE WHEN hwc_namezl='P类' THEN 1 ELSE 0 END),0) P," + " IFNULL(SUM(CASE WHEN hwc_namezl='A类' THEN 1 ELSE 0 END),0) A,"
+ " IFNULL(SUM(CASE WHEN hwc_namezl='OA' THEN 1 ELSE 0 END),0) OA," + " IFNULL(SUM(CASE WHEN hwc_namezl='OM' THEN 1 ELSE 0 END),0) OM,"
+ " IFNULL(SUM(CASE WHEN hwc_namezl='OO' THEN 1 ELSE 0 END),0) OO," + " IFNULL(SUM(CASE WHEN hwc_namezl='OP' THEN 1 ELSE 0 END),0) OP";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_employee e ";
else
sqlstr = sqlstr + " FROM hr_month_employee e ";
sqlstr = sqlstr + " WHERE e.`empstatid` IN(" + empstids + ") ";
if (isnowmonth) {
} else {
if (yms.size() == 1)
sqlstr = sqlstr + " and yearmonth=" + yearmonths + "";
else if (yms.size() > 1)
sqlstr = sqlstr + "AND yearmonth IN (" + yearmonths + ") ";
else
throw new Exception("月度长度不能为0");
}
if (empclass == 2)
sqlstr = sqlstr + " and e.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and e.emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and e.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and e.sp_name like '%" + spname + "%'";
}
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
sqlstr = parExtSQL("e", sqlstr);
if (!isnowmonth)
sqlstr = sqlstr + " GROUP BY yearmonth";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
// childs包含子节点
public List<HashMap<String, String>> getEmployeeClass(Hr_employee he, JSONObject dw, String yearmonth, boolean childs) throws Exception {
String sqlstr = null;
if (childs)
sqlstr = String.format(EmployeeClassSql, yearmonth, "AND o.idpath LIKE '" + dw.getString("idpath") + "%'");
else
sqlstr = String.format(EmployeeClassSql, yearmonth, "AND o.orgid=" + dw.getString("orgid"));
return HRUtil.getReadPool().openSql2List(sqlstr);
}
private String EmployeeClassSql = "SELECT wc.hw_code, IFNULL(tb1.ct,0) ct " + " FROM hr_wclass wc LEFT JOIN "
+ " (SELECT hwc_idzl,hw_codezl,COUNT(*) ct FROM " + " (SELECT h.*,ho.hwc_idzl,ho.hw_codezl "
+ " FROM hr_month_employee h,hr_orgposition ho,shworg o "
+ " WHERE h.yearmonth='%s' AND h.empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) "
+ " AND h.ospid=ho.ospid AND h.orgid=o.orgid and o.usable=1 " + " %s " + " ) tb " + " GROUP BY hwc_idzl,hw_codezl) tb1 "
+ " ON wc.hwc_id=tb1.hwc_idzl " + " WHERE wc.type_id=1 ";
@ACOAction(eventname = "findblackaddrpt", Authentication = true, notes = "员工加黑分析")
public String findblackaddrpt() throws Exception {
String[] notnull = {};
String sqlstr = "SELECT * FROM hr_black_add WHERE stat=9 " + CSContext.getIdpathwhere();
return new CReport(HRUtil.getReadPool(), sqlstr, "createtime desc", notnull).findReport();
}
@ACOAction(eventname = "findblackdelrpt", Authentication = true, notes = "员工减黑分析")
public String findblackdelrpt() throws Exception {
String[] notnull = {};
String sqlstr = "SELECT * FROM hr_black_del WHERE stat=9 " + CSContext.getIdpathwhere() + " order by createtime desc";
return new CReport(HRUtil.getReadPool(), sqlstr, "createtime desc", notnull).findReport();
}
@ACOAction(eventname = "findzyrpt", Authentication = true, notes = "员工专业分析")
public String findzyrpt() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
List<String> yearmonths = new ArrayList<String>();
yearmonths.add(yearmonth);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths); // 第一个为当前机构
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
int sumpeo = 0;
JSONArray rows = new JSONArray();
for (int i = 0; i < dws.size(); i++) {
boolean includechld = (!includechild || (i != 0));// 包含子机构 且 为自身机构时候
// 不查询子机构数据
JSONObject dw = dws.getJSONObject(i);
JSONArray dwrst = getOrgZYPres(he, dw, yearmonth, empclass, spname, findtype, includechld);
if (dwrst.size() != 0) {
rows.addAll(dwrst);
JSONObject row = dwrst.getJSONObject(dwrst.size() - 1);
sumpeo += row.getInt("ct");
}
}
JSONObject srow = new JSONObject();
srow.put("ct", sumpeo);
srow.put("orgname", "合计");
srow.put("bl", "1");
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(rows, scols);
return null;
}
}
private JSONArray getOrgZYPres(Hr_employee he, JSONObject dw, String yearmonth, int empclass, String spname, int findtype, boolean childs) throws Exception {
boolean isnowmonth = isNowMonth("'" + yearmonth + "'");
String sqlstr = "SELECT '" + yearmonth + "' yearmonth, '" + dw.getString("orgname") + "' orgname, major,COUNT(*) ct "
+ "FROM " + ((isnowmonth) ? "hr_employee" : "hr_month_employee")
+ " where 1=1 ";
if (!isnowmonth)
sqlstr = sqlstr + "and yearmonth='" + yearmonth + "'";
sqlstr += " and empstatid in( " + empstids + " ) ";
if (childs)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
if (empclass == 2)
sqlstr = sqlstr + " and emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL(null, sqlstr);
sqlstr = sqlstr + " GROUP BY major";
JSONArray dwrst = HRUtil.getReadPool().opensql2json_O(sqlstr);
int sumpeo = 0;
for (int i = 0; i < dwrst.size(); i++) {
JSONObject to = dwrst.getJSONObject(i);
sumpeo = sumpeo + to.getInt("ct");
}
DecimalFormat dec = new DecimalFormat("0.0000");
for (int i = 0; i < dwrst.size(); i++) {
JSONObject to = dwrst.getJSONObject(i);
to.put("bl", dec.format((float) to.getInt("ct") / sumpeo));
}
if (dwrst.size() != 0) {
JSONObject to = new JSONObject();
to.put("yearmonth", yearmonth);
to.put("orgname", dw.getString("orgname"));
to.put("major", "小计");
to.put("ct", sumpeo);
dwrst.add(to);
return dwrst;
} else
return dwrst;
}
private int zlzwbzrpttreeid = 0;
@ACOAction(eventname = "findzlzwbzrpt", Authentication = true, notes = "职类职位编制分析")
public String findzlzwbzrpt() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
String ps = parms.get("parms");
if (ps == null) {
throw new Exception("需要参数orgcode");
}
List<JSONParm> jps = CJSON.getParms(ps);
JSONParm jp = getParmByName(jps, "orgcode");
if (jp == null) {
throw new Exception("需要参数orgcode");
}
String orgcode = jp.getParmvalue();
Shworg org = new Shworg();
org.findBySQL("select * from shworg where usable=1 and code='" + orgcode + "'", false);
if (org.isEmpty())
throw new Exception("编码为【" + orgcode + "】的机构不存在");
JSONArray dws = HRUtil.getOrgsByPid(org.orgid.getValue());
Hr_employee he = new Hr_employee();
dws.add(0, org.toJsonObj());
// System.out.println("dws:" + dws.toString());
zlzwbzrpttreeid = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
dw.put("treeid", zlzwbzrpttreeid++);
getzlzwbz(HRUtil.getReadPool(), dw, true);
}
String scols = parms.get("cols");
if (scols == null) {
return dws.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private void getzlzwbz(CDBPool pool, JSONObject dw, boolean childs) throws Exception {
String w = null;
if (childs)
w = "idpath LIKE '" + dw.getString("idpath") + "%'";
else
w = "orgid=" + dw.getString("orgid");
String sqlstr = String.format(orgzlsql, w, w);
JSONArray zls = pool.opensql2json_O(sqlstr);
int dwsumemp = 0;
for (int i = 0; i < zls.size(); i++) {
JSONObject zl = zls.getJSONObject(i);
if (childs)
w = "idpath LIKE '" + dw.getString("idpath") + "%'";
else
w = "orgid=" + dw.getString("orgid");
sqlstr = String.format(orglzempctsql, w, zl.getString("hwc_idzl"));
int quota = Integer.valueOf(zl.getInt("quota"));
int empsum = Integer.valueOf(pool.openSql2List(sqlstr).get(0).get("ct"));
dwsumemp += empsum;
zl.put("empsum", empsum);
zl.put("cbnum", (empsum <= quota) ? 0 : (empsum - quota));
zl.put("treeid", zlzwbzrpttreeid++);
zl.put("state", "closed");
getzwbz(pool, dw, zl, childs);
}
dw.put("empsum", dwsumemp);
dw.put("children", zls);
}
private void getzwbz(CDBPool pool, JSONObject dw, JSONObject zl, boolean childs) throws Exception {
String w = null;
if (childs)
w = "idpath LIKE '" + dw.getString("idpath") + "%'";
else
w = "orgid=" + dw.getString("orgid");
String sqlstr = String.format(orgzlzwctsql, zl.getString("hwc_idzl"), w);
JSONArray jos = pool.opensql2json_O(sqlstr);
int s_empsum = 0;
int s_cbnum = 0;
int s_quota = 0;
for (int i = 0; i < jos.size(); i++) {
JSONObject jo = jos.getJSONObject(i);
sqlstr = String.format(zwempctsql, w, zl.getString("hwc_idzl"), jo.get("sp_id"));
int quota = Integer.valueOf(jo.getInt("quota"));
int empsum = Integer.valueOf(pool.openSql2List(sqlstr).get(0).get("empsum"));
jo.put("empsum", empsum);
jo.put("cbnum", (empsum <= quota) ? 0 : (empsum - quota));
jo.put("treeid", zlzwbzrpttreeid++);
s_empsum += Integer.valueOf(jo.getString("empsum"));
s_cbnum += Integer.valueOf(jo.getString("cbnum"));
s_quota += Integer.valueOf(jo.getString("quota"));
}
dw.put("empsum", s_empsum);
dw.put("cbnum", s_cbnum);
dw.put("quota", s_quota);
zl.put("children", jos);
}
private String zwempctsql = "SELECT COUNT(*) empsum FROM hr_employee emp "
+ " WHERE emp.ospid IN("
+ " SELECT ospid FROM hr_orgposition osp WHERE osp.%s AND osp.hwc_idzl=%s AND osp.sp_id=%s )"
+ " AND emp.empstatid IN "
+ " (SELECT statvalue FROM hr_employeestat WHERE usable = 1 AND isquota = 1) ";
private String orgzlzwctsql = "SELECT osp.sp_id, osp.sp_name orgname, ifnull(SUM(osp.quota),0) quota " + " FROM hr_orgposition osp WHERE osp.hwc_idzl = %s "
+ " AND osp.%s" + " GROUP BY osp.sp_id, osp.sp_name";
private String orglzempctsql = "SELECT COUNT(*) ct " + " FROM hr_employee e,hr_orgposition osp"
+ " WHERE e.ospid=osp.ospid AND empstatid IN(SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1)"
+ " AND osp.%s AND osp.hwc_idzl=%s";
private String orgzlsql = "select "
+ " hwc_idzl, hwc_namezl orgname, ifnull(sum(quota),0) quota "
+ "from "
+ " (select "
+ " osp.hwc_idzl, osp.hwc_namezl, osp.quota "
+ " from "
+ " hr_orgposition osp "
+ " where osp.%s "
+ " union all "
+ " SELECT "
+ " c.hwc_id hwc_idzl, c.hwc_name hwc_namezl, qc.quota "
+ " FROM "
+ " hr_quotaoc qc, shworg org, hr_wclass c "
+ " WHERE qc.orgid = org.orgid "
+ " AND qc.usable = 1 "
+ " AND qc.classid = c.hwc_id "
+ " and org.%s) tb "
+ "where hwc_idzl <> 0 "
+ "group by hwc_idzl, hwc_namezl ";
@ACOAction(eventname = "contractanalysis", Authentication = true, notes = "合同签订分析")
public String contractanalysis() throws Exception {
String yearmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM");
List<String> yms = new ArrayList<String>();
yms.add(yearmonth);
HashMap<String, String> parms = CSContext.get_pjdataparms();
String ps = parms.get("parms");
if (ps == null) {
throw new Exception("需要参数orgid");
}
List<JSONParm> jps = CJSON.getParms(ps);
JSONParm jp = getParmByName(jps, "orgid");
if (jp == null) {
throw new Exception("需要参数orgid");
}
String orgid = jp.getParmvalue();
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yms);
Hr_employee he = new Hr_employee();
DecimalFormat dec = new DecimalFormat("0.0000");
Shworg org = new Shworg();
org.findByID(orgid, false);
if (org.isEmpty())
throw new Exception("ID为【" + orgid + "】的机构不存在");
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
boolean includchd = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
Shworg countorg = new Shworg();
countorg.findByID(dw.getString("orgid"));
int empsum = getOrgEmpctSum(he, countorg, yearmonth, 0, null, 0, includchd); // 单位总人数
int signnumber = getsignnumbers(he.pool, dw, includchd);// 合同签订人数
int openend = getopenends(he.pool, dw, includchd);// 无固定合同签订人数
int emnature1 = getoverdues(he.pool, dw, includchd, "脱产");// 脱产下月合同到期人数
int emnature2 = getoverdues(he.pool, dw, includchd, "非脱产");// 非脱产下月合同到期人数
int constop = getopenends(he.pool, dw, includchd, 2);// 终止合同人数
int concancel = getopenends(he.pool, dw, includchd, 5);// 解除合同人数
int conover = getopenends(he.pool, dw, includchd, 3);// 过期合同人数
int shoudsign = getShouldSign(he.pool, dw, includchd);// 应续签人数,已签但过期的和入职但没签的总和
int realsign = getRealSign(he.pool, dw, includchd);// 实际续签人数,合同表里有续签状态人员的个数
dw.put("empsum", empsum);
dw.put("sn", signnumber);
dw.put("oe", openend);
dw.put("et1", emnature1);
dw.put("et2", emnature2);
dw.put("cs", constop);
dw.put("cc", concancel);
dw.put("co", conover);
dw.put("ss", shoudsign);
dw.put("rs", realsign);
dw.put("sn1", ((empsum > 0) ? (dec.format((float) signnumber / empsum)) : "0.000"));// 合同签订率
dw.put("oe1", ((empsum > 0) ? (dec.format((float) openend / empsum)) : "0.000"));// 无固定期限合同签订率
dw.put("cs1", ((empsum > 0) ? (dec.format((float) constop / empsum)) : "0.000"));// 终止比率
dw.put("cc1", ((empsum > 0) ? (dec.format((float) concancel / empsum)) : "0.000"));// 解除比率
dw.put("co1", ((empsum > 0) ? (dec.format((float) conover / empsum)) : "0.000"));// 过期比率
dw.put("xq1", ((empsum > 0) ? (dec.format((float) realsign / empsum)) : "0.000"));// 续签达成率。
// 实际续签人数/总人数??
}
String scols = parms.get("cols");
if (scols == null) {
return dws.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private int getsignnumbers(CDBPool pool, JSONObject dw, boolean childs) throws Exception {
String sqlstr = null;
sqlstr = "SELECT COUNT(DISTINCT er_id) ct from `hr_employee_contract` WHERE stat=9 AND contractstat=1 "
+ " AND er_id IN (SELECT er_id FROM hr_employee WHERE usable=1 "
+ " AND empstatid IN (SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1 ))";
if (childs) {
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
} else {
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
}
// sqlstr=sqlstr+" group by er_id";
if (pool.opensql2json_O(sqlstr).size() > 0) {
JSONObject jo = pool.opensql2json_O(sqlstr).getJSONObject(0);
return Integer.valueOf(jo.get("ct").toString());
} else {
return 0;
}
}
private int getopenends(CDBPool pool, JSONObject dw, boolean childs) throws Exception {
String sqlstr = null;
sqlstr = "SELECT COUNT(DISTINCT er_id) ct FROM `hr_employee_contract` WHERE stat=9 AND contractstat=1 AND deadline_type=2 ";
if (childs) {
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
} else {
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
}
;
if (pool.opensql2json_O(sqlstr).size() > 0) {
JSONObject jo = pool.opensql2json_O(sqlstr).getJSONObject(0);
return Integer.valueOf(jo.get("ct").toString());
} else {
return 0;
}
}
private int getoverdues(CDBPool pool, JSONObject dw, boolean childs, String nature) throws Exception {
String sqlstr = null;
sqlstr = "SELECT count(*) ct FROM `hr_employee_contract` con,hr_employee emp "
+ " WHERE con.stat=9 AND con.contractstat=1 AND con.end_date>DATE_ADD(CURDATE() - DAY(CURDATE()) + 1, INTERVAL 1 MONTH) AND "
+ " con.end_date<=LAST_DAY( DATE_ADD(CURDATE() - DAY(CURDATE()) + 1, INTERVAL 1 MONTH)) AND con.er_id=emp.er_id AND emp.emnature='" + nature
+ "'";
if (childs) {
sqlstr = sqlstr + " AND con.idpath LIKE '" + dw.getString("idpath") + "%'";
} else {
sqlstr = sqlstr + " AND con.orgid=" + dw.getString("orgid");
}
if (pool.openSql2List(sqlstr).isEmpty()) {
return 0;
} else {
return Integer.valueOf(pool.openSql2List(sqlstr).get(0).get("ct"));
}
}
private int getopenends(CDBPool pool, JSONObject dw, boolean childs, int constat) throws Exception {
String sqlstr = null;
sqlstr = "SELECT count(DISTINCT er_id) ct from `hr_employee_contract` WHERE stat=9 AND contractstat=" + constat;
if (childs) {
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
} else {
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
}
if (pool.openSql2List(sqlstr).isEmpty()) {
return 0;
} else {
return Integer.valueOf(pool.openSql2List(sqlstr).get(0).get("ct"));
}
}
private int getShouldSign(CDBPool pool, JSONObject dw, boolean childs) throws Exception {
String sql1 = "SELECT COUNT(*) ct FROM hr_employee_contract con WHERE con.stat=9 AND end_date<CURDATE() AND con.contractstat=1 AND er_id IN "
+ "(SELECT er_id FROM hr_employee WHERE usable=1 AND empstatid IN ( SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) ";
String sql2 = "SELECT (case COUNT(*) when COUNT(*)>0 then COUNT(*) else 0 end ) ct FROM hr_employee WHERE usable=1 AND empstatid IN ( SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) "
+ " AND er_id NOT IN (SELECT er_id FROM hr_employee_contract WHERE stat=9 AND contractstat=1 ";
if (childs) {
sql1 = sql1 + " AND idpath LIKE '" + dw.getString("idpath") + "%') ";
sql2 = sql2 + " AND idpath LIKE '" + dw.getString("idpath") + "%') AND idpath LIKE '" + dw.getString("idpath") + "%' ";
} else {
sql1 = sql1 + " AND orgid=" + dw.getString("orgid") + " ) ";
sql2 = sql2 + " AND orgid=" + dw.getString("orgid") + ") AND orgid=" + dw.getString("orgid");
}
int oversign = Integer.valueOf(pool.openSql2List(sql1).get(0).get("ct"));
int neversign = Integer.valueOf(pool.openSql2List(sql2).get(0).get("ct"));
return oversign + neversign;
}
private int getRealSign(CDBPool pool, JSONObject dw, boolean childs) throws Exception {
String sqlstr = null;
sqlstr = "SELECT (case COUNT(*) when COUNT(*)>0 then COUNT(*) else 0 end) ct FROM hr_employee_contract con WHERE con.stat=9 AND con.contractstat=6 AND con.er_id IN "
+ " (SELECT er_id FROM hr_employee WHERE usable=1 AND empstatid IN "
+ " ( SELECT statvalue FROM hr_employeestat WHERE usable=1 AND isquota=1) ";
if (childs) {
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%') GROUP BY con.er_id";
} else {
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid") + " ) GROUP BY con.er_id";
}
if (pool.openSql2List(sqlstr).isEmpty()) {
return 0;
} else {
return Integer.valueOf(pool.openSql2List(sqlstr).get(0).get("ct"));
}
}
@ACOAction(eventname = "staffretention", Authentication = true, notes = "人员流失率")
public String staffretention() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
// List<String> yearmonths = new ArrayList<String>();
// yearmonths.add(yearmonth);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 24);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return dogetdetail(dws, orgid, yearmonths, empclass, spname, findtype, parms);
}
private String dogetdetail(JSONArray dws, String orgid, List<String> yearmonths, int empclass, String spname, int findtype, HashMap<String, String> parms)
throws Exception {
for (String yearmonth : yearmonths) {
String pyearmonth = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(Systemdate.getDateByStr(yearmonth), -1), "yyyy-MM");
for (int i = 0; i < dws.size(); i++) {
int s_offjobquota = 0, s_noffjobquota = 0, s_totalquota = 0, s_emnum = 0, s_emnumoff = 0, s_emnumnoff = 0;
int s_selfleave = 0, s_quit = 0, s_dismiss = 0, s_reduce = 0, s_retire = 0, s_cpst = 0, s_ncpst = 0, s_totalleave = 0;
JSONObject dw = dws.getJSONObject(i);
String eyearmonth = dw.getString("yearmonth");
if (yearmonth.equalsIgnoreCase(eyearmonth)) {
// boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
boolean includechld = dw.getInt("_incc") == 1;
// 且
// 为自身机构时候
// 不查询子机构数据
// 机构脱产编制
dw.put("offjobquota", getOffQuota(dw, yearmonth, includechld));
s_offjobquota += dw.getInt("offjobquota");
// 机构非脱产编制 可能要从 机构职类编制获取???????
dw.put("noffjobquota", getNotOffQuota(dw, yearmonth, includechld));// 非脱产编制
s_noffjobquota += dw.getInt("noffjobquota");
dw.put("totalquota", dw.getInt("offjobquota") + dw.getInt("noffjobquota"));// 总编制数
s_totalquota += dw.getInt("totalquota");
// 实际人数
HashMap<String, String> mp = getTrueEmpCts(dw, pyearmonth, yearmonth, empclass, includechld);
dw.put("emnum", mp.get("emnum"));
dw.put("emnumoff", mp.get("emnumoff"));// 脱产人数
dw.put("emnumnoff", mp.get("emnumnoff"));//
s_emnum += dw.getInt("emnum");
s_emnumoff += dw.getInt("emnumoff");
s_emnumnoff += dw.getInt("emnumnoff");
// 离职人数
mp = getLVDatainfo(dw, yearmonth, empclass, spname, findtype, includechld);
dw.put("selfleave", mp.get("ct1"));// 自离
dw.put("quit", mp.get("ct2"));// 辞职
dw.put("dismiss", mp.get("ct3"));// 辞退
dw.put("reduce", mp.get("ct4"));// 裁员
dw.put("retire", mp.get("ct5"));// 退休
dw.put("cpst", mp.get("ct6"));// 有经济补偿
dw.put("ncpst", mp.get("ct7"));// 无经济补偿
dw.put("totalleave", dw.getInt("selfleave") + dw.getInt("quit") + dw.getInt("dismiss") + dw.getInt("reduce") + dw.getInt("retire")
+ dw.getInt("cpst") + dw.getInt("ncpst"));// 合计离职人数
s_selfleave += dw.getInt("selfleave");
s_quit += dw.getInt("quit");
s_dismiss += dw.getInt("dismiss");
s_reduce += dw.getInt("reduce");
s_retire += dw.getInt("retire");
s_cpst += dw.getInt("cpst");
s_ncpst += dw.getInt("ncpst");
s_totalleave += dw.getInt("totalleave");
// 员工流失率
DecimalFormat dec = new DecimalFormat("0.0000");
dw.put("bsf", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("selfleave") / dw.getInt("emnum"))) : "0.000"));// 自离率
dw.put("bq", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("quit") / dw.getInt("emnum"))) : "0.000"));// 辞职率
dw.put("bdm", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("dismiss") / dw.getInt("emnum"))) : "0.000"));// 辞退率
dw.put("brd", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("reduce") / dw.getInt("emnum"))) : "0.000"));// 退休率
dw.put("brt", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("retire") / dw.getInt("emnum"))) : "0.000"));// 裁员率
dw.put("bcpst", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("cpst") / dw.getInt("emnum"))) : "0.000"));// 有经济补偿
dw.put("bncpst", ((dw.getInt("emnum") > 0) ? (dec.format((float) dw.getInt("ncpst") / dw.getInt("emnum"))) : "0.000"));// 无经济补偿
dw.put("bsls", dw.getDouble("bsf") + dw.getDouble("bq"));// 主动流失率
dw.put("brls", dw.getDouble("bdm") + dw.getDouble("brd") + dw.getDouble("brt"));// 被动流失率
dw.put("btls", dw.getDouble("bcpst") + dw.getDouble("bncpst"));// 协商流失率
dw.put("btotals", dw.getDouble("bsls") + dw.getDouble("brls") + dw.getDouble("btls"));// 绝对流失率
}
//如果需要加小结
}
}
// JSONObject srow = new JSONObject();
// srow.put("offjobquota", s_offjobquota);
// srow.put("noffjobquota", s_noffjobquota);
// srow.put("totalquota", s_totalquota);
// srow.put("emnum", s_emnum);
// srow.put("emnumoff", s_emnumoff);
// srow.put("emnumnoff", s_emnumnoff);
// srow.put("selfleave", s_selfleave);
// srow.put("quit", s_quit);
// srow.put("dismiss", s_dismiss);
// srow.put("reduce", s_reduce);
// srow.put("retire", s_retire);
// srow.put("cpst", s_cpst);
// srow.put("ncpst", s_ncpst);
// srow.put("totalleave", s_totalleave);
// srow.put("orgname", "合计");
// JSONArray footer = new JSONArray();
// footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
// rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
/**
* @param dw
* @param yearmonth
* @param includechld
* @return 离职信息
* @throws Exception
*/
private HashMap<String, String> getLVDatainfo(JSONObject dw, String yearmonth, int empclass, String spname, int findtype, boolean includechld) throws Exception {
String sqlstr = "SELECT IFNULL(SUM(CASE WHEN hl.ljtype1=1 THEN 1 ELSE 0 END ),0) ct1,IFNULL(SUM(CASE WHEN hl.ljtype1=2 THEN 1 ELSE 0 END ),0) ct2,"
+ "IFNULL(SUM(CASE WHEN hl.ljtype1=3 THEN 1 ELSE 0 END ),0) ct3,IFNULL(SUM(CASE WHEN hl.ljtype1=4 THEN 1 ELSE 0 END ),0) ct4,"
+ "IFNULL(SUM(CASE WHEN hl.ljtype1=5 THEN 1 ELSE 0 END ),0) ct5,IFNULL(SUM(CASE WHEN hl.ljtype1=6 THEN 1 ELSE 0 END ),0) ct6,"
+ "IFNULL(SUM(CASE WHEN hl.ljtype1=7 THEN 1 ELSE 0 END ),0) ct7 "
+ " FROM `hr_leavejob` hl,hr_employee emp WHERE hl.stat=9 AND hl.ljtype=2 and hl.er_id=emp.er_id and hl.iscanced=2 "
+ "and DATE_FORMAT(hl.ljdate,'%Y-%m')='" + yearmonth + "'";
if (includechld)
sqlstr = sqlstr + " AND hl.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND hl.orgid=" + dw.getString("orgid");
if (empclass == 2)
sqlstr = sqlstr + " and emp.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and emp.emnature='非脱产'";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and hl.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and hl.sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL("emp", sqlstr);
return HRUtil.getReadPool().openSql2List(sqlstr).get(0);
}
/**
* @param dw
* @param yearmonth
* @param pyearmonth
* @param includechld
* @return 实际人数
* @throws Exception
*/
public static HashMap<String, String> getTrueEmpCts(JSONObject dw, String pyearmonth, String yearmonth, int empclass, boolean includechld)
throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
int d = (isnowmonth) ? 1 : 2;
String sqlstr = "SELECT ifnull(round(COUNT(*) /" + d + "),0) emnum,ifnull(round(SUM(CASE WHEN emnature='脱产' THEN 1 ELSE 0 END)/" + d + "),0) emnumoff,"
+ "ifnull(round(SUM(CASE WHEN emnature='非脱产' THEN 1 ELSE 0 END)/" + d + "),0) emnumnoff ";
if (!isnowmonth)
sqlstr = sqlstr + "FROM hr_month_employee he ";
else
sqlstr = sqlstr + "FROM hr_employee he ";
sqlstr = sqlstr + " WHERE he.empstatid IN(" + empstids + ") ";
if (!isnowmonth)
sqlstr = sqlstr + "and yearmonth in('" + pyearmonth + "','" + yearmonth + "') ";
if (includechld)
sqlstr = sqlstr + " AND he.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND he.orgid=" + dw.getString("orgid");
if (empclass == 2)
sqlstr = sqlstr + " and he.emnature='脱产'";
if (empclass == 3)
sqlstr = sqlstr + " and he.emnature='非脱产'";
sqlstr = parExtSQL("he", sqlstr);
return HRUtil.getReadPool().openSql2List(sqlstr).get(0);
}
/**
* @param dw
* @param yearmonth
* @param includechld
* @return 机构脱产编制
* @throws Exception
*/
public static int getOffQuota(JSONObject dw, String yearmonth, boolean includechld) throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String sqlstr = "SELECT IFNULL(SUM(op.quota),0) quota ";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_orgposition op,hr_standposition sp ";
else
sqlstr = sqlstr + " FROM hr_month_orgposition op,hr_standposition sp ";
sqlstr = sqlstr + " WHERE 1=1 ";
if (!isnowmonth)
sqlstr = sqlstr + " and op.yearmonth=" + yearmonth + "";
if (includechld)
sqlstr = sqlstr + " AND op.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND op.orgid=" + dw.getString("orgid");
sqlstr = sqlstr + " AND op.sp_id=sp.sp_id AND op.isoffjob=1";
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("quota"));
}
/**
* @param dw
* @param yearmonth
* @param includechld
* @return 非脱产编制
* @throws Exception
*/
public static int getNotOffQuota(JSONObject dw, String yearmonth, boolean includechld) throws Exception {
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String sqlstr = "SELECT IFNULL(SUM(q.quota),0) quota FROM ";
if (isnowmonth)
sqlstr = sqlstr + " hr_quotaoc q, hr_wclass c,shworg o";
else
sqlstr = sqlstr + " hr_month_quotaoc q, hr_wclass c,shworg o";
sqlstr = sqlstr + " WHERE q.orgid=o.orgid AND q.classid=c.hwc_id AND c.isoffjob=2 and o.usable=1 ";
if (!isnowmonth)
sqlstr = sqlstr + " and q.yearmonth='" + yearmonth + "'";
if (includechld)
sqlstr = sqlstr + " AND o.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND o.orgid=" + dw.getString("orgid");
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("quota"));
}
/**
* @param dw
* @param yearmonth
* @param includechld
* @return 入职信息 不需要关联到月结人事表
* @throws Exception
*/
public static HashMap<String, String> getEntyInfo(JSONObject dw, int empclass, String spname, int findtype, boolean includechld, Date bgdate, Date eddate) throws Exception {
String sqlstr = "SELECT IFNULL(SUM(1),0) sument, IFNULL(SUM(CASE WHEN osp.isoffjob=1 THEN 1 ELSE 0 END),0) entnumoff, "
+ " IFNULL(SUM(CASE WHEN osp.isoffjob=2 THEN 1 ELSE 0 END),0) entnumnoff"
+ " FROM `hr_entry` n, `hr_orgposition` osp WHERE n.`stat`=9 and n.ospid=osp.ospid ";
if (includechld)
sqlstr = sqlstr + " AND osp.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND osp.orgid=" + dw.getString("orgid");
sqlstr = sqlstr + " AND n.entrydate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' AND n.entrydate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'";
if (empclass == 2)
sqlstr = sqlstr + " and osp.isoffjob=1";
if (empclass == 3)
sqlstr = sqlstr + " and osp.isoffjob=2";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and osp.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and osp.sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL("osp", sqlstr);/// 可能有问题
JSONObject jo1 = HRUtil.getReadPool().opensql2json_O(sqlstr).getJSONObject(0);
//// 招募
sqlstr = "SELECT IFNULL(SUM(1),0) sument, IFNULL(SUM(CASE WHEN osp.isoffjob=1 THEN 1 ELSE 0 END),0) entnumoff, "
+ " IFNULL(SUM(CASE WHEN osp.isoffjob=2 THEN 1 ELSE 0 END),0) entnumnoff"
+ " FROM `hr_recruit_form` n, `hr_orgposition` osp WHERE n.`stat`<10 and n.ospid=osp.ospid ";
if (includechld)
sqlstr = sqlstr + " AND osp.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND osp.orgid=" + dw.getString("orgid");
sqlstr = sqlstr + " AND n.entrydate>='" + Systemdate.getStrDateyyyy_mm_dd(bgdate)
+ "' AND n.entrydate<='" + Systemdate.getStrDateyyyy_mm_dd(eddate) + "'";
if (empclass == 2)
sqlstr = sqlstr + " and osp.isoffjob=1";
if (empclass == 3)
sqlstr = sqlstr + " and osp.isoffjob=2";
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and osp.sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and osp.sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL("osp", sqlstr);/// 可能有问题
JSONObject jo2 = HRUtil.getReadPool().opensql2json_O(sqlstr).getJSONObject(0);
HashMap<String, String> rst = new HashMap<String, String>();
rst.put("sument", String.valueOf(jo1.getInt("sument") + jo2.getInt("sument")));
rst.put("entnumoff", String.valueOf(jo1.getInt("entnumoff") + jo2.getInt("entnumoff")));
rst.put("entnumnoff", String.valueOf(jo1.getInt("entnumnoff") + jo2.getInt("entnumnoff")));
return rst;
}
// ////////////////////////////////
@ACOAction(eventname = "rpt_hrrztj", Authentication = true, notes = "人员入职分析")
public String rpt_hrrztj() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String strempclass = CorUtil.getJSONParmValue(jps, "empclass", "需要参数【empclass】");
int empclass = (strempclass == null) ? 1 : Integer.valueOf(strempclass);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 24);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return dogetLVdetail(dws, orgid, yearmonths, empclass, parms);
}
private String dogetLVdetail(JSONArray dws, String orgid, List<String> yearmonths, int empclass, HashMap<String, String> parms)
throws Exception {
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
for (String yearmonth : yearmonths) {
String pyearmonth = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(Systemdate.getDateByStr(yearmonth), -1), "yyyy-MM");
Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
Date eddate = Systemdate.dateMonthAdd(bgdate, 1);// 加一月
for (int i = 0; i < dws.size(); i++) {
int s_offjobquota = 0, s_noffjobquota = 0, s_totalquota = 0, s_emnum = 0, s_emnumoff = 0, s_emnumnoff = 0;
int s_sument = 0, s_entnumoff = 0, s_entnumnoff = 0;
JSONObject dw = dws.getJSONObject(i);
// boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
// 机构脱产编制
boolean includechld = dw.getInt("_incc") == 1;
String eyearmonth = dw.getString("yearmonth");
if (yearmonth.equalsIgnoreCase(eyearmonth)) {
dw.put("offjobquota", getOffQuota(dw, yearmonth, includechld));
s_offjobquota += dw.getInt("offjobquota");
// 机构非脱产编制 可能要从 机构职类编制获取???????
dw.put("noffjobquota", getNotOffQuota(dw, yearmonth, includechld));// 非脱产编制
s_noffjobquota += dw.getInt("noffjobquota");
dw.put("totalquota", dw.getInt("offjobquota") + dw.getInt("noffjobquota"));// 总编制数
s_totalquota += dw.getInt("totalquota");
// 实际人数
HashMap<String, String> mp = getTrueEmpCts(dw, pyearmonth, yearmonth, empclass, includechld);
dw.put("emnum", mp.get("emnum"));
dw.put("emnumoff", mp.get("emnumoff"));// 脱产人数
dw.put("emnumnoff", mp.get("emnumnoff"));//
s_emnum += dw.getInt("emnum");
s_emnumoff += dw.getInt("emnumoff");
s_emnumnoff += dw.getInt("emnumnoff");
// 入职人数
mp = getEntyInfo(dw, empclass, spname, findtype, includechld, bgdate, eddate);
dw.put("sument", mp.get("sument"));
dw.put("entnumoff", mp.get("entnumoff"));// 脱产人数
dw.put("entnumnoff", mp.get("entnumnoff"));//
s_sument += dw.getInt("sument");
s_entnumoff += dw.getInt("entnumoff");
s_entnumnoff += dw.getInt("entnumnoff");
}
}
/// 小结
}
// JSONObject srow = new JSONObject();
// srow.put("offjobquota", s_offjobquota);
// srow.put("noffjobquota", s_noffjobquota);
// srow.put("totalquota", s_totalquota);
// srow.put("emnum", s_emnum);
// srow.put("emnumoff", s_emnumoff);
// srow.put("emnumnoff", s_emnumnoff);
// srow.put("sument", s_sument);
// srow.put("entnumoff", s_entnumoff);
// srow.put("entnumnoff", s_entnumnoff);
// srow.put("orgname", "合计");
// JSONArray footer = new JSONArray();
// footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
// rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
@ACOAction(eventname = "rpt_mlevtj", Authentication = true, notes = "M lev分析")
public String rpt_mlevtj() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth", "需要参数【yearmonth】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 12);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
return dogetmlevtj(dws, orgid, yearmonths, parms, spname);
}
private String dogetmlevtj(JSONArray dws, String orgid, List<String> yearmonths, HashMap<String, String> parms, String spname) throws Exception {
for (String yearmonth : yearmonths) {
int s_bzpznum = 0, s_mlev1 = 0, s_mlev2 = 0, s_mlev3 = 0, s_mlev4 = 0, s_mlev5 = 0, s_mlev6 = 0, s_mlev7 = 0, s_mlev8 = 0, s_mlevall = 0, s_mlevpc = 0, s_cbnum = 0, s_cbpc = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);
String eyearmonth = dw.getString("yearmonth");
if (yearmonth.equalsIgnoreCase(eyearmonth)) {
// Date bgdate = Systemdate.getDateByStr(Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByStr(yearmonth)));// 去除时分秒
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
boolean includechld = dw.getInt("_incc") == 1;
int bzpznum = getbzpznum(dw, isnowmonth, yearmonth, spname, includechld);// 标准配置人数
JSONObject jo = getlevs(dw, isnowmonth, yearmonth, spname, includechld);// 所有lev
int mlev1 = jo.getInt("mlev1");
int mlev2 = jo.getInt("mlev2");
int mlev3 = jo.getInt("mlev3");
int mlev4 = jo.getInt("mlev4");
int mlev5 = jo.getInt("mlev5");
int mlev6 = jo.getInt("mlev6");
int mlev7 = jo.getInt("mlev7");
int mlev8 = jo.getInt("mlev8");
dw.put("bzpznum", bzpznum);
dw.put("mlev1", mlev1);
dw.put("mlev2", mlev2);
dw.put("mlev3", mlev3);
dw.put("mlev4", mlev4);
dw.put("mlev5", mlev5);
dw.put("mlev6", mlev6);
dw.put("mlev7", mlev7);
dw.put("mlev8", mlev8);
dw.put("mlevall", mlev1 + mlev2 + mlev3 + mlev4 + mlev5 + mlev6 + mlev7 + mlev8);
dw.put("mlevpc", dw.getInt("mlevall") - bzpznum);
int cbnum = getcb(dw, isnowmonth, yearmonth, spname, includechld);// 储备
dw.put("cbnum", cbnum);
dw.put("cbpc", dw.getInt("mlevall") + cbnum - bzpznum);
s_bzpznum += bzpznum;
s_mlev1 += mlev1;
s_mlev2 += mlev2;
s_mlev3 += mlev3;
s_mlev4 += mlev4;
s_mlev5 += mlev5;
s_mlev6 += mlev6;
s_mlev7 += mlev7;
s_mlev8 += mlev8;
s_mlevall += dw.getInt("mlevall");
s_mlevpc += dw.getInt("mlevpc");
s_cbnum += dw.getInt("cbnum");
s_cbpc += dw.getInt("cbpc");
}
}
// 小结
}
// JSONObject srow = new JSONObject();
// srow.put("bzpznum", s_bzpznum);
// srow.put("mlev1", s_mlev1);
// srow.put("mlev2", s_mlev2);
// srow.put("mlev3", s_mlev3);
// srow.put("mlev4", s_mlev4);
// srow.put("mlev5", s_mlev5);
// srow.put("mlev6", s_mlev6);
// srow.put("mlev7", s_mlev7);
// srow.put("mlev8", s_mlev8);
// srow.put("mlevall", s_mlevall);
// srow.put("cbnum", s_cbnum);
// srow.put("cbpc", s_cbpc);
// srow.put("mlevpc", s_mlevpc);
// srow.put("orgname", "合计");
JSONArray footer = new JSONArray();
// footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", dws);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst.toString();
} else {
(new CReport()).export2excel(dws, scols);
return null;
}
}
private int getbzpznum(JSONObject dw, boolean isnowmonth, String yearmonth, String spname, boolean includechld) throws NumberFormatException, Exception {
String sqlstr = "SELECT IFNULL(SUM(quota),0) quota FROM ";
if (isnowmonth)
sqlstr = sqlstr + " hr_orgposition ";
else
sqlstr = sqlstr + " hr_month_orgposition ";
sqlstr = sqlstr + " WHERE hwc_namezl='M类' ";
if (!isnowmonth)
sqlstr = sqlstr + " and yearmonth='" + yearmonth + "'";
else
sqlstr = sqlstr + " and usable=1 ";
if (includechld)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
if ((spname != null) && (!spname.isEmpty())) {
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL(null, sqlstr);
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("quota"));
}
private JSONObject getlevs(JSONObject dw, boolean isnowmonth, String yearmonth, String spname, boolean includechld) throws Exception {
String sqlstr = "select " +
" ifnull(sum(if(e.lv_num=2,1,0)),0) mlev1, " + // 总监级(2.0)=职级为2.0的人员;
" IFNULL(SUM(IF(e.lv_num>2 and e.lv_num<=2.3,1,0)),0) mlev2, " + // 总监级(2.1-2.3)=职级为2.1、2.2、2.3的人员;
" IFNULL(SUM(IF(e.mlev=3 or e.sp_name = '高级经理',1,0)),0) mlev3, " + // 职位为高级经理的人员+M类数据基础表 层级为高级经理(3.0-3.1)的人员
" IFNULL(SUM(IF(e.mlev=4 or e.sp_name='经理' or e.sp_name='副经理' or e.sp_name='见习副经理' or e.sp_name='警务室主任' or e.sp_name='警务室副主任',1,0)),0) mlev4, " + // 经理级(3.1-3.3)=职位为经理、副经理、见习副经理、警务室主任、警务室副主任的人员+M类数据基础表 层级为经理(3.1-3.3)的人员;
" IFNULL(SUM(IF(e.mlev=5,1,0)),0) mlev5, " + // 产品类项目经理
" IFNULL(SUM(IF(e.mlev=6,1,0)),0) mlev6, " + // 非产品类项目经理
" IFNULL(SUM(IF(e.lv_num=4 and (e.sp_name = '高级科长' or e.sp_name = '高级车间主任' or e.mlev=7),1,0)),0) mlev7, " + // 高级科长(4.0)=职位为高级科长、高级车间主任的人员; //myh +层级是 高级科长(4.0)20200318
" IFNULL(SUM(IF(e.lv_num>4 AND e.lv_num<4.3 and e.hwc_namezl='M类' AND e.sp_name NOT LIKE '%储备%' ,1,0)),0) mlev8 ";// 科长级(4.1-4.2)=(职级为4.1、4.2M类人员)-(职位包含“储备”且职级为4.1、4.2M类人员)
if (!isnowmonth)
sqlstr = sqlstr + " FROM hr_month_employee e ";
else
sqlstr = sqlstr + " FROM hr_employee e ";
sqlstr = sqlstr + " WHERE e.empstatid IN(" + empstids + ") ";
if (!isnowmonth)
sqlstr = sqlstr + "and e.yearmonth ='" + yearmonth + "' ";
if (includechld)
sqlstr = sqlstr + " AND e.idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND e.orgid=" + dw.getString("orgid");
if ((spname != null) && (!spname.isEmpty())) {
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL("e", sqlstr);
JSONObject jo = HRUtil.getReadPool().opensql2json_O(sqlstr).getJSONObject(0);
return jo;
}
// 储备
private int getcb(JSONObject dw, boolean isnowmonth, String yearmonth, String spname, boolean includechld) throws NumberFormatException, Exception {
String sqlstr = "select ifnull(count(*),0) ct ";
if (!isnowmonth)
sqlstr = sqlstr + " FROM hr_month_employee e ";
else
sqlstr = sqlstr + " FROM hr_employee e ";
sqlstr = sqlstr + " WHERE e.empstatid IN(" + empstids + ") ";
if (!isnowmonth)
sqlstr = sqlstr + "and e.yearmonth ='" + yearmonth + "' ";
if (includechld)
sqlstr = sqlstr + " AND e.uidpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND e.uorgid=" + dw.getString("orgid");
sqlstr = sqlstr + " and hwc_namezl='M类' and sp_name LIKE '%储备%'";
if ((spname != null) && (!spname.isEmpty())) {
sqlstr = sqlstr + " and e.sp_name like '%" + spname + "%'";
}
return Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("ct"));
}
/**
* 是否当月
*
* @param ym
* @return
*/
private boolean isNowMonth(String ym) {
String nym = "'" + Systemdate.getStrDateByFmt(new Date(), "yyyy-MM") + "'";
System.out.println("nym:" + nym + " ym:" + ym);
return (nym.equalsIgnoreCase(ym));
}
@ACOAction(eventname = "rpt_zwqstj", Authentication = true, notes = "职位趋势分析")
public String rpt_zwqstj() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
String orgid = CorUtil.getJSONParmValue(jps, "orgid", "需要参数【orgid】");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
boolean includechild = Boolean.valueOf(CorUtil.getJSONParmValue(jps, "includechild", "需要参数【includechild】"));
String spname = CorUtil.getJSONParmValue(jps, "spname");
String iswzjq_str = CorUtil.getJSONParmValue(jps, "findtype");
int findtype = (iswzjq_str == null) ? 1 : Integer.valueOf(iswzjq_str);
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 24);
JSONArray dws = HRUtil.getOrgsByOrgid(orgid, includechild, yearmonths);
JSONObject rst = findSpQS(dws, orgid, yearmonths, spname, includechild, findtype, parms);
// dws = HRUtil.getOrgsByOrgid(orgid, false, yearmonths);
// JSONArray chartdata = buildXLChartData(findEmployeeXLAndQS(dws, orgid, yearmonths, empclass, false, parms).getJSONArray("rows"));
// rst.put("chartdata", chartdata);
JSONArray chartdata = buildZWChartData(rst.getJSONArray("rows"));
rst.put("chartdata", chartdata);
return rst.toString();
}
private JSONArray buildZWChartData(JSONArray rows) throws ParseException {
JSONArray rst = new JSONArray();
List<String> ctsers = new ArrayList<String>();
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
String sp_name = row.getString("sp_name");
if (!ctsers.contains(sp_name))
ctsers.add(sp_name);
}
int i = 0;
for (String sp_name : ctsers) {
rst.add(buildZWFChartDateRow(rows, "fd" + (++i), sp_name));
}
return rst;
}
private TwoInt getTwoIntByInt1(List<TwoInt> ints, int int1) {
for (TwoInt oint : ints) {
if (oint.getInt1() == int1)
return oint;
}
return null;
}
private JSONObject buildZWFChartDateRow(JSONArray rows, String fdname, String lable) throws ParseException {
JSONObject ss = new JSONObject();
ss.put("label", lable);
// HashMap<Integer, Integer> ymdatas = new HashMap<Integer, Integer>();
List<TwoInt> ymdatas = new ArrayList<TwoInt>();
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
String spname = row.getString("sp_name");
if (lable.equalsIgnoreCase(spname)) {
String yearmonth = row.getString("yearmonth");
Integer ymint = Integer.valueOf(yearmonth.replace("-", ""));
int emnum = row.getInt("emnum");
// 取出数据
TwoInt oint = getTwoIntByInt1(ymdatas, ymint);
int ymemnum = ((oint == null) ? 0 : oint.getInt2());
ymemnum = ymemnum + emnum;
// 存储数据
if (oint == null)
ymdatas.add(new TwoInt(ymint, ymemnum));
else
oint.setInt2(ymemnum);
}
}
// 排序
Collections.sort(ymdatas, new Comparator<TwoInt>() {
// 升序排序
public int compare(TwoInt o1, TwoInt o2) {
if (o1.getInt1() > o2.getInt1())
return 1;
else if (o1.getInt1() < o2.getInt1())
return -1;
else
return 0;
}
});
JSONArray ssArray = new JSONArray();
for (TwoInt oint : ymdatas) {
JSONArray cd = new JSONArray();
String dtstr = String.valueOf(oint.getInt1()) + "01";
Date dt = new SimpleDateFormat("yyyyMMdd").parse(dtstr);
// Date dt = Systemdate.getDateByStr(yearmonth + "-01");
dt = Systemdate.dateMonthAdd(dt, 1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
cd.add(calendar.getTimeInMillis());
// cd.add();
cd.add(oint.getInt2());
ssArray.add(cd);
}
ss.put("data", ssArray);
return ss;
}
private JSONObject findSpQS(JSONArray dws, String orgid, List<String> yearmonths, String spname, boolean includechild, int findtype, HashMap<String, String> parms) throws Exception {
JSONArray rows = new JSONArray();
Hr_employee he = new Hr_employee();
int s_sumpeo = 0;
for (int i = 0; i < dws.size(); i++) {
JSONObject dw = dws.getJSONObject(i);// 机构 年月
boolean includechld = (!includechild || (!orgid.equals(dw.getString("orgid"))));// 包含子机构
// 且
// 为自身机构时候
// 不查询子机构数据
JSONArray cts = getZWQSData(he, dw, dw.getString("yearmonth"), spname, includechld, findtype);
for (int j = 0; j < cts.size(); j++) {
JSONObject row = JSONObject.fromObject(dw.toString());
JSONObject ct = cts.getJSONObject(j);
int sumpeo = ct.getInt("ct");// getDegreeEmoloyssct(he, dw,
s_sumpeo += sumpeo;
row.put("emnum", sumpeo);
row.put("sp_name", ct.getString("sp_name"));
rows.add(row);
}
}
JSONObject srow = new JSONObject();
srow.put("emnum", s_sumpeo);
srow.put("orgname", "合计");
JSONArray footer = new JSONArray();
footer.add(srow);
JSONObject rst = new JSONObject();
rst.put("rows", rows);
rst.put("footer", footer);
String scols = parms.get("cols");
if (scols == null) {
return rst;
} else {
(new CReport()).export2excel(rows, scols);
return null;
}
}
/**
* @param he
* @param dw
* @param ym
* @param spname
* @param includchd
* @param findtype 精确 模糊明细 模糊汇总
* @return
* @throws Exception
*/
private JSONArray getZWQSData(Hr_employee he, JSONObject dw, String ym, String spname, boolean includchd, int findtype) throws Exception {
String ymstr = "'" + ym + "'";
boolean isnowmonth = isNowMonth(ymstr);
String sqlstr = "SELECT ";
if (isnowmonth)
sqlstr = sqlstr + " '" + ym + "' yearmonth,";
else
sqlstr = sqlstr + " yearmonth,";
if (findtype == 3)
sqlstr = sqlstr + " '" + spname + "' sp_name,";
else
sqlstr = sqlstr + " e.sp_name,";
sqlstr = sqlstr + " count(*) ct";
if (isnowmonth)
sqlstr = sqlstr + " FROM hr_employee e";
else
sqlstr = sqlstr + " FROM hr_month_employee e";
sqlstr = sqlstr + " WHERE e.`empstatid` IN(" + empstids + ") ";
if (!isnowmonth)
sqlstr = sqlstr + " and yearmonth=" + ymstr + "";
if (includchd)
sqlstr = sqlstr + " AND idpath LIKE '" + dw.getString("idpath") + "%'";
else
sqlstr = sqlstr + " AND orgid=" + dw.getString("orgid");
if ((spname != null) && (!spname.isEmpty())) {
if (findtype == 1)
sqlstr = sqlstr + " and sp_name='" + spname + "'";
else
sqlstr = sqlstr + " and sp_name like '%" + spname + "%'";
}
sqlstr = parExtSQL("e", sqlstr);
if (findtype != 3)
sqlstr = sqlstr + " group by e.sp_name";
return HRUtil.getReadPool().opensql2json_O(sqlstr);
}
@ACOAction(eventname = "getadvtechmodes", Authentication = false, notes = "获取高技模块")
public String getadvtechmodes() throws Exception {
String sqlstr = "SELECT * FROM hr_employee_advtechmode WHERE usable=1";
return HRUtil.getReadPool().opensql2json(sqlstr);
}
@ACOAction(eventname = "rptadvtech", Authentication = true, notes = "高技报表")
public String rptadvtech() throws Exception {
HashMap<String, String> parms = CSContext.get_pjdataparms();
List<JSONParm> jps = CJSON.getParms(parms.get("parms"));
int menutag = Integer.valueOf(CorUtil.getJSONParmValue(jps, "menutag", "需要参数【menutag】"));
String advmodename = CorUtil.getJSONParmValue(jps, "advmodename");
String yearmonth_begin = CorUtil.getJSONParmValue(jps, "yearmonth_begin", "需要参数【yearmonth_begin】");
String sqlstr = "SELECT * FROM hr_employee_advtechmode WHERE usable=1";
if ((advmodename != null) && (!advmodename.isEmpty()))
sqlstr = sqlstr + " and mdname='" + advmodename + "'";
JSONArray rows = new JSONArray();
JSONArray advnms = HRUtil.getReadPool().opensql2json_O(sqlstr);
JSONObject rst = new JSONObject();
if (menutag == 1) {// 分析
rows = findMonthAdvTech(yearmonth_begin, advnms);
} else if (menutag == 2) {// 趋势
String yearmonth_end = CorUtil.getJSONParmValue(jps, "yearmonth_end", "需要参数【yearmonth_end】");
List<String> yearmonths = HRUtil.buildYeatMonths(yearmonth_begin, yearmonth_end, 24);
for (String yearmonth : yearmonths) {
rows.addAll(findMonthAdvTech(yearmonth, advnms));
}
rst.put("chartdata", buildAdvtechChartData(yearmonths, rows));
} else
throw new Exception("menutag【" + menutag + "】未定义");
String scols = parms.get("cols");
if (scols == null) {
rst.put("rows", rows);
return rst.toString();
} else {
(new CReport()).export2excel(rows, scols);
return null;
}
}
private JSONArray buildAdvtechChartData(List<String> yearmonths, JSONArray rows) {
JSONArray rst = new JSONArray();
rst.add(buildAdvtechChartDateRow(yearmonths, rows, "zrnum", "主任级"));
rst.add(buildAdvtechChartDateRow(yearmonths, rows, "fzrnum", "副主任级"));
rst.add(buildAdvtechChartDateRow(yearmonths, rows, "gjnum", "高级"));
return rst;
}
private JSONObject buildAdvtechChartDateRow(List<String> yearmonths, JSONArray rows, String fdname, String lable) {
JSONObject ss = new JSONObject();
ss.put("label", lable);
JSONArray ssArray = new JSONArray();
for (String ym : yearmonths) {
JSONArray cd = new JSONArray();
Date dt = Systemdate.getDateByStr(ym + "-01");
dt = Systemdate.dateMonthAdd(dt, 1);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
cd.add(calendar.getTimeInMillis());
// cd.add(Integer.valueOf(ym.replace("-", "")));
int sum = 0;
for (int i = 0; i < rows.size(); i++) {
JSONObject row = rows.getJSONObject(i);
String yearmonth = row.getString("yearmonth");
if (yearmonth.equalsIgnoreCase(ym)) {
if (row.has(fdname))
sum += row.getInt(fdname);
}
}
cd.add(sum);
ssArray.add(cd);
}
ss.put("data", ssArray);
return ss;
}
/**
* @param yearmonth yyyy-mm
* @param advnms
* @return
* @throws Exception
*/
private JSONArray findMonthAdvTech(String yearmonth, JSONArray advnms) throws Exception {
JSONArray rst = new JSONArray();
for (int i = 0; i < advnms.size(); i++) {
JSONObject jo = advnms.getJSONObject(i);
boolean isnowmonth = Systemdate.getStrDateByFmt(new Date(), "yyyy-MM").equalsIgnoreCase(yearmonth);
String atmid = jo.getString("atmid");
String sqlstr = "SELECT '" + yearmonth + "' yearmonth, " +
"IFNULL(SUM(IF(sp_name LIKE '%主任%' AND sp_name NOT LIKE '%副主任%' ,1,0)),0) zrnum, " +
"IFNULL(SUM(IF(sp_name LIKE '%副主任%' ,1,0)),0) fzrnum, " +
"IFNULL(SUM(IF(sp_name LIKE '%高级%' ,1,0)),0) gjnum ";
if (isnowmonth)
sqlstr = sqlstr + "FROM hr_employee WHERE empstatid>0 AND empstatid<10";
else
sqlstr = sqlstr + "FROM hr_month_employee WHERE yearmonth='" + yearmonth + "'";
sqlstr = sqlstr + " and atmid=" + atmid + " and isadvtch=1";
JSONObject r = HRUtil.getReadPool().opensql2json_O(sqlstr).getJSONObject(0);
JSONObject row = JSONObject.fromObject(jo.toString());
row.put("yearmonth", r.getString("yearmonth"));
row.put("zrnum", r.getString("zrnum"));
row.put("fzrnum", r.getString("fzrnum"));
row.put("gjnum", r.getString("gjnum"));
row.put("emnum", r.getInt("zrnum") + r.getInt("fzrnum") + r.getInt("gjnum"));
sqlstr = "SELECT IFNULL(count(*),0) ct "
+ " FROM `hr_leavejob` hl,hr_employee emp WHERE hl.stat=9 AND hl.ljtype=2 and hl.er_id=emp.er_id and hl.iscanced=2 "
+ "and DATE_FORMAT(hl.ljdate,'%Y-%m')='" + yearmonth + "' and emp.isadvtch=1 and emp.atmid=" + atmid;
row.put("leavnum", HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("ct").toString());
String pyearmonth = Systemdate.getStrDateByFmt(Systemdate.dateMonthAdd(Systemdate.getDateByStr(yearmonth + "-01"), -1), "yyyy-MM");
sqlstr = "SELECT IFNULL(count(*),0) ct "
+ "FROM hr_month_employee WHERE yearmonth='" + pyearmonth + "'"
+ " and atmid=" + atmid + " and isadvtch=1";
int sumemp = (Integer.valueOf(HRUtil.getReadPool().openSql2List(sqlstr).get(0).get("ct").toString()) + row.getInt("emnum")) / 2;
float leavper = (sumemp == 0) ? 0 : row.getInt("leavnum") / sumemp;
if (leavper > 1)
leavper = 1;
row.put("leavper", leavper);
rst.add(row);
}
return rst;
}
}
<file_sep>/src/com/hr/attd/entity/Hrkq_overtime_adjust.java
package com.hr.attd.entity;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.cjpa.util.CLinkFieldInfo;
import com.corsair.cjpa.util.LinkFieldItem;
import com.corsair.server.cjpa.CJPA;
import com.hr.attd.ctr.CtrHrkq_overtime_adjust;
import java.sql.Types;
@CEntity(controller = CtrHrkq_overtime_adjust.class)
public class Hrkq_overtime_adjust extends CJPA {
@CFieldinfo(fieldname = "otad_id", iskey = true, notnull = true, caption = "加班调整ID", datetype = Types.INTEGER)
public CField otad_id; // 加班调整ID
@CFieldinfo(fieldname = "otad_code", notnull = true, codeid = 84, caption = "加班调整编码", datetype = Types.VARCHAR)
public CField otad_code; // 加班调整编码
@CFieldinfo(fieldname = "ot_id", notnull = true, caption = "加班申请ID", datetype = Types.INTEGER)
public CField ot_id; // 加班申请ID
@CFieldinfo(fieldname = "ot_code", notnull = true, caption = "加班申请编码", datetype = Types.VARCHAR)
public CField ot_code; // 加班申请编码
@CFieldinfo(fieldname = "er_id", caption = "申请人档案ID", datetype = Types.INTEGER)
public CField er_id; // 申请人档案ID
@CFieldinfo(fieldname = "employee_code", caption = "申请人工号", datetype = Types.VARCHAR)
public CField employee_code; // 申请人工号
@CFieldinfo(fieldname = "employee_name", caption = "申请人姓名", datetype = Types.VARCHAR)
public CField employee_name; // 申请人姓名
@CFieldinfo(fieldname = "orgid", notnull = true, caption = "部门ID", datetype = Types.INTEGER)
public CField orgid; // 部门ID
@CFieldinfo(fieldname = "orgcode", notnull = true, caption = "部门编码", datetype = Types.VARCHAR)
public CField orgcode; // 部门编码
@CFieldinfo(fieldname = "orgname", notnull = true, caption = "部门名称", datetype = Types.VARCHAR)
public CField orgname; // 部门名称
@CFieldinfo(fieldname = "deductoff", caption = "扣休息时数", datetype = Types.DECIMAL)
public CField deductoff; // 扣休息时数
@CFieldinfo(fieldname = "over_type", caption = "加班类型", datetype = Types.INTEGER)
public CField over_type; // 加班类型
@CFieldinfo(fieldname = "check_type", caption = "加班打卡", datetype = Types.INTEGER)
public CField check_type; // 加班打卡
@CFieldinfo(fieldname = "begin_date", caption = "申请加班开始时间", datetype = Types.TIMESTAMP)
public CField begin_date; // 申请加班开始时间
@CFieldinfo(fieldname = "end_date", caption = "申请加班结束时间", datetype = Types.TIMESTAMP)
public CField end_date; // 申请加班结束时间
@CFieldinfo(fieldname = "alterbegin_date", caption = "加班调整开始时间", datetype = Types.TIMESTAMP)
public CField alterbegin_date; // 加班调整开始时间
@CFieldinfo(fieldname = "alterend_date", caption = "加班调整结束时间", datetype = Types.TIMESTAMP)
public CField alterend_date; // 加班调整结束时间
@CFieldinfo(fieldname = "dealtype", caption = "加班处理", datetype = Types.INTEGER)
public CField dealtype; // 加班处理
@CFieldinfo(fieldname = "otrate", caption = "加班倍率", datetype = Types.DECIMAL)
public CField otrate; // 加班倍率
@CFieldinfo(fieldname = "otreason", caption = "加班事由", datetype = Types.VARCHAR)
public CField otreason; // 加班事由
@CFieldinfo(fieldname = "isoffday", caption = "是否已调休", datetype = Types.INTEGER)
public CField isoffday; // 是否已调休
@CFieldinfo(fieldname = "remark", caption = "备注", datetype = Types.VARCHAR)
public CField remark; // 备注
@CFieldinfo(fieldname = "wfid", caption = "wfid", datetype = Types.INTEGER)
public CField wfid; // wfid
@CFieldinfo(fieldname = "attid", caption = "attid", datetype = Types.INTEGER)
public CField attid; // attid
@CFieldinfo(fieldname = "stat", notnull = true, caption = "表单状态", datetype = Types.INTEGER)
public CField stat; // 表单状态
@CFieldinfo(fieldname = "idpath", notnull = true, caption = "idpath", datetype = Types.VARCHAR)
public CField idpath; // idpath
@CFieldinfo(fieldname = "entid", notnull = true, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "attribute1", caption = "备用字段1", datetype = Types.VARCHAR)
public CField attribute1; // 备用字段1
@CFieldinfo(fieldname = "attribute2", caption = "备用字段2", datetype = Types.VARCHAR)
public CField attribute2; // 备用字段2
@CFieldinfo(fieldname = "attribute3", caption = "备用字段3", datetype = Types.VARCHAR)
public CField attribute3; // 备用字段3
@CFieldinfo(fieldname = "attribute4", caption = "备用字段4", datetype = Types.VARCHAR)
public CField attribute4; // 备用字段4
@CFieldinfo(fieldname = "attribute5", caption = "备用字段5", datetype = Types.VARCHAR)
public CField attribute5; // 备用字段5
@CFieldinfo(fieldname = "orghrlev", caption = "机构人事层级", datetype = Types.INTEGER)
public CField orghrlev; // 机构人事层级
@CFieldinfo(fieldname = "emplev", caption = "人事层级", datetype = Types.INTEGER)
public CField emplev; // 人事层级
@CFieldinfo(fieldname = "lv_num", caption = "lv_num", datetype = Types.DECIMAL)
public CField lv_num; // lv_num
@CFieldinfo(fieldname = "sp_name", caption = "sp_name", datetype = Types.VARCHAR)
public CField sp_name; // sp_name
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
@CLinkFieldInfo(jpaclass = Hrkq_overtime_adjust_line.class, linkFields = { @LinkFieldItem(lfield = "otad_id", mfield = "otad_id") })
public CJPALineData<Hrkq_overtime_adjust_line> hrkq_overtime_adjust_lines;
public Hrkq_overtime_adjust() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/server/base/Loginex.java
package com.corsair.server.base;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpSession;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.PraperedSql;
import com.corsair.dbpool.util.PraperedValue;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.csession.CSession;
import com.corsair.server.csession.CToken;
import com.corsair.server.generic.Shworg;
import com.corsair.server.generic.Shworguser;
import com.corsair.server.generic.Shwuser;
import com.corsair.server.generic.Shwusertoken;
import com.corsair.server.util.DesSw;
import com.corsair.server.util.DesSwEx;
import com.hr.perm.entity.Hr_employee;
/**
* @author shangwen
* 更加安全的登录方式
*/
public class Loginex {
private static long time_maxtdes = 60 * 30;// 登录时候 允许客户端与服务器有30分钟时差
/**
* 登录
*
* @param username
* @param noncestr
* @param timestr
* @param md5sign
* @return 成功返回TOKEN
* @throws Exception
*/
public static String dologinweb(String username, String noncestr, String timestr, String md5sign) throws Exception {
Date t = Systemdate.getDateByStr(timestr, "yyyyMMddHHmmss");
if (t == null)
throw new Exception("时间戳格式错误");
long st = System.currentTimeMillis() / (1000);
long stl = t.getTime() / (1000);
if (Math.abs(st - stl) > time_maxtdes) {
// 登录时间:【2018-04-15 12:18:43】系统时间:【2018-04-15 12:17:16】 2018-04-15 12:17:16
Logsw.debug("登录时间:【" + Systemdate.getStrDateByFmt(t, "yyyy-MM-dd HH:mm:ss") + "】系统时间:【" + Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd HH:mm:ss") + "】");
Logsw.debug("登录时间:【" + st + "】系统时间:【" + stl + "】最小差异【" + time_maxtdes + "】 现在差异【" + Math.abs(st - stl) + "】");
throw new Exception("系统时间错误");
}
HttpSession session = CSContext.getSession();
Shwuser user = new Shwuser();
String sqlstr = "SELECT * FROM shwuser WHERE username=?";
PraperedSql psql = new PraperedSql();
psql.setSqlstr(sqlstr);
psql.getParms().add(new PraperedValue(java.sql.Types.VARCHAR, username.trim()));// UserName.trim().toUpperCase()
user.findByPSQL(psql);
if (user.isEmpty())
throw new Exception("用户名不存在!");
if (user.actived.getAsIntDefault(0) != 1)
throw new Exception("用户已禁用!");
String userpass = (!user.userpass.isEmpty()) ? DesSw.DESryStrHex(user.userpass.getValue(), ConstsSw._userkey) : "";
String sqlstr2="select RIGHT(id_number,6)id_number from hr_employee where employee_code='"+user.username.getValue()+"'";
String md5str = "username=" + username + "&noncestr=" + noncestr + "×tr=" + timestr + "&password=" + userpass;
//System.out.println(md5str);
md5str = DesSwEx.MD5(md5str).toUpperCase();
if (!md5str.equalsIgnoreCase(md5sign)) {
//System.out.println("正确MD5为:" + md5str);
String[] fields = { "sessionid", "remotehost", "userid", "displayname", "username", "usertype", ConstsSw.session_username,
ConstsSw.session_logined,
ConstsSw.session_logintime };
CSession.removeValue(session.getId(), fields);
throw new Exception("密码错误");
} else {
Hr_employee emp=new Hr_employee();
emp.findBySQL(sqlstr2);
if(!emp.isEmpty())//密码为身份证后6位的拒绝登陆!
{
if(emp.id_number.getValue().equals(userpass)){
String[] fields = { "sessionid", "remotehost", "userid", "displayname", "username", "usertype", ConstsSw.session_username,
ConstsSw.session_logined,
ConstsSw.session_logintime };
CSession.removeValue(session.getId(), fields);
throw new Exception("当前您的密码为初始化密码,为保障信息安全,请即时更改密码。");
}
}
CSession.putvalue(session.getId(), "sessionid", session.getId());
CSession.putvalue(session.getId(), "remotehost", CSContext.getRequest().getRemoteHost());
CSession.putvalue(session.getId(), "userid", user.userid.getValue());
CSession.putvalue(session.getId(), "displayname", user.displayname.getValue());
CSession.putvalue(session.getId(), "username", user.username.getValue());
CSession.putvalue(session.getId(), "usertype", user.usertype.getAsIntDefault(0));
CSession.putvalue(session.getId(), ConstsSw.session_userpwd, null);
CSession.putvalue(session.getId(), ConstsSw.session_logined, true);
CSession.putvalue(session.getId(), ConstsSw.session_logintime, System.currentTimeMillis());
String sessionid = (CSContext.getSession() == null) ? "" : CSContext.getSession().getId();
setLoginedParms(session, user);
Shwusertoken tk = CToken.createToken(user, null, sessionid, 0);
return tk.token.getValue();
}
}
/**
* 登录 密码是明文
*
* @param username
* @param noncestr
* @param timestr
* @param md5sign
* @return 成功返回TOKEN
* @throws Exception
*/
public static String dologinwebmw(String username, String noncestr, String timestr, String md5sign) throws Exception {
Date t = Systemdate.getDateByStr(timestr, "yyyyMMddHHmmss");
if (t == null)
throw new Exception("时间戳格式错误");
long st = System.currentTimeMillis() / (1000);
long stl = t.getTime() / (1000);
if (Math.abs(st - stl) > time_maxtdes) {
// 登录时间:【2018-04-15 12:18:43】系统时间:【2018-04-15 12:17:16】 2018-04-15 12:17:16
Logsw.debug("登录时间:【" + Systemdate.getStrDateByFmt(t, "yyyy-MM-dd HH:mm:ss") + "】系统时间:【" + Systemdate.getStrDateByFmt(new Date(), "yyyy-MM-dd HH:mm:ss") + "】");
Logsw.debug("登录时间:【" + st + "】系统时间:【" + stl + "】最小差异【" + time_maxtdes + "】 现在差异【" + Math.abs(st - stl) + "】");
throw new Exception("系统时间错误");
}
HttpSession session = CSContext.getSession();
Shwuser user = new Shwuser();
String sqlstr = "SELECT * FROM shwuser WHERE username=?";
PraperedSql psql = new PraperedSql();
psql.setSqlstr(sqlstr);
psql.getParms().add(new PraperedValue(java.sql.Types.VARCHAR, username.trim()));// UserName.trim().toUpperCase()
user.findByPSQL(psql);
if (user.isEmpty())
throw new Exception("用户名不存在!");
if (user.actived.getAsIntDefault(0) != 1)
throw new Exception("用户已禁用!");
String userpass = (!user.userpass.isEmpty()) ? ConstsSw.DESryUserPassword(user.userpass.getValue()) : "";
String md5str = "username=" + username + "&noncestr=" + noncestr + "×tr=" + timestr + "&password=" + <PASSWORD>;
//System.out.println(md5str);
md5str = DesSwEx.MD5(md5str).toUpperCase();
if (!md5str.equalsIgnoreCase(md5sign)) {
//System.out.println("正确MD5为:" + md5str);
String[] fields = { "sessionid", "remotehost", "userid", "displayname", "username", "usertype", ConstsSw.session_username,
ConstsSw.session_logined,
ConstsSw.session_logintime };
CSession.removeValue(session.getId(), fields);
throw new Exception("密码错误");
} else {
CSession.putvalue(session.getId(), "sessionid", session.getId());
CSession.putvalue(session.getId(), "remotehost", CSContext.getRequest().getRemoteHost());
CSession.putvalue(session.getId(), "userid", user.userid.getValue());
CSession.putvalue(session.getId(), "displayname", user.displayname.getValue());
CSession.putvalue(session.getId(), "username", user.username.getValue());
CSession.putvalue(session.getId(), "usertype", user.usertype.getAsIntDefault(0));
CSession.putvalue(session.getId(), ConstsSw.session_userpwd, null);
CSession.putvalue(session.getId(), ConstsSw.session_logined, true);
CSession.putvalue(session.getId(), ConstsSw.session_logintime, System.currentTimeMillis());
String sessionid = (CSContext.getSession() == null) ? "" : CSContext.getSession().getId();
setLoginedParms(session, user);
Shwusertoken tk = CToken.createToken(user, null, sessionid, 0);
return tk.token.getValue();
}
}
private static void setLoginedParms(HttpSession session, Shwuser user) throws Exception {
defaultorgid(session, user);
Object o = CSession.getvalue(session.getId(), "curentid");
if (o == null) {
throw new Exception("登录用户【" + user.username.getValue() + "】没有默认机构");
}
setIdpathlike(o.toString(), user.userid.getValue(), session);
}
// 需要包含不可用机构的权限
private static void defaultorgid(HttpSession session, Shwuser user) throws Exception {
CJPALineData<Shworguser> ous = new CJPALineData<Shworguser>(Shworguser.class);
ous.setPool(user.pool);
String sqlstr = "select * from shworguser where userid=" + user.userid.getValue();
ous.findDataBySQL(sqlstr, true, true);
for (CJPABase oub : ous) {
Shworguser ou = (Shworguser) oub;
if (ou.isdefault.getAsIntDefault(0) == 1) {
Shworg org = new Shworg();
org.findByID(ou.orgid.getValue());
// if (org.usable.getAsInt() == 1) {
CSession.putvalue(session.getId(), "defaultorgid", ou.orgid.getValue());
CSession.putvalue(session.getId(), "curentid", org.entid.getValue());
break;
// }
}
}
}
/**
* 登录成功后,给session设置机构,idpath ,idpathwhere 等信息
* 需要包含不可用机构的权限
*
* @param entid
* @param userid
* @param session
* @throws Exception
*/
private static void setIdpathlike(String entid, String userid, HttpSession session) throws Exception {
CJPALineData<Shworg> userorgs = new CJPALineData<Shworg>(Shworg.class);
String sqlstr = "select a.* from shworg a,shworguser b where a.orgid=b.orgid and a.entid=" + entid + " and b.userid=" + userid;
userorgs.findDataBySQL(sqlstr, true, true);
List<String> allidpaths = new ArrayList<String>();
List<String> allorgids = new ArrayList<String>();
for (CJPABase cjpa : userorgs) {
Shworg borg = (Shworg) cjpa;
allidpaths.add(borg.idpath.getValue());
allorgids.add(borg.orgid.getValue());
}
sqlstr = "SELECT fidpath,forgid FROM shworg_find WHERE orgid=" + CSession.getvalue(session.getId(), "defaultorgid");// session.getAttribute("");
List<HashMap<String, String>> idps = DBPools.defaultPool().openSql2List(sqlstr);
for (HashMap<String, String> idp : idps) {
allidpaths.add(idp.get("fidpath"));
allorgids.add(idp.get("forgid"));
}
// 去掉子 idpath 及重复 idpath
List<String> ridps = new ArrayList<String>();
for (String idp : allidpaths) {
if (isNeedAppIdpath(ridps, idp)) {
ridps.add(idp);
}
}
String oidstr = "";
List<String> orgids = new ArrayList<String>();
for (String orgid : allorgids) {
if (!orgids.contains(orgid)) {
orgids.add(orgid);
oidstr = oidstr + orgid + ",";
}
}
String fdips = "";
String idpwhr = "";
for (String idp : ridps) {
idpwhr = idpwhr + "( idpath like '" + idp + "%') or ";
fdips = fdips + idp + "#";
}
if (fdips.length() > 0) {
fdips = fdips.substring(0, fdips.length() - 1);
CSession.putvalue(session.getId(), "idpaths", fdips);
}
if (idpwhr.length() > 0) {
idpwhr = idpwhr.substring(0, idpwhr.length() - 3);
idpwhr = " and (" + idpwhr + ")";
CSession.putvalue(session.getId(), "idpathwhere", idpwhr);
}
if (oidstr.length() > 0) {
oidstr = oidstr.substring(0, oidstr.length() - 1);
CSession.putvalue(session.getId(), "curorgids", oidstr);
}
}
/**
* 是否需要添加IDPATH
*
* @param ridps
* @param idp
* @return
*/
private static boolean isNeedAppIdpath(List<String> ridps, String idp) {
if (idp == null)
return false;// 不给加入,标识为存在
// System.out.println("isNeedAppIdpath:" + idp);
Iterator<String> it = ridps.iterator();
while (it.hasNext()) {
String ridp = it.next();
// System.out.println(idp + ":" + ridp);
if (idp.equalsIgnoreCase(ridp))
return false;
if ((idp.length() > ridp.length()) && (idp.substring(0, ridp.length()).equals(ridp))) {
return false;
}
if ((idp.length() < ridp.length()) && (ridp.substring(0, idp.length()).equals(idp))) {
it.remove();
return true;
}
}
return true;
}
}
<file_sep>/src/com/corsair/server/genco/COSystemMangent.java
package com.corsair.server.genco;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import com.corsair.dbpool.CDBPool;
import com.corsair.dbpool.DBPools;
import com.corsair.dbpool.util.CJSON;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.GetNewSEQID;
import com.corsair.server.weixin.WXUtil;
@ACO(coname = "web.system")
public class COSystemMangent {
@ACOAction(eventname = "getdblist", notes = "获取数据库列表", Authentication = true)
public String getDataBaseList() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(baos);
jg.writeStartArray();
for (CDBPool pool : DBPools.getDbpools()) {
jg.writeStartObject();
jg.writeStringField("poolname", pool.pprm.name);
jg.writeEndObject();
}
jg.writeEndArray();
jg.close();
return baos.toString("utf-8");
}
@ACOAction(eventname = "getWxAppList", notes = "获取微信APPID列表", ispublic = true, Authentication = true)
public String getWxAppList() throws Exception {
String fsep = System.getProperty("file.separator");
String dirroot = ConstsSw._root_filepath + "WEB-INF" + fsep + "conf" + fsep + "wxmenu" + fsep;
File d = new File(dirroot);
List<HashMap<String, String>> fs = new ArrayList<HashMap<String, String>>();
for (File f : d.listFiles()) {
HashMap<String, String> fh = new HashMap<String, String>();
String filename = f.getName();
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
String extf = filename.substring(dot + 1);
if ((extf != null) && (extf.equalsIgnoreCase("json"))) {// 只处理JSON文件
filename = filename.substring(0, dot);
fh.put("appid", filename);
fs.add(fh);
}
}
}
return CJSON.List2JSON(fs);
}
@ACOAction(eventname = "resetseq", notes = "重置序列", Authentication = true)
public String resetseq() throws Exception {
HashMap<String, String> parms = CSContext.parPostDataParms();
String poolname = parms.get("poolname");
if ((poolname == null) || (poolname.isEmpty())) {
throw new Exception("poolname不能为空 ");
}
GetNewSEQID.resetSeq(poolname);
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "createwxmenu", notes = "创建微信菜单", Authentication = true)
public String createWXMenu() throws Exception {
String appid = CSContext.getParms().get("appid");
if ((appid == null) || (appid.isEmpty())) {
throw new Exception("appid不能为空 ");
}
WXUtil.createMenu(appid);
return "{\"result\":\"OK\"}";
}
@ACOAction(eventname = "testInitHtml", notes = "初始化页面", Authentication = false)
public String testInitHtml() throws Exception {
// CHtmlTemplateJS.testHtmlInit();
return "{\"result\":\"OK\"}";
}
}
<file_sep>/src/com/corsair/dbpool/DBPoolParms.java
package com.corsair.dbpool;
/**
* 连接池参数
*
* @author Administrator
*
*/
public class DBPoolParms {
/**
* 连接池名称
*/
public String name = "";
/**
* 是否默认连接池
*/
public boolean isdefault = false;
/**
* 数据库类型
*/
public int dbtype = 1;
/**
* 连接器
*/
public String dirver = "oracle.jdbc.driver.OracleDriver";
/**
* 连接串
*/
public String url = "";
/**
* 数据库名
*/
public String schema = "";
/**
* 登录用户名
*/
public String user = "";
/**
* 登录密码
*/
public String password = "";
/**
* 是否加密的密码
*/
public boolean encpassword = false;
/**
* 初始化连接数
*/
public int minsession = 5;
/**
* 最大连接数
*/
public int maxsession = 500;
/**
* 连接池检查一遍链接间隔时间 秒
*/
public int checkcontime = 10;//
/**
* 数据库session超时时间 获取连接 后 超时 范围内没有处理的 // 下次链接检查的时候将重置为可用状态
*/
public int timeout = 60;//
}
<file_sep>/src/com/hr/util/hrmail/Hr_emailsend_log.java
package com.hr.util.hrmail;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity(caption = "邮件发送日志", tablename = "Hr_emailsend_log")
public class Hr_emailsend_log extends CJPA {
@CFieldinfo(fieldname = "emid", iskey = true, notnull = true, precision = 16, scale = 0, caption = "自己的ID", datetype = Types.INTEGER)
public CField emid; // 自己的ID
@CFieldinfo(fieldname = "emsdid", precision = 16, scale = 0, caption = "别人的ID", datetype = Types.INTEGER)
public CField emsdid; // 别人的ID
@CFieldinfo(fieldname = "aynemid", codeid = 117, notnull = true, precision = 16, scale = 0, caption = "同步ID", datetype = Types.VARCHAR)
public CField aynemid; // 同步ID
@CFieldinfo(fieldname = "employee_code", notnull = true, precision = 16, scale = 0, caption = "工号", datetype = Types.VARCHAR)
public CField employee_code; // 工号
@CFieldinfo(fieldname = "employee_name", notnull = true, precision = 64, scale = 0, caption = "姓名", datetype = Types.VARCHAR)
public CField employee_name; // 姓名
@CFieldinfo(fieldname = "address", notnull = true, precision = 64, scale = 0, caption = "收件人", datetype = Types.VARCHAR)
public CField address; // 收件人
@CFieldinfo(fieldname = "extid", precision = 64, scale = 0, caption = "扩展ID", datetype = Types.VARCHAR)
public CField extid; // 扩展ID
@CFieldinfo(fieldname = "address_bcc", precision = 64, scale = 0, caption = "抄送", datetype = Types.VARCHAR)
public CField address_bcc; // 抄送
@CFieldinfo(fieldname = "address_cc", precision = 64, scale = 0, caption = "秘送", datetype = Types.VARCHAR)
public CField address_cc; // 秘送
@CFieldinfo(fieldname = "approvaldate", precision = 64, scale = 0, caption = "回写审批时间", datetype = Types.VARCHAR)
public CField approvaldate; // 回写审批时间
@CFieldinfo(fieldname = "approvalman", precision = 64, scale = 0, caption = "回写审批人", datetype = Types.VARCHAR)
public CField approvalman; // 回写审批人
@CFieldinfo(fieldname = "mailbody", precision = 1024, scale = 0, caption = "邮件内容", datetype = Types.VARCHAR)
public CField mailbody; // 邮件内容
@CFieldinfo(fieldname = "mailsubject", notnull = true, precision = 128, scale = 0, caption = "邮件标题", datetype = Types.VARCHAR)
public CField mailsubject; // 邮件标题
@CFieldinfo(fieldname = "mailtype", notnull = true, precision = 3, scale = 0, caption = "邮件类型", datetype = Types.VARCHAR)
public CField mailtype; // 邮件类型
@CFieldinfo(fieldname = "wfurl", notnull = true, precision = 512, scale = 0, caption = "审批URL", datetype = Types.VARCHAR)
public CField wfurl; // 审批URL
@CFieldinfo(fieldname = "entid", notnull = true, precision = 5, scale = 0, caption = "entid", datetype = Types.INTEGER)
public CField entid; // entid
@CFieldinfo(fieldname = "creator", notnull = true, precision = 32, scale = 0, caption = "创建人", datetype = Types.VARCHAR)
public CField creator; // 创建人
@CFieldinfo(fieldname = "createtime", notnull = true, precision = 19, scale = 0, caption = "创建时间", datetype = Types.TIMESTAMP)
public CField createtime; // 创建时间
@CFieldinfo(fieldname = "updator", precision = 32, scale = 0, caption = "更新人", datetype = Types.VARCHAR)
public CField updator; // 更新人
@CFieldinfo(fieldname = "updatetime", precision = 19, scale = 0, caption = "更新时间", datetype = Types.TIMESTAMP)
public CField updatetime; // 更新时间
@CFieldinfo(fieldname = "removed", precision = 1, scale = 0, caption = "是否已经从同步数据删除", defvalue = "2", datetype = Types.INTEGER)
public CField removed; // 是否已经从同步数据删除
@CFieldinfo(fieldname = "pushsuccess", notnull = true, precision = 1, scale = 0, caption = "推送状态", defvalue = "2", datetype = Types.INTEGER)
public CField pushsuccess; // 推送状态 1 新建未推送 2 新建推送完成 3 更新失败 4 更新完成
@CFieldinfo(fieldname = "repuhstimes", notnull = true, precision = 3, scale = 0, caption = "从新推送次数", defvalue = "0", datetype = Types.INTEGER)
public CField repuhstimes; // 从新推送次数
@CFieldinfo(fieldname = "attr1", precision = 32, scale = 0, caption = "备用字段1", datetype = Types.VARCHAR)
public CField attr1; // 备用字段1
@CFieldinfo(fieldname = "attr2", precision = 32, scale = 0, caption = "备用字段2", datetype = Types.VARCHAR)
public CField attr2; // 备用字段2
@CFieldinfo(fieldname = "attr3", precision = 32, scale = 0, caption = "备用字段3", datetype = Types.VARCHAR)
public CField attr3; // 备用字段3
@CFieldinfo(fieldname = "attr4", precision = 32, scale = 0, caption = "备用字段4", datetype = Types.VARCHAR)
public CField attr4; // 备用字段4
@CFieldinfo(fieldname = "attr5", precision = 32, scale = 0, caption = "备用字段5", datetype = Types.VARCHAR)
public CField attr5; // 备用字段5
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Hr_emailsend_log() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
}
<file_sep>/src/com/corsair/dbpool/util/Logsw.java
package com.corsair.dbpool.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* 日志
*
* @author Administrator
*
*/
public class Logsw {
public static boolean Debug_Mode = true;
public static boolean savedblog = false;
public static String LogPath = "c:\\corsair\\log";
public static CFileWriter logfile = null;
public static CFileWriter errfile = null;
public static CFileWriter dblogfile = null;
public static String context = null;
public Logsw() {
}
/**
* 关闭日志
*/
public static void close() {
if (logfile != null)
logfile.close();
if (errfile != null)
errfile.close();
if (dblogfile != null)
dblogfile.close();
}
/**
* 记录数据库日志
*
* @param msg 日志内容
*/
public static void dblog(String msg) {
String wstr = msg + " " + Systemdate.getStrDate();
if (context != null)
wstr = "【" + context + "】" + wstr;
if (Debug_Mode) {
System.out.println(wstr);
}
if (savedblog) {
writefile(3, wstr);
}
}
// 强制输出
/**
* 输出DEBUG信息
*
* @param msg
* @param forceout
*/
public static void debug(String msg, boolean forceout) {
String wstr = msg + " " + Systemdate.getStrDate();
if (context != null)
wstr = "【" + context + "】" + wstr;
if (Debug_Mode || forceout) {
System.out.println(wstr);
}
writefile(1, wstr);
}
/**
* 输出DEBUG信息
*
* @param msg
*/
public static void debug(String msg) {
debug(msg, false);
}
/**
* 输出DEBUG信息 并抛出错误
*
* @param e
*/
public static void debug(Exception e) {
String wstr = e.getLocalizedMessage() + " " + Systemdate.getStrDate();
if (context != null)
wstr = "【" + context + "】" + wstr;
if (Debug_Mode) {
e.printStackTrace();
System.out.println(Systemdate.getStrDate());
}
writefile(1, wstr);
}
/**
* 输出错误信息
*
* @param msg
*/
public static void error(String msg) {
System.out.print(msg);
writefile(2, msg);
}
/**
* 输出错误信息
*
* @param e
* @throws Exception
*/
public static void error(Exception e) throws Exception {
error(getStackTrace(e));
throw e;
}
/**
* 输出错误信息 终止错误抛出
*
* @param e
*/
public static void errorNotThrow(Exception e) {
error(getStackTrace(e));
}
/**
* 输出错误信息
*
* @param msg 扩展信息
* @param e
* @throws Exception
*/
public static void error(String msg, Exception e) throws Exception {
String wstr = "";
if ((msg != null) && (!msg.isEmpty()))
wstr = msg + " " + Systemdate.getStrDate();
wstr = wstr + "\r\n" + getExceptionStackTraceMsg(e);
if (context != null)
wstr = "【" + context + "】" + wstr;
error(wstr);
throw e;
}
/**
* 获取错误字符串
*
* @param e
* @return
*/
private static String getExceptionStackTraceMsg(Exception e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return printWriter.toString();
}
public static void main(String[] args) {
// int count = 1000;
// System.out.println("start");
// long begin3 = System.currentTimeMillis();
// for (int i = 0; i < count; i++) {
// writefile(2, i + "测试java 文件操作\r\n");
// }
// long end3 = System.currentTimeMillis();
// System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");
//
// System.out.println("end");
// String sd1 = "2017-03-01 12:30";
// String sd2 = "2017-05-1 12:30";
// System.out.println(Systemdate.getBetweenMonth(Systemdate.getDateByStr(sd1),
// Systemdate.getDateByStr(sd2)));
String fn = "D:\\MyWorks2\\zy\\webservice\\tomcat71\\webapps\\dlhr\\";
File f = new File(fn);
System.out.println(f.getName());
}
/**
* 获取文件对象
*
* @param cfw
* @param fname
* @return
* @throws IOException
*/
private static CFileWriter ckfw(CFileWriter cfw, String fname) throws IOException {
CFileWriter rst = cfw;
if (rst == null) {
rst = new CFileWriter(fname);
} else if (!fname.equals(rst.getFname())) {
rst.close();
rst = new CFileWriter(fname);
}
return rst;
}
private static void checkfw(int type, String fname) {
try {
if (type == 1) {
logfile = ckfw(logfile, fname);
} else if (type == 2) {
errfile = ckfw(errfile, fname);
} else if (type == 3) {
dblogfile = ckfw(dblogfile, fname);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void writefile(int type, String msg) {
String fsep = System.getProperty("file.separator");
String fname = null;
if (type == 1) {
fname = fsep + "debug";
}
if (type == 2) {
fname = fsep + "error";
}
if (type == 3) {
fname = fsep + "dblog";
}
File file = new File(LogPath);
if (!file.exists() && !file.isDirectory())
file.mkdirs();
fname = LogPath + fname + Systemdate.getStrDateYYMMDD() + ".log";
checkfw(type, fname);
// System.out.println(fname);
if (type == 1) {
logfile.Writeline(msg);
} else if (type == 2) {
errfile.Writeline(msg);
} else if (type == 3) {
dblogfile.Writeline(msg);
}
}
/**
* 获取错误信息
*
* @param aThrowable
* @return
*/
public static String getStackTrace(Throwable aThrowable) {
if (aThrowable == null) {
return "null";
}
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/**
* 输出DEBUG
*
* @param value
*/
public static void debug(int value) {
Logsw.debug(String.valueOf(value));
}
}
<file_sep>/src/com/corsair/dbpool/util/PraperedValue.java
package com.corsair.dbpool.util;
/**
* 参数化SQL参数值对象
*
* @author Administrator
*
*/
public class PraperedValue {
private Object value = null;
private int fieldtype;
public PraperedValue() {
}
public PraperedValue(int fieldtype, Object value) {
this.value = value;
this.fieldtype = fieldtype;
}
public Object getValue() {
return value;
}
public int getFieldtype() {
return fieldtype;
}
public void setValue(Object value) {
this.value = value;
}
public void setFieldtype(int fieldtype) {
this.fieldtype = fieldtype;
}
}
<file_sep>/src/com/hr/.svn/pristine/d3/d33514a08f72642ab54ac002a063b7418ebf64fc.svn-base
package com.hr.perm.co;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.dbpool.CDBConnection;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.base.CSContext;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.retention.ACO;
import com.corsair.server.retention.ACOAction;
import com.corsair.server.util.CExcelField;
import com.corsair.server.util.CExcelUtil;
import com.corsair.server.util.DictionaryTemp;
import com.corsair.server.util.UpLoadFileEx;
import com.hr.base.entity.Hr_orgposition;
import com.hr.perm.entity.Hr_employee;
import com.hr.perm.entity.Hr_empptjob_app;
@ACO(coname = "web.hr.empptja")
public class COHr_empptjob_app {
@ACOAction(eventname = "impexcel", Authentication = true, ispublic = false, notes = "入职导入Excel")
public String impexcel() throws Exception {
if (!CSContext.isMultipartContent())
throw new Exception("没有文件");
String batchno = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");// 批次号
CJPALineData<Shw_physic_file> pfs = UpLoadFileEx.doupload(false);
int rst = 0;
if (pfs.size() > 0) {
Shw_physic_file p = (Shw_physic_file) pfs.get(0);
rst = parserExcelFile(p, batchno);
for (CJPABase pfb : pfs) {
Shw_physic_file pf = (Shw_physic_file) pfb;
UpLoadFileEx.delAttFile(pf.pfid.getValue());
}
}
JSONObject jo = new JSONObject();
jo.put("rst", rst);
jo.put("batchno", batchno);
return jo.toString();
}
private int parserExcelFile(Shw_physic_file pf, String batchno) throws Exception {
String fs = System.getProperty("file.separator");
String fullname = ConstsSw.geAppParmStr("UDFilePath") + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
File file = new File(fullname);
if (!file.exists()) {
fullname = ConstsSw._root_filepath + "attifiles" + fs + pf.ppath.getValue() + fs + pf.pfname.getValue();
file = new File(fullname);
if (!file.exists())
throw new Exception("文件" + fullname + "不存在!");
}
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fullname));
int sn = workbook.getNumberOfSheets();
if (sn <= 0)
throw new Exception("excel<" + fullname + ">没有sheet");
HSSFSheet aSheet = workbook.getSheetAt(0);// 获得一个sheet
return parserExcelSheet(aSheet, batchno);
}
private int parserExcelSheet(HSSFSheet aSheet, String batchno) throws Exception {
if (aSheet.getLastRowNum() == 0) {
return 0;
}
List<CExcelField> efds = initExcelFields();
efds = CExcelUtil.parserExcelSheetFields(aSheet, efds, 0);// 解析title 并检查必须存在的列
List<Map<String, String>> values = CExcelUtil.getExcelValues(aSheet, efds, 0);
Hr_employee emp = new Hr_employee();
Hr_orgposition osp = new Hr_orgposition();
Hr_empptjob_app ptja = new Hr_empptjob_app();
CDBConnection con = emp.pool.getCon(this);
DictionaryTemp dictemp = new DictionaryTemp();// 数据字典缓存
con.startTrans();
int rst = 0;
try {
for (Map<String, String> v : values) {
String employee_code = v.get("employee_code");
if ((employee_code == null) || (employee_code.isEmpty()))
continue;
rst++;
emp.clear();
emp.findBySQL("SELECT * FROM hr_employee WHERE employee_code='" + employee_code + "'");
if (emp.isEmpty())
throw new Exception("工号【" + employee_code + "】的人事资料不存在");
ptja.clear();
Date startdate = Systemdate.getDateByStr(v.get("startdate"));
Date enddate = Systemdate.getDateByStr(v.get("enddate"));
if (startdate.getTime() >= enddate.getTime())
throw new Exception("工号【" + employee_code + "】兼职申请起止日期错误");
String sd = Systemdate.getStrDateByFmt(startdate, "yyyy-MM-dd");
String ed = Systemdate.getStrDateByFmt(enddate, "yyyy-MM-dd");
osp.findBySQL("select * from hr_orgposition where ospcode='" + v.get("newospcode") + "'");
if (osp.isEmpty())
throw new Exception("工号【" + employee_code + "】兼职职位【" + v.get("newospcode") + "】不存在");
if (osp.usable.getAsIntDefault(0) == 2)
throw new Exception("工号【" + employee_code + "】兼职职位【" + v.get("newospcode") + "】不可用");
if (emp.lv_num.getAsFloat() > osp.lv_num.getAsFloat()) {
// System.out.println(emp.lv_num.getAsFloat() + ":" + osp.lv_num.getAsFloat());
throw new Exception("工号【" + employee_code + "】兼职职级必须低于主职职级");
}
ptja.applaydate.setAsDatetime(new Date()); // 申请时间
ptja.startdate.setValue(sd); // 开始时间
ptja.enddate.setValue(ed); // 结束时间
ptja.breaked.setValue("2"); // 已终止
ptja.ptjalev.setValue(dictemp.getVbCE("734", v.get("ptjalev"), false, "工号【" + employee_code + "】的兼职层级【" + v.get("ptjalev") + "】不存在")); // 兼职层级
ptja.ptjatype.setValue(dictemp.getVbCE("729", v.get("ptjatype"), false, "工号【" + employee_code + "】的兼职范围【" + v.get("ptjatype") + "】不存在")); // 兼职范围
ptja.ptreason.setValue(v.get("ptreason")); // 兼职原因
ptja.issubsidy.setValue(dictemp.getVbCE("5", v.get("issubsidy"), false, "工号【" + employee_code + "】是否申请补贴【" + v.get("issubsidy") + "】不存在")); // 申请补贴
ptja.subsidyarm.setValue(v.get("subsidyarm")); // 月度补贴金额
ptja.er_id.setValue(emp.er_id.getValue()); // 人事ID
ptja.employee_code.setValue(emp.employee_code.getValue()); // 工号
ptja.id_number.setValue(emp.id_number.getValue()); // 身份证号
ptja.employee_name.setValue(emp.employee_name.getValue()); // 姓名
ptja.degree.setValue(emp.degree.getValue()); // 学历
ptja.hiredday.setValue(emp.hiredday.getValue()); // 入职日期
ptja.odorgid.setValue(emp.orgid.getValue()); // 主职部门ID
ptja.odorgcode.setValue(emp.orgcode.getValue()); // 主职部门编码
ptja.odorgname.setValue(emp.orgname.getValue()); // 主职部门名称
ptja.odorghrlev.setValue("0"); // 主职部门人事级别 流程用到的 这里可以不处理
ptja.odlv_id.setValue(emp.lv_id.getValue()); // 主职职级ID
ptja.odlv_num.setValue(emp.lv_num.getValue()); // 主职职级
ptja.odhg_id.setValue(emp.hg_id.getValue()); // 主职职等ID
ptja.odhg_code.setValue(emp.hg_code.getValue()); // 主职职等编码
ptja.odhg_name.setValue(emp.hg_name.getValue()); // 主职职等名称
ptja.odospid.setValue(emp.ospid.getValue()); // 主职职位ID
ptja.odospcode.setValue(emp.ospcode.getValue()); // 主职职位编码
ptja.odsp_name.setValue(emp.sp_name.getValue()); // 主职职位名称
ptja.odattendtype.setValue(v.get("odattendtype")); // 主职出勤类别
ptja.oldhwc_namezl.setValue(emp.hwc_namezl.getValue()); // 主职职类
ptja.neworgid.setValue(osp.orgid.getValue()); // 兼职部门ID
ptja.neworgcode.setValue(osp.orgcode.getValue()); // 兼职部门编码
ptja.neworgname.setValue(osp.orgname.getValue()); // 兼职部门名称
ptja.newlv_id.setValue(osp.lv_id.getValue()); // 兼职职级ID
ptja.newlv_num.setValue(osp.lv_num.getValue()); // 兼职职级
ptja.newhg_id.setValue(osp.hg_id.getValue()); // 兼职职等ID
ptja.newhg_code.setValue(osp.hg_code.getValue()); // 兼职职等编码
ptja.newhg_name.setValue(osp.hg_name.getValue()); // 兼职职等名称
ptja.neworghrlev.setValue("0"); // 兼职部门人事级别
ptja.newospid.setValue(osp.ospid.getValue()); // 兼职职位ID
ptja.newospcode.setValue(osp.ospcode.getValue()); // 兼职职位编码
ptja.newsp_name.setValue(osp.sp_name.getValue()); // 兼职职位名称
ptja.newattendtype.setValue(v.get("newhwc_namezl")); // 兼职出勤类别
ptja.newhwc_namezl.setValue(osp.hwc_namezl.getValue()); // 兼职职类
ptja.remark.setValue(v.get("remark")); // 备注
ptja.save(con);
ptja.wfcreate(null, con);
}
con.submit();
return rst;
} catch (Exception e) {
con.rollback();
throw e;
} finally {
con.close();
}
}
private List<CExcelField> initExcelFields() {
List<CExcelField> efields = new ArrayList<CExcelField>();
efields.add(new CExcelField("工号", "employee_code", true));
efields.add(new CExcelField("兼职层级", "ptjalev", true));
efields.add(new CExcelField("兼职范围", "ptjatype", true));
efields.add(new CExcelField("开始时间", "startdate", true));
efields.add(new CExcelField("结束时间", "enddate", true));
efields.add(new CExcelField("申请补贴", "issubsidy", true));
efields.add(new CExcelField("月度补贴金额", "subsidyarm", true));
efields.add(new CExcelField("兼职机构职位编码", "newospcode", true));
efields.add(new CExcelField("主职出勤类别", "odattendtype", false));
efields.add(new CExcelField("兼职出勤类别", "newattendtype", false));
efields.add(new CExcelField("兼职原因", "ptreason", false));
efields.add(new CExcelField("备注", "remark", false));
return efields;
}
}
<file_sep>/src/com/corsair/server/weixin/WXHttps.java
package com.corsair.server.weixin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.SSLContext;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import com.corsair.cjpa.CJPABase.CJPAStat;
import com.corsair.dbpool.util.Logsw;
import com.corsair.server.base.CSContext;
import com.corsair.server.generic.Shw_physic_file;
import com.corsair.server.util.FilePath;
import com.corsair.server.util.UpLoadFileEx;
/**
* 微信HTTPS类
*
* @author Administrator
*
*/
public class WXHttps {
// {"errcode":41002,"errmsg":"appid missing"}
public static String getHttps(String url, Map<String, String> parms) throws Exception {
String strp = "";
if (parms != null) {
Iterator<String> it = parms.keySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
String value = parms.get(key);
strp = strp + "&" + key + "=" + value;
}
}
String strurl = url;
if (!strp.isEmpty()) {
if (strurl.indexOf("?") < 0)
strurl = strurl + "?";
strurl = strurl + strp.substring(1);
}
CloseableHttpClient httpclient = getsslHttpClient(null, null);
HttpGet get = new HttpGet(strurl);
HttpResponse resp = httpclient.execute(get);
return getResStr(resp, strurl);
}
public static String postHttps(String url, Map<String, String> parms, String data, boolean needcert) throws Exception {
String strp = "";
if (parms != null) {
Iterator<String> it = parms.keySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
String value = parms.get(key);
strp = strp + "&" + key + "=" + value;
}
}
String strurl = url;
if (!strp.isEmpty()) {
if (strurl.indexOf("?") < 0)
strurl = strurl + "?";
strurl = strurl + strp.substring(1);
}
CloseableHttpClient httpclient = getsslHttpClient(null, null);
HttpPost httppost = new HttpPost(strurl);
Logsw.debug("posturl:" + strurl);
Logsw.debug("postData:" + data);
httppost.addHeader("Content-Type", "text/json");
httppost.setEntity(new StringEntity(data, "utf-8"));//
HttpResponse resp = httpclient.execute(httppost);
return getResStr(resp, strurl);
}
public static String postHttps(String url, Map<String, String> parms, String data) throws Exception {
return postHttps(url, parms, data, false);
}
public static String postWXPayHttps(String url, String data, String certfile, String certpsw) throws Exception {
CloseableHttpClient httpclient = getsslHttpClient(certfile, certpsw);
HttpPost httppost = new HttpPost(url);
Logsw.debug("posturl:" + url);
Logsw.debug("postData:" + data);
httppost.addHeader("Content-Type", "text/xml");
httppost.setEntity(new StringEntity(data, "utf-8"));//
HttpResponse resp = httpclient.execute(httppost);
int code = resp.getStatusLine().getStatusCode();
if (code == 200) {
HttpEntity entity = resp.getEntity();
if (null != entity) {
return EntityUtils.toString(entity, "UTF-8");
} else
throw new Exception("httppost 错误,NUll【" + code + "】URL:" + url);
} else {
throw new Exception("httppost 错误【" + code + "】URL:" + url);
}
}
public static String postWXPayHttps(String url, String data) throws Exception {
return postWXPayHttps(url, data, null, null);
}
private static String getResStr(HttpResponse resp, String url) throws Exception {
int code = resp.getStatusLine().getStatusCode();
if (code == 200) {
HttpEntity entity = resp.getEntity();
if (null != entity) {
String rst = EntityUtils.toString(entity, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
if (rootNode.has("errcode")) {
JsonNode errnode = rootNode.findPath("errcode");
int errcode = errnode.asInt();
if (errcode == 0)
return rst;
else {
String ermsg = WXErrCode.getErrMsg(errcode);
if (ermsg == null)
ermsg = rootNode.path("errmsg").asText();
throw new Exception("httpget 错误【" + errcode + ":" + ermsg + "】");
}
} else
return rst;
} else
throw new Exception("httpget 错误,NUll【" + code + "】");
} else {
throw new Exception("httpget 错误【" + code + "】");
}
}
private static CloseableHttpClient getsslHttpClient(String certfile, String certpsw) throws Exception {
SSLContext sslContext = null;
if (certfile == null) {
sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {// 信任所有
return true;
}
}).build();
} else {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(new File(certfile)), certpsw.toCharArray());
sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(keyStore, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).loadKeyMaterial(keyStore, certpsw.toCharArray()).build();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
}
/**
* 新增临时素材
*
* @param appid
* @param pfid
* @param type
* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* 图片(image): 1M,支持JPG格式
* 语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
* 视频(video):10MB,支持MP4格式
* 缩略图(thumb):64KB,支持JPG格式
* @return
* @throws Exception
*/
public static String uploadWxTempFile(String appid, int pfid, String type) throws Exception {
Shw_physic_file pf = new Shw_physic_file();
pf.findByID(String.valueOf(pfid));
if (pf.isEmpty())
throw new Exception("ID为【" + pfid + "】的物理文件不存在");
String fullname = UpLoadFileEx.getPhysicalFileName(pf);
File file = new File(fullname);
if ((!file.exists()) || (!file.isFile()))
throw new Exception("文件" + fullname + "不存在!");
return uploadWxTempFile(appid, file, type);
}
/**
* 新增临时素材
*
* @param appid
* @param file
* @param type
* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* 图片(image): 1M,支持JPG格式
* 语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
* 视频(video):10MB,支持MP4格式
* 缩略图(thumb):64KB,支持JPG格式
* @return media_id
* @throws Exception
*/
public static String uploadWxTempFile(String appid, File file, String type) throws Exception {
checkUploadFile(file, type);
String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + WXUtil.getTonken(appid) + "&type=" + type;
HttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(file);
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart("media", bin).build();
httppost.setEntity(reqEntity);
HttpResponse res = httpClient.execute(httppost);
String rst = getResStr(res, url);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(rst);
if (rootNode.has("media_id"))
return rootNode.path("media_id").getTextValue();
else
throw new Exception("上传文件返回值未发现期待的media_id参数");
// {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
}
private static void checkUploadFile(File file, String type) throws Exception {
if (!file.exists())
throw new Exception("上传的文件不存在");
String fileName = file.getName();
System.out.println("fileName:" + fileName);
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
float size = file.length() / 1024;
if (type.equals("image")) {
if (!("jpg".equalsIgnoreCase(prefix) || "jpeg".equalsIgnoreCase(prefix)))
throw new Exception("上传的图片文件只支持JPG格式");
if (size > 1024) {
throw new Exception("上传的图片文件不能大于1M");
}
} else if (type.equals("voice")) {
if (!("AMR".equalsIgnoreCase(prefix) || "MP3".equalsIgnoreCase(prefix)))
throw new Exception("上传的声音文件只支持ARM/MP3格式");
if (size > 2 * 1024) {
throw new Exception("上传的声音文件不能大于2M");
}
} else if (type.equals("video")) {
if (!"MP4".equalsIgnoreCase(prefix))
throw new Exception("上传的video文件只支持MP4格式");
if (size > 10 * 1024) {
throw new Exception("上传的video文件不能大于10M");
}
} else if (type.equals("thumb")) {
if (!("jpg".equalsIgnoreCase(prefix) || "jpeg".equalsIgnoreCase(prefix)))
throw new Exception("上传的图片文件只支持JPG格式");
if (size > 64) {
throw new Exception("上传的图片文件不能大于64K");
}
}
}
private static boolean isCanLoad(String ct) {
if (ct.indexOf("image/jpeg") >= 0)
return true;
if (ct.indexOf("audio/amr") >= 0)
return true;
return false;
}
private static String getExtFileName(String ct) {
if (ct.indexOf("image/jpeg") >= 0)
return ".jpg";
if (ct.indexOf("audio/amr") >= 0)
return ".amr";
return "";
}
/**
* 获取临时素材
*
* @param appid
* @param media_id
* @return
* @throws Exception
*/
public static Shw_physic_file dowloadloadWxTempFile(String appid, String media_id) throws Exception {
String strurl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + WXUtil.getTonken(appid) + "&media_id=" + media_id;
System.out.println(strurl);
CloseableHttpClient httpclient = getsslHttpClient(null, null);
HttpGet get = new HttpGet(strurl);
HttpResponse resp = httpclient.execute(get);
int code = resp.getStatusLine().getStatusCode();
if (code == 200) {
HttpEntity entity = resp.getEntity();
if (null != entity) {
String ct = entity.getContentType().toString().toLowerCase();
System.out.println(ct); // audio/amr
if (isCanLoad(ct)) {
FilePath fp = UpLoadFileEx.getFilePath();
String extfname = getExtFileName(ct);// ".jpg";
String fname = UpLoadFileEx.getNoReptFileName(extfname);// 数据库里面存的文件名
File f = new File(fp.FilePath + fname);
FileOutputStream output = null;
InputStream input = null;
try {
output = new FileOutputStream(f);
input = entity.getContent();
byte b[] = new byte[1024];
int j = 0;
while ((j = input.read(b)) != -1) {
output.write(b, 0, j);
}
String un = (CSContext.getUserNameEx() == null) ? "SYSTEM" : CSContext.getUserNameEx();
DecimalFormat df = new DecimalFormat("0.##");
Shw_physic_file pf = new Shw_physic_file();
pf.ppath.setValue(fp.aPath);
pf.pfname.setValue(fname);
pf.create_time.setAsDatetime(new Date());
pf.creator.setValue(un);
pf.displayfname.setValue(fname);
pf.filesize.setValue(df.format(f.length() / (1024f)));// K
pf.extname.setValue(extfname);
pf.fsid.setAsInt(0);
pf.setJpaStat(CJPAStat.RSINSERT);
pf.save();
return pf;
} finally {
if (input != null)
input.close();
if (output != null) {
output.flush();
output.close();
}
}
} else if (ct.indexOf("application/json") >= 0) {
JSONObject jo = JSONObject.fromObject(EntityUtils.toString(entity, "UTF-8"));
if (jo.has("errcode")) {
throw new Exception("错误【" + jo.getString("errcode") + "】【" + jo.getString("errmsg") + "】");
} else {
if (jo.has("video_url")) {
throw new Exception("获取到视频素材了,还不支持哈哈,自己去下载把【" + jo.getString("video_url") + "】");
} else
throw new Exception("错误,啥意思?【" + jo.toString() + "】");
}
} else {
throw new Exception("错误,ContentType啥意思?【" + ct + "】");
}
} else
throw new Exception("httpget 错误,NUll【" + code + "】");
} else {
throw new Exception("httpget 错误【" + code + "】");
}
}
}
<file_sep>/src/com/corsair/server/listener/SWSpecClass.java
package com.corsair.server.listener;
public class SWSpecClass {
public enum SwSpecClassType {
servetContextInit
}
private SwSpecClassType clsType;
private Object clsObj;
public SWSpecClass() {
}
public SWSpecClass(SwSpecClassType clsType, Object clsObj) {
this.clsType = clsType;
this.clsObj = clsObj;
}
public SwSpecClassType getClsType() {
return clsType;
}
public void setClsType(SwSpecClassType clsType) {
this.clsType = clsType;
}
public Object getClsObj() {
return clsObj;
}
public void setClsObj(Object clsObj) {
this.clsObj = clsObj;
}
}
<file_sep>/src/com/corsair/server/cjpa/CWDNotifyParm.java
package com.corsair.server.cjpa;
import com.corsair.server.base.ConstsSw;
import com.corsair.server.cjpa.CWFNotify.NotityType;
/**
* 流程通知参数
*
* @author Administrator
*
*/
public class CWDNotifyParm {
// 到达通知 0 不通知 1 邮件通知 2 短信通知 3 微信推送 A 提交人 B审批过的人 C所有人 D当前节点参与人 如:12AC代表邮件短信通知提交人、所有参与人
private boolean notity = false;// 是否通知
private boolean mail = false;
private boolean sms = false;
private boolean wechat = false;
private boolean creator = false;
private boolean subeduser = false;
private boolean alluser = false;
private boolean curprocuser = false;
public CWDNotifyParm(NotityType nt) {
String af = null;
if (nt == NotityType.ntArrive)
af = ConstsSw.getSysParm("WFArriveNotify");
if (nt == NotityType.ntFinish)
af = ConstsSw.getSysParm("WFFinishNotify");
if (nt == NotityType.ntBreak)
af = ConstsSw.getSysParm("WFBreakNotify");
if (nt == NotityType.ntRefuse)
af = ConstsSw.getSysParm("WFRefuseNotify");
if (nt == NotityType.ntPress) {
af = ConstsSw.getSysParm("WFPressNotify");
}
if (nt == NotityType.ntTransfer) {
af = ConstsSw.getSysParm("WFTransferNotify");
}
if ((af == null) || (af.isEmpty()))
return;
char[] cs = af.toCharArray();
for (char c : cs) {
if (c == '0') {
setallfalse();
return;
}
if (c == '1')
mail = true;
if (c == '2')
sms = true;
if (c == '3')
wechat = true;
if (c == 'A')
creator = true;
if (c == 'B')
subeduser = true;
if (c == 'C')
alluser = true;
if (c == 'D')
curprocuser = true;
}
notity = ((mail || sms || wechat) && (creator || alluser || curprocuser));
if (nt == NotityType.ntPress) {
notity = (mail || sms || wechat);
}
}
private void setallfalse() {
notity = false;// 是否通知
mail = false;
sms = false;
wechat = false;
creator = false;
subeduser = false;
alluser = false;
curprocuser = false;
}
public boolean isNotity() {
return notity;
}
public boolean isMail() {
return mail;
}
public boolean isCreator() {
return creator;
}
public boolean isSubeduser() {
return subeduser;
}
public boolean isAlluser() {
return alluser;
}
public boolean isCurprocuser() {
return curprocuser;
}
public boolean isSms() {
return sms;
}
public boolean isWechat() {
return wechat;
}
}
<file_sep>/WebContent/webapp/js/common/cpopinfo2.js
/**
* Created by shangwen on 2016/6/14.
* need jsbanding2.js
*/
function CPopInfoWindow(options) {
var issetEditValue = false;
var voptions = options;
if (!voptions.windowfilter)
throw new Error("没有设置windowfilter属性!");
var iwobj = $(voptions.windowfilter);
if (iwobj.attr('class').indexOf("easyui-window") < 0)
throw new Error("非easyui-window窗口,不允许弹出!");
var els_all = [];//所有输入框对象
var lables = [];
var isloadingdata = false;
var datachanged = true;
function onValueChange(fdname, newValue, oldValue, newRowValue, ele) {
if (oldValue != newValue) {
if ((voptions.onValueChange) && (!isloadingdata)) {//&& (!issetEditValue)
voptions.onValueChange(fdname, newValue, oldValue, newRowValue, ele);
}
setDataChanged(true, "");
}
}
this.setDataChanged = setDataChanged;
function setDataChanged(value, mask) {
datachanged = value;
if (datachanged) {
}
}
var JSONBandingFrm = new TJSONBandingFrm({
filter: voptions.windowfilter,
onChange: onValueChange
})
;//数据绑定
initbts();//初始化按钮事件
function initbts() {
var els = JSONBandingFrm.getInputArray();
els_all = els.els_all;
//els_readonly = els.els_readonly;
lables = els.els_lables;
//initInput();
var bts = iwobj.find("a[cjoptions]").each(function (index, el) {
var co = $.c_parseOptions($(this));
if (co.caction == "act_ok") {
el.onclick = function () {
acceptAllGrid();
//从界面获取数据
var jdata = voptions.jsonData; //iwobj.c_toJsonData(voptions.jsonData, voptions.isNew);
JSONBandingFrm.toJsonData(els_all, jdata, voptions.isNew);
//获取列表数据
//需要重新load grid 数据吗? 可能不需要!
if (!JSONBandingFrm.checkNotNull(els_all, lables, jdata)) return false;
if (voptions.afterGetData) {
voptions.afterGetData(jdata);
}
if ((voptions.onOK) && (voptions.onOK(voptions.isNew, jdata)))
iwobj.window('close');
};
}
if (co.caction == "act_cancel") {
el.onclick = function () {
if (voptions.onCancel) {
var errmsg = voptions.onCancel();
if (errmsg)alert(errmsg);
}
iwobj.window('close');
}
}
});
}
this.close = close;
function close() {
clearInputData();
iwobj.window('close');
}
this.getdata = getdata;
function getdata() {
// return iwobj.c_toJsonData(voptions.jsonData, voptions.isNew);
var jdata = voptions.jsonData; //iwobj.c_toJsonData(voptions.jsonData, voptions.isNew);
return JSONBandingFrm.toJsonData(els_all, jdata, voptions.isNew);
}
this.setFieldReadOnly = setFieldReadOnly;
function setFieldReadOnly(fdname, readonly) {
JSONBandingFrm.setFieldReadOnly(fdname, readonly);
}
this.show = show;
function show(options) {
if (options)
extendOptions(options);
if (voptions.isNew)
iwobj.c_setJsonDefaultValue(voptions.jsonData, true);
if (voptions.onShow) {
voptions.onShow(voptions.isNew, voptions.jsonData);
}
showDetail();
//iwobj.window({onOpen: onWindowShow});
iwobj.window('open');
iwobj.find(".easyui-tabs").each(function (index, el) {
$(this).tabs("select", 0);
});
}
this.showDetail = showDetail;
function showDetail(jsdata) {
isloadingdata = true;
if (jsdata)
voptions.jsonData = jsdata;
clearInputData();
setData2Input();
setData2Grid();
if (voptions.afterShowDetail)
voptions.afterShowDetail(voptions.jsonData);
setDataChanged(false);
isloadingdata = false;
}
this.setAllReadOnly = setAllReadOnly;
function setAllReadOnly(readonly) {
JSONBandingFrm.setAllInputReadOnly(els_all, readonly);
}
this.reSetInputReadOnly = reSetInputReadOnly;
function reSetInputReadOnly() {
for (var i = 0; i < els_all.length; i++) {
var co = els_all[i].cop;
if (!co.readonly) {
JSONBandingFrm.setInputReadOnly(els_all[i], false);
} else {
JSONBandingFrm.setInputReadOnly(els_all[i], true);
}
}
}
this.getDataChanged = function () {
return datachanged;
};
this.extendOptions = extendOptions;
function extendOptions(NewOptions) {
voptions = $.extend(voptions, NewOptions);
}
this.getOptions = function () {
return voptions;
};
function onWindowShow() {
if (voptions.onShow) {
voptions.onShow(voptions.isNew, voptions.jsonData);
}
}
function clearInputData() {
JSONBandingFrm.clearMainData(undefined, []);
iwobj.find("table[cjoptions][class*='easyui-datagrid']").each(function (index, el) {
$(this).datagrid("loadData", []);
});
iwobj.find("table[cjoptions][class*='easyui-treegrid']").each(function (index, el) {
$(this).treegrid("loadData", []);
});
}
this.getFieldValue = function (fdname) {
var v = $getInputValue(els_all, fdname);
if (v)
return v;
else
return voptions.jsonData[fdname];
};
this.getField = getField;
function getField(fdname) {
for (var i = 0; i < els_all.length; i++) {
var co = els_all[i].cop;
//alert(co.fdname + " " + fdname);
if (co.fdname == fdname) {
return $(els_all[i]);
}
}
}
this.setFieldValue = setFieldValue;
function setFieldValue(fdname, value) {
issetEditValue = true;
try {
voptions.jsonData[fdname] = value;
JSONBandingFrm.setFieldValue(fdname, value);
}
finally {
issetEditValue = false;
}
}
this.setFieldReadOnly = setFieldReadOnly;
function setFieldReadOnly(fdname, readonly) {
JSONBandingFrm.setFieldReadOnly(fdname, readonly);
}
function findElinput(els_all, fdname) {
for (var i = 0; i < els_all.length; i++) {
var co = $.c_parseOptions($(els_all[i]));
if (co.fdname == fdname) {
return els_all[i]
}
}
return undefined;
}
function setData2Input() {
JSONBandingFrm.fromJsonData(els_all, voptions.jsonData);
}
function setData2Grid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = voptions.jsonData[id];
if ($(this).datagrid) {
if (tbdata != undefined) {
//if (tbdata.length > 0) 如果为空 也需要载入 数据 以载入数据和Grid的关联关系,否则空数据无法保存
$(this).datagrid("loadData", tbdata);
//else
// $(this).datagrid("loadData", []);
}
}
});
}
function acceptAllGrid() {
iwobj.find(".easyui-datagrid[id]").each(function (index, el) {
var id = $(el).attr("id");
var tbdata = voptions.jsonData[id];
if ((tbdata) && ($(this).datagrid)) {
$(this).datagrid("acceptChanges");
}
});
}
function $getInputValue(els_all, fdname) {
for (var i = 0; i < els_all.length; i++) {
var co = $.c_parseOptions($(els_all[i]));
//var et = getInputType(els_all[i]);
if (co.fdname == fdname) {
var v = $(els_all[i]).textbox("getValue");
return v;
}
}
return undefined;
}
/*
function onValueChange(newValue, oldValue) {
var obj = $(this);
var co = $.c_parseOptions(obj);
if ((co != undefined) && (voptions.onEditChanged) && (!issetEditValue)) {
voptions.onEditChanged(co.fdname, newValue, oldValue);
}
}*/
}
<file_sep>/src/com/corsair/server/websocket/AWebsocket.java
package com.corsair.server.websocket;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @author Administrator
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface AWebsocket {
String vport();
}
<file_sep>/WebContent/webapp/js/hrms/cactivex.js
/**
* Created by shangwen on 2016/10/15.
*/
$(document).ready(function () {
var hrmsact = document.getElementById("hrmsact");
if (hrmsact == undefined) {
var hm = "<OBJECT ID='hrmsact' style='display: none' CLASSID='CLSID:DD300566-1717-4382-84B1-D6AB4D492E0B' align=center hspace=0 vspace=0></OBJECT>";
$(hm).appendTo("body");
}
});
function $ReadIDCardInfo() {
return docallactproc(1);
}
function $TakePhoto() {
return docallactproc(2);
}
function $ScanPhoto() {
return docallactproc(3);
}
function docallactproc(tp) {
if (browinfo.browser == "IE") {
try {
hrmsact.testproc()
var ocxinited = true;
} catch (e) {
var ocxinited = false;
}
if (ocxinited) {
if (tp == 1)
return JSON.parse(hrmsact.readidcardinfo());
if (tp == 2)
return hrmsact.takephoto();
if (tp == 3)
return hrmsact.sacnphoto();
} else {
alert("HRMS插件未能正确安装 或 浏览器安全级别已禁止Activex运行!");
}
} else {
alert("硬件接口插件暂时只支持IE系列浏览器!");
}
}
<file_sep>/src/com/hr/timer/TaskKqSendWx.java
package com.hr.timer;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import org.json.JSONObject;
import com.corsair.cjpa.CJPABase;
import com.corsair.cjpa.CJPALineData;
import com.corsair.dbpool.util.Logsw;
import com.corsair.dbpool.util.Systemdate;
import com.corsair.server.generic.Shworg;
import com.hr.attd.entity.Hrkq_bckqrst;
import com.hr.attd.entity.Hrkq_parms;
import com.hr.msg.entity.Hr_kq_day_report;
import com.hr.msg.entity.Hr_kq_depart_day_report;
import com.hr.msg.entity.Hr_msg_config;
import com.hr.msg.entity.Wx_msg_send;
import com.hr.util.DateUtil;
import com.hr.util.HRUtil;
import com.hr.util.wx.SendMsgUtil;
import net.sf.json.JSONArray;
/*
* 运算当月无打卡,补签次数
*/
public class TaskKqSendWx extends TimerTask {
// 亲爱的{{employee_name}},您好!您{{time}}号考勤漏打卡{{yer_no_card_num}}次({{yer_no_card_times}}),本月合计漏打卡{{no_card_num}}次,截止目前已补签{{make_up_num}}次,请及时登录系统处理异常,谢谢。
// 尊敬的{{employee_name}},您好!截止{{time}}{{orgname}}应出勤人数{{zz}}人,实际出勤{{cq}}人、调休{{tx}}人、请假{{qj}}人、出差{{cc}}人、未打卡{{wdk}}人,出勤达成率为{{dcl}},谢知悉!
private void sendWxDepart() {
// 获取模板
try {
String msgTemplate = "";
Hrkq_parms msg_template = new Hrkq_parms();
CJPALineData<Wx_msg_send> saveMsgList = new CJPALineData<Wx_msg_send>(Wx_msg_send.class);
List<Hr_kq_depart_day_report> reportList = new ArrayList<Hr_kq_depart_day_report>();
String sqlstr = "select * from hrkq_parms where parmcode='WX_KQ_MSG_DEPART'";
msg_template.findBySQL(sqlstr);
if (!msg_template.isEmpty()) {
// 先获取配置所有订阅的公司
msgTemplate = msg_template.parmvalue.getValue();
String sql = "select DISTINCT(orgname) as orgname,idpath from Hr_msg_config where usable='1'";
CJPALineData<Hr_msg_config> cas = new CJPALineData<Hr_msg_config>(Hr_msg_config.class);
cas.findDataBySQL(sql);
for (CJPABase jpa : cas) {
Hr_msg_config ca = (Hr_msg_config) jpa;
Hr_kq_depart_day_report report = new Hr_kq_depart_day_report();
report.orgname.setValue(ca.orgname.getValue());
getDepartKqRealTime(report, ca.idpath.getValue(), Systemdate.getStrDateyyyy_mm_dd());
reportList.add(report);
}
// 获取订阅关系
// 尊敬的{{employee_name}},您好!截止{{time}}{{orgname}}应出勤人数{{zz}}人,实际出勤{{cq}}人、调休{{tx}}人、请假{{qj}}人、出差{{cc}}人、未打卡{{wdk}}人,出勤达成率为{{cqdcl}},谢知悉!
String sqlconfig = "select * from Hr_msg_config where usable='1'";
cas.findDataBySQL(sqlconfig);
for (CJPABase jpa : cas) {
Hr_msg_config msgConfig = (Hr_msg_config) jpa;
for (Hr_kq_depart_day_report report : reportList) {
if (report.orgname.getValue().equals(msgConfig.orgname.getValue())) {
msgTemplate = msg_template.parmvalue.getValue();
msgTemplate = msgTemplate.replace("{{employee_name}}", msgConfig.employee_name.getValue());
msgTemplate = msgTemplate.replace("{{orgname}}", msgConfig.orgname.getValue());
msgTemplate = msgTemplate.replace("{{time}}", Systemdate.getStrDate());
msgTemplate = msgTemplate.replace("{{zz}}", report.zz.getValue());
msgTemplate = msgTemplate.replace("{{cq}}", report.cq.getValue());
msgTemplate = msgTemplate.replace("{{tx}}", report.tx.getValue());
msgTemplate = msgTemplate.replace("{{qj}}", report.qj.getValue());
msgTemplate = msgTemplate.replace("{{cc}}", report.cc.getValue());
msgTemplate = msgTemplate.replace("{{wdk}}", report.wdk.getValue());
msgTemplate = msgTemplate.replace("{{cqdcl}}", report.cqdcl.getValue());
String retult = SendMsgUtil.sendText(msgConfig.employee_code.getValue(), msgTemplate);
JSONObject jsonObj = new JSONObject(retult);
Wx_msg_send msg = new Wx_msg_send();
msg.errcode.setValue(jsonObj.get("errcode").toString());
msg.errmsg.setValue(jsonObj.get("errmsg").toString());
msg.send_time.setValue(Systemdate.getStrDate());
msg.content.setValue(msgTemplate);
msg.employee_code.setValue(msgConfig.employee_code.getValue());
saveMsgList.add(msg);
}
}
}
if (saveMsgList.size() > 0) {
saveMsgList.saveBatchSimple();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void getDepartKqRealTime(Hr_kq_depart_day_report report, String idpath, String dqdate) throws Exception {
String reportOrgSql = "select a.employee_code,orgname,noclock,emnature,hiredday,t.cq,t2.qj,t3.cc,t4.tx from hr_employee a" +
" LEFT JOIN (select b.empno, '1' as cq from hrkq_swcdlst b WHERE DATE_FORMAT(b.skdate,'%Y-%m-%d')='" + dqdate + "' GROUP BY b.empno) as t on t.empno=a.employee_code" +
" LEFT JOIN (select b.employee_code, '1' as qj from hrkq_holidayapp b WHERE (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='" + dqdate + "' and b.timeed>='" + dqdate + "') or (DATE_FORMAT(b.timebg,'%Y-%m-%d')<='" + dqdate+ "' and b.timeedtrue>='" + dqdate + "') and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t2 on t2.employee_code=a.employee_code" +
" LEFT JOIN (select b.employee_code, '1' as cc from hrkq_business_trip b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='" + dqdate + "' and b.end_date>='" + dqdate+ "' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t3 on t3.employee_code=a.employee_code" +
" LEFT JOIN (select b.employee_code, '1' as tx from hrkq_wkoff b WHERE DATE_FORMAT(b.begin_date,'%Y-%m-%d')<='" + dqdate + "' and b.end_date>='" + dqdate+ "' and (b.stat='9' or b.stat='2') GROUP BY b.employee_code) as t4 on t4.employee_code=a.employee_code" +
" where a.idpath like '" + idpath + "%' and a.sp_name<>'项目实习生' and a.empstatid<>'12' and a.empstatid<>'13' and a.empstatid<>'0' and a.idpath NOT LIKE '1,253,7987,%' and a.idpath not LIKE '1,8761,8762,8772,%' and a.hiredday<='" + dqdate + "'";
List<HashMap<String, String>> reportList = HRUtil.getReadPool().openSql2List(reportOrgSql);
int zz = reportList.size();
int cc = 0;
int tx = 0;
int qj = 0;
int mdk = 0;
int cq = 0;
int tcwdk = 0;// 脱产无打卡
int ftcwdk = 0;// 非脱产无打卡
int rzdtwdk = 0;// 当天入职无打卡
for (HashMap<String, String> entity : reportList) {
String scc = "";
String stx = "";
String sqj = "";
String scq = "";
if (entity.get("cc") != null) {
scc = entity.get("cc");
}
if (entity.get("tx") != null) {
stx = entity.get("tx");
}
if (entity.get("qj") != null) {
sqj = entity.get("qj");
}
if (entity.get("cq") != null) {
scq = entity.get("cq");
}
if (scc.equals("1") && entity.get("noclock").equals("2")) {
cc++;
} else if (stx.equals("1") && entity.get("noclock").equals("2")) {
tx++;
} else if (sqj.equals("1")&& entity.get("noclock").equals("2")) {
qj++;
} else if (scq.equals("1") && entity.get("noclock").equals("2")) {
cq++;
} else {
// 缺勤
if (entity.get("emnature").equals("脱产") && entity.get("noclock").equals("2")) {
tcwdk++;
} else if (entity.get("emnature").equals("非脱产") && entity.get("noclock").equals("2")) {
ftcwdk++;
}
// 统计当天入职无打卡
// System.out.print(entity.get("hiredday"));
String hiredday = Systemdate.getStrDateyyyy_mm_dd(Systemdate.getDateByyyyy_mm_dd(entity.get("hiredday")));
if (hiredday.equals(dqdate)) {
rzdtwdk++;
}
}
if (entity.get("noclock").equals("1")) {
mdk++;
cq++;
}
}
report.zz.setValue(zz);
report.cc.setValue(cc);
report.tx.setValue(tx);
report.qj.setValue(qj);
report.ftcwdk.setValue(ftcwdk);
report.tcwdk.setValue(tcwdk);
report.rzdtwdk.setValue(rzdtwdk);
report.cq.setValue(cq);
report.date.setValue(dqdate);
report.wdk.setValue(ftcwdk + tcwdk);
if (zz > 0) {
double sum = cq + cc + tx;
sum = sum / zz * 100;
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (sum > 100) {
report.cqdcl.setValue("100%");
} else {
report.cqdcl.setValue(sum + "%");
}
} else {
report.cqdcl.setValue("0%");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int minute=calendar.get(Calendar.MINUTE);
int hour=calendar.get(Calendar.HOUR_OF_DAY);
calendar.get(Calendar.SUNDAY);
if(calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY )
{
if(hour==21 && minute==1){
//if(hour==9 && minute==46){
sendWxDepart();// 推送部门无打卡数据
}
}
}catch(Exception e){
Logsw.dblog("部门考勤推送结束:"+e.toString());
}
}
}
<file_sep>/src/com/corsair/server/generic/Shwkv.java
package com.corsair.server.generic;
import com.corsair.cjpa.CField;
import com.corsair.cjpa.CJPALineData;
import com.corsair.cjpa.util.CEntity;
import com.corsair.cjpa.util.CFieldinfo;
import com.corsair.dbpool.CDBConnection;
import com.corsair.server.cjpa.CJPA;
import java.sql.Types;
@CEntity()
public class Shwkv extends CJPA {
@CFieldinfo(fieldname = "kvid", iskey = true, notnull = true, caption = "kvid", datetype = Types.INTEGER)
public CField kvid; // kvid
@CFieldinfo(fieldname = "kvcode", notnull = true, caption = "kvcode", datetype = Types.VARCHAR)
public CField kvcode; // kvcode
@CFieldinfo(fieldname = "kvvalue", notnull = true, caption = "kvvalue", datetype = Types.VARCHAR)
public CField kvvalue; // kvvalue
public String SqlWhere; // 查询附加条件
public int MaxCount; // 查询最大数量
// 自关联数据定义
public Shwkv() throws Exception {
}
@Override
public boolean InitObject() {// 类初始化调用的方法
super.InitObject();
return true;
}
@Override
public boolean FinalObject() { // 类释放前调用的方法
super.FinalObject();
return true;
}
public static String getkvvalue(String kvcode) throws Exception {
String sqlstr = "select * from shwkv where kvcode='" + kvcode + "'";
Shwkv kv = new Shwkv();
kv.findBySQL(sqlstr);
if (kv.isEmpty())
return null;
else
return kv.kvvalue.getValue();
}
public static void setkvvalue(CDBConnection con, String kvcode, String value) throws Exception {
String sqlstr = "select * from shwkv where kvcode='" + kvcode + "'";
Shwkv kv = new Shwkv();
kv.findBySQL(sqlstr);
kv.kvcode.setValue(kvcode);
kv.kvvalue.setValue(value);
kv.save(con);
}
}
| 9993689d096b60da6ba5255829c8c0e9c20139b6 | [
"JavaScript",
"Java"
] | 223 | Java | ballen101/dlhr-09-22 | 3e650ac4fd231e55c7cb26870c8c9411540ef749 | a744e6535ecafcc8c6abcb473fc8b763034c63b7 |
refs/heads/master | <repo_name>jvtm/journalpump<file_sep>/test/test_journalpump.py
from journalpump.journalpump import JournalPump, ElasticsearchSender, KafkaSender, LogplexSender
import json
def test_journalpump_init(tmpdir):
# Logplex sender
journalpump_path = str(tmpdir.join("journalpump.json"))
config = {
"readers": {
"foo": {
"senders": {
"bar": {
"logplex_token": "foo",
"logplex_log_input_url": "http://logplex.com",
"output_type": "logplex",
},
},
},
},
}
with open(journalpump_path, "w") as fp:
fp.write(json.dumps(config))
a = JournalPump(journalpump_path)
for rn, r in a.readers.items():
assert rn == "foo"
r.running = False
for sn, s in r.senders.items():
assert sn == "bar"
s.running = False
assert isinstance(s, LogplexSender)
# Kafka sender
config = {
"readers": {
"foo": {
"senders": {
"bar": {
"output_type": "kafka",
"logplex_token": "foo",
"kafka_address": "localhost",
"kafka_topic": "foo",
},
},
},
},
}
with open(journalpump_path, "w") as fp:
fp.write(json.dumps(config))
a = JournalPump(journalpump_path)
for rn, r in a.readers.items():
assert rn == "foo"
r.running = False
for sn, s in r.senders.items():
assert sn == "bar"
s.running = False
assert isinstance(s, KafkaSender)
# Elasticsearch sender
config = {
"readers": {
"foo": {
"senders": {
"bar": {
"output_type": "elasticsearch",
"elasticsearch_url": "https://foo.aiven.io",
"elasticsearch_index_prefix": "fooprefix",
},
},
},
},
}
with open(journalpump_path, "w") as fp:
fp.write(json.dumps(config))
a = JournalPump(journalpump_path)
for rn, r in a.readers.items():
assert rn == "foo"
r.running = False
for sn, s in r.senders.items():
assert sn == "bar"
s.running = False
assert isinstance(s, ElasticsearchSender)
| ea364b700daf3200e823acf0f83ac348ec3dc115 | [
"Python"
] | 1 | Python | jvtm/journalpump | d9857db9abaf45c834d814750cc723bde6269765 | 8e69899f3c5c728d6e4adff9c487e3c323aae16e |
refs/heads/master | <repo_name>franleplant/ser-example-ml<file_sep>/src/augment_data.py
import numpy as np
import librosa
def noise(data):
"""Add white noice to the librosa sound """
noise_amp = 0.035 * np.random.uniform() * np.amax(data)
data = data + noise_amp * np.random.normal(size=data.shape[0])
return data
def stretch(data, rate=0.8):
return librosa.effects.time_stretch(data, rate)
def shift(data):
shift_range = int(np.random.uniform(low=-5, high=5) * 1000)
return np.roll(data, shift_range)
def pitch(data, sampling_rate, pitch_factor=0.7):
return librosa.effects.pitch_shift(data, sampling_rate, pitch_factor)
def augment_data(data, sample_rate):
"""
grab a single audio file and by augmenting it turn it into 4,
we return a list made of the original data and the new data
"""
return [
data,
noise(data),
pitch(stretch(data), sample_rate),
# shift(data),
]
<file_sep>/src/get_features.py
import numpy as np
import librosa
def calc_zero_crossing_rate(data):
return np.mean(librosa.feature.zero_crossing_rate(y=data).T, axis=0)
def calc_chroma_stft(data, sample_rate):
stft = np.abs(librosa.stft(data))
return np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T, axis=0)
def calc_mfcc(data, sample_rate):
return np.mean(librosa.feature.mfcc(y=data, sr=sample_rate).T, axis=0)
def calc_rms(data):
return np.mean(librosa.feature.rms(y=data).T, axis=0)
def calc_melspectrogram(data, sample_rate):
return np.mean(librosa.feature.melspectrogram(y=data, sr=sample_rate).T, axis=0)
def get_features(data, sample_rate):
zcr = calc_zero_crossing_rate(data)
chroma = calc_chroma_stft(data, sample_rate)
mfcc = calc_mfcc(data, sample_rate)
rms = calc_rms(data)
mel = calc_melspectrogram(data, sample_rate)
# print("features")
# print("zcr", len(zcr))
# print("chroma", len(chroma))
# print("mfcc", len(mfcc))
# print("rms", len(rms))
# print("mel", len(mel))
# we unfold all values into a very long array, instead of having an array of arrays
return np.hstack([zcr, chroma, mfcc, rms, mel])
# def run(path):
# duration and offset are used to take care of the no audio in start and the ending of each audio files as seen above.
# data, sample_rate = librosa.load(path, duration=2.5, offset=0.6)
# without augmentation
# res1 = extract_features(data)
# result = np.array(res1)
# data with noise
# noise_data = noise(data)
# res2 = extract_features(noise_data)
# result = np.vstack((result, res2)) # stacking vertically
# data with stretching and pitching
# new_data = stretch(data)
# data_stretch_pitch = pitch(new_data, sample_rate)
# res3 = extract_features(data_stretch_pitch)
# result = np.vstack((result, res3)) # stacking vertically
# return result
<file_sep>/src/get_data.py
import os
import pandas as pd
import numpy as np
RAVDESS = "./train-data/ravdess/audio_speech_actors_01-24/"
CREMA = "./train-data/cremad/AudioWAV/"
SAVEE = "./train-data/savee/"
TESS = "./train-data/tess/TESS Toronto emotional speech set data/"
def normalize_ravdess():
"""
grab the files and turn them into a pandas data frame
of the shape emotion: "angry", path: "path to the file"
"""
emotion_map = {
1: "neutral",
2: "calm",
3: "happy",
4: "sad",
5: "angry",
6: "fear",
7: "disgust",
8: "surprise",
}
rows = []
for dir in os.listdir(RAVDESS):
# as their are 20 different actors in our previous directory we need to extract files for each actor.
actor_dir = os.listdir(RAVDESS + dir)
for file in actor_dir:
if file.startswith("."):
print("skipping dotfile", file)
continue
name, extension = file.split(".")
[
modality,
channel,
emotion_id,
intensity,
statement,
repetition,
actor,
] = name.split("-")
emotion = emotion_map[int(emotion_id)]
file_path = RAVDESS + dir + "/" + file
rows.append((emotion, file_path))
df = pd.DataFrame(rows, columns=["emotion", "path"])
# print(df.head())
return df
def normalize_crema():
emotion_map = {
'NEU': "neutral",
'HAP': "happy",
'SAD': "sad",
'ANG': "angry",
'FEA': "fear",
'DIS': "disgust",
}
rows = []
for file in os.listdir(CREMA) :
if file.startswith("."):
print("skipping dotfile", file)
continue
# storing file paths
file_path = CREMA + file
# storing file emotions
[id, actor, emotion_id, modifier]=file.split('_')
emotion = emotion_map[emotion_id]
if not emotion:
print("skipping unknown emotion file", file)
continue
rows.append((emotion, file_path))
df = pd.DataFrame(rows, columns=["emotion", "path"])
# print(df.head())
return df
def normalize_savee():
rows = []
emotion_map = {
'n': "neutral",
'h': "happy",
'sa': "sad",
'a': "angry",
'f': "fear",
'd': "disgust",
"su": "surprise"
}
for file in os.listdir(SAVEE):
file_path = SAVEE + file
part = file.split('_')[1]
ele = part[:-6]
if not ele:
continue
emotion = emotion_map[ele]
rows.append((emotion, file_path))
df = pd.DataFrame(rows, columns=["emotion", "path"])
# print(df.head())
return df
def normalize_tess():
rows = []
for directory in os.listdir(TESS):
if directory.startswith("."):
print("skipping dotfile", directory)
continue
for file in os.listdir(TESS + directory):
if file.startswith("."):
print("skipping dotfile", file)
continue
file_path = TESS + directory + '/' + file
[name, extension] = file.split('.')
[actor, word, emotion_id] = name.split('_')
emotion = emotion_id
if emotion_id=='ps':
emotion = 'surprise'
rows.append((emotion, file_path))
df = pd.DataFrame(rows, columns=["emotion", "path"])
# print(df.head())
return df
<file_sep>/requirements.txt
absl-py==0.11.0
appdirs==1.4.4
astunparse==1.6.3
black==20.8b1
cachetools==4.2.0
certifi==2020.12.5
chardet==4.0.0
click==7.1.2
cycler==0.10.0
flatbuffers==1.12
gast==0.3.3
google-auth==1.24.0
google-auth-oauthlib==0.4.2
google-pasta==0.2.0
grpcio==1.32.0
h5py==2.10.0
idna==2.10
joblib==1.0.0
Keras-Preprocessing==1.1.2
kiwisolver==1.3.1
Markdown==3.3.3
matplotlib==3.3.3
mypy-extensions==0.4.3
numpy==1.19.5
oauthlib==3.1.0
opt-einsum==3.3.0
pandas==1.2.1
pathspec==0.8.1
Pillow==8.1.0
protobuf==3.14.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2020.5
regex==2020.11.13
requests==2.25.1
requests-oauthlib==1.3.0
rsa==4.7
scikit-learn==0.24.1
scipy==1.6.0
six==1.15.0
tensorboard==2.4.1
tensorboard-plugin-wit==1.8.0
tensorflow==2.4.1
tensorflow-estimator==2.4.0
termcolor==1.1.0
threadpoolctl==2.1.0
toml==0.10.2
typed-ast==1.4.2
typing-extensions==3.7.4.3
urllib3==1.26.2
Werkzeug==1.0.1
wrapt==1.12.1
<file_sep>/src/get_training_data.py
import sys
import librosa
import pandas as pd
import numpy as np
from get_data import normalize_ravdess, normalize_crema, normalize_savee, normalize_tess
from augment_data import augment_data
from get_features import get_features
def get_training_data(dataframe):
# print(ravdess.head())
print(dataframe.head())
X = []
Y = []
for index, row in dataframe.iterrows():
# print(index, row)
emotion = row["emotion"]
path = row["path"]
print("processing file", path)
# print(emotion, path)
# duration and offset are used to take care of the no audio
# in start and the ending of each audio files as seen above.
data, sample_rate = librosa.load(path, duration=2.5, offset=0.6)
# augment_data returns the original data as the first element
for augmented_data in augment_data(data, sample_rate):
features = get_features(augmented_data, sample_rate)
# Storing a single list of all the features plus the last one is the target label
X.append(features)
Y.append(emotion)
df = pd.DataFrame(X)
df["label"] = Y
return df
def get_training_data_ravdess():
print("processing ravdess")
ravdess = normalize_ravdess()
df = get_training_data(ravdess)
# Save it as a cache
df.to_csv("training_data_ravdess.csv")
def get_training_data_crema():
print("processing crema")
crema = normalize_crema()
df = get_training_data(crema)
# Save it as a cache
df.to_csv("training_data_crema.csv")
def get_training_data_savee():
print("processing savee")
savee = normalize_savee()
df = get_training_data(savee)
# Save it as a cache
df.to_csv("training_data_savee.csv")
def get_training_data_tess():
print("processing tess")
tess = normalize_tess()
df = get_training_data(tess)
# Save it as a cache
df.to_csv("training_data_tess.csv")
def get_training_data_all():
# TODO paralelize these funcs
get_training_data_crema()
get_training_data_ravdess()
get_training_data_savee()
get_training_data_tess()
if __name__ == "__main__":
if len(sys.argv) == 1:
print("get all training data, you should probably paralelize individually")
get_training_data_all()
else:
[script_name, source_id] = sys.argv
if source_id == "ravdess":
get_training_data_ravdess()
if source_id == "crema":
get_training_data_crema()
if source_id == "savee":
get_training_data_savee()
if source_id == "tess":
get_training_data_tess()
else:
print("invalid dataset id")
<file_sep>/src/main.py
import numpy as np
from matplotlib import pyplot
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import librosa
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from get_features import get_features
print(tf.__version__)
print(keras.__version__)
labels = ['neutral', 'calm', 'happy', 'sad', 'angry', 'fear', 'disgust', 'surprise']
model = keras.models.load_model("./model.h5")
model.summary()
validation_audio = [
"./happy.mp3",
"./happy.m4a",
"./happy2.m4a",
"./lucas_nienpedo.mp3",
"./sol_maichu.m4a",
"./fran_scared.m4a",
"./fran_scared2.m4a",
"./lucas_cursing.mp3",
"./nacho_happy.mp3",
]
for path in validation_audio:
print("procesing", path)
data, sampling_rate = librosa.load(path, duration=2.5, offset=0.6)
features = get_features(data, sampling_rate)
features_transposed = np.expand_dims([features], axis=2)
res = model.predict(features_transposed)
max_id = np.argmax(res[0])
print("prediction", labels[max_id])
print("predictions")
for score, label in zip(res[0], labels):
print(label, score)
<file_sep>/src/model2.py
import numpy as np
import pandas as pd
from tensorflow import keras
from tensorflow.keras import layers, callbacks
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
df_ravdess = pd.read_csv("training_data_ravdess.csv", index_col=0)
df_crema = pd.read_csv("training_data_crema.csv", index_col=0)
df_savee = pd.read_csv("training_data_savee.csv", index_col=0)
df_tess = pd.read_csv("training_data_tess.csv", index_col=0)
df = df_ravdess.append(df_crema).append(df_savee).append(df_tess)
print(df.head())
# print(dir(df))
# All rows, all cols but the last one (which is the labels)
X = df.iloc[:, :-1].values
Y = df["label"].values
encoder = OneHotEncoder()
Y = encoder.fit_transform(np.array(Y).reshape(-1, 1)).toarray()
print("labels", Y)
# splitting data
x_train, x_test, y_train, y_test = train_test_split(X, Y, random_state=0, shuffle=True)
print("train, test split")
print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
print(x_train)
model = keras.models.Sequential(
[
layers.Input(shape=(162)),
layers.BatchNormalization(),
layers.Dense(512, kernel_initializer="he_normal", activation="elu"),
layers.Dense(512, kernel_initializer="he_normal", activation="elu"),
layers.Dense(512, kernel_initializer="he_normal", activation="elu"),
layers.BatchNormalization(),
layers.Dropout(0.2),
layers.Dense(256, kernel_initializer="he_normal", activation="elu"),
layers.Dense(256, kernel_initializer="he_normal", activation="elu"),
layers.Dense(256, kernel_initializer="he_normal", activation="elu"),
layers.BatchNormalization(),
layers.Dropout(0.2),
layers.Dense(128, kernel_initializer="he_normal", activation="elu"),
layers.Dropout(0.2),
layers.Dense(64, kernel_initializer="he_normal", activation="elu"),
layers.Dropout(0.2),
layers.Dense(units=8, activation="softmax"),
]
)
model.compile(optimizer="nadam", loss="categorical_crossentropy", metrics=["accuracy"])
rlrp = callbacks.ReduceLROnPlateau(
monitor="loss", factor=0.4, verbose=0, patience=2, min_lr=0.0000001
)
history = model.fit(
x_train,
y_train,
batch_size=64,
epochs=100,
validation_data=(x_test, y_test),
callbacks=[rlrp],
)
print(
"Accuracy of our model on test data : ",
model.evaluate(x_test, y_test)[1] * 100,
"%",
)
model.save("model2.h5")
model.summary()
<file_sep>/README.md
## Requirements
- python3
- pyenv
- pip3
## Installing
```bash
# create the venv
python3 -m venv my-env
# activate env
source ./my-env/bin/activate
# deactivate env
deactivate
# install new packages
pip3 install some-package
# create a list of dependencies from installed packages
pip freeze > requirements.txt
# install deps from requirements
pip3 install -r requirements.txt
```
## Autoformatting
```bash
python3 -m black src/
```
## Data
Data is too large to put it in the repo, please download it and place it
in `train-data`
- `train-data/ravdess` -> https://www.kaggle.com/uwrfkaggler/ravdess-emotional-speech-audio
- `train-data/cremad` -> https://www.kaggle.com/ejlok1/cremad
- `train-data/savee` -> https://www.kaggle.com/ejlok1/surrey-audiovisual-expressed-emotion-savee
- `train-data/tess` -> https://www.kaggle.com/ejlok1/toronto-emotional-speech-set-tess
Original notebook https://www.kaggle.com/franleplant/notebookc90b5d379c
## Usage
This model requires the training features to be calculated, you can do that
by either using the `training_data_*.csv` previously generated, or generating new ones
by using `python3 src/get_training_data.py`.
After that is done (it is going to take a while) you need to train the model.
A pretrained model will be stored in `model.h5`, if you want to train it you
can run `python3 src/model.py`.
Finally you can now evaluate new files by using `src/main.py`
| 41b63e7c13065681b5384d92b1640cf82fb68de3 | [
"Markdown",
"Python",
"Text"
] | 8 | Python | franleplant/ser-example-ml | 6720bb1755cec2f4c58131b10974ab7ebcdeb27f | ad4ae4b1d090d283fabb1a979a30510f94271231 |
refs/heads/master | <file_sep>const express = require('express');
const app = express();
const passport = require('passport')
const cookiePaser = require('cookie-parser')
const session = require('express-session')
const PassportLocal = require('passport-local').Strategy
const port = 8081
app.use(express.urlencoded({extended: true}))
app.use(cookiePaser('mi ultra hiper secreto'))
app.use(session({
secret: 'mi ultra hiper secreto',
resave: true, // volver a guardar la session
saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())
passport.use(new PassportLocal(function(username, password, done) {
if (username == 'prueba' && password == '<PASSWORD>'){
return done(null, {
id: 1,
name: 'Jonnathan'
})
} else {
return done(null, false)
}
}));
passport.serializeUser(function(user, done){
done(null,user.id)
})
passport.deserializeUser(function(id, done){
done(null, {
id: 1,
name: 'Jonnathan'
})
})
app.set('view engine', 'ejs');
app.get("/", (req, res, next)=>{
//Si el usuario no inicio sessión se redirecciona desde aqui,
//Caso constrario ya puede ingresar a la pagina principal
if (req.isAuthenticated()){
return next();
} else {
res.redirect("/login")
}
},// no inicio session
(req,res)=>{
res.send("Servidor funcionando de manera correcta")
})
app.get("/login", (req,res)=>{
res.render("login")
})
app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }));
app.listen(port,()=>{
console.log("Servidor esta funcionando en el puerto: "+ port)
})<file_sep># LoginPassportjs
Crear un servidor usando passport.js y node.js
| 1bac93ca294c8edd9e78e070e626f644dd46f773 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | JonnHenry/LoginPassportjs | 77bcf1b4d3690445e372ec3afee1e6818d6040d1 | a7a2a3362792b037cb07f4614cfd1c28f6e04f48 |
refs/heads/master | <file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
<style type="text/css">
div{
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
font-family: 黑体, serif;
}
#title
{
font-family: 黑体, serif;
font-size : 100px;
height: 300px;
margin-left: auto;
margin-right: auto;
padding-top: 100px;
color:white;
vertical-align:center;
}
body
{
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
#left_bar
{
position:fixed;
left:0%;
right:60px;
top:0%;
z-index: 1030;
width:40px;
font-size:35px;
}
.left_option{
margin-top: 10px;
width:100%;
box-sizing: border-box;
text-align:center;
padding-top:8px;
padding-bottom:8px;
overflow: hidden;
color:white;
}
#userInfo
{
margin-left: auto;
margin-right: auto;
width:75%;
height:700px;
font-size:40px;
margin-top: 100px;
margin-bottom: 200px;
}
#userInfoImg
{
float:left;
width:30%;
height:auto;
}
img
{
width : 100%;
background-color:red;
}
#userInfoTex
{
text-align:left;
float:left;
width:70%;
color:white;
}
.CuserInfoTex
{
margin-left:10%;
}
#event
{
margin-left: auto;
margin-right: auto;
width:75%;
height:1200px;
font-size:40px;
margin-bottom:200px;
}
#subEvent
{
overflow:scroll;
heigh:auto;
}
#redBlock
{
height:100%;
}
.events
{
margin-left: auto;
margin-right: auto;
width:90%;
word-wrap: break-word;
word-break:break-all;
background-color:white;
text-align:left;
}
#comments
{
margin-left: auto;
margin-right: auto;
margin-bottom: 400px;
width:75%;
height:1200px;
font-size:60px;
margin-top: 5%;
text-align:left;
color:white;
}
#charge
{
margin-left: auto;
margin-right: auto;
width:75%;
height:300px;
font-size:40px;
margin-top: 15%;
overflow: hidden;
}
.infraTitle
{
text-align:left;
color:white;
font-size:45px;
}
#box{
width:75%;
height:50px;
font-size:45px;
}
.button
{
width:auto;
font-size:40px;
height:auto;
}
#scrolling
{
overflow:scroll;
font-size:40px;
height:1100px;
color:black;
}
</style>
</head>
<body onunload="setCookieM()">
<?php
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$link = new mysqli("localhost","root","12345","quguangjie");
if(!isset($_SESSION['userId']))
header("Location:visitorLogin.php");
$idNum = $_SESSION['userId'];
$query = "select * from User where number = '$idNum'";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
//echo "<div>您的用户信息为:ID " . $row['ID'] . " shopName " . $row['shopName'] . " seryCode " . $row['seryCode'] . " shopAddress " . $row['shopAddress'] . " mainService " . $row['mainService'] . "picSource" . $row['shopPicture'] . "</div>";
}
?>
<div id = "title" >我的<br/>去逛街
</div>
<div id = "left_bar">
<div class = "left_option" onclick="scroll1()">基本信息</div>
<div class = "left_option" onclick="scroll2()">当前活动</div>
<div class = "left_option" onclick="scroll3()">我的评论</div>
<div class = "left_option" onclick="selectMap()">进入地图</div>
<div class = "left_option" onclick="logout()">退出</div>
</div>
<?php
if(isset($_FILES['picUp']))
{
if ((($_FILES["picUp"]["type"] == "image/gif")
|| ($_FILES["picUp"]["type"] == "image/jpeg")
|| ($_FILES["picUp"]["type"] == "image/pjpeg"))
&& ($_FILES["picUp"]["size"] < 1000000))
{
if ($_FILES["picUp"]["error"] > 0)
{
echo "Return Code: " . $_FILES["picUp"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["picUp"]["tmp_name"],
"userPic/" . $_SESSION['userId'] . ".jpg");
}
}
}
if(isset($_POST['coordinate1']))
{
$coordinate1 = test_input($_POST['coordinate1']);
echo " <script type=\"text/javascript\">window.scrollTo(0,'$coordinate1');</script>
";
}
?>
<div id = "userInfo">
<div id = "userInfoImg">
<img id ="img" src="<?php echo $row["head"];?>" onclick = "location.assign('headUp.php')" alt="未找到图片,点击添加"/>
</div>
<div id = "userInfoTex">
<p class = "CuserInfoTex">名字:<?php echo $row['name'] ?></P>
<p class = "CuserInfoTex">手机号码:<?php echo $row['cellnumber'] ?></P>
<p class = "CuserInfoTex">账号等级:<?php $ex = floor(pow($row['experience']+1,0.4)); echo $ex; ?></P>
<p class = "CuserInfoTex">经验值:<?php echo $row['experience'] . "/" . (floor(pow($ex+1,2.5))); ?></p>
</div>
</div>
<div id = "event">
<div id="redBlock">
<p class = "infraTitle">当前活动</p>
<form id ="mapSelect" action="userMain.php" method="post">
<select id = "box" name="site" onchange="send()">
<option value="null" selected="selected">请选择地图</option>
<?php
$query = "select * from Map order by name";
$result = $link->query($query);
while($maps = $result->fetch_assoc())
{
echo "<option value=" . $maps['number'] . ">" . $maps['name'] . "</option>";
}
//<option value="sjtuShop">上海交通大学闵行校区</option>
?>
</select></p>
<input type="text" hidden=true name="coordinate" id="coordinate"/>
</form>
<?php
// define variables and set to empty values
if(isset($_POST['site']))
{
$eventInfo = test_input($_POST['site']);
$coordinate = test_input($_POST['coordinate']);
$query = "select number,name,shortevent,event from Shop where mapno='$eventInfo' order by level;";
$result = $link->query($query);
echo "<div id=\"subEvent\">";
while($row = $result->fetch_assoc()) {
echo "<div class = \"events\" onclick = 'forDetail(" . $row['number'] . ")'>店名:" . $row['name']. " <br/>活动信息:" . $row['shortevent'] . "</div>";
echo "<div class = \"events\" id=\"" . $row['number'] . "\"hidden=true >活动详情:" . $row['event'] . "<form action=\"viewShop.php\" method=\"post\" ><input hidden=true type=\"text\" value = \"" . $row['number'] . "\" name = \"shopId\"/><input hidden=true type=\"text\" value = \"" . $eventInfo . "\" name = \"mapName\"/><input class=\"button\" type=\"submit\" value = \"点击进入店家页面\"></form></div>";
echo "<br/>";
}
echo "</div>";
}
?>
</div>
<form id ="callForDetail" hidden=true action="userMain.php" method="post">
<input id = "cfdId" type="text" name="eventId"/>
</form>
</div>
<div id="comments">
<p class = "infraTitle">我的评论</p>
<div id="scrolling">
<?php
$query = "select Shop.name shopname,content,Remark.score remarkscore,time from Shop,Remark where Remark.userno = '$idNum' and Shop.number = Remark.shopno order by Remark.time desc;";
$result = $link->query($query);
$i=0;
while($row = $result->fetch_assoc()) {
echo "<div class = \"events\" >我对 " . $row['shopname']. " <br/>评论道:" . $row['content'] . "</div>";
echo "<br/>";
$i++;
}
if($i==0)
{
echo "<div class = \"events\" >我还没有做出任何评价</div>";
}
?>
</div>
</div>
<script type="text/javascript">
function scroll1()
{
window.scrollTo(0,0);
}
function scroll2()
{
window.scrollTo(0,1500);
}
function scroll3()
{
window.scrollTo(0,2700);
}
function logout()
{
location.assign("logOut.php");
}
function send()
{
var mapSelection = document.getElementById("box");
document.getElementById("coordinate").value=window.pageYOffset;
if(mapSelection.value!="null")
{
document.getElementById("mapSelect").submit();
}
}
function forDetail(id)
{
document.getElementById(id).hidden=!document.getElementById(id).hidden;
}
function changePic()
{
document.getElementById("picUpload").hidden=!document.getElementById("picUpload").hidden;
}
function submitPic()
{
document.getElementById("formPicUpload").submit();
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function setCookieM()
{
setCookie("userMainCo",window.pageYOffset,1);
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return ""
}
function selectMap()
{
location.assign("selectMap.php");
}
var co =getCookie("userMainCo");
if(co!="")
window.scrollTo(0,co);
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var img = document.getElementById("img")
{
if(img.height>800)
{
img.height="800";
}
}
</script>
</body>
</html>
<file_sep><html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8>
<head>
<link src="quguangjie.index.css" rel="stylesheet" type="text/css"/>
</head>
<body onload="init()">
<img src="background.jpg" id="backgroundImg">
</img>
<div id="mask" hidden=true>
</div>
<div text-align = "center" class="title">LI HE's test web App</div>
<?php
session_start();
$lat = $long = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$lat = test_input($_POST["Latitude"]);
$long = test_input($_POST["Longitude"]);
}
if(!$lat =="")
{
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from Map";
$result = $link->query($query);
$min = 720.0;
$targetMap = -1;
while($row = $result->fetch_assoc())
{
if(abs($lat-$row['coordinatex'])+abs($long-$row['coordinatey'])<$min)
{
$min = abs($lat-$row['coordinatex'])+abs($long-$row['coordinatey']);
$targetMap = $row['number'];
}
}
if($targetMap!=-1)
{
$_SESSION['mapId'] = $targetMap;
echo "<script>location.assign('svgmaps/" . $targetMap . ".php')</script>";
}
else{
echo "<h1 type='color = red'>sorry, can't find map at:</h1>";
echo "<h1>latitude:$lat</h1>";
echo "<h1>longtitude:$long</h1>";
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text-align = "center" class="title" id="quGuangJie">去逛街</div>
<div class="button" id="dingWei" onclick="getLocation()">定位我的位置</div>
<div class="button" id="lieBiao" onclick="findSite()">让我从列表选择</div>
<div class="button" id="denglu" onclick="login()">登录</div>
<div class="button" id="zhuce" onclick="register()">注册</div>
<div id="shangPu" onclick="sellers()">商铺入口</div>
<form hidden=true id="GPS" method="post" action="index.php">
<input id="Longitude" name="Longitude"/>
<input id="Latitude" name="Latitude"/>
</form>
</body>
<script type="text/javascript">
var alpha=0;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
document.getElementById("Latitude").value = position.coords.latitude;
document.getElementById("Longitude").value=position.coords.longitude;
document.getElementById("GPS").submit();
}
function jumping(p)
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("location.assign('"+p+"');",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
function findSite()
{
jumping("selectMap.php");
}
function login()
{
jumping("visitorLogin.php");
}
function register()
{
jumping("visitorRegister.php");
}
function sellers()
{
jumping("shopLogin.php");
}
var width = window.innerWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("quGuangJie");
title.style.fontSize = length/7+"px";
var small = document.getElementById("shangPu");
small.style.fontSize = length/28+"px";
var buttons = document.getElementsByClassName("button");
for(var i=0; i<buttons.length;++i)
{
buttons[i].style.fontSize = length/15+"px";
buttons[i].style.height = length/13+"px";
}
document.getElementById("backgroundImg").width=width;
</script>
</body>
</html>
<file_sep>
<!DOCTYPE html>
<html>
<body>
</head>
<body>
<script type="text/javascript">
<?php
$distance=9999;
$savePlace="";
$Longitude="";
$Latitude="";
if(isset($_POST['Longitude'])&&isset($_POST['Latitude']))
{
$Longitude=$_POST['Longitude'];
$Latitude=$_POST['Latitude'];
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from mapList";
$result = $link->query($query);
while($row = $result->fetch_assoc())
{
$temp=($Longitude-$row['Longitude'])*($Longitude-$row['Longitude'])+($Latitude-$row['Latitude'])*($Latitude-$row['Latitude']);
if(100 < $distance)
{
$distance = $temp;
$savePlace = $row['savePlace'];
}
}
echo "location.assign(\"" . $savePlace . "\")";
}
?>
</script>
</body>
</html><file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<style type="text/css">
div{
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
font-family: 黑体, serif;
font-size:35px;
}
#title
{
font-family: 黑体, serif;
font-size : 100px;
height: 300px;
margin-left: auto;
margin-right: auto;
padding-top: 100px;
color:white;
vertical-align:center;
}
#back
{
font-family: 黑体, serif;
font-size : 100px;
height: 300px;
margin-left: auto;
margin-right: auto;
padding-top: 100px;
color:white;
vertical-align:center;
}
body
{
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
.events
{
margin-left: auto;
margin-right: auto;
width:90%;
word-wrap: break-word;
word-break:break-all;
background-color:white;
text-align:left;
}
.button
{
width:auto;
font-size:40px;
height:auto;
}
#searchOut
{
width:75%;
margin:auto;
}
</style>
<body>
<div id="title">
搜索结果
</div>
<div id="searchOut">
<?php
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$keyWord="";
$shopMap="";
$userName="";
$aimArr="";
$link = new mysqli("localhost","root","12345","quguangjie");
if(isset($_POST['keyWord'])&&isset($_SESSION['mapId']))
{
$keyWord = test_input($_POST['keyWord']);
$mapId = $_SESSION['mapId'];
$query = "select * from Shop where mapno = $mapId and (service like '%$keyWord%' or name like '%$keyWord%') order by level";
$result = $link->query($query);
$i=0;
while($row = $result->fetch_assoc()) {
echo "<div class = \"events\" onclick = 'forDetail(" . $row['number'] . ")'>店名:" . $row['name']. " <br/>主要业务:" . $row['service'] . " <br/>商铺位置:" . $row['address'] . "</div>";
echo "<form action=\"viewShop.php\" method=\"post\" ><input hidden=true type=\"text\" value = \"" . $row['number'] . "\" name = \"shopId\"/><input hidden=true type=\"text\" value = \"" . $_SESSION['mapId'] . "\" name = \"mapName\"/><input class=\"button\" type=\"submit\" value = \"点击进入店家页面\"></form>";
echo "<br/>";
$aimArr[$i++]=$row['name'];
}
}
$_SESSION['aimArray']=$aimArr;
echo count($_SESSION['aimArray']);
?>
</div>
<div onclick="back()" id="back">
返回
</div>
<script type="text/javascript">
function back()
{
location.assign("svgmaps/<?php echo $_SESSION['mapId'] ?>.php")
}
</script>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8>
<head>
<style type="text/css">
#title
{
font-family: 黑体, serif;
font-size : 25px;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
body
{
font-family: 黑体, serif;
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
form
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
p
{
font-size: 1.5em;
text-align:center;
}
/*
.box
{
height :45px;
width: 200px;
}
*/
#ruzhu
{
width : 90px;
margin-left: auto;
margin-right: auto;
margin-top: 15%;
}
#mask
{
background-color: #4d7b95;;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
</style>
</head>
<body>
<div id="mask" hidden=true></div>
<?php
// define variables and set to empty values
$name = $passCode = $checkCode = $cellNum = $veriCode = "";
$cellExist=false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$passCode = test_input($_POST["passCode"]);
$checkCode = test_input($_POST["checkCode"]);
$cellNum = test_input($_POST["cellNum"]);
$veriCode = test_input($_POST["veriCode"]);
}
if($name!="")
{
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from User where cellno = '$cellNum'";
$result = $link->query($query);
if(var_dump($result))
$cellExist=true;
else
{
$query = "insert into User(name,passcode,cellnumber)
values('$name','$passCode','$cellNum')";
if($link->query($query) == TRUE) {
$query = "select number from User where name = '$name'";
$result = $link->query($query);
$row = $result->fetch_assoc();
$_SESSION["userId"] = $row["number"];
echo "<script type=\"text/javascript\" > location.assign('userMain.php') </script>";
}
else{
echo "failed!!!";
}
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id = "title" >注册<br/>去逛街
</div>
<form id ="register" action="visitorRegister.php" method="post">
<p class = "inputing">起个名字*: <input class = "box" type="text" name="name" value = "<?php echo $name ?>"/><b class = "prompt"></b></p>
<p class = "inputing">设个密码*: <input id = "passcode" class = "box" type="password" name="passCode" value = "<?php echo $passCode ?>" onblur = "checkPasscode()"/><b class = "prompt"></b></p>
<p class = "inputing">重复一次*: <input id = "confirming" class = "box" type="password" name="checkCode" value = "<?php echo $checkCode ?>" onblur = "checkConfirming()"/><b class = "prompt""></b></p>
<p class = "inputing">手机号码*: <input class = "box" type="text" name="cellNum" value = "<?php echo $cellNum ?>" /><b class = "prompt"><?php if($cellExist) echo "已经存在的手机号"?></b></p>
<button class = "buttons" type="button" onclick = "sendVeriCode()">发送验证码</button>
<p class = "inputing">输入验证码*:<input class = "box" type="text" name="veriCode" value = "<?php echo $veriCode ?>" /><b class = "prompt"></b></p>
<br />
</form>
<p>*项不能为空</p>
<button class = "buttons" type="button" onclick = "trySubmit()">注册</button>
<script type="text/javascript">
/*
function checkPasscode()
{
var passcode = document.getElementById("passcode");
if(passcode.value.length<5)
{
passcode.focus();
var a=document.getElementById("a2");
a.textContent = "密码应长于5位";
}
}*/
function trySubmit()
{
var boxing = document.getElementsByClassName("box");
var flag=true;
for(var i=0; i<boxing.length;++i)
{
if(boxing[i].value.length==0) {boxing[i].nextElementSibling.textContent = "此项不能为空"; flag=false;}
else boxing[i].nextElementSibling.textContent = "";
}
if(boxing[1].value!=boxing[2].value)
{
boxing[2].nextElementSibling.textContent = "和之前输入的不同哦";
flag = false;
}
if(flag)
{
jumping();
}
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("title");
title.style.fontSize = length/8+"px";
var inputing = document.getElementsByClassName("inputing");
for(var i=0; i<inputing.length;++i)
{
inputing[i].style.fontSize = length/25+"px";
}
var prompting = document.getElementsByClassName("prompt");
for(var i=0; i<prompting.length;++i)
{
prompting[i].style.fontSize = length/40+"px";
}
var box = document.getElementsByClassName("box");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/4+"px";
box[i].style.height = height/21+"px";
box[i].style.fontSize = height/28+"px";
}
box = document.getElementsByClassName("longBox");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/2+"px";
box[i].style.height = height/21+"px";
box[i].style.fontSize = height/28+"px";
}
var alpha=0;
function jumping()
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("document.getElementById('register').submit();",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
</script>
</body>
</html>
<file_sep><html>
<body>
<?php
$link = new mysqli("localhost","root","12345","quguangjie");
$query = //"update mapList set savePlace = 'svgmaps/sjtu.svg' where mapName = '上海交通大学闵行校区' ";
//"insert into mapList (mapName,address,savePlace)
//values( '上海交通大学闵行校区','上海市闵行区东川路800号','D:/svgmaps/sjtu.svg')";
"CREATE TABLE Persons
(
Id int not null auto_increment primary key,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)";
if($link->query($query) == TRUE) {
echo "成功";
}
else{
echo "失败!!!";
}
?>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
<link src="quguangjie.index.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="title">
搜索结果
</div>
<div id="searchOut">
<?php
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$keyWord="";
$shopMap="";
$userName="";
$aimArr="";
$link = new mysqli("localhost","root","1<PASSWORD>","quguangjie");
if(isset($_POST['keyWord'])&&isset($_SESSION['mapId']))
{
$keyWord = test_input($_POST['keyWord']);
$mapId = $_SESSION['mapId'];
$query = "select * from Shop where mapno = $mapId and (service like '%$keyWord%' or name like '%$keyWord%') order by level";
$result = $link->query($query);
$i=0;
while($row = $result->fetch_assoc()) {
echo "<div class = \"events\" onclick = 'forDetail(" . $row['number'] . ")'>店名:" . $row['name']. " <br/>主要业务:" . $row['service'] . " <br/>商铺位置:" . $row['address'] . "</div>";
echo "<form action=\"viewShop.php\" method=\"post\" ><input hidden=true type=\"text\" value = \"" . $row['number'] . "\" name = \"shopId\"/><input hidden=true type=\"text\" value = \"" . $_SESSION['mapId'] . "\" name = \"mapName\"/><input class=\"button\" type=\"submit\" value = \"点击进入店家页面\"></form>";
echo "<br/>";
$aimArr[$i++]=$row['name'];
}
}
$_SESSION['aimArray']=$aimArr;
echo count($_SESSION['aimArray']);
?>
</div>
<div onclick="back()" id="back">
返回
</div>
<script type="text/javascript">
function back()
{
location.assign("svgmaps/<?php echo $_SESSION['mapId'] ?>.php")
}
</script>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
<link src="quguangjie.view.css" rel="stylesheet" type="text/css"/>
</head>
<?php
$link = new mysqli("localhost","root","<PASSWORD>","quguangjie");
$idNum = "";
$row = "";
if(isset($_FILES['picUp']))
{
if ((($_FILES["picUp"]["type"] == "image/jpeg")
|| ($_FILES["picUp"]["type"] == "image/pjpeg"))
&& ($_FILES["picUp"]["size"] < 1000000))
{
if ($_FILES["picUp"]["error"] > 0)
{
echo "Return Code: " . $_FILES["picUp"]["error"] . "<br />";
}
else
{
if(isset($_SESSION["userId"]))
{
$idNum = $_SESSION["userId"];
move_uploaded_file($_FILES["picUp"]["tmp_name"],"userPic/" . $_SESSION['userId'] . ".jpg");
$query = "update User set head='userPic/$idNum.jpg' where number = $idNum";
$link->query($query);
$query = "select head from User where number = '$idNum'";
$result = $link->query($query);
$row = $result->fetch_assoc();
}
else if(isset($_SESSION["shopId"]))
{
$idNum = $_SESSION["shopId"];
move_uploaded_file($_FILES["picUp"]["tmp_name"],"shopPic/" . $_SESSION['shopId'] . ".jpg");
$query = "update Shop set head='shopPic/$idNum.jpg' where number = $idNum";
$link->query($query);
$query = "select head from Shop where number = '$idNum'";
$result = $link->query($query);
$row = $result->fetch_assoc();
}
}
}
else echo "wrong file type or too big file!";
}
if($row=="")
{
if(isset($_SESSION["userId"]))
{
$idNum = $_SESSION["userId"];
$query = "select head from User where number = '$idNum'";
$result = $link->query($query);
$row = $result->fetch_assoc();
}
else if(isset($_SESSION["shopId"]))
{
$idNum = $_SESSION["shopId"];
$query = "select head from Shop where number = '$idNum'";
$result = $link->query($query);
$row = $result->fetch_assoc();
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<body onmouseup="mouseUp(event)" onmousemove="transPic(event)">
<img hidden="true" src="<?php echo $row["head"]; ?>" id="img" onload="cont()"></img>
<div style="position:fixed;left:0px;top:0px;width:100%;height:100%;z-index:-1;"></div>
<div id = "title" >更换头像
</div>
<div style="margin-bottom:100px">
<form method = "post" action ="headUp.php" enctype="multipart/form-data">
<input type = "file" name = "picUp"/>
<input type = "submit" value = "上传图片"/>
</form>
</div>
<div id="cover">
<canvas id="canvas1" width="2000" height="2000" style="border:1px solid #c3c3c3;float:left;">
Your browser does not support the canvas element.
</canvas>
<canvas id="canvas2" width="2000" height="2000" style="border:1px solid #c3c3c3;float:left;">
Your browser does not support the canvas element.
</canvas>
<canvas id="canvas3" width="2000" height="2000" style="position:absolute;border:1px solid #c3c3c3;" onmousedown="mouseDown(event)">
Your browser does not support the canvas element.
</canvas>
</div>
<script type="text/javascript">
var haveMouse=1;
var contFlag=0;
var width = window.innerWidth;
var canvas1=document.getElementById("canvas1");
var canvas2=document.getElementById("canvas2");
var canvas3=document.getElementById("canvas3");
var ctx1 = canvas1.getContext("2d");
var ctx2 = canvas2.getContext("2d");
var ctx3 = canvas3.getContext("2d");
var cover = document.getElementById("cover");
var singleMove = document.getElementById("move");
canvas2.style.marginLeft = cover.style.marginLeft = width/9 + "px";
canvas3.height = canvas3.width = canvas2.height = canvas2.width = canvas1.height = canvas1.width = width/3;
canvas3.style.left = canvas1.offsetLeft + "px";
canvas3.style.top = canvas1.offsetTop + "px";
canvas3.style.zIndex = 5;
ctx1.fillStyle="#ffffff";
ctx1.fillRect(0,0,canvas1.width,canvas1.height);
ctx3.globalAlpha = 0.45;
ctx3.fillRect(0,0,canvas3.width,canvas3.height);
ctx3.clearRect(canvas3.width/5,canvas3.width/5,canvas3.width*3/5,canvas3.width*3/5);
ctx3.fillStyle="#ff0000";
ctx3.strokeStyle="#ff0000";
ctx3.lineWidth = 3;
ctx3.globalAlpha = 1;
ctx3.strokeRect(canvas3.width/5,canvas3.width/5,canvas3.width*3/5,canvas3.width*3/5);
ctx3.fillRect(canvas3.width*4/5-canvas3.width/60,canvas3.width*4/5-canvas3.width/60,canvas3.width/30,canvas3.width/30);
var rectLeft = canvas3.width/5;
var rectRight = canvas3.width*4/5;
var rectTop = canvas3.width/5;
var rectBottom = canvas3.width*4/5;
var mouseX=0;
var mouseY=0;
var transX=0;
var transY=0;
var offsetX=0;
var offsetY=0;
var transPattern=0;
function cont()
{
var img=document.getElementById("img");
if(img.width>img.height)
{
var NimgHeight = img.height*canvas1.width/img.width;
var NimgWidth = canvas1.width;
offsetX=0;
offsetY=(canvas1.height-NimgHeight)/2;
}
else
{
var NimgHeight = canvas1.height;
var NimgWidth = img.width*canvas1.height/img.height;
offsetX=(canvas1.width-NimgWidth)/2;
offsetY=0;
}
ctx1.drawImage(img,0,0,img.width,img.height,offsetX,offsetY,NimgWidth,NimgHeight);
drawCanvas2();
}
function mouseDown(event)
{
mouseX = event.clientX;
mouseY = event.clientY;
if(abs(event.pageX-rectRight-canvas1.offsetLeft)+abs(event.pageY-rectBottom-canvas1.offsetTop)<width/20)
{
transPattern=1;
}
else
{
transPattern=2;
}
}
function mouseUp(event)
{
if(event.clientX==mouseX&&event.clientY==mouseY)
{
transPattern=0;
transX=transY=0;
var trans=0;
var x = event.pageX-canvas1.offsetLeft;
var y = event.pageY-canvas1.offsetTop;
if(inRect(x,y,rectLeft,rectTop,rectRight,rectBottom))
{
var centerX=(rectLeft+rectRight)/2;
var centerY=(rectTop+rectBottom)/2;
transX=x-centerX;
transY=y-centerY;
if(rectBottom+transY>canvas1.height) transY=canvas1.height-rectBottom;
if(rectRight+transX>canvas1.width) transX=canvas1.width-rectRight;
if(rectLeft+transX<0) transX=0-rectLeft;
if(rectTop+transY<0) transY=0-rectTop;
rectBottom+=transY;
rectRight+=transX;
rectLeft+=transX;
rectTop+=transY;
}
else if(abs(x-rectRight)+abs(y-rectBottom)>abs(x-rectLeft)+abs(y-rectTop))
{
trans = max(x-rectLeft,y-rectTop);
rectLeft+=trans;
rectTop+=trans;
}
else
{
trans = min(x-rectRight,y-rectBottom);
rectRight+=trans;
rectBottom+=trans;
}
ctx3.clearRect(0,0,canvas3.width,canvas3.height);
ctx3.globalAlpha = 0.45;
ctx3.fillStyle="#000000";
ctx3.fillRect(0,0,canvas3.width,canvas3.height);
ctx3.clearRect(rectLeft,rectTop,rectRight-rectLeft,rectBottom-rectTop);
ctx3.fillStyle="#ff0000";
ctx3.strokeStyle="#ff0000";
ctx3.lineWidth = 3;
ctx3.globalAlpha = 1;
ctx3.strokeRect(rectLeft,rectTop,rectRight-rectLeft,rectBottom-rectTop);
ctx3.fillRect(rectRight-canvas3.width/60,rectBottom-canvas3.width/60,canvas3.width/30,canvas3.width/30);
drawCanvas2();
}
else
{
var oldTrPtt = transPattern;
transPattern=0;
rectRight += transX;
rectBottom += transY;
if(oldTrPtt == 2)
{
rectLeft += transX;
rectTop += transY;
}
transX=0;
transY=0;
drawCanvas2();
}
}
function transPic(event)
{
if(transPattern==0)
return;
else if(transPattern==1)
{
transX = transY = absMin(event.clientX-mouseX,event.clientY-mouseY);
if(rectRight+transX>canvas3.width) transX = transY = canvas3.width-rectRight;
if(rectBottom+transY>canvas3.width) transX = transY = canvas3.width-rectBottom;
if(rectRight+transX<rectLeft) transX = transY = rectLeft-rectRight;
if(rectBottom+transY<rectTop) transX = transY = rectTop-rectBottom;
refresh();
}
else if(transPattern==2)
{
transX = event.clientX-mouseX;
transY = event.clientY-mouseY;
if(rectRight+transX>canvas3.width) transX = canvas3.width-rectRight;
if(rectBottom+transY>canvas3.width) transY = canvas3.width-rectBottom;
if(rectLeft+transX<0) transX = 0-rectLeft;
if(rectTop+transY<0) transY = 0-rectTop;
refresh();
}
}
function refresh()
{
ctx3.clearRect(0,0,canvas3.width,canvas3.height);
ctx3.globalAlpha = 0.45;
ctx3.fillStyle="#000000";
ctx3.fillRect(0,0,canvas3.width,canvas3.height);
if(transPattern==1)
{
ctx3.clearRect(rectLeft,rectTop,rectRight-rectLeft+transX,rectBottom-rectTop+transY);
ctx3.fillStyle="#ff0000";
ctx3.strokeStyle="#ff0000";
ctx3.lineWidth = 3;
ctx3.globalAlpha = 1;
ctx3.strokeRect(rectLeft,rectTop,rectRight-rectLeft+transX,rectBottom-rectTop+transY);
}
else if(transPattern==2)
{
ctx3.clearRect(rectLeft+transX,rectTop+transY,rectRight-rectLeft,rectBottom-rectTop);
ctx3.fillStyle="#ff0000";
ctx3.strokeStyle="#ff0000";
ctx3.lineWidth = 3;
ctx3.globalAlpha = 1;
ctx3.strokeRect(rectLeft+transX,rectTop+transY,rectRight-rectLeft,rectBottom-rectTop);
}
ctx3.fillRect(rectRight+transX-canvas3.width/60,rectBottom+transY-canvas3.width/60,canvas3.width/30,canvas3.width/30);
}
function drawCanvas2()
{
ctx2.fillStyle="#ffffff";
ctx2.fillRect(0,0,canvas2.width,canvas2.height);
if(offsetY>0)
{
if(rectTop<offsetY)
{
ctx2.drawImage(img,
rectLeft*img.width/canvas1.width, 0,
(rectRight-rectLeft)*img.width/canvas1.width, min((rectBottom-offsetY)*img.height/(canvas1.height-offsetY*2),img.height),
0, (offsetY-rectTop)*canvas2.height/(rectBottom-rectTop),
canvas2.width, min(rectBottom-offsetY,canvas1.height-2*offsetY)*canvas2.height/(rectBottom-rectTop));
}
else
{
ctx2.drawImage(img,
rectLeft*img.width/canvas1.width, (rectTop-offsetY)*img.height/(canvas1.height-offsetY*2),
(rectRight-rectLeft)*img.width/canvas1.width, min((rectBottom-rectTop),(canvas1.height-offsetY-rectTop))*img.height/(canvas1.height-offsetY*2),
0, 0,
canvas2.width, min(rectBottom-rectTop,canvas1.height-offsetY-rectTop)*canvas2.height/(rectBottom-rectTop));
}
}
else if(offsetX>0)
{
if(rectLeft<offsetX)
{
ctx2.drawImage(img,
0, rectTop*img.height/canvas1.height,
min((rectRight-offsetX)*img.width/(canvas1.width-offsetX*2),img.width), (rectBottom-rectTop)*img.height/canvas1.height,
(offsetX-rectLeft)*canvas2.width/(rectRight-rectLeft), 0,
min(rectRight-offsetX,canvas1.width-2*offsetX)*canvas2.width/(rectRight-rectLeft), canvas2.height);
}
else
{
ctx2.drawImage(img,
(rectLeft-offsetX)*img.width/(canvas1.width-offsetX*2), rectTop*img.height/canvas1.height,
min((rectRight-rectLeft),(canvas1.width-offsetX-rectLeft))*img.width/(canvas1.width-offsetX*2), (rectBottom-rectTop)*img.height/canvas1.height,
0, 0,
min(rectRight-rectLeft,canvas1.width-offsetX-rectLeft)*canvas2.width/(rectRight-rectLeft), canvas2.height);
}
}
}
function abs(a)
{
if(a>0) return a;
else return 0-a;
}
function absMin(a,b)
{
if(abs(a)<abs(b)) return a;
else return b;
}
function min(a,b)
{
return a<b?a:b;
}
function max(a,b)
{
return a>b?a:b;
}
function inRect(x,y,l,t,r,b)
{
if(x>=l&&x<=r&&y>=t&&y<=b) return true;
else return false;
}
</script>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
</head>
<body>
<form action="shopMain.php" method="post" id="form">
<input type="text" name="ID" id = "idNum"/>
</form>
<?php
// define variables and set to empty values
$shopName = $passCode = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$shopName = test_input($_POST["shopName"]);
$passCode = test_input($_POST["passCode"]);
$shopSite = test_input($_POST["site"]);
}
$link = new mysqli("localhost","root","12345","quguangjie");
$query = $shopSite=="sjtuShop"?"select * from sjtuShop where shopName = '$shopName'":"";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
if($row['passCode']!=$passCode)
{
echo "<script type=\"text/javascript\"> location.assign(\"shopLogin2.php\");</script>";
}
else
{
$_SESSION['ID']=$row['ID'];
$_SESSION['map']=$shopSite;
echo "<script type=\"text/javascript\"> location.assign(\"shopMain.php\");</script>";
}
}
else{
echo "<script type=\"text/javascript\"> location.assign(\"shopLogin2.php\");</script>";
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>fdafoehfifi</h1>
</body>
</html>
<file_sep>// JavaScript Document
var pol2DObjArray = new Array();
function pol2DObj(offsetX, offsetY, width, height)
{
this.offsetX=offsetX;
this.offsetY=offsetY;
this.width=width;
this.height=height;
}
function appendPol2DObj(offsetX, offsetY, width, height)
{
pol2DObjArray.push(new pol2DObj(offsetX, offsetY, width, height));
return pol2DObjArray.length-1;
}
function writeText(text,xCoord,yCoord)
{
specialGl.font="15px Georgia";
var width = specialGl.measureText(text).width;
var xOff = 0;
var yOff = 0;
if(yCoord>gl.viewportHeight - 25) yOff = 45;
if(xCoord>gl.viewportWidth - width -16) xOff = width + 16;
var imgData=specialGl.createImageData(specialGl.measureText(text).width + 16,25);
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i+0]=0;
imgData.data[i+1]=88;
imgData.data[i+2]=220;
imgData.data[i+3]=222;
}
specialGl.putImageData(imgData,xCoord-xOff,yCoord-yOff);
specialGl.fillText(text,xCoord-xOff+8,yCoord-yOff+19);
return appendPol2DObj(xCoord-xOff,yCoord-yOff,width + 16,25);
}
function clearPol2DObj(pol2DObjIndex)
{
var imgData=specialGl.createImageData(pol2DObjArray[pol2DObjIndex].width,pol2DObjArray[pol2DObjIndex].height);
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i+0]=0;
imgData.data[i+1]=0;
imgData.data[i+2]=0;
imgData.data[i+3]=0;
}
specialGl.putImageData(imgData,pol2DObjArray[pol2DObjIndex].offsetX,pol2DObjArray[pol2DObjIndex].offsetY);
pol2DObjArray.splice(pol2DObjIndex);
}<file_sep><!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8><style type="text/css">
#title
{
font-family: 黑体, serif;
font-size : 25px;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
body
{
font-family: 黑体, serif;
background-color:#4d7b95;;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
form
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
p
{
font-size: 1.5em;
}
.box
{
height :20px;
width: 200px
}
#ruzhu
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 15%;
}
#mask
{
background-color: #4d7b95;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
</style>
<body >
<div id="mask" hidden=true></div>
<?php
// define variables and set to empty values
$shopName = $passCode = $shopSite = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$shopName = test_input($_POST["shopName"]);
$passCode = test_input($_POST["passCode"]);
$shopSite = test_input($_POST["site"]);
}
$nameExist = true;
$codeCorrect = true;
$link = new mysqli("localhost","root","12345","quguangjie");
if($shopSite!="")
{
echo $shopSite;
$query = "select number,passcode from Shop where name = '$shopName' and mapno = $shopSite";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
if($row['passcode']!=$passCode)
{
$codeCorrect = false;
}
else
{
$_SESSION['shopId']=$row['number'];
$_SESSION['map']=$shopSite;
echo "<script type=\"text/javascript\"> location.assign(\"shopMain.php\");</script>";
}
}
else{
$nameExist = false;
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id = "title" >登录<br/>去逛街
</div>
<form id = "logIn" action="shopLogin.php" method="post">
<p class = "inputing">您的店名: <input class = "box" type="text" name="shopName" value = "<?php echo $shopName ?>"/><b class = "prompt"><?php if(!$nameExist) echo "没有这家店呀" ?></b></b></p>
<p class = "inputing">您的密码: <input class = "box" type="password" name="passCode" value = "<?php echo $passCode ?>" /><b class = "prompt"><?php if(!$codeCorrect) echo "密码输错了呢" ?></b></b></p>
<p class = "inputing">您的位置:
<select class = "box" name="site">
<option value="null" selected="selected">请选择地图</option>
<?php
$query = "select * from Map order by name";
$result = $link->query($query);
while($maps = $result->fetch_assoc())
{
echo "<option value=" . $maps['number'] . ">" . $maps['name'] . "</option>";
}
//<option value="sjtuShop">上海交通大学闵行校区</option>
?>
</select><b class = "prompt"></b></p>
</form>
<button type="button" onclick = "trySubmit()">登录</button>
<div id = "ruzhu" onclick = "jumpToShopRegister()">我要入驻去逛街
</div>
<script type="text/javascript">
function jumpToShopRegister()
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",50);
var t=setTimeout("location.assign('shopRegister.php');",1000);
}
function trySubmit()
{
var boxing = document.getElementsByClassName("box");
var flag=true;
for(var i=0; i<boxing.length;++i)
{
if(boxing[i].value.length==0) {boxing[i].nextElementSibling.textContent = "此项不能为空"; flag=false;}
else boxing[i].nextElementSibling.textContent = "";
}
if(boxing[2].value=="null") {boxing[2].nextElementSibling.textContent = "此项不能为空"; flag=false;}
else boxing[2].nextElementSibling.textContent = "";
if(flag)
{
jumping();
}
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("title");
title.style.fontSize = length/8+"px";
var inputing = document.getElementsByClassName("inputing");
for(var i=0; i<inputing.length;++i)
{
inputing[i].style.fontSize = length/25+"px";
}
var box = document.getElementsByClassName("box");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/4+"px";
}
var prompting = document.getElementsByClassName("prompt");
for(var i=0; i<prompting.length;++i)
{
prompting[i].style.fontSize = length/40+"px";
}
var alpha=0;
function jumping(p)
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("document.getElementById('logIn').submit();",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
</script>
</body>
</html>
<file_sep><html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8>
<head charset>
<style type="text/css">
.title
{
font-family: 黑体, serif;
font-size:5em;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 12%;
}
body
{
background-color:4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
.button
{
font-family: 黑体, serif;
text-align:center;
height:5%;
color: #ffffff;
padding-top:15px;
padding-bottom:15px;
background:rgba(0, 0, 0, 0.4);
}
#dingWei
{
width:70%;
margin-top:15%;
margin-left:15%;
}
#lieBiao
{
width:70%;
margin-top:10%;
margin-left:15%;
}
#denglu
{
margin-left:15%;
font-family: 黑体, serif;
text-align:center;
width:35%;
color: #ffffff;
margin-left:15%;
padding-top:15px;
padding-bottom:15px;
margin-top:10%;
float:left;
padding-bottom:15px;
}
#zhuce
{
margin-top:10%;
width:35%;
float:left;
padding-bottom:15px;
}
#shangPu
{
margin-top:25%;
margin-left:70%;
width:30%;
color:white;
}
#mask
{
background-color: #4d7b95;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
#backgroundImg{
position:fixed;
left:0px;
top:0px;
z-index:-2;
}
</style>
</head>
<body onload="init()">
<img src="background.jpg" id="backgroundImg">
</img>
<div id="mask" hidden=true>
</div>
<div text-align = "center" class="title">LI HE's test web App</div>
<?php
session_start();
$lat = $long = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$lat = test_input($_POST["Latitude"]);
$long = test_input($_POST["Longitude"]);
}
if(!$lat =="")
{
$link = new mysqli("localhost","root","1<PASSWORD>","quguangjie");
$query = "select * from Map";
$result = $link->query($query);
$min = 720.0;
$targetMap = -1;
while($row = $result->fetch_assoc())
{
if(abs($lat-$row['coordinatex'])+abs($long-$row['coordinatey'])<$min)
{
$min = abs($lat-$row['coordinatex'])+abs($long-$row['coordinatey']);
$targetMap = $row['number'];
}
}
if($targetMap!=-1)
{
$_SESSION['mapId'] = $targetMap;
echo "<script>location.assign('svgmaps/" . $targetMap . ".php')</script>";
}
else{
echo "<h1 type='color = red'>sorry, can't find map at:</h1>";
echo "<h1>latitude:$lat</h1>";
echo "<h1>longtitude:$long</h1>";
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text-align = "center" class="title" id="quGuangJie">去逛街</div>
<div class="button" id="dingWei" onclick="getLocation()">定位我的位置</div>
<div class="button" id="lieBiao" onclick="findSite()">让我从列表选择</div>
<div class="button" id="denglu" onclick="login()">登录</div>
<div class="button" id="zhuce" onclick="register()">注册</div>
<div id="shangPu" onclick="sellers()">商铺入口</div>
<form hidden=true id="GPS" method="post" action="index.php">
<input id="Longitude" name="Longitude"/>
<input id="Latitude" name="Latitude"/>
</form>
</body>
<script type="text/javascript">
var alpha=0;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
document.getElementById("Latitude").value = position.coords.latitude;
document.getElementById("Longitude").value=position.coords.longitude;
document.getElementById("GPS").submit();
}
function jumping(p)
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("location.assign('"+p+"');",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
function findSite()
{
jumping("selectMap.php");
}
function login()
{
jumping("visitorLogin.php");
}
function register()
{
jumping("visitorRegister.php");
}
function sellers()
{
jumping("shopLogin.php");
}
var width = window.innerWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("quGuangJie");
title.style.fontSize = length/7+"px";
var small = document.getElementById("shangPu");
small.style.fontSize = length/28+"px";
var buttons = document.getElementsByClassName("button");
for(var i=0; i<buttons.length;++i)
{
buttons[i].style.fontSize = length/15+"px";
buttons[i].style.height = length/13+"px";
}
document.getElementById("backgroundImg").width=width;
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>SJTU-map</title>
<style type="text/css">
div#container
{
position:absolute;
top:0px;
left:0px;
width:370.167px;
height:451.5px;
}
#in
{
position:fixed;
right:5%;
top:45%;
width:6%; height:6%
}
#out
{
position:fixed;
right:5%;
top:55%;
width:6%; height:6%
}
#submit
{
position:fixed;
left:10px;
top:10px;
z-index:1030;
width:100px;
height:50px;
font-size:40;
}
#cancel
{
position:fixed;
left:10px;
top:70px;
z-index:1030;
width:100px;
height:50px;
font-size:40;
}
#search
{
position:fixed;
left:10px;
bottom:10px;
z-index:1030;
width:250px;
height:50px;
font-size:40;
}
</style>
<script>
var zoomspeed = 1.5;
var px=1;
var py=1;
function bigger()
{
if(zoomlevel==5) return;
centerx=(window.pageXOffset+window.innerWidth/2)*zoomspeed-window.innerWidth/2;
centery=(window.pageYOffset+window.innerHeight/2)*zoomspeed-window.innerHeight/2;
mapw *= zoomspeed;
maph *= zoomspeed;
zoom *= zoomspeed;
map.style.width = mapw+"px";
map.style.height = maph+"px";
zoomlevel += 1;
window.scrollTo(centerx,centery);
}
function smaller()
{
if(zoomlevel==1) return;
centerx=(window.pageXOffset+window.innerWidth/2)/zoomspeed-window.innerWidth/2;
centery=(window.pageYOffset+window.innerHeight/2)/zoomspeed-window.innerHeight/2;
mapw /= zoomspeed;
maph /= zoomspeed;
zoom /= zoomspeed;
map.style.width = mapw+"px";
map.style.height = maph+"px";
zoomlevel -= 1;
window.scrollTo(centerx,centery);
}
function init()
{
map=document.getElementById("container");
svge=document.getElementById("svgElement");
mapw=map.offsetWidth;
maph=map.offsetHeight;
zoom = document.body.clientWidth/370.167;
mapw *= zoom;
maph *= zoom;
map.style.width = mapw+"px";
map.style.height = maph+"px";
zoomlevel = 1;
}
function put(event)
{
px=(event.clientX+window.pageXOffset)/zoom;
py=(event.clientY+window.pageYOffset)/zoom;
node=svge.getElementById("seleted");
node.setAttribute('cx',px);
node.setAttribute('cy',py);
}
function submit()
{
document.getElementById("npx").value=px;
document.getElementById("npy").value=py;
document.getElementById("np").submit();
}
function cancel()
{
location.assign("../shopMain.php");
}
var shopEvents=new Array();
<?php
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from sjtuShopEventInfo";
$result = $link->query($query);
$num_rows = $result->num_rows;
$count=0;
while($row=$result->fetch_assoc())
{
echo "shopEvents[" . $count++ . "]=\"" . $row['shopName'] . "\";
shopEvents[" . $count++ . "]=\"" . $row['eventMessage'] . "\";
shopEvents[" . $count++ . "]=" . $row['eventCoordinateX'] . ";
shopEvents[" . $count++ . "]=" . $row['eventCoordinateY'] . ";
shopEvents[" . $count++ . "]=\"" . $row['eventDetail'] . "\";";
}
?>
</script>
</head>
<body onload="init();" >
<button id="submit" onclick="submit()">¸üÐÂ</button>
<button id="cancel" onclick="cancel()">È¡Ïû</button>
<form method="post" action="../locating.php" id="np">
<input hidden=true name="npx" id="npx"/>
<input hidden=true name="npy" id="npy"/>
</form>
<div id="search">
<form id="searchForm" method="post" action="search.php">
<input type="text"/>
<input type="submit"/>
</form>
</div>
<div onclick="put(event)">
<div id="container" width="370.167" height="450">
<svg id="svgElement" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 370.167 450" enable-background="new 0 0 370.167 450" xml:space="preserve">
<polyline fill="#39B54A" stroke="#000000" stroke-width="0.75" points="370.167,412.584 305.25,410.875 268.792,408.875 269,448
370.167,448 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M268.298,105H308.5v71.25c0,0,0,3.25-2.375,5.125
s-4.75,1.875-4.75,1.875h-32.869L268.298,105z"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="310.5,104.5 310.5,127.625 362.125,127.625 362.125,105 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="310.5,130.125 310.5,183.25 362.875,183.25 362.125,130.125
"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M268.542,185.667H294c0,0,2.668-0.5,5.334,2s2,4.896,2,4.896
L301.408,300c0,0-2.074,0.834-5.408,4.667s-3,5.958-3,5.958H268.72L268.542,185.667z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M320.625,186.375h42.25L364,301.833h-59.332l-0.834-99.521
c0,0-0.166-6.312,4.668-10.979S320.625,186.375,320.625,186.375z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M297.333,310.625l11.832,2.875c0,0,2.334-7.167-3.75-8.667
C299.333,303.333,297.333,310.625,297.333,310.625z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M297,313.5c0,0,0.334,1.583,3.084,3.083s4.082,1.167,4.082,1.167
s-0.185-1.083-2.758-2.75C298.833,313.333,297,313.5,297,313.5z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M268.726,313.5l25.148,0.75l5.375,5.625l5.625,0.625l2.625,1.125
c0,0,3.25,5.375,4.5,9.75s1.875,9.203,1.875,9.203v52.297c0,0-1.25,4.5-5.875,9.25s-9.75,5.625-9.75,5.625l-29.334-1.627
L268.726,313.5z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M317.375,73.625l-6.041,10.625l5.291,1.417l2.875,2.708h33.875V60.991
l-4.438,1.384c0,0-4.188,9.49-11.188,12.308s-15.084,0.692-15.084,0.692L317.375,73.625z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M147.25,301.375L179.5,309v5.625l-6.75,46.125
c0,0-3.125,18-17.625,28.625s-33,9.958-33,9.958l9.375-40.583l14.625-4.604l2.25-9.646l-1.75-7.25l4.75-20.25L147.25,301.375z"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="219.625,313.125 253.617,313.625 254.923,405.25
207.75,398.375 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M124.125,402.125v20.25h-7.25l-1.625,2.125l1.625,22.5h85.875v-26.667
l2.168-19.458l-43.583-6.5c0,0-9.958,1.809-18.333,4.967S124.125,402.125,124.125,402.125z"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="205.75,409.75 204.5,422.667 204.917,447 255.5,448
254.923,407.875 222.5,403.375 220.063,410.938 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M88,311.5l5.5,43.916v41.375L64.917,388.5l-45.25-0.167V335.25
c0,0,2.271-8.313,4.396-11.813s4.938-6.375,9.5-7.875S88,311.5,88,311.5z"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="87.75,4 87.75,101.75 9,101.75 9,104.75 87.75,106 87.75,160
32.5,160 31.5,188.25 4.5,188.25 4.5,4 "/>
<rect x="91.5" y="4" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="122.5" height="24.25"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="91.5,30 91.5,47.5 158.75,47.75 158.75,30.25 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="91.5,49.125 91.5,91.5 91.5,101.625 175.875,101.625
175.875,77.125 159.25,76.875 159.063,49.5 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="160.688,69.281 160.688,75.406 182.125,75.375 190.5,73
190.5,69.25 "/>
<rect x="160.688" y="30" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="30.125" height="38.125"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="192.813,30 192.813,59 215.438,59 214,30 "/>
<polyline fill="#39B54A" stroke="#000000" stroke-width="0.75" points="250.617,97.594 250.513,101.625 178.353,101.625
178.353,80.938 215.166,80.938 215.166,79.125 181.478,79.125 190.978,76.125 214.666,76.125 214.666,74.563 192.978,74.563
192.978,60.375 215.603,60.375 216.791,91.5 "/>
<line fill="none" stroke="#000000" stroke-width="0.75" x1="249.188" y1="0" x2="255.5" y2="451.5"/>
<line fill="none" stroke="#000000" stroke-width="0.75" x1="268.083" y1="0" x2="269" y2="451.5"/>
<path fill="none" stroke="#000000" stroke-width="0.75" d="M122.5,91.75"/>
<rect x="91.5" y="105" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="22.875" height="13.625"/>
<rect x="116.875" y="105" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="59.5" height="14.5"/>
<rect x="91.5" y="120.75" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="22.875" height="28.375"/>
<rect x="91.5" y="151.125" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="22.875" height="9"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="116.875,121.5 116.875,149.875 162.875,149.125
162.875,121.5 "/>
<rect x="116.875" y="151.125" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="46" height="9.5"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M164.5,145c0,2.25,3.25,5,6.375,4.875s4.75-2,5-4
s0.125-17.25,0-20.375s-2.75-4.75-5.563-4.75s-5.688,2.375-5.813,4.625S164.5,145,164.5,145z"/>
<rect x="178.188" y="105" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="39.938" height="14.5"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="178.188,121.5 178.188,145.75 176.375,149.125
218.125,149.125 218.125,121.5 "/>
<rect x="164.444" y="151.125" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="53.681" height="9.5"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="7,173.833 11.833,173.833 11.833,148.333 26.667,148.333
26.667,182.833 29.833,182.833 29.833,170.667 31.167,170.833 32,144 7,144 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="12.333,181.5 13.813,183.813 17.5,181.5 16,179.125 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="34.333,162.833 33.833,188.25 82.583,188.25 87,191.333
87,162.833 "/>
<rect x="35.167" y="165.833" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="19.583" height="6.333"/>
<rect x="35.167" y="179.125" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="19.583" height="5.958"/>
<rect x="61.917" y="178.75" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="18.333" height="6.333"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="58.417,165.833 58.417,172.167 82.917,172.167
82.917,181.917 85.917,181.917 85.917,165.833 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M4.5,190.833v61.333c0,0,74.083,0.5,77.417,0
c-0.167-3.167,0.917-17.25,3.917-23.25s10.333-13.417,10.25-17.083s-15.5-21-15.5-21H4.5L4.5,190.833z"/>
<path fill="#B3B3B3" stroke="#000000" stroke-width="0.75" d="M8,198.417c0,0-0.5,14.583,0,14.75s6.417,0,6.417,0v2.917h10.167
l0.333-17.667H8L8,198.417z"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="29.167,201.833 29.167,212.083 37.25,212.083 37.25,201.833
34.833,201.833 34.833,199.75 56.833,199.75 56.833,193.5 31.167,193.5 31.083,201.583 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="7.778,219 7.778,226.25 20.167,226.25 20.167,223.583
27.917,223.333 27.917,219 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="33.833,227.583 33.833,233.5 52.667,233.5 52.333,227.583 "/>
<rect x="68.167" y="197.75" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="17" height="4.75"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="58.917,228 58.917,234 72.333,234 79.583,226.25
79.583,223.333 74.25,223.333 74.167,225.833 71.75,228 "/>
<rect x="75.25" y="210.25" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="15.417" height="5.417"/>
<rect x="68.167" y="211.167" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="4.5" height="4.167"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="81.75,257.334 81.917,262.083 39.833,262.083 39.833,284.583
4.083,284.583 4.333,257.334 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="18.75,273.583 18.75,278.833 37.833,279.833 37.833,274.5 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="4.5,91.5 87.75,91.5 87.75,97.594 4.5,97.438 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="91.5,91.5 175.875,91.5 175.875,97.438 91.5,97.594 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="178.188,91.5 239.917,91.5 242.417,93.834 250.513,93.834
250.617,97.594 178.188,97.25 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="4.5,252.167 4.5,257.334 81.75,257.334 81.917,252.167 "/>
<rect x="191.285" y="163" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="27.59" height="12.875"/>
<rect x="164.444" y="163" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="24.369" height="35.875"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="165.938,175.875 165.938,180.938 185.375,180.938
185.375,190.833 165.25,190.833 165.25,196.875 187.75,196.875 187.75,175.875 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M89.625,162.833v34.042L98,207.5c0,0,0.813,1,2.5,1
s2.438-0.75,2.438-0.75s4.75-3.188,7.563-4.938s11.188-3.938,11.188-3.938h40.5l-0.031-36.042L89.625,162.833L89.625,162.833z"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="90.5,163.938 90.5,172.375 114.375,172.375 114.375,165.833
97.25,165.833 97.25,163.938 "/>
<rect x="92.188" y="176.625" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="22.188" height="5.875"/>
<rect x="92.188" y="187.688" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="22.438" height="5.5"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="123.25,173.875 123.25,180.563 131.688,180.563
131.688,187.375 136.563,187.375 136.563,173.875 "/>
<rect x="122.938" y="189.5" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="14.188" height="5.5"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="140,184.875 140,195.813 147,195.813 147,189.938
160.313,189.938 160.313,183.167 155,183.167 155,185 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M42,264.25v22.5H4.083V447H111v-24.5h-6.5l-9.458-9.458l-1.354-13.792
l-27.313-8.375v13.25h-59V388.75h9c0,0-0.421-48.381,0-53.75c1.25-5.125,4.375-10.375,6.75-13.875s6.125-7,11.25-7.875
S87.5,309.5,87.5,309.5l-5.583-45.25H42z"/>
<rect x="8.667" y="390.083" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="56.25" height="13.417"/>
<rect x="24.583" y="335.25" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="9.333" height="40.333"/>
<path fill="#FFFF00" stroke="#000000" stroke-width="0.75" d="M36.792,330v49.25h3.958c0,0,4.25,6.125,12,6.125
s12.167-6.25,12.167-6.25h3.833V368.75h3.5v-23.875h-3V330.75h-5.125c0,0-3.5-5.75-11.25-5.75s-10.234,5.016-10.234,5.016
L36.792,330z"/>
<rect x="41" y="337.625" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="23.917" height="36.125"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="72.25,409.833 82.667,420.333 93.5,410.333 82,399.333 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="47.833,413.667 52.958,417.5 56.583,412.5 52.208,409.167 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="216.5,4 249.188,4 250.513,93.834 242.417,93.834
239.917,91.5 219,91.5 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="221.5,105 221.5,184.167 251.789,184.167 250.671,105 "/>
<rect x="222.667" y="163.938" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="10.332" height="5.5"/>
<rect x="223.667" y="172.375" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="10.332" height="3.5"/>
<rect x="237.5" y="164.667" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="6.668" height="2.667"/>
<rect x="237.5" y="169.438" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="5.5" height="2.938"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="191.285,177.833 191.285,197.5 205.08,184.167
218.875,184.167 218.875,177.833 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="201.5,179.563 201.5,184.167 206.578,183.167 217.333,182.5
217.333,178.667 206.578,178.667 205.08,179.563 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="206.563,186.375 190.438,200.938 190.438,230.625
219.875,229.938 219.25,186.375 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="194.75,200.25 193.125,203.5 199.063,206.438
217.688,206.438 217.688,202.375 199.75,202.75 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="194.75,211.125 193.125,214.563 199.125,217.75
218.375,217.75 218.375,213.75 200,214.125 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="195.063,223.125 193.125,226.188 199.438,228.813
218.375,228.5 218.375,225.125 200.188,225.969 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="190.438,232.188 190.438,248.688 220.5,248.688
219.875,231.875 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="198.188,234.625 194.313,234.625 194.313,243.625
195,243.625 195,244.906 196.563,244.906 196.563,247.469 207.531,247.469 207.531,246.188 208.75,246.188 208.75,245.125
209.688,245.125 209.688,238.281 206.093,238.281 206.093,235.469 203.5,235.469 203.5,234.781 200.375,234.781 200.375,232.781
198.218,232.781 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="190.438,250.813 190.438,259.875 220.5,259.375
220.5,250.188 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M124.375,201.75c3.042,0,63.375,0,63.375,0L187,249.5
c0,0-95.667,0-102.5,0c-0.167-8.083,2.5-17.375,5.125-22.25s8.25-12.25,12.125-15.375S121.333,201.75,124.375,201.75z"/>
<rect x="222.667" y="105.833" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="27.082" height="54.792"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="221,186.375 224.125,310 253.565,310 251.789,186.375 "/>
<rect x="224.625" y="188.75" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="20.875" height="3.813"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="223.688,202.313 223.688,206.438 230.125,206.438
235.063,209.063 237.283,206 230.938,202.813 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="223.688,215.188 223.688,219.438 229.75,219.438
235.063,221.875 237.283,219.313 230.485,216.125 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="224,225.063 224,228.813 230.063,228.813 235.125,231.875
237.283,228.469 230.642,225.625 "/>
<polygon fill="#FFFF00" stroke="#000000" stroke-width="0.75" points="240.313,203 240.313,234.938 227.813,234.938
227.813,245.625 246.625,245.625 246.125,203 "/>
<rect x="84.493" y="250.833" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="37.632" height="8.792"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="123.292,250.833 123.292,259.625 187.25,259.875
187.25,250.833 "/>
<rect x="84.493" y="252.875" fill="#00AAFF" stroke="#000000" stroke-width="0.75" width="37.632" height="4.459"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="123.292,252.875 123.292,256.75 187.25,257.334
187.25,252.875 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="190.438,252.875 190.438,257.334 220.5,256.75 220.5,252.125
"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="222.662,252.125 222.776,256.625 252.789,256 252.789,251 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="227,293.875 227,302.25 244.125,303 244.125,297.125
232.125,296.875 232.125,293.875 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="226,259.875 226,262.25 247.875,262.25 247.875,267.5
250.125,267.5 250.125,259.875 "/>
<rect x="226" y="267.5" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="21.375" height="2"/>
<polygon fill="#FFFF00" stroke="#000000" stroke-width="0.75" points="224,270.25 224.875,292.875 250.125,293.5 250.125,270.25 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="189.75,262 183.5,306.5 222,310.625 221,262 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="189.875,275.625 189.875,279 193.125,285.5 187.75,289.625
187.75,293.5 191.625,294.75 197,301.375 197,305.625 200.375,305.625 205.468,303 211.875,307.75 214.25,307.75 215.75,304.25
212.5,299.25 214.625,297.25 202,281 204.5,279.25 212.25,289.5 215.75,286.75 208.75,276.75 207.25,272.375 199,274 200.5,278.75
197.625,280.5 194.313,275.375 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="204.625,263.688 204.625,270.25 212,270.25 212,277.25
215.75,277.25 215.75,263.688 "/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="84.493,262 187.25,262 180.5,305.5 129.125,292.375
127.625,298 145,301.75 149.375,317 144.5,337.5 146.125,344.25 144.5,352 130.875,356.75 129.75,357.875 119.625,399.333
96.125,399.333 96.25,354.146 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M183.5,309.125l-8.375,56.25c0,0-2.375,8.25-5.75,13.125
S163,387.125,163,387.125l4.375,5.875l37.875,5.375l12.125-85.25L183.5,309.125z"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="233.75,322.75 233.75,336.25 248.25,336.25 248.25,322.125
"/>
<path fill="#FFFF00" stroke="#000000" stroke-width="0.75" d="M218,343.625l-6.75,49.25l4.5,0.5c0,0,3.25,5.75,10.625,6.5
s8.375-0.5,11.75-2.625s6.5-8.75,6.5-8.75L249,356.75c0,0-0.5-6-3.125-9.5s-9.576-7.125-14.539-6.625
c-4.961,0.5-9.336,3.625-9.336,3.625L218,343.625z"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M220.375,353.75l-4,28.625c0,0-0.625,11.25,10.875,13.5
s13.75-9,13.75-9l3.875-30.25c0,0-0.877-10.691-11.125-12S220.375,353.75,220.375,353.75z"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="180.25,278 176.75,297.167 180.583,298.083 183.5,278.417 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="126.917,270.917 124.875,276.667 128.667,281.833
148.083,286.833 151.25,292.75 166.167,296.333 169.083,294.667 170.417,288.833 166.5,287.667 162.625,290.063 155.271,288.042
152.5,284.333 154.417,282.667 150.813,276.5 146,275.417 144.333,276.583 139.583,275.5 138.583,276.167 133.333,275.083
131.583,272.375 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="155.583,309.125 165.167,313.833 164.083,318.25
151.75,322.667 150.813,325 156,326.417 165.917,320.083 164.833,325 163.833,324.917 163,328.5 167.833,330.083 169.417,326.167
172.667,327.083 173.75,323 167.833,321.75 169.333,314.583 173.75,315.583 174.833,311 169.5,309.5 168.917,311.5 156.25,306.417
"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="153.167,334.667 152.417,337.5 162.417,341.75
161.333,346.75 148.667,350.75 147.917,353.75 153.25,355 162.417,348.333 160.417,356.917 164.917,358.5 170.167,354.167
170.167,351.25 165.5,350.358 164.333,353.75 162.417,353.25 163.583,348.333 164.583,348.417 166.167,343.083 170.667,343.833
171.75,339.167 166.333,337.75 165.833,339.833 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="136.333,358.5 134.167,363.833 139.5,365.333 138,372.083
134.917,371.5 134.167,374.917 139.5,376.167 136.333,384.167 129.833,384.667 129.167,389 130.333,390.917 134.333,391.75
136.25,390.833 137.667,386.667 142.667,388.167 143.667,384.167 139.5,383.083 141.25,376.833 153.5,381 154.167,377.75
141.667,373.083 143.5,365.667 160.667,367.333 161.333,364.667 142.917,362.583 143.167,360.417 "/>
<path fill="none" stroke="#000000" stroke-width="0.75" d="M157.083,391.75L163,392.5c0,0-1.083-2.084-2.958-2.417
S157.083,391.75,157.083,391.75z"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="186.667,313.125 186.333,315.75 189.417,316.333
188.917,318.25 192.333,318.833 192.667,315.979 195.667,316.333 195.667,313.125 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="200.167,315.25 199.75,318.25 214.75,319.417
215.333,315.979 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="198.667,326 198.167,328.833 213.333,330.083
213.833,327.583 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="197.083,336.667 196.583,339.583 211.833,340.578
212.333,337.667 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="184.333,327.25 184,330.083 186.917,330.833 186.917,333.583
190.188,334 190.188,331.75 193.583,332.5 193.583,329.667 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="182.917,340.167 182.5,343.417 185.333,344 185.333,346.083
188.792,346.584 188.792,343.375 191.75,343.375 192.167,340.578 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="195.667,341 194.75,349.417 199.167,350 199.75,347.667
206,348.25 207.167,342.583 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="208.5,343.375 207.75,351.5 210.75,351.5 211.583,343.833 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="184.417,349.417 184.417,351.917 188.792,352.5
188.792,350.358 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="179.5,354.833 178.833,358.5 194.083,359.167 194.75,356.333
"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="198.917,353.25 198.167,356.333 201.917,357 200.958,359.624
205,360.417 205,357.75 208.417,358.5 207.75,355.333 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="177.667,365.75 177.167,369.083 192.833,369.667
192.833,366.583 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="197.333,366.583 196.917,369.667 200.083,369.667
200.083,371.417 203.292,371.917 203.292,368.833 206.833,369.25 206.833,366.583 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="191.583,378.5 191.583,381.333 206.417,381.917 206.417,379
"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="189.833,388.25 189.333,391.272 204.917,392.5
204.917,389.75 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="177.917,375.667 177.583,378.5 180.917,379 180.583,381
183.583,381.5 183.917,379.083 187.25,379.167 187.25,376.583 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="170.667,385.667 170.667,388.583 174.083,388.583
173.333,391.75 176.417,391.75 177.167,389.25 180.167,390.046 180.833,387.5 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="10.833,290.667 10.833,314.833 25.333,314.833
25.333,290.167 "/>
<path fill="#B3B3B3" stroke="#000000" stroke-width="0.75" d="M91.625,300.375l1.875,1l0.625-1.625c0,0,1.375,1.938,4.5,2.313
s6-1.154,6-1.154L103.75,299l-2.188,0.563l-0.438-4.375l3.188,0.625l0.688-3.438c0,0-5.375-1.063-8.5,1.25
S91.625,300.375,91.625,300.375z"/>
<path fill="#00AAFF" stroke="#000000" stroke-width="0.75" d="M129.75,263.375h-4.063l-11.625,4.75l-8.125,6.563l-4.438,7.938
l0.75,3.563l8.438,14.438v2.813L108,305.313h-3l-4.875-2.375l-1.5-0.063L97.688,304l-2.063-0.75L93.188,312l0.875,7.063v1.313
L97.188,325l3.375,0.5l1.125,1.563l0.563,12.063l3,9.813l3.688,5.875l3.063,2.5l4.188,3.063l3.688,3.938c0,0-0.125,0.438,1.25,0.313
s2.188-1.563,2.188-1.563l2.313-4.563l3.542-3.125l5.083-2.875l4.875-1.125l3.063-2.938l0.375-1.5l-1.438-2l1-2.375l-0.5-4.563
l1.5-5.938l-0.688-7.438l2.125-6.875v-6.5l-3.813-5.5l-6-3.313l-6.438,0.938l-3.438,0.188l-2.75-2.188l-2.75,0.313l-1-3.75l1-7.313
l-2.875-8.75l2.688-9.938l10.313-7.688L129.75,263.375z"/>
<rect x="111" y="389.5" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="5.875" height="4.875"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="4.083,429.625 87.25,426.5 104.25,424.5 111,424.5
111,430.625 98.875,430.625 92.5,429.75 4.083,432.625 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="127.125,405.25 127.125,409.833 133.5,409.833 133.5,420.688
143,420.688 143,416.375 136.375,416.375 136.375,407.75 144.563,407.75 144.563,403.375 137.125,403.375 137.125,404.75 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="150.813,402 150.813,406.75 161.333,404.375 162.125,400.094
"/>
<path fill="#FFC496" stroke="#000000" stroke-width="0.75" d="M167.625,406.123c0,0-3,8.377,5.75,10.127s11.042-5.063,11.042-5.063
L199,413.75l0.5-3.917l-2.582-0.708l0.207-2.375l6.168,0.875l0.457-4.203l-8.375-1.547h-11.5l-3.042,0.75L179.5,404
c0,0,2.209,6.125-2.333,6.75s-4.292-4-4.292-4L167.625,406.123z"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="157.083,413.875 157.083,420.688 162.125,420.333
162.125,413.375 "/>
<rect x="162.125" y="431.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="7" height="7.625"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="115.25,424.5 202.75,422.667 202.75,425.667 191.583,424.5
174.333,427.667 134.667,428.563 116.875,431.25 115.737,431.25 "/>
<rect x="192.813" y="430.75" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="4.438" height="3.438"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="174.375,428.625 176.563,430.75 172.438,432.469
171.438,433.875 173.5,436.5 171,437 170,440.25 172.063,439.938 172.625,438.438 173.75,438.875 175.625,441.688 181.438,442.75
185.439,442.125 192.813,441.813 194.313,440.313 196.625,440.188 196.625,441.25 198.125,441.25 199.375,439.938 201.063,438.875
200.625,438 199.625,437.563 197.25,436 193.938,436.625 191.125,433.25 190.438,433 191.313,436.938 192.313,440.438
185.439,441.125 183.438,436.5 184.375,433.313 182.938,431.25 178.563,431.25 178.375,429.688 177.375,429.438 175.375,428.125 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="207.75,410.625 206.833,415.25 218.875,417.031
219.5,412.031 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="222.125,405.25 221.25,410.625 232.625,412.031 233.5,406.75
"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="235.375,409.206 234.5,412.625 236.25,418.375
241.625,417.031 241.125,412.031 247.25,412.625 247.25,416.537 249.188,416.537 249.188,418.375 250.75,418.375 250.75,416.537
249.875,415.375 250.75,409.206 238.875,406.75 "/>
<path fill="#FFC496" stroke="#000000" stroke-width="0.75" d="M209,433.125v4.75h6.5c0,0,0.375,3.5,4,4.875s6.5-1.375,6.5-1.375h6
v-4.125l-12.5,0.25v-4.375H209z"/>
<rect x="226.875" y="428.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="19.375" height="6.063"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="207.75,400.875 206.417,407.875 219,409.206 220.5,403.375
"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="268.093,5.25 268.542,101.625 307.75,101.625 307.75,90
285.667,89.833 285.667,66.333 298.5,66 299.167,17.5 326.167,17 326.167,5.25 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M301,19.333v23l23.168,8.333c0,0,3.832,0.333,5.5-3.167
c1.666-3.5-2.5-8.333-2.5-8.333l-0.334-19.833H301z"/>
<polygon fill="#39B54A" stroke="#000000" stroke-width="0.75" points="301,44.167 322.667,52.333 314.5,73.167 308.333,84.167
308,87.667 287.5,87.667 287.5,68 301,67.667 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="302.5,50.675 302.5,55.833 320.167,55.833 320.167,52.167 "/>
<rect x="290.667" y="71" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="13.5" height="14.667"/>
<rect x="329.333" y="5.25" fill="#39B54A" stroke="#000000" stroke-width="0.75" width="22" height="12.25"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M329.333,19.333v19.5c0,0,1.666,0.167,2.666,2.333
s1.334,4.5,1.334,4.5H352.5V19.333H329.333z"/>
<rect x="332.833" y="36.333" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.332" height="5.5"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M325.167,53.254l-7,18.746c0,0,9.832,5.167,17.5,1.5
c7.666-3.667,12.166-12,12.166-12l4.668-2V47.167h-19.668c0,0,0.168,1.708-2.521,3.896S325.167,53.254,325.167,53.254z"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="331.563,51.313 331.563,56.563 348.938,55.833
348.938,50.675 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="322.938,63.063 321.563,68.25 328,69.875 339.875,69.875
340.563,64.688 327.875,64.813 "/>
<rect x="318.75" y="79.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="30.188" height="6.417"/>
<polygon fill="none" stroke="#000000" stroke-width="0.75" points="310.5,89.5 310.5,101.625 352.5,101.625 352.5,90.125 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="268.505,93.834 273.5,91.5 307.75,91.5 307.75,97.594
274,97.594 268.505,96.75 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="310.5,91.5 349.5,91.5 352.5,92.875 352.5,97.594
310.5,97.594 "/>
<rect x="292.125" y="133.229" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="12.125" height="26.896"/>
<rect x="292.125" y="110" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="15.625" height="14"/>
<rect x="312.25" y="110" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="48.5" height="14"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="313.75,132.125 313.75,138.5 332.375,138.5 332.375,132.625
"/>
<rect x="339.25" y="132.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="20.75" height="7"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="313.75,145.25 313.75,150.75 326.625,150.75 326.625,146.125
"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="344.75,148 344.75,153.875 360,153.875 360,147.25 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="314.625,158 314.625,163 326.625,164.375 326.625,160.125 "/>
<rect x="328.75" y="172" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="11.625" height="5.125"/>
<rect x="345.75" y="160.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="15" height="6.75"/>
<rect x="345.75" y="173.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="14.25" height="6.375"/>
<path fill="#00AAFF" stroke="#000000" stroke-width="0.75" d="M273.375,153.875l-1.125,23.25c0,0,0,1.375,2,2.5s4.375,1,4.375,1
l12.875,0.004l0.625-1.004c0,0,4.5,1.758,7.813,1.004s5.313-2.254,5.313-2.254v-7l1.625-7l-1-2.625L303,162.125l-1.375,2.25
l-2.25-0.875h-8l-2.976-2.313c0,0,0.351-3.688-1.399-5.563S273.375,153.875,273.375,153.875z"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="288,268.5 288,305.833 291.667,305.833 293.167,298.438
298.833,298.438 298.833,291.167 292.667,291 292.5,285.333 295.5,285.167 295.5,273.667 298.833,273.667 298.833,268.5 "/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="268.542,250.188 301.408,250.188 301.378,257.334
268.644,257.334 "/>
<rect x="289.333" y="259.875" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="10.666" height="4.625"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="341.333,188.75 341.333,210.333 355.167,210.333
355.167,206.667 352.375,206.833 352.375,202.313 355.833,197.667 354.5,195.667 352.375,197.167 346.5,197.5 346.5,188.75 "/>
<path fill="#00AAFF" stroke="#000000" stroke-width="0.75" d="M334.563,190l4.938,26.015h17.166L360,239.5l-6,6.125h-11.332
l-5.979,0.708l-7.188-2.229l-4,1.521l-6.666-3.125l-2.334,1.604v2.229c0,0,0.25,1.333-1.875,1.167s-4.957-3.271-4.957-7.219
c0-3.948,2.332-3.281,2.332-3.281s2.084,0.333,3.084-0.25s1-2.75,1-2.75s2.25,0.25,2.25-2.083s-2.418-2.667-2.418-2.667
l-0.332-2.333l-5.334-1.75l-0.582-1.333l1-2.25l-1.75-4.833l0.75-2.333l-0.75-2.667c0,0-0.418-7.167,0.332-9.333
s4.918-6.667,4.918-6.667s3.584-4.25,5.416-5.167C321.417,189.667,334.563,190,334.563,190z"/>
<rect x="304.234" y="250.188" fill="#00AAFF" stroke="#000000" stroke-width="0.75" width="59.262" height="7.146"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="344.583,263.583 344.583,269.833 362,269.5 362,263 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="344.167,277.833 344.167,283.167 362,284 361.5,279.333 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="344.583,292.75 344.583,299.167 362,299.167 362,292.417 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="307.25,261 307.25,267.667 333.865,267.667 333.865,261.75
"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="309.75,295.792 309.75,299.167 332.667,299.167
332.667,293.167 314.75,293.167 314.5,295.792 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="327.813,307.375 327.813,316.5 333.5,316.5 340.875,323.875
340.875,327.688 350.813,328 351.25,318.875 359.625,319 359.625,306.188 354.125,306.188 354.938,314.813 350.938,314.813
351,307.563 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M310.938,305l1.75,9.313c0,0,14.438,5.188,21.563,11.188
s15.875,12.75,15.875,12.75s6.5-4.625,10.188-13.938C364.001,315,363.75,305,363.75,305H310.938z"/>
<polygon fill="#FFFF00" stroke="#000000" stroke-width="0.75" points="277.5,332.75 277.5,351 308,350.375 308,332.125 "/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="309.75,334.25 310.938,350.125 312.875,350.125
311.313,334.25 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M313.875,318.25l16.5,8.125l35.375,31.875l0.625,2.375l-0.875,48.25
h-37.688c0,0-2.938-1-6.563-4.875s-5.875-10.375-5.875-10.375l0.25-50.375c0,0,0-3.5-1.75-10.125s-4.27-12.875-4.27-12.875
s-0.355-1.813,1.332-2.469S313.875,318.25,313.875,318.25z"/>
<path fill="#FFC496" stroke="#000000" stroke-width="0.75" d="M312.875,324.167h3.209v-3.583h-1.604c0,0-0.979-0.166-1.604,0.667
S312.875,324.167,312.875,324.167z"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="316.083,327.417 316.083,332.125 323.5,332.125
323.5,339.167 317.417,339.167 317.5,343.834 324.5,343.834 324.5,340.584 336.583,340.667 336.583,335.917 325.583,335.625
325.167,327.417 "/>
<rect x="339.5" y="344.417" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="6.834" height="5.708"/>
<rect x="318.083" y="351.501" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="13.5" height="4.916"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="335.417,353.959 335.417,359.417 340,359.417 340,356.417
337.975,353.959 "/>
<rect x="349.667" y="353.001" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="7" height="4.916"/>
<rect x="318.083" y="364.334" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="13.5" height="4.5"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="335.917,364.334 335.917,369.417 343.667,369.417
344,364.334 "/>
<rect x="357.167" y="366.584" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="7.25" height="4.583"/>
<rect x="317.75" y="376.667" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8" height="5.917"/>
<rect x="318.5" y="389.417" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.418" height="5.834"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="331.583,401.417 331.25,407.334 339.958,407.334
339.958,401.417 "/>
<rect x="345.167" y="401.417" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.832" height="5.917"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="348.083,388.667 348.083,394.501 364.417,394.084
364.083,388.667 "/>
<rect x="348.583" y="377.084" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="15.832" height="5.917"/>
<rect x="306.167" y="36.333" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.896" height="5.5"/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M304,407.75l18.709,1.125l-8.834-11.208c0,0-1.726,3.021-4.299,5.333
C307.001,405.313,304,407.75,304,407.75z"/>
<polygon fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="204.5,422.667 254.923,420.688 254.923,423.5
204.537,424.835 "/>
<polyline fill="#39B54A" stroke="#000000" stroke-width="0.75" points="370.167,4.625 353.375,4.625 356.25,101 370.167,101 "/>
<polyline fill="#39B54A" stroke="#000000" stroke-width="0.75" points="370.167,105 364.875,105 365.75,183.25 370.167,183.25 "/>
<polyline fill="#39B54A" stroke="#000000" stroke-width="0.75" points="370.167,186.375 365.625,186.375 366.25,244.625
370.167,244.625 "/>
<path fill="#39B54A" stroke="#000000" stroke-width="0.75" d="M370.167,248.125h-3.793c0,0,0.375,59.624,0,62.5
s-3.332,13.292-5.125,16.792c-1.791,3.5-8.875,12.458-8.875,12.458l17.793,16.813"/>
<polyline fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="370.167,93.125 356.015,93.125 356.148,97.594
370.167,97.594 "/>
<polyline fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="370.167,250.188 366.387,250.188 366.387,257.334
370.167,257.334 "/>
<polyline fill="#00AAFF" stroke="#000000" stroke-width="0.75" points="370.167,416.333 268.946,420.678 268.953,424
370.167,420.166 "/>
<path fill="#B3B3B3" stroke="#000000" stroke-width="0.75" d="M46.75,71.25l1.5-5.75c0,0-11.25-5-13.25-18.25s0.75-17.25,8-21
S57,28,60.75,30.5s7.5,6.5,10,13.25c1.917,4.75,1,7.25,1,7.25l6,1.375c0,0,1-1,2.625-0.625s2.25,1.5,1.875,4.125
s-0.75,4-3.125,3.875s-3.042-2.417-2.875-4.875c-1.242-0.291-3.667-0.875-5.125-1.125C71,55.917,67.5,61.333,65,62.75
c0.76,1.278,2.75,4.625,2.75,4.625L69.125,67c0,0-0.25,1.875-2.125,2.75s-3.5,0.375-3.5,0.375l1.375-1.25c0,0-1.875-2.75-2.75-4.25
c-1.5,1.5-7.25,3-10.875,1.5C50.575,68.893,50,71.25,50,71.25s3.875,0.5,3.25,3.875s-2,2.625-4.5,2.125s-3.625-1.5-3.375-3.5
S46.75,71.25,46.75,71.25z"/>
<rect x="96.333" y="17.167" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.833" height="4.667"/>
<rect x="122.167" y="19.5" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.5" height="3.833"/>
<rect x="131.833" y="18.167" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.167" height="3.667"/>
<rect x="153.167" y="20" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="3.833" height="4.167"/>
<rect x="162" y="21.417" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.167" height="3.562"/>
<rect x="187.167" y="23.198" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8" height="3.135"/>
<rect x="196.333" y="21.417" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.666" height="3.562"/>
<rect x="96.333" y="32.833" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.833" height="4"/>
<rect x="115" y="34.833" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.833" height="3.167"/>
<rect x="139.167" y="41.5" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.833" height="4.333"/>
<rect x="152.5" y="35.875" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="2.583" height="2.875"/>
<rect x="98" y="50.667" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17" height="4"/>
<rect x="116.5" y="51.334" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.667" height="4.499"/>
<rect x="162" y="79.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.313" height="3.625"/>
<rect x="162" y="40.5" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.625"/>
<rect x="179.75" y="42.313" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.375" height="2.938"/>
<rect x="163" y="51.334" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="4.875" height="4.499"/>
<rect x="162" y="62.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.625"/>
<rect x="179.75" y="60.625" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.375" height="3.875"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="195.167,38 195.167,41.5 213,41.5 212.5,38 "/>
<rect x="205.25" y="47" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="5.375" height="3"/>
<rect x="204.667" y="53.584" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="8.332" height="3.416"/>
<rect x="195.167" y="68.375" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.832" height="3.625"/>
<rect x="179.75" y="83.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.375" height="3.25"/>
<rect x="198.125" y="84.875" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.875" height="2.875"/>
<rect x="224.5" y="10.75" fill="#FFFF00" stroke="#000000" stroke-width="0.75" width="14.875" height="78"/>
<rect x="101.125" y="112.625" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="4.625" height="4.125"/>
<rect x="175.594" y="153.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.281" height="3.5"/>
<rect x="198.156" y="154.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.844" height="3.5"/>
<rect x="179.75" y="141.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.375" height="3.25"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="198.125,139.75 198.156,143.5 214.401,143.5 214.401,139.75
"/>
<rect x="195.375" y="126.375" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17" height="4.125"/>
<polygon fill="#FFC496" stroke="#000000" stroke-width="0.75" points="180.375,113.375 180.375,117.5 197.125,117.5 197.25,113.375
"/>
<rect x="198.156" y="114.688" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.844" height="3.563"/>
<rect x="157.5" y="113.375" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.875" height="3.375"/>
<rect x="95.5" y="122.625" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="24.5"/>
<rect x="118.375" y="114.688" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.438"/>
<rect x="136" y="113.375" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17" height="3.375"/>
<rect x="140.875" y="126.25" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.75"/>
<rect x="118.375" y="141.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.25"/>
<rect x="140.875" y="139.75" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.625"/>
<rect x="118.375" y="153.875" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="17.625" height="3.875"/>
<rect x="140.875" y="153.125" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="16.625" height="3.5"/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="160.313,204.75 160.313,219 168.25,219 168.25,216.5
180.25,216.375 180.25,205.375 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="152.5,225.125 152.5,232 172.375,232 171,239.125
164.444,239.125 164.444,245.25 177.625,245.25 177.625,235.188 181.25,235.188 181.25,228.667 173.75,228.667 173.625,225.125 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="151.25,235.875 151.25,243 156.625,248.375 162.625,248.375
162.625,242.75 156.938,242.875 156.938,235.875 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="130.031,204.75 130.031,211.167 135.25,211.167 135.25,218.5
124.375,218.5 124.375,223.875 141.125,223.875 141.125,219 137.125,219 137.125,211.167 153.625,211.167 153.625,204.75 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="90.667,228.667 88.5,239.25 90.667,241.375 91.25,243.5
89.625,244.375 89.625,248.375 98.875,248.375 97.875,243.75 93.688,243.75 92.188,240.25 98.25,240.375 98.25,238.521 93,237.375
93.125,235.875 96.625,235.875 96.625,228.667 "/>
<polygon fill="#B3B3B3" stroke="#000000" stroke-width="0.75" points="100.25,230.625 100.25,235.875 106.75,235.875
106.75,246.375 124.875,246.375 124.875,240.875 109.625,240.875 109.625,234 118.5,234 118.5,229.25 106,229.25 106,230.625 "/>
<rect x="205.938" y="190.813" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="11.75" height="3.5"/>
<rect x="45" y="266" fill="#B3B3B3" stroke="#000000" stroke-width="0.75" width="6" height="3.167"/>
<rect x="210.813" y="170.292" fill="#FFC496" stroke="#000000" stroke-width="0.75" width="4.5" height="4.167"/>
<line fill="none" stroke="#000000" stroke-width="0.75" x1="258.625" y1="0" x2="262.357" y2="451.5"/>
<circle id="seleted" cx="50" cy="50" r="4" stroke="black" stroke-width="1" fill="red"/>
</svg>
</div>
</div>
<div>
<button id="in" type="button" onclick="bigger();">+</button>
<button id="out" type="button" onclick="smaller();">-</button>
</div>
</body>
</html><file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8>
<head>
<style type="text/css">
#title
{
font-family: 黑体, serif;
font-size : 25px;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
body
{
font-family: 黑体, serif;
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
form
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
p
{
font-size: 1.5em;
text-align:center;
}
/*
.box
{
height :45px;
width: 200px;
}
*/
#ruzhu
{
width : 90px;
margin-left: auto;
margin-right: auto;
margin-top: 15%;
}
#mask
{
background-color: #4d7b95;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
</style>
</head>
<body >
<div id="mask" hidden=true></div>
<?php
// define variables and set to empty values
$shopName = $map = $passCode = $checkCode = $seryCode = $shopAddress = $mainService = "";
$exist1=false;
$exist2=false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$shopName = test_input($_POST["shopName"]);
$map = test_input($_POST["site"]);
$passCode = test_input($_POST["passCode"]);
$checkCode = test_input($_POST["checkCode"]);
$seryCode = test_input($_POST["seryCode"]);
$shopAddress = test_input($_POST["shopAddress"]);
$mainService = test_input($_POST["mainService"]);
}
if($shopName!="")
{
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from sjtuShop where shopName = '$shopName'";
$result = $link->query($query);
$query = "select * from sjtuShop where seryCode = '$seryCode'";
$result1 = $link->query($query);
if($result->fetch_assoc())
{
$exist1=true;
}
if($result1->fetch_assoc())
{
$exist2=true;
}
if(!$exist1&&!$exist2)
{
$query = "insert into sjtuShop(shopName,passCode,seryCode,shopAddress,mainService,level)
values('$shopName','$passCode','$seryCode','$shopAddress','$mainService',1)";
if($link->query($query) == TRUE) {
$query = "select * from sjtuShop where shopName = '$shopName'";
$result = $link->query($query);
$row = $result->fetch_assoc();
$_SESSION["shopId"] = $row["ID"];
$idNum = $row["ID"];
$_SESSION['map'] = "sjtuShop";
$query = "insert into sjtuShopEventInfo(shopName, eventMessage, eventDetail, eventCoordinateX, eventCoordinateY, shopId, level)
values('$shopName', ' ', ' ', '-1', '-1', '$idNum', '2');";
if(!$link->query($query))
echo $query;
/* if($link->query($query) == TRUE) {
$query = "select * from sjtuShop where shopName = '$shopName'";
$result = $link->query($query);
$row = $result->fetch_assoc();
$_SESSION["shopId"] = $row["ID"];
$_SESSION['map'] = "sjtuShop";*/
echo "<script type=\"text/javascript\" > location.assign('shopMain.php') </script>";
}
else{
echo "failed!!!";
}
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<body >
<div id = "title" >入驻<br/>去逛街
</div>
<form id ="register" action="shopRegister.php" method="post">
<p class = "inputing">您的店名*: <input class = "box" type="text" name="shopName" value = "<?php echo $shopName ?>" /><b class = "prompt"><?php if($exist1) echo "这家店已经注册了" ?></b></p>
<p class = "inputing">您的位置*:
<select class = "box" name="site" >
<option value="null" selected="selected">请选择地图</option>
<option value="sjtuShop">上海交通大学闵行校区</option>
</select><b class = "prompt"></b></p>
<p class = "inputing">您的密码*: <input id = "passcode" class = "box" type="password" name="passCode" value = "<?php echo $passCode ?>" onblur = "checkPasscode()"/><b class = "prompt"></b></p>
<p class = "inputing">重复密码*: <input id = "confirming" class = "box" type="password" name="checkCode" value = "<?php echo $checkCode ?>" onblur = "checkConfirming()"/><b class = "prompt""></b></p>
<p class = "inputing">执照编码*: <input class = "box" type="text" name="seryCode" value = "<?php echo $seryCode ?>" /><b class = "prompt"><?php if($exist2) echo "这家店已经注册了" ?></b></p>
<p class = "inputing">商铺地址: <input class = "longBox" type="text" name="shopAddress" value = "<?php echo $shopAddress ?>" /><b class = "prompt"></b></p>
<p class = "inputing">主要业务(以空格分隔): <input class = "longBox" type="text" name="mainService" value = "<?php echo $mainService ?>" /><b class = "prompt"></b></p>
<br />
</form>
<p>*项不能为空</p>
<button type="button" onclick = "trySubmit()">入驻</button>
<script type="text/javascript">
/*
function checkPasscode()
{
var passcode = document.getElementById("passcode");
if(passcode.value.length<5)
{
passcode.focus();
var a=document.getElementById("a2");
a.textContent = "密码应长于5位";
}
}*/
function trySubmit()
{
var boxing = document.getElementsByClassName("box");
var flag=true;
for(var i=0; i<boxing.length;++i)
{
if(boxing[i].value.length==0) {boxing[i].nextElementSibling.textContent = "此项不能为空"; flag=false;}
else boxing[i].nextElementSibling.textContent = "";
}
if(boxing[1].value=="null")
{
boxing[1].nextElementSibling.textContent = "此项不能为空";
flag=false;
}
else boxing[1].nextElementSibling.textContent = "";
if(boxing[2].value!=boxing[3].value)
{
boxing[3].nextElementSibling.textContent = "和之前输入的不同哦";
flag = false;
}
if(flag)
{
jumping();
}
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("title");
title.style.fontSize = length/8+"px";
var inputing = document.getElementsByClassName("inputing");
for(var i=0; i<inputing.length;++i)
{
inputing[i].style.fontSize = length/25+"px";
}
var prompting = document.getElementsByClassName("prompt");
for(var i=0; i<prompting.length;++i)
{
prompting[i].style.fontSize = length/40+"px";
}
var box = document.getElementsByClassName("box");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/4+"px";
box[i].style.height = height/21+"px";
box[i].style.fontSize = height/28+"px";
}
box = document.getElementsByClassName("longBox");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/2+"px";
box[i].style.height = height/21+"px";
box[i].style.fontSize = height/28+"px";
}
var alpha=0;
function jumping()
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("document.getElementById('register').submit();",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
</script>
</body>
</html>
<file_sep><!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport" charset = utf-8>
<style type="text/css">
#title
{
font-family: 黑体, serif;
font-size : 25px;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
body
{
font-family: 黑体, serif;
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
form
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
p
{
font-size: 1.5em;
}
.box
{
height :20px;
width: 200px
}
#ruzhu
{
width : auto;
margin-left: auto;
margin-right: auto;
margin-top: 15%;
}
#mask
{
background-color: #4d7b95 ;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
</style>
<body >
<div id="mask" hidden=true></div>
<?php
// define variables and set to empty values
$cellNum = $passCode ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$cellNum = test_input($_POST["cellNum"]);
$passCode = test_input($_POST["passCode"]);
}
$nameExist = true;
$codeCorrect = true;
$link = new mysqli("localhost","root","12345","quguangjie");
if($cellNum!="")
{
$query = "select * from User where cellnumber = '$cellNum'";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
echo "<h1>" . $row['passcode'] . "</h1>";
if($row['passcode']!=$passCode)
{
$codeCorrect = false;
}
else
{
$_SESSION['userId']=$row['number'];
if(!isset($_SESSION['fromShopId']))
echo "<script type=\"text/javascript\" > location.assign('userMain.php') </script>";
else
{
$fromOK="true";
}
}
}
else{
$nameExist = false;
}
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id = "title" >登录<br/>去逛街
</div>
<form id = "logIn" action="visitorLogin.php" method="post">
<p class = "inputing">手机号码: <input class = "box" type="text" name="cellNum" value = "<?php echo $cellNum ?>"/><b class = "prompt"><?php if(!$nameExist) echo "未注册的号码" ?></b></b></p>
<p class = "inputing">您的密码: <input class = "box" type="password" name="passCode" value = "<?php echo $passCode ?>" /><b class = "prompt"><?php if(!$codeCorrect) echo "密码输错了呢" ?></b></b></p>
</form>
<button type="button" onclick = "trySubmit()">登录</button>
<form id="from" action="viewShop.php" method="post" hidden=true>
<input type="text" name="shopId" value="<?php if(isset($fromOK)) echo $_SESSION['fromShopId']; ?>"></input>
<input type="text" name="mapName" value="<?php if(isset($fromOK)) echo $_SESSION['frommapName']; ?>"></input>
</form>
<script type="text/javascript">
function trySubmit()
{
var boxing = document.getElementsByClassName("box");
var flag=true;
for(var i=0; i<boxing.length;++i)
{
if(boxing[i].value.length==0) {boxing[i].nextElementSibling.textContent = "此项不能为空"; flag=false;}
else boxing[i].nextElementSibling.textContent = "";
}
if(flag)
{
jumping();
//document.getElementById("logIn").submit();
}
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("title");
title.style.fontSize = length/8+"px";
var inputing = document.getElementsByClassName("inputing");
for(var i=0; i<inputing.length;++i)
{
inputing[i].style.fontSize = length/25+"px";
}
var box = document.getElementsByClassName("box");
for(var i=0; i<box.length;++i)
{
box[i].style.width = length/4+"px";
}
var prompting = document.getElementsByClassName("prompt");
for(var i=0; i<prompting.length;++i)
{
prompting[i].style.fontSize = length/40+"px";
}
var alpha=0;
function jumping()
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("document.getElementById('logIn').submit();",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
<?php if(isset($fromOK))
{
unset($_SESSION['fromShopId']);
unset($_SESSION['frommapName']);
unset($fromOK);
echo "document.getElementById(\"from\").submit();";
}
?>
</script>
</body>
</html>
<file_sep>//************************************************************************
//POL is a file type difined by polarskie, which is aimed at finding a bridge between obj file and WebGL. To use this file and //the converting exporter in any conversial field involves RIGHT problem, please contact polarskie before you or your team use //them for any purpose except for learning, also when you have any question or Improvement.
//Email: <EMAIL>
var MACROnearest = 0.1;
var MACROfarest = 1000;
var MACROangle = 15;
var gl;
var specialGl;
var shaderProgram = new Array();
var lastTime;
function initGL(canvas, specialCanvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
gl.widthDivHeight = canvas.width/canvas.height;
} catch (e) {
}
if (!gl) {
alert("Could not initialise WebGL, sorry :-(");
}
specialGl = specialCanvas.getContext("2d");
polCameraArray.push(new polCameraObject());
polCameraArray[0].enable=true;
for(var i in keyPressed)
{
keyPressed[i]=false;
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function appendShader(fs, vs, type)
{
if(type==97) //cartoon shader
{
var fragmentShader = getShader(gl, fs);
var vertexShader = getShader(gl, vs);
var index = shaderProgram.length;
shaderProgram.push(gl.createProgram());
shaderProgram[index].type = type;
gl.attachShader(shaderProgram[index], fragmentShader);
gl.attachShader(shaderProgram[index], vertexShader);
gl.linkProgram(shaderProgram[index]);
if (!gl.getProgramParameter(shaderProgram[index], gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram[index]);
shaderProgram[index].vertexPositionAttribute = gl.getAttribLocation(shaderProgram[index], "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram[index].vertexPositionAttribute);
shaderProgram[index].textureCoordAttribute = gl.getAttribLocation(shaderProgram[index], "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram[index].textureCoordAttribute);
shaderProgram[index].vertexNormalAttribute = gl.getAttribLocation(shaderProgram[index], "aVertexNormal");
gl.enableVertexAttribArray(shaderProgram[index].vertexNormalAttribute);
shaderProgram[index].pMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uPMatrix");
shaderProgram[index].mvMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uMVMatrix");
shaderProgram[index].nMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uNMatrix"); //matrix for stroking
}
else
{
var fragmentShader = getShader(gl, fs);
var vertexShader = getShader(gl, vs);
var index = shaderProgram.length;
shaderProgram.push(gl.createProgram());
shaderProgram[index].type = type;
gl.attachShader(shaderProgram[index], fragmentShader);
gl.attachShader(shaderProgram[index], vertexShader);
gl.linkProgram(shaderProgram[index]);
if (!gl.getProgramParameter(shaderProgram[index], gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram[index]);
shaderProgram[index].vertexPositionAttribute = gl.getAttribLocation(shaderProgram[index], "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram[index].vertexPositionAttribute);
shaderProgram[index].textureCoordAttribute = gl.getAttribLocation(shaderProgram[index], "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram[index].textureCoordAttribute);
shaderProgram[index].vertexNormalAttribute = gl.getAttribLocation(shaderProgram[index], "aVertexNormal");
gl.enableVertexAttribArray(shaderProgram[index].vertexNormalAttribute);
if(type%3==0) //texture or colour
{
shaderProgram[index].samplerUniform = gl.getUniformLocation(shaderProgram[index], "uSampler");
}
else
{
shaderProgram[index].colorUniform = gl.getUniformLocation(shaderProgram[index], "uColor");
}
if(type%2==0) //lighting
{
shaderProgram[index].nMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uNMatrix");
shaderProgram[index].useLightingUniform = gl.getUniformLocation(shaderProgram[index], "uUseLighting");
shaderProgram[index].ambientColorUniform = gl.getUniformLocation(shaderProgram[index], "uAmbientColor");
shaderProgram[index].lightAssistUniform = gl.getUniformLocation(shaderProgram[index], "uLightAssist");
shaderProgram[index].lightColorUniform = gl.getUniformLocation(shaderProgram[index], "uLightColor");
shaderProgram[index].lightStyleUniform = gl.getUniformLocation(shaderProgram[index], "uLightStyle");
shaderProgram[index].lightNumUniform = gl.getUniformLocation(shaderProgram[index], "uLightNum");
if(type%16==0)
{
//the shader is supposed to be shadering the shadow by shadow mapping
}
}
if(type%5==0) //the shader is one that render out a transparent mesh
{
shaderProgram[index].alphaUniform = gl.getUniformLocation(shaderProgram[index], "uAlpha");
}
shaderProgram[index].pMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uPMatrix");
shaderProgram[index].mvMatrixUniform = gl.getUniformLocation(shaderProgram[index], "uMVMatrix");
}
return shaderProgram.length-1;
}
var mvMatrix;
var pMatrix;
function drawPol(polObjIndex, shaderIndex)
{
gl.useProgram(shaderProgram[shaderIndex]);
//attributes
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram[shaderIndex].vertexPositionAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].normalDirectionBuffer);
gl.vertexAttribPointer(shaderProgram[shaderIndex].vertexNormalAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].normalDirectionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].textureCoordBuffer);
gl.vertexAttribPointer(shaderProgram[shaderIndex].textureCoordAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].textureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
//special shader ------- cartoon shader
if(shaderProgram[shaderIndex].type==97)
{
gl.cullFace(gl.FRONT);
gl.enable(gl.CULL_FACE);
gl.uniformMatrix4fv(shaderProgram[shaderIndex].pMatrixUniform, false, polCameraArray[polCameraArray.tempCam].pMatrix.toArray());
var finalMvMatrix = polCameraArray[polCameraArray.tempCam].rotMatrix.mul(polCameraArray[polCameraArray.tempCam].posMatrix.mul(polObjArray[polObjIndex].transformMatrix.mat));
gl.uniformMatrix4fv(shaderProgram[shaderIndex].mvMatrixUniform, false,
finalMvMatrix.toArray());
var finalNMatrix = polCameraArray[polCameraArray.tempCam].rotMatrix.mul(polObjArray[polObjIndex].transformMatrix.rotateMat);
gl.uniformMatrix4fv(shaderProgram[shaderIndex].nMatrixUniform, false,
finalNMatrix.toArray());
for(var i=0;i<polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryNum;++i)
{
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i]);
gl.drawElements(gl.TRIANGLES, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i].numItems, gl.UNSIGNED_SHORT, 0);
}
gl.cullFace(gl.BACK);
gl.disable(gl.CULL_FACE);
for(var j in polObjArray[polObjIndex].secondShader) drawPol(polObjIndex, polObjArray[polObjIndex].secondShader[j]);
return 0;
}
//lighting shader
if(shaderProgram[shaderIndex].type%2==0)
{
gl.uniform1i(shaderProgram[shaderIndex].useLightingUniform, 1);
gl.uniform3f(
shaderProgram[shaderIndex].ambientColorUniform,
polObjArray[polObjIndex].ambientColor[0],
polObjArray[polObjIndex].ambientColor[1],
polObjArray[polObjIndex].ambientColor[2]
);
gl.uniform3fv(shaderProgram[shaderIndex].lightAssistUniform, polObjArray[polObjIndex].lightAssist);
gl.uniform3fv(
shaderProgram[shaderIndex].lightColorUniform,
polObjArray[polObjIndex].lightColor
);
gl.uniform1iv(
shaderProgram[shaderIndex].lightStyleUniform,
polObjArray[polObjIndex].lightStyle
);
gl.uniform1i(shaderProgram[shaderIndex].lightNumUniform, polObjArray[polObjIndex].lightNum);
}
//blending shader
if(shaderProgram[shaderIndex].type%5==0)
{
gl.uniform1f(shaderProgram[shaderIndex].alphaUniform, 0.5);
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
}
else
{
gl.enable(gl.DEPTH_TEST);
gl.disable(gl.BLEND);
}
//matrixes setting
gl.uniformMatrix4fv(shaderProgram[shaderIndex].pMatrixUniform, false, polCameraArray[polCameraArray.tempCam].pMatrix.toArray());
var finalMvMatrix = polCameraArray[polCameraArray.tempCam].rotMatrix.mul(polCameraArray[polCameraArray.tempCam].posMatrix.mul(polObjArray[polObjIndex].transformMatrix.mat));
gl.uniformMatrix4fv(shaderProgram[shaderIndex].mvMatrixUniform, false,
finalMvMatrix.toArray());
if(shaderProgram[shaderIndex].type%2==0)
{
var finalNMatrix = polCameraArray[polCameraArray.tempCam].rotMatrix.mul(polObjArray[polObjIndex].transformMatrix.rotateMat);
gl.uniformMatrix4fv(shaderProgram[shaderIndex].nMatrixUniform, false, finalNMatrix.toArray());
if(shaderProgram[shaderIndex].type%16==0)
{
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, polShadowFrameTexbuffer);
}
}
//geometry drawing
for(var i=0;i<polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryNum;++i)
{
//geometry color or texture coords
if(shaderProgram[shaderIndex].type%3!=0)
{
gl.uniform3f(shaderProgram[shaderIndex].colorUniform, polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryColor[i][0], polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryColor[i][1], polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryColor[i][2]);
}
else
{
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, polMeshArray[polObjArray[polObjIndex].polMeshIndex].polTexture[i]);
gl.uniform1i(shaderProgram[shaderIndex].samplerUniform, 1);
}
//indexes
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i]);
//drawElements
gl.drawElements(gl.TRIANGLES, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i].numItems, gl.UNSIGNED_SHORT, 0);
}
//document.write(polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryNum);
}
<file_sep>
<!DOCTYPE html>
<html>
<head>
<link src="quguangjie.index.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="mask" hidden=true>
</div>
<div text-align = "center" class="title" id="quGuangJie">选地图<br/>去逛街!</div>
<form hidden='true' id='form' method="post">
<input name="mapId"></input>
</form>
<?php
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from Map order by name";
$result = $link->query($query);
while($row = $result->fetch_assoc())
{
echo "<div class = \"selection\" onclick = \"jumping('" . $row['number'] . "')\">" . $row['name'] . "</div>";
}
?>
<script type="text/javascript">
var alpha=0;
function jumping(p)
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("loadMap(" + p + ");",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
function loadMap(p)
{
var form = document.getElementById("form");
form.action = "svgmaps/" + p + ".php";
form.children[0].value = p;
form.submit();
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("quGuangJie");
title.style.fontSize = length/8+"px";
</script>
</body>
</html><file_sep>//************************************************************************
//POL is a file type difined by polarskie, which is aimed at finding a bridge between obj file and WebGL. To use this file and //the converting exporter in any conversial field involves RIGHT problem, please contact polarskie before you or your team use //them for any purpose except for learning, also when you have any question or improvement.
//Email: <EMAIL>
function Vector(ax,ay,az)
{
if(arguments.length<3)
{
ax=0,ay=0,az=0;
}
this.x=ax;
this.y=ay;
this.z=az;
}
Vector.prototype.absolute = function()
{
return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);
}
Vector.prototype.normalize = function()
{
if(this.x==0&&this.y==0&&this.z==0) return 0;
var absolute = this.absolute();
this.x/=absolute;
this.y/=absolute;
this.z/=absolute;
}
Vector.prototype.dot = function(another)
{
return this.x*another.x+this.y*another.y+this.z+another.z;
}
Vector.prototype.cross = function(another)
{
var out = new Vector();
out.x=this.y*another.z-this.z*another.y;
out.y=this.z*another.x-this.x*another.z;
out.z=this.x*another.y-this.y*another.x;
return out;
}
function Matrix()
{
this.m11=1.0;
this.m22=1.0;
this.m33=1.0;
this.m44=1.0;
this.m12=0.0;
this.m13=0.0;
this.m14=0.0;
this.m21=0.0;
this.m23=0.0;
this.m24=0.0;
this.m31=0.0;
this.m32=0.0;
this.m34=0.0;
this.m41=0.0;
this.m42=0.0;
this.m43=0.0;
}
//var newObj = oldObj.copy();
Matrix.prototype.copy = function()
{
var temp = new Matrix();
temp.m11=this.m11;
temp.m12=this.m12;
temp.m13=this.m13;
temp.m14=this.m14;
temp.m21=this.m21;
temp.m22=this.m22;
temp.m23=this.m23;
temp.m24=this.m24;
temp.m31=this.m31;
temp.m32=this.m32;
temp.m33=this.m33;
temp.m34=this.m34;
temp.m41=this.m41;
temp.m42=this.m42;
temp.m43=this.m43;
temp.m44=this.m44;
return temp;
}
Matrix.prototype.mul = function(another)
{
var product = new Matrix();
product.m11=this.m11*another.m11+this.m12*another.m21+this.m13*another.m31+this.m14*another.m41;
product.m12=this.m11*another.m12+this.m12*another.m22+this.m13*another.m32+this.m14*another.m42;
product.m13=this.m11*another.m13+this.m12*another.m23+this.m13*another.m33+this.m14*another.m43;
product.m14=this.m11*another.m14+this.m12*another.m24+this.m13*another.m34+this.m14*another.m44;
product.m21=this.m21*another.m11+this.m22*another.m21+this.m23*another.m31+this.m24*another.m41;
product.m22=this.m21*another.m12+this.m22*another.m22+this.m23*another.m32+this.m24*another.m42;
product.m23=this.m21*another.m13+this.m22*another.m23+this.m23*another.m33+this.m24*another.m43;
product.m24=this.m21*another.m14+this.m22*another.m24+this.m23*another.m34+this.m24*another.m44;
product.m31=this.m31*another.m11+this.m32*another.m21+this.m33*another.m31+this.m34*another.m41;
product.m32=this.m31*another.m12+this.m32*another.m22+this.m33*another.m32+this.m34*another.m42;
product.m33=this.m31*another.m13+this.m32*another.m23+this.m33*another.m33+this.m34*another.m43;
product.m34=this.m31*another.m14+this.m32*another.m24+this.m33*another.m34+this.m34*another.m44;
product.m41=this.m41*another.m11+this.m42*another.m21+this.m43*another.m31+this.m44*another.m41;
product.m42=this.m41*another.m12+this.m42*another.m22+this.m43*another.m32+this.m44*another.m42;
product.m43=this.m41*another.m13+this.m42*another.m23+this.m43*another.m33+this.m44*another.m43;
product.m44=this.m41*another.m14+this.m42*another.m24+this.m43*another.m34+this.m44*another.m44;
return product;
}
Matrix.prototype.toArray = function()
{
return Array(this.m11, this.m21, this.m31, this.m41,
this.m12, this.m22, this.m32, this.m42,
this.m13, this.m23, this.m33, this.m43,
this.m14, this.m24, this.m34, this.m44);
}
/*no minus, transposed
Matrix.prototype.inverse = function()
{
var adjoint=new Matrix();
adjoint.m11=this.m22*(this.m33*this.m44-this.m34*this.m43)
-this.m23*(this.m32*this.m44-this.m34*this.m42)
+this.m24*(this.m32*this.m43-this.m33*this.m42);
adjoint.m21=this.m21*(this.m33*this.m44-this.m34*this.m43)
-this.m23*(this.m31*this.m44-this.m34*this.m41)
+this.m24*(this.m31*this.m43-this.m33*this.m41);
adjoint.m31=-this.m22*(this.m31*this.m44-this.m34*this.m41)
+this.m21*(this.m32*this.m44-this.m34*this.m42)
-this.m24*(this.m32*this.m41-this.m31*this.m42);
adjoint.m41=this.m22*(this.m33*this.m41-this.m31*this.m43)
-this.m23*(this.m32*this.m41-this.m31*this.m42)
+this.m21*(this.m32*this.m43-this.m33*this.m42);
adjoint.m12=this.m12*(this.m33*this.m44-this.m34*this.m43)
-this.m13*(this.m32*this.m44-this.m34*this.m42)
+this.m14*(this.m32*this.m43-this.m33*this.m42);
adjoint.m22=this.m11*(this.m33*this.m44-this.m34*this.m43)
-this.m13*(this.m31*this.m44-this.m34*this.m41)
+this.m14*(this.m31*this.m43-this.m33*this.m41);
adjoint.m32=-this.m12*(this.m31*this.m44-this.m34*this.m41)
+this.m11*(this.m32*this.m44-this.m34*this.m42)
-this.m14*(this.m32*this.m41-this.m31*this.m42);
adjoint.m42=this.m12*(this.m33*this.m41-this.m31*this.m43)
-this.m13*(this.m32*this.m41-this.m31*this.m42)
+this.m11*(this.m32*this.m43-this.m33*this.m42);
adjoint.m13=-this.m22*(this.m13*this.m44-this.m14*this.m43)
+this.m23*(this.m12*this.m44-this.m14*this.m42)
-this.m24*(this.m12*this.m43-this.m13*this.m42);
adjoint.m23=-this.m21*(this.m13*this.m44-this.m14*this.m43)
+this.m23*(this.m11*this.m44-this.m14*this.m41)
-this.m24*(this.m11*this.m43-this.m13*this.m41);
adjoint.m33=this.m22*(this.m11*this.m44-this.m14*this.m41)
-this.m21*(this.m12*this.m44-this.m14*this.m42)
+this.m24*(this.m12*this.m41-this.m11*this.m42);
adjoint.m43=-this.m22*(this.m13*this.m41-this.m11*this.m43)
+this.m23*(this.m12*this.m41-this.m11*this.m42)
-this.m21*(this.m12*this.m43-this.m13*this.m42);
adjoint.m14=this.m22*(this.m33*this.m14-this.m34*this.m13)
-this.m23*(this.m32*this.m14-this.m34*this.m12)
+this.m24*(this.m32*this.m13-this.m33*this.m12);
adjoint.m24=this.m21*(this.m33*this.m44-this.m34*this.m43)
-this.m23*(this.m31*this.m44-this.m34*this.m41)
+this.m24*(this.m31*this.m43-this.m33*this.m41);
adjoint.m34=-this.m22*(this.m31*this.m44-this.m34*this.m41)
+this.m21*(this.m32*this.m44-this.m34*this.m42)
-this.m24*(this.m32*this.m41-this.m31*this.m42);
adjoint.m44=this.m22*(this.m33*this.m41-this.m31*this.m43)
-this.m23*(this.m32*this.m41-this.m31*this.m42)
+this.m21*(this.m32*this.m43-this.m33*this.m42);
}
*/
Matrix.prototype.inverse = function()
{
var adjoint=new Matrix();
adjoint.m11=this.m22*(this.m33*this.m44-this.m34*this.m43)
-this.m23*(this.m32*this.m44-this.m34*this.m42)
+this.m24*(this.m32*this.m43-this.m33*this.m42);
adjoint.m21=-this.m12*(this.m33*this.m44-this.m34*this.m43)
+this.m13*(this.m32*this.m44-this.m34*this.m42)
-this.m14*(this.m32*this.m43-this.m33*this.m42);
adjoint.m31=this.m12*(this.m23*this.m44-this.m24*this.m43)
-this.m13*(this.m22*this.m44-this.m24*this.m42)
+this.m14*(this.m22*this.m43-this.m23*this.m42);
adjoint.m41=-this.m12*(this.m23*this.m34-this.m24*this.m33)
+this.m13*(this.m22*this.m34-this.m24*this.m32)
-this.m14*(this.m22*this.m33-this.m23*this.m32);
adjoint.m12=-this.m21*(this.m33*this.m44-this.m34*this.m43)
+this.m23*(this.m31*this.m44-this.m34*this.m41)
-this.m24*(this.m31*this.m43-this.m33*this.m41);
adjoint.m22=this.m11*(this.m33*this.m44-this.m34*this.m43)
-this.m13*(this.m31*this.m44-this.m34*this.m41)
+this.m14*(this.m31*this.m43-this.m33*this.m41);
adjoint.m32=-this.m11*(this.m23*this.m44-this.m24*this.m43)
+this.m13*(this.m21*this.m44-this.m24*this.m41)
-this.m14*(this.m21*this.m43-this.m23*this.m41);
adjoint.m42=this.m11*(this.m23*this.m34-this.m24*this.m33)
-this.m13*(this.m21*this.m34-this.m24*this.m31)
+this.m14*(this.m21*this.m33-this.m23*this.m31);
adjoint.m13=this.m21*(this.m32*this.m44-this.m34*this.m42)
-this.m22*(this.m31*this.m44-this.m34*this.m41)
+this.m24*(this.m31*this.m42-this.m32*this.m41);
adjoint.m23=-this.m11*(this.m32*this.m44-this.m34*this.m42)
+this.m12*(this.m31*this.m44-this.m34*this.m41)
-this.m14*(this.m31*this.m42-this.m32*this.m41);
adjoint.m33=this.m11*(this.m22*this.m44-this.m24*this.m42)
-this.m12*(this.m21*this.m44-this.m24*this.m41)
+this.m14*(this.m21*this.m42-this.m22*this.m41);
adjoint.m43=-this.m11*(this.m22*this.m34-this.m24*this.m32)
+this.m12*(this.m21*this.m34-this.m24*this.m31)
-this.m14*(this.m21*this.m32-this.m22*this.m31);
adjoint.m14=-this.m21*(this.m32*this.m43-this.m33*this.m42)
+this.m22*(this.m31*this.m43-this.m33*this.m41)
-this.m23*(this.m31*this.m42-this.m32*this.m41);
adjoint.m24=this.m11*(this.m32*this.m43-this.m33*this.m42)
-this.m12*(this.m31*this.m43-this.m33*this.m41)
+this.m13*(this.m31*this.m42-this.m32*this.m41);
adjoint.m34=-this.m11*(this.m22*this.m43-this.m23*this.m42)
+this.m12*(this.m21*this.m43-this.m23*this.m41)
-this.m13*(this.m21*this.m42-this.m22*this.m41);
adjoint.m44=this.m11*(this.m22*this.m33-this.m23*this.m32)
-this.m12*(this.m21*this.m33-this.m23*this.m31)
+this.m13*(this.m21*this.m32-this.m22*this.m31);
var truth=this.m11*adjoint.m11+this.m12*adjoint.m12+this.m13*adjoint.m13+this.m14*adjoint.m14;
adjoint.m11/=truth;
adjoint.m12/=truth;
adjoint.m13/=truth;
adjoint.m14/=truth;
adjoint.m21/=truth;
adjoint.m22/=truth;
adjoint.m23/=truth;
adjoint.m24/=truth;
adjoint.m31/=truth;
adjoint.m32/=truth;
adjoint.m33/=truth;
adjoint.m34/=truth;
adjoint.m41/=truth;
adjoint.m42/=truth;
adjoint.m43/=truth;
adjoint.m44/=truth;
adjoint=adjoint.transpose();
return adjoint;
}
Matrix.prototype.transpose = function()
{
var temp = new Matrix();
temp.m11=this.m11;
temp.m12=this.m21;
temp.m13=this.m31;
temp.m14=this.m41;
temp.m21=this.m12;
temp.m22=this.m22;
temp.m23=this.m32;
temp.m24=this.m42;
temp.m31=this.m13;
temp.m32=this.m23;
temp.m33=this.m33;
temp.m34=this.m43;
temp.m41=this.m14;
temp.m42=this.m24;
temp.m43=this.m34;
temp.m44=this.m44;
return temp;
}
function polMat()
{
this.px=0;
this.py=0;
this.pz=0;
this.sx=1;
this.sy=1;
this.sz=1;
this.mat=new Matrix();
this.rotateMat=new Matrix();
}
polMat.prototype.copy = function(copy)
{
var temp = new polMat();
temp.mat = this.mat.copy();
temp.rotateMat = this.rotateMat.copy();
temp.px = this.px;
temp.py = this.py;
temp.pz = this.pz;
temp.sx = this.sx;
temp.sy = this.sy;
temp.sz = this.sz;
return temp;
}
//Pay attention that it is multiplied on the left side because the WebGL use column vector
polMat.prototype.append = function(another)
{
this.px+=another.px;
this.py+=another.py;
this.pz+=another.pz;
this.sx*=another.sx;
this.sy*=another.sy;
this.sz*=another.sz;
this.mat=another.mat.mul(this.mat);
this.rotateMat=another.rotateMat.mul(this.rotateMat);
}
polMat.prototype.toArray = function()
{
var array = [this.mat.m11, this.mat.m21, this.mat.m31, this.mat.m41,
this.mat.m12, this.mat.m22, this.mat.m32, this.mat.m42,
this.mat.m13, this.mat.m23, this.mat.m33, this.mat.m43,
this.mat.m14, this.mat.m24, this.mat.m34, this.mat.m44];
return array;
}
/*
polMat.prototype.copy(copie)
{
this.m11=copie.m11;
this.m22=copie.m22;
this.m33=copie.m33;
this.m44=copie.m44;
this.m12=copie.m12;
this.m13=copie.m13;
this.m14=copie.m14;
this.m21=copie.m21;
this.m23=copie.m23;
this.m24=copie.m24;
this.m31=copie.m31;
this.m32=copie.m32;
this.m34=copie.m34;
this.m41=copie.m41;
this.m42=copie.m42;
this.m43=copie.m43;
this.px=copie.px;
this.py=copie.py;
this.pz=copie.pz;
}
*/
polMat.prototype.translateBy = function(bx, by, bz)
{
var temp = new Matrix();
temp.m14=bx;
temp.m24=by;
temp.m34=bz;
this.px+=bx;
this.py+=by;
this.pz+=bz;
this.mat=temp.mul(this.mat)
}
polMat.prototype.translateTo = function(tx, ty, tz)
{
var temp = new Matrix();
temp.m14=tx-this.px;
temp.m24=ty-this.py;
temp.m34=tz-this.pz;
this.px=tx;
this.py=ty;
this.pz=tz;
this.mat=temp.mul(this.mat)
}
//right handed
polMat.prototype.rotateXBy = function(rad)
{
this.mat=new Matrix();
this.mat.m11=this.sx;
this.mat.m22=this.sy;
this.mat.m33=this.sz;
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m22=rc;
temp.m33=rc;
temp.m32=rs;
temp.m23=-rs;
this.rotateMat=temp.mul(this.rotateMat);
this.mat=this.rotateMat.mul(this.mat);
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=tempp.mul(this.mat);
}
polMat.prototype.rotateYBy = function(rad)
{
this.mat=new Matrix();
this.mat.m11=this.sx;
this.mat.m22=this.sy;
this.mat.m33=this.sz;
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m11=rc;
temp.m33=rc;
temp.m31=-rs;
temp.m13=rs;
this.rotateMat=temp.mul(this.rotateMat);
this.mat=this.rotateMat.mul(this.mat);
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=tempp.mul(this.mat);
}
polMat.prototype.rotateZBy = function(rad)
{
this.mat=new Matrix();
this.mat.m11=this.sx;
this.mat.m22=this.sy;
this.mat.m33=this.sz;
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m22=rc;
temp.m11=rc;
temp.m12=-rs;
temp.m21=rs;
this.rotateMat=temp.mul(this.rotateMat);
this.mat=this.rotateMat.mul(this.mat);
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=tempp.mul(this.mat);
}
polMat.prototype.rotateAxisBy = function(rx,ry,rz,rad)
{
this.mat=new Matrix();
this.mat.m11=this.sx;
this.mat.m22=this.sy;
this.mat.m33=this.sz;
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m11=rc+(1-rc)*rx*rx;
temp.m12=(1-rc)*rx*ry-rz*rs;
temp.m13=(1-rc)*rx*rz+ry*rs;
temp.m21=(1-rc)*rx*ry+rz*rs;
temp.m22=rc+(1-rc)*ry*ry;
temp.m23=(1-rc)*ry*rz-rx*rs;
temp.m31=(1-rc)*rx*rz-ry*rs;
temp.m32=(1-rc)*ry*rz+rx*rs;
temp.m33=rc+(1-rc)*rz*rz;
this.rotateMat=temp.mul(this.rotateMat);
this.mat=this.rotateMat.mul(this.mat);
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=tempp.mul(this.mat);
}
//this is supposed to be called by camera.
polMat.prototype.worldRotateAxisByCam = function(rx,ry,rz,rad)
{
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m11=rc+(1-rc)*rx*rx;
temp.m12=(1-rc)*rx*ry-rz*rs;
temp.m13=(1-rc)*rx*rz+ry*rs;
temp.m21=(1-rc)*rx*ry+rz*rs;
temp.m22=rc+(1-rc)*ry*ry;
temp.m23=(1-rc)*ry*rz-rx*rs;
temp.m31=(1-rc)*rx*rz-ry*rs;
temp.m32=(1-rc)*ry*rz+rx*rs;
temp.m33=rc+(1-rc)*rz*rz;
this.mat=temp.mul(this.mat);
}
polMat.prototype.rotateAxisTo = function(rx,ry,rz,rad)
{
this.mat=new Matrix();
this.mat.m11=this.sx;
this.mat.m22=this.sy;
this.mat.m33=this.sz;
var temp=new Matrix();
var rc=Math.cos(rad);
var rs=Math.sin(rad);
temp.m11=rc+(1-rc)*rx*rx;
temp.m12=(1-rc)*rx*ry-rz*rs;
temp.m13=(1-rc)*rx*rz+ry*rs;
temp.m21=(1-rc)*rx*ry+rz*rs;
temp.m22=rc+(1-rc)*ry*ry;
temp.m23=(1-rc)*ry*rz-rx*rs;
temp.m31=(1-rc)*rx*rz-ry*rs;
temp.m32=(1-rc)*ry*rz+rx*rs;
temp.m33=rc+(1-rc)*rz*rz;
this.rotateMat=temp.copy();
this.mat=temp.mul(this.mat);
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=tempp.mul(this.mat);
}
polMat.prototype.resizeBy = function(bx,by,bz)
{
var temp = new Matrix();
this.sx*=bx;
this.sy*=by;
this.sz*=bz;
temp.m11=this.sx;
temp.m22=this.sy;
temp.m33=this.sz;
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=this.rotateMat.mul(temp);
this.mat=tempp.mul(this.mat);
}
polMat.prototype.resizeTo = function(tx,ty,tz)
{
var temp = new Matrix();
this.sx=tx;
this.sy=ty;
this.sz=tz;
temp.m11=tx;
temp.m22=ty;
temp.m33=tz;
var tempp = new Matrix();
tempp.m14=this.px;
tempp.m24=this.py;
tempp.m34=this.pz;
this.mat=this.rotateMat.mul(temp);
this.mat=tempp.mul(this.mat);
}
function matProject(c,k,h,i)
{
var f=c*Math.PI/180;
var a=i-h;
var e=Math.cos(f)/Math.sin(f);
var d=new Matrix();
d.m11=e/k;
d.m22=e;
d.m33=-(i+h)/a;
d.m43=-1;
d.m34=-2*h*i/a;
d.m44=0;
return d;
}
//优化空间!!!!
function matInterpolation(proportion,matA,matB)
{
var temp=new polMat();
aProportion=1-proportion;
temp.px=matA.px*proportion+matB.px*aProportion;
temp.py=matA.py*proportion+matB.py*aProportion;
temp.pz=matA.pz*proportion+matB.pz*aProportion;
temp.sx=matA.sx*proportion+matB.sx*aProportion;
temp.sy=matA.sy*proportion+matB.sy*aProportion;
temp.sz=matA.sz*proportion+matB.sz*aProportion;
temp.mat.m11=matA.mat.m11*proportion+matB.mat.m11*aProportion;
temp.mat.m12=matA.mat.m12*proportion+matB.mat.m12*aProportion;
temp.mat.m13=matA.mat.m13*proportion+matB.mat.m13*aProportion;
temp.mat.m14=matA.mat.m14*proportion+matB.mat.m14*aProportion;
temp.mat.m21=matA.mat.m21*proportion+matB.mat.m21*aProportion;
temp.mat.m22=matA.mat.m22*proportion+matB.mat.m22*aProportion;
temp.mat.m23=matA.mat.m23*proportion+matB.mat.m23*aProportion;
temp.mat.m24=matA.mat.m24*proportion+matB.mat.m24*aProportion;
temp.mat.m31=matA.mat.m31*proportion+matB.mat.m31*aProportion;
temp.mat.m32=matA.mat.m32*proportion+matB.mat.m32*aProportion;
temp.mat.m33=matA.mat.m33*proportion+matB.mat.m33*aProportion;
temp.mat.m34=matA.mat.m34*proportion+matB.mat.m34*aProportion;
temp.mat.m41=matA.mat.m41*proportion+matB.mat.m41*aProportion;
temp.mat.m42=matA.mat.m42*proportion+matB.mat.m42*aProportion;
temp.mat.m43=matA.mat.m43*proportion+matB.mat.m43*aProportion;
temp.mat.m44=matA.mat.m44*proportion+matB.mat.m44*aProportion;
temp.rotateMat.m11=matA.rotateMat.m11*proportion+matB.mat.m11*aProportion;
temp.rotateMat.m12=matA.rotateMat.m12*proportion+matB.rotateMat.m12*aProportion;
temp.rotateMat.m13=matA.rotateMat.m13*proportion+matB.rotateMat.m13*aProportion;
temp.rotateMat.m14=matA.rotateMat.m14*proportion+matB.rotateMat.m14*aProportion;
temp.rotateMat.m21=matA.rotateMat.m21*proportion+matB.rotateMat.m21*aProportion;
temp.rotateMat.m22=matA.rotateMat.m22*proportion+matB.rotateMat.m22*aProportion;
temp.rotateMat.m23=matA.rotateMat.m23*proportion+matB.rotateMat.m23*aProportion;
temp.rotateMat.m24=matA.rotateMat.m24*proportion+matB.rotateMat.m24*aProportion;
temp.rotateMat.m31=matA.rotateMat.m31*proportion+matB.rotateMat.m31*aProportion;
temp.rotateMat.m32=matA.rotateMat.m32*proportion+matB.rotateMat.m32*aProportion;
temp.rotateMat.m33=matA.rotateMat.m33*proportion+matB.rotateMat.m33*aProportion;
temp.rotateMat.m34=matA.rotateMat.m34*proportion+matB.rotateMat.m34*aProportion;
temp.rotateMat.m41=matA.rotateMat.m41*proportion+matB.rotateMat.m41*aProportion;
temp.rotateMat.m42=matA.rotateMat.m42*proportion+matB.rotateMat.m42*aProportion;
temp.rotateMat.m43=matA.rotateMat.m43*proportion+matB.rotateMat.m43*aProportion;
temp.rotateMat.m44=matA.rotateMat.m44*proportion+matB.rotateMat.m44*aProportion;
return temp;
}<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
<link src="quguangjie.view.css" rel="stylesheet" type="text/css"/>
</head>
<body onunload="setCookieM()">
<?php
// define variables and set to empty values
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$link = new mysqli("localhost","root","12345","quguangjie");
$shopId = $_SESSION['shopId'];
$query = "select * from Shop where number = '$shopId'";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
/*
$shopName = $row['name'];
$passCode = $row['passcode'];
$seryCode = $row['certificate'];
$shopAddress = $row['address'];
$mainService = $row['service'];
$shopCoordinateX = $row['coordinateX'];
$shopCoordinateY = $row['coordinateY'];*/
//echo "<div>您的用户信息为:ID " . $row['ID'] . " shopName " . $row['shopName'] . " seryCode " . $row['seryCode'] . " shopAddress " . $row['shopAddress'] . " mainService " . $row['mainService'] . "picSource" . $row['shopPicture'] . "</div>";
}
?>
<div id = "top_bar">
<div class = "top_option" id="top_left" onclick="scroll1()">我的店铺</div>
<div class = "top_div"></div>
<div class = "top_option" id="top_mid" onclick="scroll2()">编辑活动</div>
<div class = "top_div"></div>
<div class = "top_option" id="top_right" onclick="scroll3()">收到的评论</div>
<div class = "top_div"></div>
<div class = "top_option" id="top_right" onclick="scroll4()">会员充值</div>
<div class = "top_div"></div>
<div class = "top_option" onclick="logout()">退出</div>
</div>
<?php
if(isset($_FILES['picUp']))
{
if ((($_FILES["picUp"]["type"] == "image/gif")
|| ($_FILES["picUp"]["type"] == "image/jpeg")
|| ($_FILES["picUp"]["type"] == "image/pjpeg"))
&& ($_FILES["picUp"]["size"] < 1000000))
{
if ($_FILES["picUp"]["error"] > 0)
{
echo "Return Code: " . $_FILES["picUp"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["picUp"]["tmp_name"],
"sjtuShopPic/" . $_SESSION['shopId'] . ".jpg");
}
}
}
if(isset($_POST['coordinate1']))
{
$coordinate1 = $_POST['coordinate1'];
echo " <script type=\"text/javascript\">window.scrollTo(0,'$coordinate1');</script>
";
}
?>
<div id = "title" >我的<br/>店铺
</div>
<div id = "shopInfo">
<div id = "shopInfoImg">
<img id ="img" onclick = "location.assign('headUp.php')" src="<?php echo $row['head'];?>" alt="未找到图片,点击添加"/>
</div>
<div id = "shopInfoTex">
<p class = "CshopInfoTex"><?php echo "店名:" . $row['name'] ?></p>
<p class = "CshopInfoTex"><?php echo "执照编码:" . $row['certificate'] ?></p>
<p class = "CshopInfoTex"><?php echo "商铺地址:" . $row['address'] ?></p>
<p class = "CshopInfoTex"><?php echo "主要业务:" . $row['service'] ?></p>
<input class = "CshopInfoTex" onclick="location.assign('svgmaps/<?php echo $_SESSION['map'] . "_1.php" ?>')" value="更改地图坐标"/>
</div>
</div>
<div id = "event">
<div id = "editEvent">
编辑活动
<div id = "subEditEvent">
<?php
// define variables and set to empty values
//$query = $_SESSION['map']=="sjtuShop"?"select * from sjtuShopEventInfo where shopId = '$idNum'":"";
//$result = $link->query($query);
//$row = $result->fetch_assoc();
if(!isset($_POST['eventMessage']))
{
echo "<form action=\"shopMain.php\" id=\"editEventForm\" method=\"post\">
<p>当前活动</p>
<p>活动简讯:<input type=\"text\" name=\"eventMessage\" id=\"shortBox\" value=\"" . $row['shortevent'] . "\"/></p>
<p id = \"prompt1\"></p>
<p><div id=\"adjust1\">活动详情:</div><div id=\"adjust2\"><textarea row=\"10\" col=\"10\" name=\"eventDetail\" id=\"longBox\" value=\"" . $row['event'] . "\">" . $row['event'] . "</textarea></div></p>
<p id = \"prompt2\"></p>
<input type=\"text\" hidden=true name=\"coordinate\" id=\"coordinate\"/>
</form>
<button type=\"button\" id=\"button\" onclick=\"tryRenewEvent()\">更新</button>";
}
else// if($row['shortevent']=="")
{
$eventMessage = test_input($_POST['eventMessage']);
$eventDetail = test_input($_POST['eventDetail']);
//UPDATE `quguangjie`.`sjtushopeventinfo` SET `eventMessage`='全场二折', `eventDetail`='假的的' WHERE `ID`='2';
$query = "update Shop set event = '$eventDetail', shortevent = '$eventMessage' where number = $shopId";
if($link->query($query)) ;
else echo "query FAILED!!!!!!!!!";
echo "<form action=\"shopMain.php\" id=\"editEventForm\" method=\"post\">
<p>当前活动</p>
<p>活动简讯:<input type=\"text\" name=\"eventMessage\" id=\"shortBox\" value=\"" . $eventMessage . "\"/></p>
<p id = \"prompt1\"></p>
<p><div id=\"adjust1\">活动详情:</div><div id=\"adjust2\"><textarea row=\"10\" col=\"10\" name=\"eventDetail\" id=\"longBox\" value=\"" . $eventDetail . "\">" . $eventDetail . "</textarea></div></p>
<p id = \"prompt2\"></p>
<input type=\"text\" hidden=true name=\"coordinate\" id=\"coordinate\"/>
</form>
<button type=\"button\" id=\"button\" onclick=\"tryRenewEvent()\">更新</button>";
}/*
else
{
$eventMessage = test_input($_POST['eventMessage']);
$eventDetail = test_input($_POST['eventDetail']);
//UPDATE `quguangjie`.`sjtushopeventinfo` SET `eventMessage`='全场二折', `eventDetail`='假的的' WHERE `ID`='2';
$query = $_SESSION['map']=="sjtuShop"?"update sjtuShopEventInfo set eventMessage = '$eventMessage',eventDetail = '$eventDetail' where shopId = '$idNum'":"";
$link->query($query);
echo "<form action=\"shopMain.php\" id=\"editEventForm\" method=\"post\">
<p>当前活动</p>
<p>活动简讯:<input type=\"text\" name=\"eventMessage\" id=\"shortBox\" value=\"" . $eventMessage . "\"/></p>
<p id = \"prompt1\"></p>
<p><div id=\"adjust1\">活动详情:</div><div id=\"adjust2\"><textarea row=\"10\" col=\"10\" name=\"eventDetail\" id=\"longBox\" value=\"" . $eventDetail . "\">" . $eventDetail . "</textarea></div></p>
<p id = \"prompt2\"></p>
<input type=\"text\" hidden=true name=\"coordinate\" id=\"coordinate\"/>
</form>
<button type=\"button\" id=\"button\" onclick=\"tryRenewEvent()\">更新</button>";
}*/
if(isset($_POST['coordinate']))
{
$coordinate = test_input($_POST['coordinate']);
echo " <script type=\"text/javascript\">window.scrollTo(0,'$coordinate');</script> ";
}
?>
</div>
</div>
</div>
<div id="comments">
收到的评论
<div id="scrolling">
<?php
$query = "select name,content,score from Remark,User where shopno = '$shopId' and User.number = Remark.userno order by time desc;";
$result = $link->query($query);
while($row = $result->fetch_assoc()) {
if($row['content']!="")
{
echo "<div class = \"events\" >" . $row['name']. " 评论道:" . $row['content'] . "</div>";
echo "<div class = \"events\" >打分 " . $row['score'] . " 分</div>";
echo "<br/>";
}
else
{
echo "<div class = \"events\" >" . $row['name']. " 打分:" . $row['score'] . " 分</div>";
echo "<br/>";
}
}
?>
</div>
</div>
<div id = "charge">
请向支付宝号13166221016转账,并注明执照编号和店名
</div>
<script type="text/javascript">
/*
function trysmt()
{
document.getElementById("tsmt").submit();
}
*/
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function setCookieM()
{
setCookie("shopMainCo",window.pageYOffset,1);
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return ""
}
var co =getCookie("shopMainCo");
if(co!="")
window.scrollTo(0,co);
function scroll1()
{
window.scrollTo(0,0);
}
function scroll2()
{
window.scrollTo(0,1400);
}
function scroll3()
{
window.scrollTo(0,2600);
}
function scroll4()
{
window.scrollTo(0,3800);
}
function logout()
{
location.assign("logOut.php");
}
function tryRenewEvent()
{
var shortBox = document.getElementById("shortBox");
var longBox = document.getElementById("longBox");
if(shortBox.value.length>5)
{
document.getElementById("prompt1").textContent="长度不能超过五个字符";
}
else document.getElementById("prompt1").textContent="";
if(longBox.value.length>100)
{
var p =document.getElementById("prompt2").textContent="长度不能超过100个字符";
}
else document.getElementById("prompt2").textContent="";
if(shortBox.value.length<=10&&longBox.value.length<=100)
{
document.getElementById("editEventForm").submit();
}
}
function changePic()
{
document.getElementById("picUpload").hidden=!document.getElementById("picUpload").hidden;
}
function submitPic()
{
document.getElementById("formPicUpload").submit();
}
var img = document.getElementById("img")
{
if(img.height>800)
{
img.height="800";
}
}
</script>
</body>
</html>
<file_sep>
<!DOCTYPE HTML>
<?php
session_start();
$npx="";
$npy="";
$idNum="";
if(isset($_SESSION['shopId'])&&isset($_SESSION['map'])&&isset($_POST['npx'])&&isset($_POST['npy']))
{
$npx=$_POST['npx'];
$npy=$_POST['npy'];
$idNum=$_SESSION['shopId'];
$link = new mysqli("localhost","root","1<PASSWORD>","quguangjie");
$query = "update Shop set coordinateX = '$npx',coordinateY = '$npy' where number = '$idNum'";
$link->query($query);
echo "<script type=\"text/javascript\"> location.assign(\"shopMain.php\");</script>";
}
?><file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
</head>
<body>
<?php
session_destroy();
?>
<script type="text/javascript">
location.assign("index.php")
</script>
</body>
</html>
<file_sep>//var polCameraArray;
//function initCameraArray()
//{
var polCameraArray = 0;
polCameraArray=new Array();
polCameraArray.tempCam = 0;
//}
function polCameraObject()
{
this.nearest=0.1;
this.farest=1000;
this.angle=75;
this.widthDivHeight=gl.widthDivHeight;
this.pMatrix = matProject(15, gl.widthDivHeight, 0.1, 1000);
this.enable = false;
this.frontVec=new Vector(0,0,-1);
this.leftVec=new Vector(-1,0,0);
this.upVec=new Vector(0,1,0);
this.position=new Vector(0,0,0);
this.posMatrix = new Matrix();
this.rotMatrix = new Matrix();
}
polCameraObject.prototype.translateTo = function(tx,ty,tz)
{
this.position.x=tx;
this.position.y=ty;
this.position.z=tz;
this.posMatrix.m14=-tx;
this.posMatrix.m24=-ty;
this.posMatrix.m34=-tz;
}
polCameraObject.prototype.translateBy = function(bx,by,bz)
{
this.position.x+=bx;
this.position.y+=by;
this.position.z+=bz;
this.posMatrix.m14=-this.position.x;
this.posMatrix.m24=-this.position.y;
this.posMatrix.m34=-this.position.z;
}
polCameraObject.prototype.pitch = function(v)
{
var tangent = Math.tan(v*globalElapsedTime);
this.frontVec.x-=this.upVec.x*tangent;
this.frontVec.y-=this.upVec.y*tangent;
this.frontVec.z-=this.upVec.z*tangent;
this.frontVec.normalize();
this.upVec = this.frontVec.cross(this.leftVec);
this.rotMatrix.m11=-this.leftVec.x;
this.rotMatrix.m21=-this.leftVec.y;
this.rotMatrix.m31=-this.leftVec.z;
this.rotMatrix.m12=this.upVec.x;
this.rotMatrix.m22=this.upVec.y;
this.rotMatrix.m32=this.upVec.z;
this.rotMatrix.m13=-this.frontVec.x;
this.rotMatrix.m23=-this.frontVec.y;
this.rotMatrix.m33=-this.frontVec.z;
this.rotMatrix=this.rotMatrix.inverse();
//document.write(this.rotMatrix.toArray());
}
polCameraObject.prototype.yaw = function(v)
{
var tangent = Math.tan(v*globalElapsedTime);
this.frontVec.x+=this.leftVec.x*tangent;
this.frontVec.y+=this.leftVec.y*tangent;
this.frontVec.z+=this.leftVec.z*tangent;
this.frontVec.normalize();
this.leftVec = this.upVec.cross(this.frontVec);
this.rotMatrix.m11=-this.leftVec.x;
this.rotMatrix.m21=-this.leftVec.y;
this.rotMatrix.m31=-this.leftVec.z;
this.rotMatrix.m12=this.upVec.x;
this.rotMatrix.m22=this.upVec.y;
this.rotMatrix.m32=this.upVec.z;
this.rotMatrix.m13=-this.frontVec.x;
this.rotMatrix.m23=-this.frontVec.y;
this.rotMatrix.m33=-this.frontVec.z;
this.rotMatrix=this.rotMatrix.inverse();
}
polCameraObject.prototype.roll = function(v)
{
var tangent = Math.tan(v*globalElapsedTime);
this.upVec.x-=this.leftVec.x*tangent;
this.upVec.y-=this.leftVec.y*tangent;
this.upVec.z-=this.leftVec.z*tangent;
this.upVec.normalize();
this.leftVec = this.upVec.cross(this.frontVec);
this.rotMatrix.m11=-this.leftVec.x;
this.rotMatrix.m21=-this.leftVec.y;
this.rotMatrix.m31=-this.leftVec.z;
this.rotMatrix.m12=this.upVec.x;
this.rotMatrix.m22=this.upVec.y;
this.rotMatrix.m32=this.upVec.z;
this.rotMatrix.m13=-this.frontVec.x;
this.rotMatrix.m23=-this.frontVec.y;
this.rotMatrix.m33=-this.frontVec.z;
this.rotMatrix = this.rotMatrix.inverse();
//document.write(this.rotMatrix.mul(temp).toArray());
//document.write(this.rotMatrix.toArray());
}
polCameraObject.prototype.ahead = function(v)
{
v*=globalElapsedTime;
this.position.x+=this.frontVec.x*v;
this.position.y+=this.frontVec.y*v;
this.position.z+=this.frontVec.z*v;
this.posMatrix.m14=-this.position.x;
this.posMatrix.m24=-this.position.y;
this.posMatrix.m34=-this.position.z;
}
polCameraObject.prototype.sideway = function(v)
{
v*=globalElapsedTime;
this.position.x+=this.leftVec.x*v;
this.position.y+=this.leftVec.y*v;
this.position.z+=this.leftVec.z*v;
this.posMatrix.m14=-this.position.x;
this.posMatrix.m24=-this.position.y;
this.posMatrix.m34=-this.position.z;
}
polCameraObject.prototype.fly = function(v)
{
v*=globalElapsedTime;
this.position.x+=this.upVec.x*v;
this.position.y+=this.upVec.y*v;
this.position.z+=this.upVec.z*v;
this.posMatrix.m14=-this.position.x;
this.posMatrix.m24=-this.position.y;
this.posMatrix.m34=-this.position.z;
}
polCameraObject.prototype.reset = function()
{
this.upVec.x=0;
this.upVec.y=1;
this.upVec.z=0;
this.leftVec.y=0;
this.leftVec.normalize();
this.frontVec = this.leftVec.cross(this.upVec);
this.rotMatrix.m11=-this.leftVec.x;
this.rotMatrix.m21=-this.leftVec.y;
this.rotMatrix.m31=-this.leftVec.z;
this.rotMatrix.m12=this.upVec.x;
this.rotMatrix.m22=this.upVec.y;
this.rotMatrix.m32=this.upVec.z;
this.rotMatrix.m13=-this.frontVec.x;
this.rotMatrix.m23=-this.frontVec.y;
this.rotMatrix.m33=-this.frontVec.z;
this.rotMatrix = this.rotMatrix.inverse();
//document.write(this.rotMatrix.mul(temp).toArray());
//document.write(this.rotMatrix.toArray());
}
/*
polCameraObject.prototype.translateTo = funtion(tx,ty,tz)
{
this.transformMatrix.translateTo(-tx,-ty,-tz);
}
polCameraObject.prototype.translateBy = funtion(bx,by,bz,v)
{
this.transformMatrix.translateBy(-bx*v,-by*v,-bz*v);
}
polCameraObject.prototype.rotateByLeft = funtion(rad,v)
{
this.transformMatrix.worldRotateAxisByCam(this.leftVec.x,this.leftVect.y,this.leftVec.z,-rad*v);
}
polCameraObject.prototype.rotateByUp = funtion(rad,v)
{
this.transformMatrix.worldRotateAxisByCam(this.upVec.x,this.upVect.y,this.upVec.z,-rad*v);
}
polCameraObject.prototype.rotateByFront = funtion(rad,v)
{
var temp = this.leftVec.cross(this.upVec);
this.transformMatrix.worldRotateAxisByCam(temp.x,temp.y,temp.z,-rad*v);
}
polCameraObject.prototype.goAhead = funtion(v)
{
var temp = this.leftVec.cross(this.upVec);
this.transformMatrix.translateBy(temp.x*v,temp.y*v,temp.z*v);
}
polCameraObject.prototype.goLeft = funtion(v)
{
this.transformMatrix.translateBy(this.leftVec.x*v,this.leftVec.y*v,this.leftVec.z*v);
}
polCameraObject.prototype.goArise = funtion(v)
{
this.transformMatrix.translateBy(this.upVec.x*v,this.upVec.y*v,this.upVec.z*v);
}
*/
function appendCamera()
{
polCameraArray.push(new polCameraObject);
return polCameraArray.length-1;
}
polCameraObject.prototype.adjustCamera = function(index, a, n, f, wdh)
{
if(arguments.length==4) wdh=0;
this.nearest=n;
this.farest=f;
this.angle=a;
if(wdh!=0)
{
this.widthDivHeight=wdh;
}
this.pMatrix = matProject(this.angle, this.widthDivHeight, this.nearest, this.farest);
}<file_sep>var polShadowFramebuffer;
var polShadowFrameTexbuffer;
var polShadowFrameDepthbuffer;
var polShadowProgram;
var polShadowingLight;
function polLightShadowObj(x, y, z, type)
{
this.attibute = new Vector(x, y, z);
this.type = type;
this.matrix = new Matrix();
if(type == 1)
{
}
else if(type == 2)
{
this.matrix.m14=-x;
this.matrix.m24=-y;
this.matrix.m34=-z;
}
}
function polShadow()
{
gl.bindFramebuffer(gl.FRAMEBUFFER, polShadowFramebuffer);
gl.viewport(0, 0, polShadowFramebuffer.width, polShadowFramebuffer.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//pMatrix = matProject(MACROangle, gl.widthDivHeight, MACROnearest, MACROfarest);
for(var i in polObjArray)
{
if(polObjArray[i].shadowing)
{
drawPolShadowMap(i);
}
}
//var pickBuf = new Uint8Array(polFramebuffer.pixelNum*4);
//gl.readPixels(0, 0, polFramebuffer.width, polFramebuffer.height, gl.RGBA, gl.UNSIGNED_BYTE, pickBuf);
//for(var i = 0;i<polFramebuffer.pixelNum*4;++i) document.write(pickBuf[i]+' ');
/*
for(var i = 0;i<polFramebuffer.precisoin;++i)
{
for(var j = 0;j<polFramebuffer.precisoin;++j)
{
document.write(pickBuf[(i*polFramebuffer.precisoin+j)*4]+' '+pickBuf[(i*polFramebuffer.precisoin+j)*4+1]+' '+pickBuf[(i*polFramebuffer.precisoin+j)*4+2]+' '+pickBuf[(i*polFramebuffer.precisoin+j)*4+3]+' 11111111111 ')
}
document.write('---------------------');
}
*/
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
function polInitShadowFramebuffer(precision) {
polShadowFramebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, polShadowFramebuffer);
polShadowFramebuffer.precision=precision;
polShadowFramebuffer.width=parseInt(gl.viewportWidth*precision);
polShadowFramebuffer.height=parseInt(gl.viewportHeight*precision);
polShadowFramebuffer.texPixs = parseInt(Math.max(polShadowFramebuffer.width,polShadowFramebuffer.height));
polShadowFramebuffer.pixelNum = parseInt(polShadowFramebuffer.width*polShadowFramebuffer.height);
polShadowFrameTexbuffer = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, polShadowFrameTexbuffer);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, polShadowFramebuffer.texPixs, polShadowFramebuffer.texPixs, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
polShadowFrameDepthbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, polShadowFrameDepthbuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, polShadowFramebuffer.texPixs, polShadowFramebuffer.texPixs);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, polShadowFrameTexbuffer, 0);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, polShadowFrameDepthbuffer);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var fragmentShader = getShader(gl, "shadowMapShader-fs");
var vertexShader = getShader(gl, "shadowMapShader-vs");
polShadowProgram = gl.createProgram();
gl.attachShader(polShadowProgram, fragmentShader);
gl.attachShader(polShadowProgram, vertexShader);
gl.linkProgram(polShadowProgram);
if (!gl.getProgramParameter(polShadowProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(polShadowProgram);
polShadowProgram.vertexPositionAttribute = gl.getAttribLocation(polShadowProgram, "aVertexPosition");
gl.enableVertexAttribArray(polShadowProgram.vertexPositionAttribute);
polShadowProgram.textureCoordAttribute = gl.getAttribLocation(polShadowProgram, "aTextureCoord");
gl.enableVertexAttribArray(polShadowProgram.textureCoordAttribute);
polShadowProgram.vertexNormalAttribute = gl.getAttribLocation(polShadowProgram, "aVertexNormal");
gl.enableVertexAttribArray(polShadowProgram.vertexNormalAttribute);
polShadowProgram.pMatrixUniform = gl.getUniformLocation(polShadowProgram, "uPMatrix");
polShadowProgram.mvMatrixUniform = gl.getUniformLocation(polShadowProgram, "uMVMatrix");
polShadowProgram.pMatrix = matProject(45, 1, 0.1, polCameraArray[polCameraArray.tempCam].farest);
}
function drawPolShadowMap(polObjIndex)
{
gl.useProgram(polShadowProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].vertexPositionBuffer);
gl.vertexAttribPointer(polShadowProgram.vertexPositionAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].normalDirectionBuffer);
gl.vertexAttribPointer(polShadowProgram.vertexNormalAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].normalDirectionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].textureCoordBuffer);
gl.vertexAttribPointer(polShadowProgram.textureCoordAttribute, polMeshArray[polObjArray[polObjIndex].polMeshIndex].textureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(shaderProgram[shaderIndex].pMatrixUniform, false, polCameraArray[polCameraArray.tempCam].pMatrix.toArray());
var finalMvMatrix = polShadowingLight.matrix.mul(polObjArray[polObjIndex].transformMatrix.mat);
gl.uniformMatrix4fv(polShadowProgram.mvMatrixUniform, false, finalMvMatrix.toArray());
for(var i=0;i<polMeshArray[polObjArray[polObjIndex].polMeshIndex].geometryNum;++i)
{
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i]);
gl.drawElements(gl.TRIANGLES, polMeshArray[polObjArray[polObjIndex].polMeshIndex].indexReferBuffer[i].numItems, gl.UNSIGNED_SHORT, 0);
}
}<file_sep>
<!DOCTYPE HTML>
<?php session_start(); ?>
<html>
<head>
<style type="text/css">
#title
{
font-family: 黑体, serif;
font-size : 100px;
color: #ffffff;
width:auto;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
}
div{
font-family: 黑体, serif;
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
}
body
{
background-color: #4d7b95;
text-align:center;
}
#top_bar
{
position:fixed;
left:0%;
right:60px;
top:0%;
z-index: 1030;
width:40px;
font-size:35px;
}
.top_option{
margin-top: 10px;
width:100%;
box-sizing: border-box;
text-align:center;
padding-top:8px;
padding-bottom:8px;
overflow: hidden;
color:white;
}
#shopInfo
{
margin-left: auto;
margin-right: auto;
width:75%;
height:510px;
font-size:40px;
margin-bottom:200px;
}
#shopInfoImg
{
float:left;
width:30%;
height:100%;
}
img
{
width : 100%;
}
#shopInfoTex
{
text-align:left;
float:left;
width:70%;
}
.CshopInfoTex
{
margin-left:10%;
}
#comments
{
margin-left: auto;
margin-right: auto;
width:80%;
height:1200px;
font-size:40px;
}
.events
{
text-align:left;
width:100%;
word-wrap: break-word;
word-break:break-all;
background-color:white;
}
#addingComm
{
width:100%;
text-align:left;
}
#myComm
{
width:180px;
height:40px;
font-size:30px;
}
#myCommContent
{
width:100%;
font-size:40px;
}
</style>
</head>
<body onunload="setCookieM()">
<div id = "top_bar">
<div class = "top_option" id="top_left" onclick="gotoMap()">进入地图</div>
<div class = "top_div"></div>
<div class = "top_option" id="top_mid" onclick="gotoMain()">我的主页</div>
<div class = "top_div"></div>
<div class = "top_option" id="top_right" onclick="backtoTop()">回到顶部</div>
</div>
<?php
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$row['head']="";
$row['name']="";
$row['address']="";
$row['service']="";
$row['score']="";
$row['commentnum']="";
$idNum="";
$shopMap="";
$userName="";
$link = new mysqli("localhost","root","12345","quguangjie");
if(isset($_POST['shopId'])&&isset($_POST['mapName']))
{
$shopMap=test_input($_POST['mapName']);
$idNum = test_input($_POST['shopId']);
$_SESSION['fromShopId']=$_POST['shopId'];
$_SESSION['frommapName']=$_POST['mapName'];
$query = "select * from Shop where number = '$idNum'";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
//echo "<div>您的用户信息为:ID " . $row['ID'] . " shopName " . $row['shopName'] . " seryCode " . $row['seryCode'] . " shopAddress " . $row['shopAddress'] . " mainService " . $row['mainService'] . "picSource" . $row['shopPicture'] . "</div>";
}
if(isset($_POST['newComm']))
{
$comments=test_input($_POST['newComm']);
$ranking=test_input($_POST['ranking']);
$axis = 1;
if(strlen($comments)>14) $axis=3;
$newScore = ($row['score'] * $row['commentnum'] + $ranking * $axis)/($row['commentnum']+$axis);
$newCommentCount = $row['commentnum'] + $axis;
//echo $newScore;
$query = "update Shop set score = '$newScore',commentnum = '$newCommentCount' where number = '$idNum'";
$result = $link->query($query);
$shopName = $row['name'];
$userIdNum = $_SESSION['userId'];
//$time=time();
//echo "<h1>$time</h1>";
$query = "insert into Remark(userno,shopno,content,score)
values('$userIdNum','$idNum','$comments','$ranking')";
$link->query($query);
//更新row内容
$query = "select * from Shop where number = '$idNum'";
$result = $link->query($query);
$row = $result->fetch_assoc();
}
/*
$query = $_POST['mapName']=="sjtuShop"?"select * from sjtuShop where ID = '$idNum'":"";
$result = $link->query($query);
if($row = $result->fetch_assoc()) {
//echo "<div>您的用户信息为:ID " . $row['ID'] . " shopName " . $row['shopName'] . " seryCode " . $row['seryCode'] . " shopAddress " . $row['shopAddress'] . " mainService " . $row['mainService'] . "picSource" . $row['shopPicture'] . "</div>";
}
//echo "<div>您的用户信息为:ID " . $row['ID'] . " shopName " . $row['shopName'] . " seryCode " . $row['seryCode'] . " shopAddress " . $row['shopAddress'] . " mainService " . $row['mainService'] . "picSource" . $row['shopPicture'] . "</div>";
*/
}
?>
<div id = "title">逛店铺</div>
<div id = "shopInfo">
<div id = "shopInfoImg">
<img src="
<?php
echo $row['head'];
?>"
alt="未找到图片,点击添加"/>
</div>
<form action="svgmaps/sjtuMap.php" method="post" hidden=true id="submitAim">
<input type="text" id="aim" name="aim" value="<?php echo $row['name']; ?>"></input>
</form>
<div id = "shopInfoTex">
<p class = "CshopInfoTex"><?php echo "店名:" . $row['name'] ?></p>
<p class = "CshopInfoTex"><?php echo "评级:" . round($row['score'],1) ?></p>
<p class = "CshopInfoTex"><?php echo "商铺地址:" . $row['address'] ?></p>
<p class = "CshopInfoTex"><?php echo "主要业务:" . $row['service'] ?></p>
<p class = "CshopInfoTex"><?php echo "当前活动:" . $row['shortevent'] ?></p>
<p class = "CshopInfoTex"><?php echo "活动详情:" . $row['event'] ?></p>
</div>
</div>
<div id="comments">
<div id = "addingComm">
<button onclick="<?php if(isset($_SESSION['userId'])) echo "tryToSubmit()";
else echo "gotoMain()";
?>" id = "myComm" >添加评论</button><form method="post" action="viewShop.php" id="formComment">
<div><textarea row =10 col = 10 id="myCommContent" name="newComm"></textarea></div>
<div>打个分:<input min = "0" max = "10" type="range" id="ranking" name="ranking" /></div>
<input name="shopId" hidden=true value="<?php echo $idNum; ?>"/>
<input name="mapName" hidden=true value="<?php echo test_input($shopMap); ?>"/>
</form><p id="prompt"></p></div>
<?php
$query = "select * from Remark,User where Remark.shopno = '$idNum' and User.number = Remark.userno order by time desc;";
$result = $link->query($query);
while($row = $result->fetch_assoc()) {
if($row['content']!="")
{
echo "<div class = \"events\" >" . $row['name']. " 评论道:" . $row['content'] . "</div>";
echo "<div class = \"events\" >打分 " . $row['score'] . " 分</div>";
echo "<br/>";
}
else
{
echo "<div class = \"events\" >" . $row['name']. " 打分:" . $row['score'] . " 分</div>";
echo "<br/>";
}
}
?>
</div>
<script type="text/javascript">
function backtoTop()
{
window.scrollTo(0,0);
}
function defaultImg(p)
{
p.src="shopPic/default.jpg";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function setCookieM()
{
setCookie("viewShopCo",window.pageYOffset,1);
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return ""
}
var co =getCookie("viewShopCo");
if(co!="")
window.scrollTo(0,co);
function tryToSubmit()
{
var dd=document.getElementById("myCommContent");
if(document.getElementById("myCommContent").textLength>100)
{
document.getElementById("prompt").textContent="字数不能超过100的";
}
else
{
document.getElementById("formComment").submit();
}
}
function gotoMap()
{
document.getElementById("submitAim").submit();
}
function gotoMain()
{
<?php if(isset($_SESSION['userId'])) echo "location.assign(\"userMain.php\");";
else echo "location.assign(\"visitorLogin.php\");";
?>
}
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>SJTU-map</title>
<style type="text/css">
div#container {
position:absolute;
top:0px;
left:0px;
width:486.5px;
height:588.7px;
overflow: hidden;
}
#in {
position:fixed;
right:5%;
top:45%;
width:6%; height:6%;
font-size:40px;
}
#out {
position:fixed;
right:5%;
top:55%;
width:6%; height:6%;
font-size:40px;
}
#submit {
position:fixed;
left:10px;
top:10px;
z-index:1030;
width:100px;
height:50px;
font-size:40;
}
#cancel {
position:fixed;
left:10px;
top:70px;
z-index:1030;
width:100px;
height:50px;
font-size:40;
}
#search {
position:fixed;
left:10px;
top:10px;
z-index:1030;
width:80%;
height:100px;
font-size:60px;
}
#searchForm {
width:100%;
height:100px;
}
#searchBox {
float:left;
width:40%;
height:44px;
font-size:30px;
}
#searchButton {
float:left;
width:40%;
height:50px;
font-size:30px;
}
#toMain {
position:fixed;
left:80%;
height:50px;
top:10px;
z-index:1030;
width:19%;
font-size:30px;
}
#toIndex {
position:fixed;
left:80%;
height:50px;
top:70px;
z-index:1030;
width:19%;
font-size:30px;
}
</style>
<script>
var Mzoomspeed = 1.5,zoomspeed = 1.1;
var px=1,py=1;
var biggerId,smallerId,bigTimes,smallTimes;
var fs1=10+"px",fs2=6.7+"px",fs3=4.4+"px",fs4=3+"px",fs5=2+"px";
var cfs1=3,cfs2=2,cfs3=1.3,cfs4=0.9,cfs5=0.6;
function changeText(lv,sorb) {
if(lv==1) {
for(i=0;i<lv1.length;++i) {lv1[i].style.fontSize=fs1;clv1[i].setAttribute("r", cfs1);}
for(i=0;i<lv2.length;++i) {lv2[i].style.fontSize=0;clv2[i].setAttribute("r", 0);}
}
else if(lv==2) {
for(i=0;i<lv1.length;++i) {lv1[i].style.fontSize=fs2;clv1[i].setAttribute("r", cfs2);}
for(i=0;i<lv2.length;++i) {lv2[i].style.fontSize=fs2;clv2[i].setAttribute("r", cfs2);}
if(sorb=="s")
for(i=0;i<lv3.length;++i) {lv3[i].style.fontSize=0;clv3[i].setAttribute("r", 0);}
}
else if(lv==3) {
for(i=0;i<lv1.length;++i) {lv1[i].style.fontSize=fs3;clv1[i].setAttribute("r", cfs3);}
for(i=0;i<lv2.length;++i) {lv2[i].style.fontSize=fs3;clv2[i].setAttribute("r", cfs3);}
for(i=0;i<lv3.length;++i) {lv3[i].style.fontSize=fs3;clv3[i].setAttribute("r", cfs3);}
if(sorb=="s")
for(i=0;i<lv4.length;++i) {lv4[i].style.fontSize=0;clv4[i].setAttribute("r", 0);}
}
else if(lv==4) {
for(i=0;i<lv1.length;++i) {lv1[i].style.fontSize=fs4;clv1[i].setAttribute("r", cfs4);}
for(i=0;i<lv2.length;++i) {lv2[i].style.fontSize=fs4;clv2[i].setAttribute("r", cfs4);}
for(i=0;i<lv3.length;++i) {lv3[i].style.fontSize=fs4;clv3[i].setAttribute("r", cfs4);}
for(i=0;i<lv4.length;++i) {lv4[i].style.fontSize=fs4;clv4[i].setAttribute("r", cfs4);}
if(sorb=="s")
for(i=0;i<lv5.length;++i) {lv5[i].style.fontSize=0;clv5[i].setAttribute("r", 0);}
}
else if(lv==5) {
for(i=0;i<lv1.length;++i) {lv1[i].style.fontSize=fs5;clv1[i].setAttribute("r", cfs5);}
for(i=0;i<lv2.length;++i) {lv2[i].style.fontSize=fs5;clv2[i].setAttribute("r", cfs5);}
for(i=0;i<lv3.length;++i) {lv3[i].style.fontSize=fs5;clv3[i].setAttribute("r", cfs5);}
for(i=0;i<lv4.length;++i) {lv4[i].style.fontSize=fs5;clv4[i].setAttribute("r", cfs5);}
for(i=0;i<lv5.length;++i) {lv5[i].style.fontSize=fs5;clv5[i].setAttribute("r", cfs5);}
}
}
function bigger1() {
if(bigTimes<3) {
if(bigTimes==1)
zoomspeed=1.5;
else
zoomspeed=1.1;
centerx=(window.pageXOffset+window.innerWidth/2)*zoomspeed-window.innerWidth/2;
centery=(window.pageYOffset+window.innerHeight/2)*zoomspeed-window.innerHeight/2;
mapw *= zoomspeed;
maph *= zoomspeed;
zoom *= zoomspeed;
map.style.width = mapw+"px";
map.style.height = maph+"px";
window.scrollTo(centerx,centery);
bigTimes++;
}
else {
window.clearInterval(biggerId);
zoomlevel += 1;
changeText(zoomlevel,"b");
}
}
function bigger() {
if(zoomlevel>=5) return;
bigTimes=0;
biggerId = self.setInterval("bigger1()",30);
}
function smaller1() {
if(smallTimes<3) {
if(smallTimes==1)
zoomspeed=1.5;
else
zoomspeed=1.1;
centerx=(window.pageXOffset+window.innerWidth/2)/zoomspeed-window.innerWidth/2;
centery=(window.pageYOffset+window.innerHeight/2)/zoomspeed-window.innerHeight/2;
mapw /= zoomspeed;
maph /= zoomspeed;
zoom /= zoomspeed;
map.style.width = mapw+"px";
map.style.height = maph+"px";
window.scrollTo(centerx,centery);
smallTimes++;
}
else {
window.clearInterval(smallerId);
zoomlevel -= 1;
changeText(zoomlevel,"s");
}
}
function smaller() {
if(zoomlevel<=1) return;
smallTimes=0;
smallerId = self.setInterval("smaller1()",30);
}
function init() {
if(!(('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))) {
cc=document.getElementById("ccontainer");
cc.setAttribute("onmousedown","initscroll()");
cc.setAttribute("onmousemove","scroll()");
cc.setAttribute("onmouseup","endscroll()");
}
map=document.getElementById("container");
svge=document.getElementById("map");
i = 0;
while(i<shopEvents.length) {
t = document.createElementNS("http://www.w3.org/2000/svg","text");
t.textContent = shopEvents[i]+" "+shopEvents[i+1];
t.setAttribute("id",shopEvents[i]);
t.setAttribute("font-size",0);
t.setAttribute("fill","#000");
t.setAttribute("font-family","'SimHei'");
t.setAttribute("x", shopEvents[i+2]);
t.setAttribute("y", shopEvents[i+3]);
t.setAttribute("onclick", "pop("+i+")");
t.setAttribute("class", "lv"+shopEvents[i+5]);
c = document.createElementNS("http://www.w3.org/2000/svg","circle");
c.setAttribute("id","?c"+shopEvents[i]);
c.setAttribute("cx", shopEvents[i+2]);
c.setAttribute("cy", shopEvents[i+3]);
c.setAttribute("r", 0);
c.setAttribute("fill", "blue");
c.setAttribute("class", "clv"+shopEvents[i+5]);
i += 6;
svge.appendChild(t);
svge.appendChild(c);
}
i = 0;
while(i<aim.length) {
t = document.getElementById(aim[i]);
t.setAttribute("class","lv1");
t.setAttribute("fill","#f00");
c = document.getElementById("?c"+aim[i]);
c.setAttribute("class","clv1");
c.setAttribute("fill","red");
i += 1;
}
lv1=document.getElementsByClassName("lv1");
lv2=document.getElementsByClassName("lv2");
lv3=document.getElementsByClassName("lv3");
lv4=document.getElementsByClassName("lv4");
lv5=document.getElementsByClassName("lv5");
clv1=document.getElementsByClassName("clv1");
clv2=document.getElementsByClassName("clv2");
clv3=document.getElementsByClassName("clv3");
clv4=document.getElementsByClassName("clv4");
clv5=document.getElementsByClassName("clv5");
mapw=map.offsetWidth;
maph=map.offsetHeight;
Ozoom = zoom = document.body.clientWidth/486.5;
mapw *= zoom;
maph *= zoom;
Omapw = mapw;
Omaph = maph;
map.style.width = mapw+"px";
map.style.height = maph+"px";
zoomlevel = 1;
for(i=0;i<lv1.length;++i) {
lv1[i].style.fontSize=fs1;
clv1[i].setAttribute("r", cfs1);
}
}
function pop(d) {
if (confirm(shopEvents[d+4]+"\n\n是否进入商铺页面?")) {
document.getElementById("shopId").value=shopId[d];
document.getElementById("mapName").value="sjtuShop";
document.getElementById("viewShop").submit();
}
}
function submit() {
document.getElementById("npx").value=px;
document.getElementById("npy").value=py;
document.getElementById("np").submit();
}
function cancel() {
location.assign("../shopMain.php");
}
function initscroll() {
scrollcount=1;
document.body.style.cursor='move';
lastx=event.clientX;
lasty=event.clientY;
}
function scroll() {
if (scrollcount==1) {
thisx=event.clientX;
thisy=event.clientY;
window.scrollBy(lastx-thisx,lasty-thisy);
lastx=event.clientX;
lasty=event.clientY;
}
}
function endscroll() {
document.body.style.cursor='';
scrollcount=0;
}
var shopEvents=new Array();
var shopId=new Array();
var aim=new Array();
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mapId = test_input($_POST["mapId"]);
$_SESSION["mapId"] = $mapId;
}
else
{
$mapId = $_SESSION["mapId"];
}
$_SESSION['mapName']="sjtuShop";
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from Shop where mapno = $mapId";
$result = $link->query($query);
$num_rows = $result->num_rows;
$count=0;
while($row=$result->fetch_assoc())
{
echo "shopId[" . $count . "]=\"" . $row['number'] . "\";";
echo "shopEvents[" . $count++ . "]=\"" . $row['name'] . "\";
shopEvents[" . $count++ . "]=\"" . $row['shortevent'] . "\";
shopEvents[" . $count++ . "]=" . $row['coordinatex'] . ";
shopEvents[" . $count++ . "]=" . $row['coordinatey'] . ";
shopEvents[" . $count++ . "]=\"" . $row['event'] . "\"
shopEvents[" . $count++ . "]=" . $row['level'] . ";";
}
function test_input($data) {
$data = htmlspecialchars($data);
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if(isset($_POST['aim']))
{
echo "aim=new Array();";
echo "aim[0]=\"" . $_POST['aim'] . "\";";
}
else if(isset($_SESSION['aimArray']))
{
$aim=$_SESSION['aimArray'];
echo "aim=new Array();";
for($i=0;$i<count($aim);++$i)
echo "aim[" . $i . "]=\"" . $aim[$i] . "\";
";
}
?>
document.getElementById("container")
</script>
</head>
<body onload="init()">
<div id="search">
<form id="searchForm" method="post" action="../search.php">
<input type="text" id="searchBox" name="keyWord"/>
<input type="submit" id="searchButton"/>
</form>
</div>
<button id="toMain" onclick="location.assign('<?php if(isset($_SESSION['userId'])) echo "../userMain.php"; else echo "../visitorLogin.php"; ?>')"><?php if(isset($_SESSION['userId'])) echo "主页"; else echo "登录"; ?></button>
<button id="toIndex" onclick="location.assign('../index.html')">首页</button>
<form id="viewShop" method="post" action="../viewShop.php" hidden=true>
<input id = "shopId" type="text" name="shopId"/>
<input id="mapName" type="text" name="mapName"/>
</form>
<div id="ccontainer">
<div id="container" width="486.5" height="588.7">
<svg version="1.1" id="map" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100%" height="100%" viewBox="0 0 486.49 588.704" enable-background="new 0 0 486.49 588.704"
xml:space="preserve">
<path fill="#61C769" d="M407.78,400.167l2.326,12.377c0,0,19.187,6.895,28.652,14.865c9.47,7.977,21.099,16.941,21.099,16.941
s8.639-6.145,13.538-18.52c4.897-12.379,4.564-25.666,4.564-25.666h-70.18V400.167z"/>
<polyline fill="#61C769" points="486.49,543.133 400.222,540.866 351.772,538.208 352.049,590.2 486.49,590.2 "/>
<path fill="#61C769" d="M351.116,134.386h53.425v94.685c0,0,0,4.319-3.155,6.811c-3.154,2.492-6.313,2.492-6.313,2.492h-43.68
L351.116,134.386z"/>
<polygon fill="#61C769" points="407.198,133.722 407.198,164.453 475.804,164.453 475.804,134.386 "/>
<polygon fill="#61C769" points="407.198,167.774 407.198,238.372 476.8,238.372 475.804,167.774 "/>
<path fill="#61C769" d="M351.44,241.583h33.83c0,0,3.547-0.664,7.09,2.658c3.543,3.322,2.656,6.506,2.656,6.506l0.1,142.773
c0,0-2.756,1.107-7.188,6.201c-4.433,5.094-3.986,7.918-3.986,7.918h-32.269L351.44,241.583z"/>
<path fill="#61C769" d="M420.653,242.524h56.146l1.495,153.434h-78.847l-1.108-132.253c0,0-0.22-8.388,6.204-14.59
C410.967,242.912,420.653,242.524,420.653,242.524z"/>
<path fill="#61C769" d="M389.701,407.641l15.724,3.82c0,0,3.104-9.523-4.98-11.52C392.358,397.952,389.701,407.641,389.701,407.641z
"/>
<path fill="#61C769" d="M389.259,411.461c0,0,0.443,2.105,4.1,4.096c3.655,1.994,5.426,1.553,5.426,1.553s-0.246-1.439-3.665-3.652
C391.694,411.241,389.259,411.461,389.259,411.461z"/>
<path fill="#61C769" d="M351.685,411.461l33.42,0.996l7.144,7.475l7.478,0.832l3.486,1.494c0,0,4.318,7.145,5.979,12.957
c1.66,5.814,2.491,12.23,2.491,12.23v69.496c0,0-1.661,5.979-7.81,12.293c-6.146,6.313-12.957,7.477-12.957,7.477l-38.979-2.162
L351.685,411.461z"/>
<path fill="#61C769" d="M416.335,92.69l-8.026,14.12l7.029,1.883l3.821,3.599h45.018V75.901l-5.896,1.839
c0,0-5.565,12.611-14.867,16.356c-9.303,3.745-20.045,0.919-20.045,0.919L416.335,92.69z"/>
<path fill="#61C769" d="M190.256,395.348l42.856,10.135v7.477l-8.97,61.297c0,0-4.153,23.92-23.422,38.039
c-19.27,14.119-43.854,13.23-43.854,13.23l12.458-53.932l19.436-6.119l2.99-12.816l-2.324-9.635l6.312-26.91L190.256,395.348z"/>
<polygon fill="#61C769" points="286.435,410.963 331.606,411.627 333.342,533.387 270.653,524.252 "/>
<path fill="#61C769" d="M159.524,529.237v26.91h-9.636l-2.158,2.822l2.158,29.898h114.12V553.43l2.884-25.857l-57.919-8.639
c0,0-13.232,2.404-24.362,6.604C173.48,529.735,159.524,529.237,159.524,529.237z"/>
<polygon fill="#61C769" points="267.996,539.37 266.335,556.536 266.89,588.872 334.108,590.2 333.342,536.875 290.255,530.899
287.017,540.948 "/>
<path fill="#61C769" d="M111.518,408.803l7.309,58.359v54.982l-37.984-11.018l-60.133-0.225V440.36c0,0,3.018-11.047,5.842-15.695
c2.824-4.652,6.563-8.475,12.625-10.467C45.238,412.208,111.518,408.803,111.518,408.803z"/>
<polygon fill="#61C769" points="111.186,0.166 111.186,130.066 6.534,130.066 6.534,134.054 111.186,135.715 111.186,207.476
37.763,207.476 36.434,245.017 0.554,245.017 0.554,0.166 "/>
<rect x="116.17" y="0.166" fill="#61C769" width="162.79" height="32.226"/>
<polygon fill="#61C769" points="116.17,34.718 116.17,57.974 205.537,58.306 205.537,35.05 "/>
<polygon fill="#61C769" points="116.17,60.133 116.17,116.446 116.17,129.9 228.295,129.9 228.295,97.343 206.202,97.011
205.953,60.632 "/>
<polygon fill="#61C769" points="208.113,86.918 208.113,95.059 236.6,95.017 247.729,91.86 247.729,86.876 "/>
<rect x="208.113" y="34.718" fill="#61C769" width="40.035" height="50.665"/>
<polygon fill="#61C769" points="250.804,34.718 250.804,73.256 280.87,73.256 278.96,34.718 "/>
<polyline fill="#61C769" points="327.62,124.543 327.481,129.9 231.588,129.9 231.588,102.41 280.509,102.41 280.509,100
235.74,100 248.365,96.014 279.845,96.014 279.845,93.938 251.022,93.938 251.022,75.083 281.09,75.083 282.668,116.446 "/>
<line fill="none" x1="325.72" y1="-5.149" x2="334.108" y2="594.85"/>
<line fill="none" x1="350.831" y1="-5.149" x2="352.049" y2="594.85"/>
<path fill="none" d="M157.365,116.777"/>
<rect x="116.17" y="134.386" fill="#61C769" width="30.397" height="18.106"/>
<rect x="149.889" y="134.386" fill="#61C769" width="79.07" height="19.271"/>
<rect x="116.17" y="155.315" fill="#61C769" width="30.397" height="37.708"/>
<rect x="116.17" y="195.682" fill="#61C769" width="30.397" height="11.96"/>
<polygon fill="#61C769" points="149.889,156.313 149.889,194.02 211.02,193.023 211.02,156.313 "/>
<rect x="149.889" y="195.682" fill="#61C769" width="61.129" height="12.625"/>
<path fill="#61C769" d="M213.178,187.542c0,2.99,4.319,6.645,8.473,6.479c4.152-0.166,6.313-2.658,6.645-5.315
c0.334-2.658,0.166-22.924,0-27.077c-0.166-4.153-3.654-6.312-7.393-6.312c-3.739,0-7.559,3.156-7.725,6.146
C213.012,164.453,213.178,187.542,213.178,187.542z"/>
<rect x="231.368" y="134.386" fill="#61C769" width="53.074" height="19.271"/>
<polygon fill="#61C769" points="231.368,156.313 231.368,188.539 228.959,193.023 284.44,193.023 284.44,156.313 "/>
<rect x="213.104" y="195.682" fill="#61C769" width="71.338" height="12.625"/>
<polygon fill="#FFC496" points="3.876,225.857 10.299,225.857 10.299,191.971 30.011,191.971 30.011,237.817 34.219,237.817
34.219,221.65 35.992,221.872 37.099,186.212 3.876,186.212 "/>
<polygon fill="#FFC496" points="10.963,236.046 12.93,239.121 17.83,236.046 15.836,232.891 "/>
<polygon fill="#61C769" points="40.199,211.24 39.534,245.017 104.319,245.017 110.188,249.114 110.188,211.24 "/>
<rect x="41.307" y="215.227" fill="#91999C" width="26.024" height="8.416"/>
<rect x="41.307" y="232.891" fill="#91999C" width="26.024" height="7.917"/>
<rect x="76.856" y="232.393" fill="#91999C" width="24.362" height="8.416"/>
<polygon fill="#91999C" points="72.204,215.227 72.204,223.644 104.762,223.644 104.762,236.601 108.749,236.601 108.749,215.227
"/>
<path fill="#61C769" d="M0.554,248.45v81.507c0,0,98.45,0.662,102.879,0c-0.221-4.211,1.219-22.926,5.205-30.898
c3.987-7.973,13.731-17.83,13.621-22.701c-0.109-4.872-20.598-27.907-20.598-27.907L0.554,248.45L0.554,248.45z"/>
<path fill="#91999C" d="M5.205,258.527c0,0-0.664,19.379,0,19.601c0.665,0.222,8.528,0,8.528,0v3.876h13.511l0.443-23.478
L5.205,258.527L5.205,258.527z"/>
<polygon fill="#91999C" points="33.334,263.067 33.334,276.688 44.075,276.688 44.075,263.067 40.864,263.067 40.864,260.3
70.099,260.3 70.099,251.994 35.992,251.994 35.88,262.734 "/>
<polygon fill="#91999C" points="4.91,285.88 4.91,295.515 21.374,295.515 21.374,291.97 31.673,291.638 31.673,285.88 "/>
<polygon fill="#91999C" points="39.534,297.288 39.534,305.15 64.563,305.15 64.119,297.288 "/>
<rect x="85.161" y="257.642" fill="#91999C" width="22.591" height="6.313"/>
<polygon fill="#91999C" points="72.869,297.84 72.869,305.814 90.698,305.814 100.332,295.515 100.332,291.638 93.245,291.638
93.135,294.959 89.924,297.84 "/>
<rect x="94.574" y="274.252" fill="#91999C" width="20.488" height="7.199"/>
<rect x="85.161" y="275.472" fill="#FFC496" width="5.979" height="5.538"/>
<polygon fill="#61C769" points="103.213,336.823 103.434,343.133 47.508,343.133 47.508,373.036 0,373.036 0.332,336.823 "/>
<polygon fill="#FFC496" points="19.491,358.417 19.491,365.391 44.85,366.721 44.85,359.633 "/>
<polygon fill="#00AAFF" points="0.554,116.446 111.186,116.446 111.186,124.543 0.554,124.336 "/>
<polygon fill="#00AAFF" points="116.17,116.446 228.295,116.446 228.295,124.336 116.17,124.543 "/>
<polygon fill="#00AAFF" points="231.368,116.446 313.399,116.446 316.724,119.546 327.481,119.546 327.62,124.543 231.368,124.086
"/>
<polygon fill="#00AAFF" points="0.554,329.958 0.554,336.823 103.213,336.823 103.434,329.958 "/>
<rect x="248.772" y="211.461" fill="#61C769" width="36.664" height="17.109"/>
<rect x="213.104" y="211.461" fill="#61C769" width="32.385" height="47.674"/>
<polygon fill="#91999C" points="215.09,228.572 215.09,235.3 240.92,235.3 240.92,248.45 214.176,248.45 214.176,256.479
244.076,256.479 244.076,228.572 "/>
<path fill="#61C769" d="M113.678,211.24v45.239l11.129,14.12c0,0,1.08,1.329,3.322,1.329c2.24,0,3.239-0.997,3.239-0.997
s6.313-4.236,10.051-6.562c3.738-2.326,14.868-5.233,14.868-5.233h53.82l-0.041-47.896H113.678L113.678,211.24z"/>
<polygon fill="#91999C" points="114.84,212.708 114.84,223.92 146.567,223.92 146.567,215.227 123.811,215.227 123.811,212.708 "/>
<rect x="117.083" y="229.568" fill="#91999C" width="29.486" height="7.807"/>
<rect x="117.083" y="244.27" fill="#91999C" width="29.818" height="7.309"/>
<polygon fill="#91999C" points="158.361,225.914 158.361,234.802 169.574,234.802 169.574,243.854 176.053,243.854 176.053,225.914
"/>
<rect x="157.947" y="246.678" fill="#91999C" width="18.854" height="7.309"/>
<polygon fill="#91999C" points="180.62,240.532 180.62,255.067 189.924,255.067 189.924,247.26 207.615,247.26 207.615,238.262
200.555,238.262 200.555,240.698 "/>
<path fill="#61C769" d="M50.388,346.012v29.898H0V588.87h142.082v-32.559h-8.638l-12.568-12.568l-1.8-18.326L82.78,514.288v17.605
H4.374v-20.432h11.96c0,0-0.56-64.295,0-71.432c1.661-6.811,5.814-13.785,8.97-18.438c3.156-4.65,8.139-9.303,14.95-10.465
s70.597-4.982,70.597-4.982l-7.418-60.133H50.388L50.388,346.012z"/>
<rect x="6.092" y="513.235" fill="#FFFF00" width="74.75" height="17.83"/>
<rect x="27.242" y="440.366" fill="#91999C" width="12.402" height="53.602"/>
<path fill="#FFFF00" d="M43.467,433.387v65.449h5.26c0,0,5.647,8.139,15.947,8.139c10.299,0,16.168-8.305,16.168-8.305h5.093
v-13.787h4.652v-31.729H86.6v-18.771h-6.811c0,0-4.651-7.645-14.95-7.645c-10.299,0-13.6,6.666-13.6,6.666L43.467,433.387z"/>
<rect x="49.059" y="443.522" fill="#61C769" width="31.783" height="48.008"/>
<polygon fill="#91999C" points="90.588,539.481 104.43,553.432 118.826,540.143 103.545,525.526 "/>
<polygon fill="#FFC496" points="58.139,544.575 64.95,549.667 69.767,543.024 63.953,538.592 "/>
<polygon fill="#61C769" points="282.282,0.166 325.72,0.166 327.481,119.546 316.724,119.546 313.399,116.446 285.604,116.446 "/>
<polygon fill="#61C769" points="288.926,134.386 288.926,239.591 329.179,239.591 327.69,134.386 "/>
<rect x="290.478" y="212.708" fill="#FFC496" width="13.729" height="7.309"/>
<rect x="291.806" y="223.92" fill="#FFC496" width="13.729" height="4.651"/>
<rect x="310.188" y="213.678" fill="#FFC496" width="8.858" height="3.544"/>
<rect x="310.188" y="220.018" fill="#FFC496" width="7.31" height="3.904"/>
<polygon fill="#61C769" points="248.772,231.174 248.772,257.309 267.104,239.591 285.438,239.591 285.438,231.174 "/>
<polygon fill="#FFC496" points="262.349,233.473 262.349,239.591 269.097,238.262 283.39,237.375 283.39,232.282 269.097,232.282
267.104,233.473 "/>
<polygon fill="#61C769" points="269.076,242.524 247.647,261.877 247.647,301.331 286.767,300.415 285.937,242.524 "/>
<polygon fill="#FFC496" points="253.378,260.963 251.22,265.283 259.108,269.187 283.86,269.187 283.86,263.788 260.022,264.286 "/>
<polygon fill="#FFC496" points="253.378,275.416 251.22,279.984 259.192,284.22 284.772,284.22 284.772,278.904 260.354,279.402 "/>
<polygon fill="#FFC496" points="253.794,291.363 251.22,295.433 259.608,298.92 284.772,298.504 284.772,294.019 260.604,295.142
"/>
<polygon fill="#61C769" points="247.647,303.407 247.647,325.333 287.599,325.333 286.767,302.991 "/>
<polygon fill="#FFC496" points="257.946,306.643 252.797,306.643 252.797,318.606 253.71,318.606 253.71,320.305 255.787,320.305
255.787,323.711 270.362,323.711 270.362,322.01 271.981,322.01 271.981,320.596 273.229,320.596 273.229,311.502 268.452,311.502
268.452,307.766 265.006,307.766 265.006,306.85 260.854,306.85 260.854,304.195 257.985,304.195 "/>
<polygon fill="#61C769" points="247.647,328.159 247.647,340.2 287.599,339.536 287.599,327.327 "/>
<path fill="#61C769" d="M159.856,262.957c4.042,0,84.22,0,84.22,0l-0.997,63.456c0,0-127.132,0-136.213,0
c-0.222-10.74,3.321-23.091,6.812-29.566c3.487-6.479,10.963-16.28,16.112-20.433C134.94,272.259,155.814,262.957,159.856,262.957z"
/>
<rect x="290.478" y="135.493" fill="#FFFF00" width="35.987" height="72.813"/>
<polygon fill="#61C769" points="288.261,242.524 292.415,406.809 331.537,406.809 329.179,242.524 "/>
<rect x="293.079" y="245.682" fill="#FFC496" width="27.74" height="5.067"/>
<polygon fill="#FFC496" points="291.834,263.705 291.834,269.187 300.388,269.187 306.95,272.676 309.899,268.604 301.47,264.37 "/>
<polygon fill="#FFC496" points="291.834,280.814 291.834,286.462 299.89,286.462 306.95,289.702 309.899,286.296 300.866,282.06 "/>
<polygon fill="#FFC496" points="292.248,293.937 292.248,298.92 300.306,298.92 307.032,302.991 309.899,298.463 301.075,294.685
"/>
<polygon fill="#FFFF00" points="313.927,264.619 313.927,307.059 297.315,307.059 297.315,321.262 322.315,321.262 321.649,264.619
"/>
<rect x="106.857" y="328.182" fill="#61C769" width="50.009" height="11.686"/>
<polygon fill="#61C769" points="158.417,328.182 158.417,339.868 243.411,340.2 243.411,328.182 "/>
<rect x="106.857" y="330.899" fill="#00AAFF" width="50.009" height="5.924"/>
<polygon fill="#00AAFF" points="158.417,330.899 158.417,336.045 243.411,336.823 243.411,330.899 "/>
<polygon fill="#00AAFF" points="247.647,330.899 247.647,336.823 287.599,336.045 287.599,329.901 "/>
<polygon fill="#00AAFF" points="290.47,329.901 290.622,335.879 330.506,335.049 330.506,328.407 "/>
<polygon fill="#91999C" points="296.235,385.381 296.235,396.51 318.993,397.508 318.993,389.702 303.046,389.37 303.046,385.381
"/>
<polygon fill="#FFC496" points="294.906,340.2 294.906,343.356 323.976,343.356 323.976,350.333 326.966,350.333 326.966,340.2 "/>
<rect x="294.906" y="350.333" fill="#FFC496" width="28.405" height="2.656"/>
<polygon fill="#FFFF00" points="292.248,353.987 293.411,384.053 326.966,384.883 326.966,353.987 "/>
<polygon fill="#61C769" points="246.733,343.024 238.429,402.161 289.591,407.641 288.261,343.024 "/>
<polygon fill="#FFC496" points="246.899,361.129 246.899,365.616 251.22,374.252 244.076,379.735 244.076,384.883 249.226,386.543
256.368,395.348 256.368,400.999 260.854,400.999 267.621,397.508 276.136,403.821 279.292,403.821 281.285,399.168
276.966,392.526 279.79,389.868 263.013,368.274 266.335,365.948 276.634,379.569 281.285,375.915 271.981,362.625 269.989,356.809
259.026,358.969 261.021,365.284 257.198,367.61 252.797,360.797 "/>
<polygon fill="#FFC496" points="266.501,345.266 266.501,353.987 276.302,353.987 276.302,363.29 281.285,363.29 281.285,345.266
"/>
<polygon fill="#61C769" points="106.857,343.024 243.411,343.024 234.441,400.833 166.17,383.387 164.176,390.866 187.266,395.846
193.079,416.114 186.6,443.356 188.76,452.327 186.6,462.625 168.494,468.938 166.999,470.43 153.545,525.526 122.315,525.526
122.481,465.475 "/>
<path fill="#61C769" d="M238.429,405.649l-11.13,74.75c0,0-3.156,10.965-7.641,17.441c-4.484,6.479-8.473,11.461-8.473,11.461
l5.814,7.809l50.333,7.145l16.112-113.289L238.429,405.649z"/>
<polygon fill="#91999C" points="305.205,423.752 305.205,441.696 324.476,441.696 324.476,422.922 "/>
<path fill="#FFFF00" d="M284.274,451.497l-8.971,65.447l5.979,0.666c0,0,4.317,7.643,14.118,8.639
c9.802,0.994,11.131-0.664,15.615-3.488c4.482-2.824,8.639-11.627,8.639-11.627l5.813-42.193c0,0-0.662-7.973-4.15-12.625
c-3.487-4.648-12.728-9.469-19.32-8.803c-6.594,0.664-12.406,4.814-12.406,4.814L284.274,451.497z"/>
<path fill="#61C769" d="M287.433,464.952l-5.316,38.039c0,0-0.83,14.951,14.451,17.939c15.283,2.988,18.271-11.961,18.271-11.961
l5.148-40.199c0,0-1.164-14.205-14.783-15.945C291.587,451.084,287.433,464.952,287.433,464.952z"/>
<polygon fill="#FFC496" points="234.109,364.288 229.458,389.756 234.551,390.973 238.429,364.838 "/>
<polygon fill="#91999C" points="163.234,354.874 160.521,362.514 165.561,369.379 191.362,376.026 195.571,383.885 215.395,388.649
219.27,386.434 221.042,378.68 215.836,377.131 210.688,380.317 200.914,377.629 197.232,372.704 199.779,370.489 194.99,362.292
188.594,360.852 186.379,362.403 180.066,360.963 178.737,361.848 171.762,360.411 169.436,356.809 "/>
<polygon fill="#91999C" points="201.329,405.649 214.065,411.905 212.624,417.776 196.235,423.643 194.99,426.745 201.883,428.625
215.063,420.209 213.621,426.745 212.292,426.633 211.186,431.397 217.608,433.5 219.713,428.293 224.032,429.512 225.471,424.086
217.608,422.424 219.602,412.903 225.471,414.231 226.91,408.139 219.823,406.147 219.049,408.803 202.215,402.047 "/>
<polygon fill="#91999C" points="198.118,439.59 197.121,443.356 210.41,449.002 208.971,455.649 192.139,460.963 191.141,464.952
198.229,466.612 210.41,457.75 207.754,469.161 213.733,471.262 220.709,465.504 220.709,461.627 214.508,460.444 212.957,464.952
210.41,464.288 211.961,457.75 213.289,457.864 215.395,450.776 221.374,451.772 222.813,445.573 215.615,443.688 214.95,446.458
"/>
<polygon fill="#91999C" points="175.747,471.262 172.869,478.348 179.956,480.342 177.963,489.315 173.865,488.54 172.869,493.081
179.956,494.741 175.747,505.374 167.109,506.038 166.225,511.793 167.774,514.34 173.09,515.45 175.637,514.231 177.52,508.694
184.165,510.688 185.493,505.374 179.956,503.93 182.282,495.625 198.561,501.165 199.447,496.842 182.836,490.641 185.272,480.79
208.086,483 208.971,479.458 184.497,476.69 184.829,473.809 "/>
<path fill="none" d="M203.322,515.45l7.863,0.996c0,0-1.439-2.771-3.932-3.211C204.76,512.793,203.322,515.45,203.322,515.45z"/>
<polygon fill="#FFC496" points="242.636,410.963 242.192,414.454 246.291,415.225 245.627,417.776 250.166,418.547 250.61,414.754
254.597,415.225 254.597,410.963 "/>
<polygon fill="#FFC496" points="260.577,413.79 260.022,417.776 279.956,419.327 280.729,414.754 "/>
<polygon fill="#FFC496" points="258.583,428.075 257.919,431.836 278.073,433.5 278.737,430.176 "/>
<polygon fill="#FFC496" points="256.479,442.25 255.813,446.125 276.08,447.448 276.744,443.579 "/>
<polygon fill="#FFC496" points="239.535,429.735 239.093,433.5 242.97,434.499 242.97,438.151 247.315,438.706 247.315,435.713
251.827,436.709 251.827,432.948 "/>
<polygon fill="#FFC496" points="237.653,446.901 237.099,451.217 240.864,451.995 240.864,454.76 245.461,455.426 245.461,451.165
249.392,451.165 249.944,447.448 "/>
<polygon fill="#FFC496" points="254.597,448.006 253.378,459.194 259.248,459.965 260.022,456.868 268.328,457.641 269.879,450.112
"/>
<polygon fill="#FFC496" points="271.649,451.165 270.653,461.959 274.642,461.959 275.747,451.772 "/>
<polygon fill="#FFC496" points="239.646,459.194 239.646,462.514 245.461,463.29 245.461,460.444 "/>
<polygon fill="#FFC496" points="233.112,466.389 232.227,471.262 252.491,472.151 253.378,468.381 "/>
<polygon fill="#FFC496" points="258.916,464.288 257.919,468.381 262.901,469.268 261.628,472.754 266.999,473.809 266.999,470.264
271.54,471.262 270.653,467.053 "/>
<polygon fill="#FFC496" points="230.676,480.899 230.012,485.327 250.831,486.102 250.831,482.002 "/>
<polygon fill="#FFC496" points="256.812,482.002 256.258,486.102 260.465,486.102 260.465,488.426 264.729,489.092 264.729,484.995
269.437,485.547 269.437,482.002 "/>
<polygon fill="#FFC496" points="249.169,497.84 249.169,501.606 268.883,502.381 268.883,498.504 "/>
<polygon fill="#FFC496" points="246.845,510.797 246.181,514.815 266.89,516.446 266.89,512.792 "/>
<polygon fill="#FFC496" points="231.01,494.077 230.565,497.84 234.995,498.504 234.551,501.165 238.538,501.829 238.982,498.616
243.411,498.725 243.411,495.292 "/>
<polygon fill="#FFC496" points="221.374,507.366 221.374,511.241 225.913,511.241 224.917,515.45 229.016,515.45 230.012,512.125
233.998,513.184 234.885,509.799 "/>
<polygon fill="#91999C" points="8.97,381.12 8.97,413.235 28.239,413.235 28.239,380.456 "/>
<path fill="#91999C" d="M116.336,394.022l2.491,1.326l0.831-2.158c0,0,1.827,2.574,5.98,3.072c4.152,0.498,7.974-1.531,7.974-1.531
l-1.163-2.537l-2.908,0.748l-0.582-5.814l4.237,0.832l0.914-4.57c0,0-7.144-1.41-11.295,1.662
C118.66,388.125,116.336,394.022,116.336,394.022z"/>
<path fill="#00AAFF" d="M166.999,344.85H161.6l-15.448,6.314l-10.797,8.723l-5.897,10.549l0.997,4.734l11.214,19.188v3.738
l-3.572,2.488h-3.986l-6.479-3.156l-1.994-0.082l-1.244,1.494l-2.742-0.996l-3.238,11.627l1.163,9.387v1.744l4.153,6.145
l4.484,0.666l1.495,2.076l0.749,16.031l3.986,13.039l4.9,7.809l4.07,3.322l5.564,4.07l4.902,5.23c0,0-0.166,0.582,1.66,0.416
c1.827-0.166,2.908-2.076,2.908-2.076l3.074-6.064l4.707-4.152l6.755-3.818l6.479-1.494l4.069-3.904l0.498-1.994l-1.911-2.658
l1.329-3.154l-0.664-6.063l1.993-7.893l-0.915-9.883l2.823-9.139v-8.641l-5.066-7.309l-7.973-4.402l-8.557,1.246l-4.568,0.25
l-3.654-2.908l-3.654,0.416l-1.328-4.98l1.328-9.719l-3.82-11.627l3.572-13.207l13.705-10.219L166.999,344.85z"/>
<rect x="142.082" y="512.458" fill="#FFFF00" width="7.807" height="6.48"/>
<polygon fill="#00AAFF" points="0,565.782 110.521,561.627 133.112,558.969 142.082,558.969 142.082,567.11 125.969,567.11
117.497,565.948 0,569.766 "/>
<polygon fill="#91999C" points="163.512,533.387 163.512,539.481 171.983,539.481 171.983,553.905 184.607,553.905 184.607,548.172
175.803,548.172 175.803,536.709 186.684,536.709 186.684,530.899 176.801,530.899 176.801,532.723 "/>
<polygon fill="#FFC496" points="194.99,529.071 194.99,535.381 208.971,532.225 210.022,526.54 "/>
<path fill="#FFC496" d="M217.331,534.547c0,0-3.987,11.133,7.642,13.459c11.627,2.324,14.674-6.729,14.674-6.729l19.379,3.404
l0.664-5.205l-3.434-0.938l0.275-3.156l8.195,1.164l0.605-5.586l-11.129-2.059h-15.283l-4.041,0.998l-1.771,1.824
c0,0,2.936,8.143-3.102,8.973c-6.035,0.83-5.703-5.314-5.703-5.314L217.331,534.547z"/>
<polygon fill="#FFC496" points="203.322,544.85 203.322,553.905 210.022,553.432 210.022,544.188 "/>
<rect x="210.022" y="567.942" fill="#FFC496" width="9.302" height="10.133"/>
<polygon fill="#00AAFF" points="147.73,558.969 264.01,556.536 264.01,560.522 249.169,558.969 226.246,563.178 173.533,564.37
149.889,567.942 148.377,567.942 "/>
<rect x="250.804" y="567.276" fill="#FFC496" width="5.896" height="4.568"/>
<polygon fill="#00AAFF" points="226.303,564.454 229.209,567.276 223.727,569.559 222.398,571.428 225.139,574.917 221.816,575.583
220.488,579.901 223.229,579.487 223.977,577.493 225.471,578.075 227.963,581.813 235.688,583.221 241.005,582.391
250.804,581.979 252.797,579.985 255.87,579.819 255.87,581.231 257.862,581.231 259.524,579.487 261.769,578.075 261.187,576.911
259.856,576.331 256.7,574.252 252.299,575.083 248.562,570.596 247.647,570.264 248.812,575.5 250.14,580.151 241.005,581.065
238.345,574.917 239.591,570.68 237.681,567.942 231.867,567.942 231.617,565.866 230.288,565.534 227.631,563.79 "/>
<polygon fill="#FFC496" points="270.653,540.532 269.437,546.676 285.438,549.043 286.269,542.401 "/>
<polygon fill="#FFC496" points="289.757,533.387 288.595,540.532 303.71,542.401 304.873,535.381 "/>
<polygon fill="#FFC496" points="307.365,538.647 306.202,543.19 308.526,550.833 315.671,549.043 315.006,542.401 323.146,543.19
323.146,548.387 325.72,548.387 325.72,550.833 327.797,550.833 327.797,548.387 326.634,546.842 327.797,538.647 312.017,535.381
"/>
<path fill="#FFC496" d="M272.315,570.43v6.314h8.638c0,0,0.498,4.652,5.315,6.479c4.814,1.828,8.638-1.826,8.638-1.826h7.974v-5.48
l-16.609,0.332v-5.814h-13.953L272.315,570.43L272.315,570.43z"/>
<rect x="296.069" y="563.79" fill="#FFC496" width="25.746" height="8.059"/>
<polygon fill="#61C769" points="270.653,527.577 268.883,536.875 285.604,538.647 287.599,530.899 "/>
<polygon fill="#61C769" points="350.845,1.828 351.44,129.9 403.544,129.9 403.544,114.453 374.198,114.229 374.198,83
391.252,82.559 392.138,18.106 428.019,17.441 428.019,1.828 "/>
<path fill="#61C769" d="M394.574,20.542v30.564l30.788,11.074c0,0,5.092,0.443,7.309-4.208c2.216-4.651-3.32-11.074-3.32-11.074
l-0.442-26.356H394.574z"/>
<polygon fill="#61C769" points="394.574,53.544 423.367,64.396 412.515,92.083 404.319,106.701 403.876,111.352 376.634,111.352
376.634,85.216 394.574,84.773 "/>
<polygon fill="#FFC496" points="396.567,62.192 396.567,69.048 420.045,69.048 420.045,64.176 "/>
<rect x="380.843" y="89.203" fill="#FFC496" width="17.939" height="19.491"/>
<rect x="432.226" y="1.828" fill="#61C769" width="29.234" height="16.279"/>
<path fill="#61C769" d="M432.226,20.542v25.914c0,0,2.215,0.222,3.543,3.1c1.329,2.878,1.771,5.98,1.771,5.98h25.473V20.542H432.226
z"/>
<rect x="436.877" y="43.134" fill="#FFC496" width="23.032" height="7.309"/>
<path fill="#61C769" d="M426.689,65.621l-9.303,24.912c0,0,13.063,6.866,23.256,1.993c10.188-4.873,16.167-15.947,16.167-15.947
l6.202-2.658V57.532h-26.138c0,0,0.226,2.27-3.35,5.177C429.953,65.617,426.689,65.621,426.689,65.621z"/>
<polygon fill="#FFC496" points="435.189,63.041 435.189,70.018 458.279,69.048 458.279,62.192 "/>
<polygon fill="#FFC496" points="423.728,78.656 421.9,85.549 430.454,87.708 446.235,87.708 447.149,80.814 430.288,80.98 "/>
<rect x="418.162" y="100.166" fill="#FFC496" width="40.117" height="8.528"/>
<polygon fill="none" points="407.198,113.788 407.198,129.9 463.013,129.9 463.013,114.619 "/>
<polygon fill="#00AAFF" points="351.392,119.546 358.028,116.446 403.544,116.446 403.544,124.543 358.692,124.543 351.392,123.421
"/>
<polygon fill="#00AAFF" points="407.198,116.446 459.026,116.446 463.013,118.272 463.013,124.543 407.198,124.543 "/>
<rect x="382.78" y="171.898" fill="#FFC496" width="16.111" height="35.742"/>
<rect x="382.78" y="141.03" fill="#FFFF00" width="20.764" height="18.605"/>
<rect x="409.524" y="141.03" fill="#FFFF00" width="64.45" height="18.605"/>
<polygon fill="#FFC496" points="411.518,170.433 411.518,178.903 436.269,178.903 436.269,171.097 "/>
<rect x="445.404" y="170.433" fill="#FFC496" width="27.574" height="9.302"/>
<polygon fill="#FFC496" points="411.518,187.874 411.518,195.183 428.627,195.183 428.627,189.037 "/>
<polygon fill="#FFC496" points="452.714,191.528 452.714,199.335 472.979,199.335 472.979,190.532 "/>
<polygon fill="#FFC496" points="412.681,204.817 412.681,211.461 428.627,213.289 428.627,207.642 "/>
<rect x="431.451" y="223.421" fill="#FFC496" width="15.448" height="6.811"/>
<rect x="454.043" y="207.642" fill="#FFC496" width="19.935" height="8.97"/>
<rect x="454.043" y="225.083" fill="#FFC496" width="18.938" height="8.472"/>
<path fill="#00AAFF" d="M357.862,199.335l-1.494,30.897c0,0,0,1.828,2.658,3.322c2.656,1.495,5.813,1.329,5.813,1.329l17.109,0.005
l0.83-1.334c0,0,5.979,2.336,10.384,1.334c4.402-1.002,7.063-2.996,7.063-2.996v-9.302l2.157-9.302l-1.327-3.488l-3.821,0.499
l-1.827,2.99l-2.989-1.163h-10.632l-3.955-3.074c0,0,0.467-4.901-1.856-7.393C373.644,199.167,357.862,199.335,357.862,199.335z"/>
<polygon fill="#91999C" points="377.298,351.663 377.298,401.274 382.172,401.274 384.165,391.448 391.694,391.448 391.694,381.784
383.5,381.563 383.278,374.032 387.265,373.809 387.265,358.528 391.694,358.528 391.694,351.663 "/>
<polygon fill="#00AAFF" points="351.44,327.327 395.116,327.327 395.076,336.823 351.576,336.823 "/>
<rect x="379.069" y="340.2" fill="#FFC496" width="14.175" height="6.145"/>
<polygon fill="#91999C" points="448.173,245.682 448.173,274.363 466.557,274.363 466.557,269.492 462.847,269.711 462.847,263.705
467.442,257.532 465.671,254.873 462.847,256.867 455.039,257.309 455.039,245.682 "/>
<path fill="#00AAFF" d="M439.176,247.343l6.563,34.571h22.812l4.433,31.209l-7.977,8.141h-15.059l-7.946,0.938l-9.552-2.961
l-5.314,2.021l-8.856-4.154l-3.104,2.133v2.961c0,0,0.332,1.771-2.49,1.553c-2.823-0.221-6.587-4.348-6.587-9.594
c0-5.248,3.1-4.359,3.1-4.359s2.77,0.441,4.099-0.332c1.328-0.773,1.328-3.653,1.328-3.653s2.99,0.332,2.99-2.769
c0-3.102-3.213-3.545-3.213-3.545l-0.441-3.102l-7.088-2.326l-0.771-1.771l1.327-2.99l-2.324-6.423l0.997-3.1l-0.997-3.544
c0,0-0.558-9.524,0.439-12.402c0.996-2.878,6.535-8.86,6.535-8.86s4.763-5.648,7.197-6.867
C421.706,246.899,439.176,247.343,439.176,247.343z"/>
<rect x="398.872" y="327.327" fill="#00AAFF" width="78.753" height="9.496"/>
<polygon fill="#FFC496" points="452.491,345.125 452.491,353.432 475.638,352.991 475.638,344.352 "/>
<polygon fill="#FFC496" points="451.938,364.065 451.938,371.153 475.638,372.258 474.973,366.057 "/>
<polygon fill="#FFC496" points="452.491,383.885 452.491,392.417 475.638,392.417 475.638,383.446 "/>
<polygon fill="#FFC496" points="402.88,341.696 402.88,350.553 438.248,350.553 438.248,342.692 "/>
<polygon fill="#FFC496" points="406.202,387.928 406.202,392.417 436.656,392.417 436.656,384.442 412.847,384.442 412.515,387.928
"/>
<polygon fill="#FFC496" points="430.206,403.323 430.206,415.45 437.764,415.45 447.564,425.25 447.564,430.317 460.771,430.733
461.352,418.606 472.481,418.772 472.481,401.747 465.172,401.747 466.253,413.208 460.938,413.208 461.02,403.573 "/>
<polygon fill="#FFFF00" points="363.345,437.042 363.345,461.295 403.876,460.463 403.876,436.211 "/>
<polygon fill="#FFC496" points="406.202,439.04 407.78,460.131 410.354,460.131 408.279,439.04 "/>
<path fill="#61C769" d="M411.684,417.776l21.928,10.797l47.01,42.357l0.831,3.156l-1.163,64.119h-50.083c0,0-3.904-1.33-8.722-6.48
c-4.818-5.148-7.811-13.785-7.811-13.785l0.332-66.941c0,0,0-4.65-2.323-13.455c-2.325-8.807-5.677-17.109-5.677-17.109
s-0.472-2.41,1.771-3.281C410.021,416.28,411.684,417.776,411.684,417.776z"/>
<path fill="#FFC496" d="M410.354,425.637h4.266v-4.762h-2.132c0,0-1.302-0.223-2.131,0.885
C409.525,422.87,410.354,425.637,410.354,425.637z"/>
<polygon fill="#FFC496" points="414.618,429.958 414.618,436.211 424.475,436.211 424.475,445.573 416.391,445.573 416.501,451.774
425.804,451.774 425.804,447.456 441.86,447.565 441.86,441.25 427.242,440.866 426.689,429.958 "/>
<rect x="445.737" y="452.547" fill="#FFC496" width="9.081" height="7.584"/>
<rect x="417.275" y="461.961" fill="#FFC496" width="17.938" height="6.529"/>
<polygon fill="#FFC496" points="440.311,465.227 440.311,472.483 446.401,472.483 446.401,468.495 443.71,465.227 "/>
<rect x="459.248" y="463.956" fill="#FFC496" width="9.302" height="6.531"/>
<rect x="417.275" y="479.014" fill="#FFC496" width="17.938" height="5.98"/>
<polygon fill="#FFC496" points="440.976,479.014 440.976,485.772 451.274,485.772 451.717,479.014 "/>
<rect x="469.215" y="482.004" fill="#FFC496" width="9.637" height="6.09"/>
<rect x="416.833" y="495.405" fill="#FFC496" width="10.632" height="7.861"/>
<rect x="417.83" y="512.348" fill="#FFC496" width="11.188" height="7.752"/>
<polygon fill="#FFC496" points="435.216,528.293 434.773,536.159 446.345,536.159 446.345,528.293 "/>
<rect x="453.268" y="528.293" fill="#FFC496" width="23.695" height="7.861"/>
<polygon fill="#FFC496" points="457.143,511.35 457.143,519.106 478.85,518.549 478.405,511.35 "/>
<rect x="457.808" y="495.958" fill="#FFC496" width="21.039" height="7.861"/>
<rect x="401.44" y="43.134" fill="#FFC496" width="22.452" height="7.309"/>
<path fill="#61C769" d="M398.561,536.709l24.86,1.496l-11.737-14.896c0,0-2.294,4.016-5.714,7.088
C402.549,533.471,398.561,536.709,398.561,536.709z"/>
<polygon fill="#00AAFF" points="266.335,556.536 333.342,553.905 333.342,557.641 266.384,559.417 "/>
<polyline fill="#61C769" points="486.49,0.997 464.176,0.997 467.996,129.069 486.49,129.069 "/>
<polyline fill="#61C769" points="486.49,134.386 479.458,134.386 480.62,238.372 486.49,238.372 "/>
<polyline fill="#61C769" points="486.49,242.524 480.454,242.524 481.285,319.932 486.49,319.932 "/>
<path fill="#61C769" d="M486.49,324.584h-5.04c0,0,0.498,79.232,0,83.057c-0.499,3.82-4.429,17.662-6.812,22.314
c-2.381,4.648-11.795,16.555-11.795,16.555l23.646,22.346"/>
<polyline fill="#00AAFF" points="486.49,118.604 467.684,118.604 467.86,124.543 486.49,124.543 "/>
<polyline fill="#00AAFF" points="486.49,327.327 481.467,327.327 481.467,336.823 486.49,336.823 "/>
<polyline fill="#00AAFF" points="486.49,548.118 351.978,553.891 351.985,558.305 486.49,553.209 "/>
<path fill="#91999C" d="M56.7,89.536l1.994-7.642c0,0-14.95-6.645-17.608-24.252c-2.658-17.608,0.997-22.923,10.631-27.907
c9.635-4.983,18.605,2.326,23.588,5.648c4.983,3.322,9.967,8.638,13.289,17.608c2.547,6.312,1.33,9.634,1.33,9.634l7.974,1.828
c0,0,1.329-1.329,3.487-0.831c2.16,0.499,2.99,1.994,2.492,5.482s-0.996,5.316-4.152,5.149c-3.156-0.166-4.043-3.212-3.821-6.478
c-1.649-0.387-4.873-1.163-6.812-1.495c-0.166,2.879-4.816,10.077-8.14,11.96c1.01,1.698,3.655,6.146,3.655,6.146l1.826-0.499
c0,0-0.332,2.492-2.823,3.654c-2.492,1.163-4.651,0.499-4.651,0.499l1.827-1.661c0,0-2.492-3.654-3.654-5.648
c-1.994,1.994-9.635,3.987-14.452,1.994c-0.897,3.678-1.661,6.811-1.661,6.811s5.15,0.664,4.319,5.149s-2.658,3.488-5.98,2.824
c-3.322-0.664-4.817-1.993-4.485-4.651C55.205,90.2,56.7,89.536,56.7,89.536z"/>
<rect x="122.592" y="17.664" fill="#FFC496" width="23.697" height="6.202"/>
<rect x="156.922" y="20.765" fill="#FFC496" width="11.295" height="5.094"/>
<rect x="169.768" y="18.993" fill="#FFC496" width="22.813" height="4.873"/>
<rect x="198.118" y="21.429" fill="#FFC496" width="5.095" height="5.538"/>
<rect x="209.856" y="23.312" fill="#FFC496" width="22.813" height="4.734"/>
<rect x="243.301" y="25.679" fill="#FFC496" width="10.634" height="4.166"/>
<rect x="255.481" y="23.312" fill="#FFC496" width="22.146" height="4.734"/>
<rect x="122.592" y="38.482" fill="#FFC496" width="23.697" height="5.315"/>
<rect x="147.398" y="41.141" fill="#FFC496" width="22.369" height="4.209"/>
<rect x="179.514" y="50" fill="#FFC496" width="23.697" height="5.758"/>
<rect x="197.232" y="42.524" fill="#FFC496" width="3.433" height="3.821"/>
<rect x="124.807" y="62.183" fill="#FFC496" width="22.591" height="5.315"/>
<rect x="149.391" y="63.068" fill="#FFC496" width="23.479" height="5.979"/>
<rect x="209.856" y="100" fill="#FFC496" width="11.047" height="4.817"/>
<rect x="209.856" y="48.671" fill="#FFC496" width="22.093" height="4.817"/>
<rect x="233.444" y="51.081" fill="#FFC496" width="11.13" height="3.904"/>
<rect x="211.186" y="63.068" fill="#FFC496" width="6.478" height="5.979"/>
<rect x="209.856" y="77.409" fill="#FFC496" width="22.093" height="4.817"/>
<rect x="233.444" y="75.416" fill="#FFC496" width="11.13" height="5.149"/>
<polygon fill="#FFC496" points="253.933,45.35 253.933,50 277.631,50 276.966,45.35 "/>
<rect x="267.332" y="57.309" fill="#FFC496" width="7.146" height="3.987"/>
<rect x="266.558" y="66.059" fill="#FFC496" width="11.069" height="4.54"/>
<rect x="253.933" y="85.715" fill="#FFC496" width="23.694" height="4.817"/>
<rect x="233.444" y="105.481" fill="#FFC496" width="23.09" height="4.319"/>
<rect x="257.862" y="107.642" fill="#FFC496" width="22.426" height="3.821"/>
<rect x="292.913" y="9.137" fill="#FFFF00" width="19.77" height="103.655"/>
<rect x="128.959" y="144.519" fill="#FFC496" width="6.146" height="5.481"/>
<rect x="227.922" y="198.338" fill="#FFC496" width="21.636" height="4.651"/>
<rect x="257.903" y="199.833" fill="#FFC496" width="22.385" height="4.651"/>
<rect x="233.444" y="182.393" fill="#FFC496" width="23.09" height="4.319"/>
<polygon fill="#FFC496" points="257.862,180.564 257.903,185.549 279.492,185.549 279.492,180.564 "/>
<rect x="254.209" y="162.791" fill="#FFC496" width="22.591" height="5.481"/>
<polygon fill="#FFC496" points="234.275,145.516 234.275,150.997 256.534,150.997 256.7,145.516 "/>
<rect x="257.903" y="147.26" fill="#FFC496" width="22.385" height="4.735"/>
<rect x="203.876" y="145.516" fill="#FFC496" width="22.425" height="4.485"/>
<rect x="121.484" y="157.808" fill="#FFC496" width="22.093" height="32.558"/>
<rect x="151.883" y="147.26" fill="#FFC496" width="22.094" height="4.569"/>
<rect x="175.305" y="145.516" fill="#FFC496" width="22.592" height="4.485"/>
<rect x="181.783" y="162.625" fill="#FFC496" width="22.093" height="4.983"/>
<rect x="151.883" y="182.393" fill="#FFC496" width="22.094" height="4.319"/>
<rect x="181.783" y="180.564" fill="#FFC496" width="22.093" height="4.817"/>
<rect x="151.883" y="199.335" fill="#FFC496" width="23.422" height="5.15"/>
<rect x="181.783" y="198.338" fill="#FFC496" width="22.093" height="4.651"/>
<polygon fill="#91999C" points="207.615,266.943 207.615,285.88 218.162,285.88 218.162,282.559 234.109,282.393 234.109,267.774
"/>
<polygon fill="#91999C" points="197.232,294.019 197.232,303.157 223.645,303.157 221.816,312.625 213.104,312.625 213.104,320.764
230.62,320.764 230.62,307.391 235.438,307.391 235.438,298.728 225.471,298.728 225.305,294.019 "/>
<polygon fill="#91999C" points="195.571,308.305 195.571,317.776 202.715,324.917 210.688,324.917 210.688,317.444 203.129,317.61
203.129,308.305 "/>
<polygon fill="#91999C" points="167.372,266.943 167.372,275.472 174.309,275.472 174.309,285.216 159.856,285.216 159.856,292.359
182.115,292.359 182.115,285.88 176.801,285.88 176.801,275.472 198.727,275.472 198.727,266.943 "/>
<polygon fill="#91999C" points="115.063,298.728 112.182,312.792 115.063,315.616 115.836,318.44 113.678,319.6 113.678,324.917
125.969,324.917 124.641,318.772 119.076,318.772 117.083,314.122 125.139,314.288 125.139,311.823 118.162,310.297
118.328,308.305 122.979,308.305 122.979,298.728 "/>
<polygon fill="#91999C" points="127.797,301.331 127.797,308.305 136.434,308.305 136.434,322.258 160.521,322.258 160.521,314.952
140.256,314.952 140.256,305.814 152.049,305.814 152.049,299.5 135.438,299.5 135.438,301.331 "/>
<rect x="268.246" y="248.423" fill="#FFC496" width="15.614" height="4.651"/>
<rect x="54.374" y="348.338" fill="#91999C" width="7.974" height="4.209"/>
<rect x="274.726" y="221.152" fill="#FFC496" width="5.979" height="5.538"/>
<line fill="none" x1="338.261" y1="-5.149" x2="343.222" y2="594.85"/>
</svg>
</div>
</div>
<div>
<button id="in" type="button" onclick="bigger();">+</button>
<button id="out" type="button" onclick="smaller();">-</button>
</div>
</body>
</html><file_sep>
<!DOCTYPE html>
<html>
<body>
<style type="text/css">
.title
{
font-family: 黑体, serif;
font-size:5em;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
margin-bottom: 25%;
}
body
{
background-color: #4d7b95;
text-align:center;
position:relative;
animation:myfirst 1s;
-moz-animation:myfirst 1s; /* Firefox */
-webkit-animation:myfirst 1s; /* Safari and Chrome */
-o-animation:myfirst 1s; /* Opera */
}
@keyframes myfirst
{
0% {left:100%;}
100% {left:0px;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {left:100%;}
100% {left:0px;}
}
@-webkit-keyframes myfirst /* Safari 和 Chrome */
{
0% {left:100%;}
100% {left:0px;}
}
@-o-keyframes myfirst /* Opera */
{
0% {left:100%;}
100% {left:0px;}
}
.selection
{
background:rgba(0, 0, 0, 0.4);
font-family: 黑体, serif;
color: #ffffff;
width:auto;
margin-left: auto;
margin-right: auto;
margin-top: 5%;
margin-bottom: 25%;
font-size:24px;
}
#mask
{
background-color: #4d7b95;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
z-index:1032;
opacity: 0; /* 通用,其他浏览器 有效*/
}
</style>
</head>
<body>
<div id="mask" hidden=true>
</div>
<div text-align = "center" class="title" id="quGuangJie">选地图<br/>去逛街!</div>
<form hidden='true' id='form' method="post">
<input name="mapId"></input>
</form>
<?php
$link = new mysqli("localhost","root","12345","quguangjie");
$query = "select * from Map order by name";
$result = $link->query($query);
while($row = $result->fetch_assoc())
{
echo "<div class = \"selection\" onclick = \"jumping('" . $row['number'] . "')\">" . $row['name'] . "</div>";
}
?>
<script type="text/javascript">
var alpha=0;
function jumping(p)
{
document.getElementById("mask").hidden=false;
self.setInterval("wiping()",20);
var t=setTimeout("loadMap(" + p + ");",600);
}
function wiping()
{
document.getElementById("mask").style.opacity=(alpha+=0.07);
}
function loadMap(p)
{
var form = document.getElementById("form");
form.action = "svgmaps/" + p + ".php";
form.children[0].value = p;
form.submit();
}
var width = screen.availWidth;
var height = screen.availWidth;
var length = width;
var title = document.getElementById("quGuangJie");
title.style.fontSize = length/8+"px";
</script>
</body>
</html><file_sep>
<!DOCTYPE HTML>
<?php
session_start();
if(isset($_SESSION['map']))
{
if($_SESSION['map']=="sjtuShop")
echo "<script type=\"text/javascript\"> location.assign(\"svgmaps/sjtuLocating.php\");</script>";
}
?> | a98992638ccdf1187646a1f3be4f3da5b6680c4b | [
"JavaScript",
"PHP"
] | 27 | PHP | polarskie/www | 0753b266f443428003383d22aede67989a806a1c | 01adcb59f18a874ab19134e7dcd3cb17172efcec |
refs/heads/master | <file_sep><?php
namespace in2Cms\Controllers;
use Illuminate\Http\Request;
class ModuleController extends BaseController
{
/**
* @param $name
* @param Request $req
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function getIndex($name, Request $req)
{
$module = $this->cms->getModuleByName($name);
$records = $module->in2CmsGetListAll();
return $this->view('module.index', ['records' => $records]);
}
}<file_sep><?php
namespace in2Cms\Channel;
class EditorField extends InputField
{
/**
* @param null $obj
* @return string
*/
public function render($obj = null)
{
$name = $this->name;
$ret[] = '<textarea class="in2-editor in2-input" name="in2['. $name .']">'. (empty($obj) ? '' : $obj->{$name}) .'</textarea>';
$ret[] = '<script>
tinymce.init({
selector:\'.in2-editor\',
plugins : \'autoresize advlist autolink link image lists charmap imagetools print preview\',
images_upload_base_path: \'/assets\',
images_upload_url: \'cms/module/media/upload\',
images_upload_credentials: true,
autoresize_min_height: 350,
autoresize_on_init: true
});
</script>';
return join("\n", $ret);
}
}<file_sep><?php
namespace in2Cms\Channel;
class SimpleInputField extends InputField
{
/**
* @param Object $obj
* @return string
*/
public function render($obj = null)
{
$name = $this->name;
$ret[] = '<input class="in2-input" name="in2['. $name .']" type="'. $this->type .'" value="' . (empty($obj) ? '' : $obj->{$name}) . '">';
return join("\n", $ret);
}
}<file_sep><?php
namespace in2Cms;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use in2Cms\Channel\InputField;
abstract class Channel
{
/**
* local cache for module instance
* @var AsIn2CmsModuleInterface|null
*/
protected $module;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $slug;
/**
* @var InputField[]
*/
protected $fields = [];
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* @param $s
*/
public function setSlug($s)
{
$this->slug = $s;
}
/**
* @param int $num
* @return \Illuminate\Database\Eloquent\Collection
*/
public function all($num = -1)
{
if ($num < 0) {
return $this->query()->get();
}
return $this->query()->limit($num)->get();
}
/**
* @return mixed
*/
public function count()
{
return $this->query()->count();
}
/**
* @param $id
* @return mixed|static
*/
public function findById($id)
{
return $this->query()->find($id);
}
/**
* @return Builder
*/
public function query()
{
$ref = $this;
return $this->getModule()->in2CmsQueryWithScope(function(EloquentBuilder $query) use ($ref){
return $ref->retrieveScope($query);
});
}
/**
* @param InputField $field
* @return InputField
*/
public function addInputField(InputField $field)
{
return $this->fields[$field->getName()] = $field;
}
/**
* @return array
*/
public function getInputFields()
{
return $this->fields;
}
public function setup() {}
/**
* @return AsIn2CmsModuleInterface|null
*/
protected function getModule()
{
if (!$this->module) {
$this->module = $this->retrieveModule();
}
return $this->module;
}
/**
* @return string
*/
abstract public function getChannelName();
/**
* @return AsIn2CmsModuleInterface
*/
abstract protected function retrieveModule();
/**
* @param EloquentBuilder $builder
* @return Builder
*/
abstract protected function retrieveScope(EloquentBuilder $builder);
}<file_sep># in2CMS
**This library is still under development. It's not stable enough for production use by default.**
in2CMS is an CMS build for Laravel 5.x. The main purpose of this CMS is simplify the website development. Scalability is concerned but not the most matter thing. So I keep API as simple as possible and full customizable for Content Managing.
This library will not break any components in Laravel.
That means you can remove it clearly if you do not want to use it anymore.
## Getting Start
```
composer require in2dream/in2cms
```
```
php artisan in2:init
```
Add `in2Cms\in2CmsServiceProvider` before
```
App\Providers\AppServiceProvider::class,
```
To add modules or channels, do it in `app/Providers/AppServiceProvider.php` like:
```
/** @var in2Cms $cms */
$cms = app(in2Cms::class);
$cms->registerModule('post', Post::class);
$cms->registerChannel('news', NewsChannel::class);
```
editing ...<file_sep><?php
namespace in2Cms\Module;
interface MediaInterface
{
public function persistentMediaData();
public function hookAfterUpload();
public function hookBeforeUpload();
}<file_sep><?php
namespace in2Cms\Module\Traits;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use in2Cms\Module\Meta;
trait SimpleRecordTrait
{
/**
* @return Collection
*/
public function in2CmsGetListAll()
{
return $this->all();
}
/**
* @param $id
*/
public function in2CmsFindById($id)
{
return $this->query()->find($id);
}
/**
* @param Request $req
* @return mixed
*/
public function in2CmsGetListByFilter(Request $req)
{
$filter = new ListFilter($req->all());
$cri = $this->query();
$keywords = $filter->getKeywords();
if (count($keywords) > 0) {
foreach ($keywords as $pair) {
$cri = $cri->where($pair[0], 'like', '%' . $pair[1] . '%');
}
}
$cri->orderBy($filter->getOrder(), $filter->getOrderType());
// TODO: ページごとのレコード数設定
$cri->limit($filter->getNum());
$cri->offset(($filter->getPage() - 1) * $filter->getNum());
return $cri->get();
}
/**
* @param $id
* @return Model
*/
public function in2CmsGetFindById($id)
{
return $this->where('id', $id)->first();
}
/**
* @param $params
* @return $this
*/
public function in2CmsGetUpdate(array $params)
{
$this->update($params);
return $this;
}
/**
* @return Meta
*/
public function in2CmsGetMeta()
{
$meta = new Meta();
$meta->label = static::class;
return $meta;
}
/**
* @param callable $func
* @return mixed
*/
public function in2CmsQueryWithScope(callable $func)
{
return $func($this->query());
}
}<file_sep><?php
namespace in2Cms;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use in2Cms\Commands\in2InitCommand;
use in2Cms\Commands\in2MakeChannelCommand;
class in2CmsServiceProvider extends ServiceProvider
{
/**
* @var string
*/
protected $namespace = 'in2Cms\\Controllers';
/**
* Bootstrap the application services.
*
* @param Router $router
* @internal param in2Cms $cms
*/
public function boot(Router $router)
{
parent::boot($router);
$this->map($router);
}
/**
* @param Router $router
*/
public function map(Router $router)
{
$router->group([
'namespace' => $this->namespace,
'prefix' => config('cms.base'),
'middleware' => 'web' // TODO: use specific middleware
], function(Router $router) {
require __DIR__ . '/routes.php';
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->commands([
in2InitCommand::class,
in2MakeChannelCommand::class
]);
in2Cms::register(app());
}
}
<file_sep><?php
namespace in2Cms\Channel;
class TextInputField extends SimpleInputField
{
/**
* @var string
*/
protected $type = 'text';
/**
* TextInputField constructor.
* @param $name
*/
public function __construct($name)
{
parent::__construct($name, $this->type);
}
}<file_sep><?php
namespace in2Cms;
class in2CmsException extends \Exception
{
}<file_sep><?php
namespace in2Cms\Component\Helper;
use Illuminate\Foundation\Application;
use in2Cms\in2Cms;
class ViewHelper
{
/**
* @var in2Cms
*/
protected $cms;
/**
* ViewHelper constructor.
* @param in2Cms $cms
*/
public function __construct(in2Cms $cms)
{
$this->cms = $cms;
}
/**
* @param $s
* @return string
*/
public function url($s)
{
return $this->cms->getBasePath() . $s;
}
}<file_sep><?php
namespace in2Cms;
use Illuminate\Foundation\Application;
use League\Flysystem\Exception;
use Twig_Environment;
use Twig_Loader_Filesystem;
class in2Cms
{
/**
* @var array
*/
protected $modules = array();
/**
* @var array
*/
protected $channels = array();
/**
* @var Twig_Environment
*/
protected $twig;
/**
* @var Application
*/
protected $app;
/**
* @var array
*/
protected $setting = array();
/**
* in2Cms constructor.
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
$this->initTwig();
// TODO: move to setting
$this->setting['basePath'] = config('cms.base');
}
protected function initTwig()
{
if (!config('cms')) return;
$dirs = [
resource_path('views/in2'),
__DIR__ . '/View'
];
$loader = new Twig_Loader_Filesystem($dirs);
$option = [];
// cache only in production
if ($this->app->environment('production'))
{
$option['cache'] = $this->app->storagePath() . '/view/in2';
}
$this->twig = new Twig_Environment($loader, $option);
}
/**
* @param $alias
* @param $className
*/
public function registerModule($alias, $className)
{
$this->modules[$alias] = new $className;
}
/**
* @param $name
* @param $className
*/
public function registerChannel($name, $className)
{
$this->channels[$name] = new $className;
$this->channels[$name]->setSlug($name);
$this->channels[$name]->setup();
}
/**
* @param $name
* @return AsIn2CmsModuleInterface
* @throws in2CmsException
*/
public function getModuleByName($name)
{
if (!isset($this->modules[$name])) throw new in2CmsException('module not found: ' . $name);
return $this->modules[$name];
}
/**
* @param $name
* @return Channel
* @throws in2CmsException
*/
public function getChannelByName($name)
{
if (!isset($this->channels[$name])) throw new in2CmsException('channel not found: ' . $name);
return $this->channels[$name];
}
/**
* @param $path
* @param array $vars
* @return string
*/
public function render($path, array $vars = [])
{
$real = join('/', explode('.', $path)) . '.twig';
return $this->twig->render($real, $vars);
}
/**
* @return array
*/
public function exportToView()
{
return [
'modules' => $this->modules,
'channels' => $this->channels
];
}
public function getBasePath()
{
return $this->setting['basePath'];
}
/**
* @param Application $app
*/
public static function register(Application $app)
{
$app->singleton(in2Cms::class, function() use ($app){
return new in2Cms($app);
});
}
}<file_sep><?php
namespace in2Cms\Commands;
use Illuminate\Console\Command;
class in2MakeModuleCommand extends Command
{
/**
* @var string
*/
public $signature = 'in2:make:module
{name : Channel Name}';
/**
* @var string
*/
public $description = '';
/**
*
*/
public function handle()
{
$this->comment('make new channel');
}
}<file_sep><?php
namespace in2Cms\Controllers;
use Illuminate\Http\Request;
class RootController extends BaseController
{
/**
* @param Request $req
* @return string
*/
public function getIndex(Request $req)
{
return $this->view('index', []);
}
}<file_sep><?php
namespace in2Cms\Component\Helper;
use League\Flysystem\Exception;
class LazyLoad
{
/**
* @var array
*/
protected $vars = [];
/**
* @var array
*/
protected $cache = [];
/**
* LazyLoader constructor.
* @param array $vars
*/
public function __construct(array $vars = [])
{
$this->vars = $vars;
}
/**
* @param $instance
* @param $method
* @param array $args
* @return \Closure
*/
protected function lazyLoad($instance, $method, array $args = [])
{
return call_user_func_array([$instance, $method], $args);
}
/**
* @param $name
* @param $arguments
* @return \Closure
* @throws Exception
*/
public function __call($name, $arguments = [])
{
if (isset($this->cache[$name])) return $this->cache[$name];
if (!isset($this->vars[$name])) throw new Exception('var: ' . $name . ' not found');
$var = $this->vars[$name];
$args = isset($var[2]) ? $var[2] : [];
$ret = $this->lazyLoad($var[0], $var[1], array_merge($args, $arguments));
$this->cache['name'] = $ret;
return $ret;
}
}<file_sep><?php
namespace in2Cms\Module;
class Meta
{
public $label;
}<file_sep><?php
/** @var \Illuminate\Routing\Router $router */
$router->get('/', 'RootController@getIndex');
// routes for module
$router->get('module/{name}', 'ModuleController@getIndex');
// routes for channel
$router->get('channel/{name}/edit', 'ChannelController@getEdit');
$router->post('channel/{name}/update', 'ChannelController@postUpdate');
$router->get('channel/{name}', 'ChannelController@getIndex');<file_sep><?php
namespace in2Cms\Commands;
use Illuminate\Console\Command;
class in2MakeChannelCommand extends Command
{
public $signature = 'in2:make:channel
{name : Channel Name}';
public $description = '';
public function handle()
{
$this->comment('make new channel');
}
}<file_sep><?php
namespace in2Cms\Controllers;
use Illuminate\Http\Request;
use in2Cms\Component\Helper\LazyLoad;
use in2Cms\in2CmsException;
class ChannelController extends BaseController
{
/**
* @param $name
* @param Request $req
* @return string
* @throws \in2Cms\in2CmsException
*/
public function getIndex($name, Request $req)
{
$channel = $this->cms->getChannelByName($name);
return $this->view('channel.index', [
'items' => $channel->all(),
'channel' => $channel,
'lazy' => new LazyLoad([
'count' => [$channel, 'count']
])
]);
}
/**
* @param $name
* @param Request $req
* @return string
* @throws in2CmsException
*/
public function getEdit($name, Request $req)
{
$channel = $this->cms->getChannelByName($name);
$single = $channel->findById($req->input('id'));
if (!$single) throw new in2CmsException($channel->getSlug() . ' data not found: ' . $req->input('id'));
return $this->view('channel.edit', [
'channel' => $channel,
'single' => $single,
'csrf_token' => csrf_token()
]);
}
/**
* @param $name
* @param Request $req
* @return \Illuminate\Http\RedirectResponse
* @throws in2CmsException
*/
public function postUpdate($name, Request $req)
{
$id = $req->input('id');
$channel = $this->cms->getChannelByName($name);
$record = $channel->findById($id);
$record->update($req->input('in2'));
return redirect()->back();
}
}<file_sep><?php
namespace in2Cms\Controllers;
use Illuminate\Routing\Controller;
use in2Cms\Component\Helper\ViewHelper;
use in2Cms\in2Cms;
class BaseController extends Controller
{
/**
* @var in2Cms
*/
protected $cms;
/**
* @var ViewHelper
*/
protected $viewHelper;
/**
* BaseController constructor.
* @param in2Cms $cms
* @param ViewHelper $viewHelper
*/
public function __construct(in2Cms $cms, ViewHelper $viewHelper)
{
$this->cms = $cms;
$this->viewHelper = $viewHelper;
}
/**
* @param $path
* @param array $vars
* @return string
*/
public function view($path, array $vars = [])
{
return $this->cms->render($path, array_merge($vars, [
'in2' => $this->cms->exportToView(),
'helper' => $this->viewHelper
]));
}
}<file_sep><?php
namespace in2Cms\Channel;
abstract class InputField
{
/**
* @var string
*/
protected $type;
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $comment;
/**
* InputField constructor.
* @param $name
* @param string $type
*/
public function __construct($name, $type = 'text')
{
$this->type = $type;
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getComment()
{
return $this->comment;
}
/**
* @param Object $obj
* @return mixed
*/
abstract public function render($obj = null);
}<file_sep><?php
namespace in2Cms;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use in2Cms\Module\Meta;
interface AsIn2CmsModuleInterface
{
/**
* List all records
* @return Collection
*/
public function in2CmsGetListAll();
/**
* List records by filter
* @param Request $req
* @return mixed
*/
public function in2CmsGetListByFilter(Request $req);
/**
* @param $id
* @return mixed
*/
public function in2CmsFindById($id);
/**
* Update record
* @param array $params
* @return mixed
*/
public function in2CmsUpdate(array $params);
/**
* Get edit url
* @return mixed
*/
public function in2CmsGetEditUrl();
/**
* Get update url
* @return mixed
*/
public function in2CmsGetUpdateUrl();
/**
* default params for creating a new instance
* @param Request $req
* @return mixed
*/
public function in2CmsGetDefaultParams(Request $req);
/**
* @return Meta
*/
public function in2CmsGetMeta();
/**
* @param callable $func
* @return Builder
*/
public function in2CmsQueryWithScope(callable $func);
}<file_sep><?php
namespace in2Cms\Controllers;
class MediaController extends BaseController
{
public function getIndex()
{
}
}<file_sep><?php
namespace in2Cms\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class in2InitCommand extends Command
{
/**
* @var Filesystem
*/
protected $fs;
/**
* @var string
*/
public $signature = 'in2:init';
/**
* @var string
*/
public $description = 'Init in2CMS';
/**
* in2InitCommand constructor.
* @param Filesystem $fs
*/
public function __construct(Filesystem $fs)
{
$this->fs = $fs;
parent::__construct();
}
/**
* handle
*/
public function handle()
{
$target = config_path('cms.php');
// check if config exists
if ($this->fs->exists($target))
{
$this->warn($target . ' already exists.'. "\n" .'To continue, please remove it first.');
return;
}
// copy config file
$this->fs->copy(__DIR__ . '/../cms.php', $target);
$this->info('Deploy: ' . $target);
$this->comment('This file is for configuring the cms. Please check it out.');
$viewDir = resource_path('views/in2');
$this->fs->makeDirectory($viewDir);
$this->info('Created: ' . $viewDir);
$this->comment('This directory is for overriding admin views.');
$jsDir = public_path('js/in2');
$this->fs->copy(__DIR__ . '/../public/js/in2', $jsDir);
$this->info('Deploy: ' . $jsDir);
$this->comment('This directory is for deploy public assets.');
}
} | ce35a663fdfb34ac6ee3a131ec50150a4f9d33b2 | [
"Markdown",
"PHP"
] | 24 | PHP | in2dream/in2cms | 05999c9469481b3e8f48e0f137a4389335ef399c | d9b5dc1c0efc990f0fef64dbd614f27045451a25 |
refs/heads/master | <repo_name>Allen-Bayern/waka-animation<file_sep>/README.md
# 动画效果
使用anime.js来做。
## 展示方法:
若您使用`visual studio code`,则可以安装插件Live Server以展示。
图示:

安装完成后,在右下角会出现一个`Go Live`图标。
图示:

点击即可展示。显示效果如下图:

## 参考:
1. https://codepen.io/Paolo-Duzioni/pen/jvrxpL
2. https://codepen.io/juliangarnier/pen/aWERWX
3. https://codepen.io/allen-bayern/pen/abwodyo
4. https://codepen.io/ainalem/pen/mLqvee
## 分支信息:
1. `master`分支:必须为当前可以稳定运行的版本;
2. `dev`分支:**开发中**,用来折腾新功能;
3. `res0`分支:使用es5的稳定运行版本;
4. `res1`分支:使用es6特性的新版本,浏览器容易崩;
5. `res1_rew`分支:**开发中**,对`res1`分支重写,通过`babel`或`TypeScript`等手段以求es6代码可以运行。写成之后与`res1`分支合并并删除。<file_sep>/src/scripts/main.js
// author: Yuebing
const elem = {
'wrap' : document.querySelector('.waka'),
'logo' : document.querySelector('svg'),
'w': document.querySelector('.w'),
'a1': document.querySelector('.a2'),
'k': document.querySelector('.k'),
'a2' : document.querySelector('.a1'),
'thumb': document.querySelector('.finger'),
'characters': document.querySelector('.character')
};
// -----------------------------------------------------------------
// hover函数
// 下方18行代码的作用是当鼠标靠近waka时,它能放大。离开时缩小
const animateButton = (scale, duration, elasticity) =>{
anime.remove(elem['wrap']);
anime(
{
targets : elem['wrap'],
scale : scale,
duration : duration,
elasticity : elasticity
}
);
};
const enterButton = () =>{
animateButton(1.2, 800, 400);
};
const leaveButton = () => {
animateButton(1.0, 600, 300);
};
elem['wrap'].addEventListener('mouseenter', enterButton, false);
elem['wrap'].addEventListener('mouseleave', leaveButton, false);
// ----------------------------------------------------------------
// 从天而降的数值
const transy = [-100, 0];
// 使用timeline
let tl = anime.timeline({
easing: 'spring',
duration: 500,
loop: true
});
tl.add({
targets : elem['w'],
translateY: transy,
direction: 'alternate',
}).add({
targets: elem['a1'],
translateY: transy,
direction: 'alternate',
}).add({
targets: elem['k'],
translateY: transy,
direction: 'alternate',
}).add({
targets: elem['a2'],
translateY: transy,
direction: 'alternate',
}).add({
targets: elem['thumb'],
translateY: transy,
direction: 'alternate',
}).add({
targets: elem['characters'],
translateY: transy,
direction: 'alternate',
}); | 9b0ccefd3dca579a88b1aeeb73aff9490738eedb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Allen-Bayern/waka-animation | 4367768451602a94a49d3a277a4ffdc7f920778e | 83ae252d1e22555825d9b0b9f2a9592075669599 |
refs/heads/master | <file_sep>function getNoLines(element) {
var hardlines = element.value.split('\n');
var total = hardlines.length;
for (var i = 0, len = hardlines.length; i < len; i++) {
total += Math.max(Math.round(hardlines[i].length / element.cols), 1) - 1;
}
return total;
}
function expandoCheck(element) {
var lines = getNoLines(element);
var aMaxSetting = parseInt(element.rows) * 0.9;
var aMinSetting = parseInt(element.rows) * 0.6;
if (((lines > aMaxSetting) || (lines < aMinSetting)) && lines > 16)
element.rows = '' + (parseInt(getNoLines(element)) + 6);
}
function insertTextile(field, prefix, suffix) {
var selection;
field = $(field);
field.focus();
// IE preliminary support
if (document.selection) {
selection = document.selection.createRange();
var selectionText = (selection.text == '') ? 'enter text':selection.text;
if (prefix.match(/\n[*]/) || prefix.match(/\n1[.]/)) {
selectionText = selectionText.replace(/(\r\n|\n)/g, prefix);
var duplicate = selection.duplicate();
duplicate.moveStart('character', -1);
prefix = (duplicate.text.match(/^(\r\n|\n)/)) ? prefix.replace(/(\r\n|\n)/, ''):prefix;
}
selection.text = prefix + selectionText + suffix;
}
// The rest
if (field.selectionStart || field.selectionStart == '0') {
var startSelection = field.selectionStart;
var endSelection = field.selectionEnd;
var selectionLength = endSelection - startSelection;
var preSelection = field.value.substring(0, startSelection)
var postSelection = field.value.substring(endSelection, field.value.length);
if (typeof(selection) == 'undefined')
selection = field.value.substring(startSelection, endSelection);
if (prefix[0] == '\n' && prefix[prefix.length] != ' ' && preSelection[preSelection.length] != '\n' && !prefix.match(/\n[*]/) && !prefix.match(/\n1[.]/)) {
var continuation;
for(i = preSelection.length; (i >= 0 && preSelection[i] != '\n'); i--) {
if(preSelection[i] == prefix[1]) {
var newLineCheck = i - 1
if(newLineCheck == 0 || preSelection[newLineCheck] == '\n')
continuation = true;
}
}
if (!continuation)
prefix = '\n' + prefix;
} else if (prefix.match(/\n[*]/) || prefix.match(/\n1[.]/)) {
selection = selection.replace(/(\r\n|\n)/g, prefix);
if (preSelection.substring(preSelection.length, 1).match(/(\r\n|\n)/)) {
prefix = prefix.replace(/\n/, '');
}
}
if (startSelection == endSelection) {
var insertText = 'enter text'
field.value = preSelection + prefix + insertText + suffix + postSelection;
var startPoint = preSelection.length + prefix.length;
var endPoint = preSelection.length + prefix.length + insertText.length;
} else {
field.value = preSelection + prefix + selection + suffix + postSelection;
var startPoint = preSelection.length + prefix.length + selectionLength + suffix.length;
var endPoint = startPoint;
}
field.blur(); field.focus(); // Reload preview
field.setSelectionRange(startPoint, endPoint);
}
}
function insertTextileLink(field, external) {
var linkUrl = prompt('Please enter the address:', 'http://');
if (linkUrl == null)
return;
else if (external)
insertTextile(field, '<a href="' + linkUrl + '" target="_blank">', '</a>');
else
insertTextile(field, '"', '":' + linkUrl);
} | a5cd46b7389da9c051c30b7ad91e00c78042d692 | [
"JavaScript"
] | 1 | JavaScript | cementhorses/textile_buttons | 326327d462bf2ed099434be438cebb6c4804d833 | dd90c3fc8e38f1d5a84d2ccf19f473df05ed5a88 |
refs/heads/master | <repo_name>casualsubversive/activerecord_marathon<file_sep>/db/migrate/20150910160812_add_first_last_to_reader.rb
class AddFirstLastToReader < ActiveRecord::Migration
def change
add_column :readers, :last_name, :string, null: false, default: "Smith"
rename_column :readers, :name, :first_name
end
end
<file_sep>/app/models/reader.rb
class Reader < ActiveRecord::Base
has_many :checkouts
has_many :books, through: :checkouts
validates :name, presence: true
validates :email, presence: true, uniqueness: true
end
<file_sep>/db/migrate/20150910161711_no_one_gets_a_name_anymore.rb
class NoOneGetsANameAnymore < ActiveRecord::Migration
def change
remove_column :readers, :first_name, :string
remove_column :readers, :last_name, :string
end
end
<file_sep>/app/models/book.rb
class Book < ActiveRecord::Base
has_many :checkouts
has_many :categorizations
has_many :categories, through: :categorizations
validates :title, presence: true
validates :rating, numericality: { minimum: 0, maximum: 100 }, allow_nil: true
end
| c4563f53d7c2f6c5e72b0943b661331b838997ea | [
"Ruby"
] | 4 | Ruby | casualsubversive/activerecord_marathon | 8c178eae5d6ca6d25314d3036c48fa1052693a3f | 0ea2d41d49f1fd716f19bc68f9864054e272c068 |
refs/heads/master | <file_sep>import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class KKServer {
public static void main(String[] args) {
System.setProperty("java.security.policy", "security.policy");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
System.out.println("Server startuje.. czekaj.");
System.setProperty("java.rmi.server.hostname", "192.168.43.47");
LocateRegistry.createRegistry(1099);
GameInterface game = Game.getInstance();
Naming.rebind("//192.168.43.47/Game", game);
System.out.println("Server jest gotowy.");
} catch (MalformedURLException | RemoteException ex) {
ex.printStackTrace();
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* @author tomek.buslowski
*/
public interface GameInterface extends Remote, Observer {
public boolean addPlayer(PlayerInterface player) throws RemoteException;
public void removePlayer(PlayerInterface player) throws RemoteException;
public PlayerInterface findPlayer(PlayerInterface player) throws RemoteException;
public String getFreeSymbol() throws RemoteException;
public String getGameInfo() throws RemoteException;
public boolean WAITING() throws RemoteException;
public boolean PLAYING() throws RemoteException;
public PlayerInterface getActualPlayer() throws RemoteException;
public String[] getFields() throws RemoteException;
public void setField(int i) throws RemoteException;
public void setNextPlayer() throws RemoteException;
}
| d3fc1ca6d03f821fcd8b409cdcc3452652afc5f8 | [
"Java"
] | 2 | Java | Vaviorky/RMITicTacToeServer | 37bb010756fe0d272239c859ddcd66899e87a1a5 | d0f29a080e240ca4caf9c9765fe26abe7496c50d |
refs/heads/main | <file_sep>package com.fermedu.poster.form;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
/**
* @Program: poster-generator
* @Create: 2021-02-16 21:20
* @Author: JustThink
* @Description:
* @Include:
**/
@Data
public class CompanyInfoForm {
@NotEmpty(message="It should not be empty")
private String companyName;
@NotEmpty(message="It should not be empty")
private String companyLogo;
@NotEmpty(message="It should not be empty")
private String companyWebsite;
}
<file_sep># Hosted
> See a hosted version at:
> http://172.16.17.32:8280/
# Introduction
This is a demo project generating a data object to a poster.
# Get started
## Mapping a data object to XML
> so other programs can work with this demo app.
## Api
[](https://imgchr.com/i/ygfcFO)
## Mapping a data object to graphics
> a poster in this case
## Api
[](https://imgchr.com/i/ygfyTK)
| 36719250a021997431d0985cf7e450c1d1c7ffdc | [
"Markdown",
"Java"
] | 2 | Java | thebirdandfish/poster-generator | 42b00d063ef8df88ed1811c4115401ff1a3ba0ff | 4f02ac5dee5e623fe6e5a3790a46b31a97dc7543 |
refs/heads/master | <repo_name>daniela-becheanu/POO--tema1<file_sep>/src/fileio/ActorInputData.java
package fileio;
import actor.ActorsAwards;
import java.util.ArrayList;
import java.util.Map;
/**
* Information about an actor, retrieved from parsing the input test files
* <p>
* DO NOT MODIFY
*/
public final class ActorInputData {
/**
* actor name
*/
private String name;
/**
* description of the actor's career
*/
private String careerDescription;
/**
* videos starring actor
*/
private ArrayList<String> filmography;
/**
* awards won by the actor
*/
private final Map<ActorsAwards, Integer> awards;
private int awardsNo;
public ActorInputData(final String name, final String careerDescription,
final ArrayList<String> filmography,
final Map<ActorsAwards, Integer> awards) {
this.name = name;
this.careerDescription = careerDescription;
this.filmography = filmography;
this.awards = awards;
this.awardsNo = 0;
for (Map.Entry<ActorsAwards, Integer> entry : awards.entrySet()) {
this.awardsNo += entry.getValue();
}
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public ArrayList<String> getFilmography() {
return filmography;
}
public void setFilmography(final ArrayList<String> filmography) {
this.filmography = filmography;
}
public Map<ActorsAwards, Integer> getAwards() {
return awards;
}
public String getCareerDescription() {
return careerDescription;
}
public void setCareerDescription(final String careerDescription) {
this.careerDescription = careerDescription;
}
public int getAwardsNo() {
return awardsNo;
}
/**
* Computes the grade of the ActorInputData object, which is the mean of the movies and serials
* he played in.
*
* @param input the database from which the movies and serials are taken
* @return the computed grade
*/
public double computeGrade(final Input input) {
double sum;
double number;
sum = 0;
number = 0;
for (MovieInputData movie : input.getMovies()) {
if (filmography.contains(movie.getTitle()) && movie.computeGrade() != 0) {
sum += movie.computeGrade();
number++;
}
}
for (SerialInputData serial : input.getSerials()) {
if (filmography.contains(serial.getTitle()) && serial.computeGrade() != 0) {
sum += serial.computeGrade();
number++;
}
}
if (number == 0) {
return 0;
}
return sum / number;
}
@Override
public String toString() {
return "ActorInputData{"
+ "name='" + name + '\''
+ ", careerDescription='"
+ careerDescription + '\''
+ ", filmography=" + filmography + '}';
}
}
<file_sep>/src/compare/CompareRatingsNo.java
package compare;
import fileio.UserInputData;
import java.util.Comparator;
public class CompareRatingsNo implements Comparator<UserInputData> {
@Override
public final int compare(final UserInputData user1, final UserInputData user2) {
if (user2.getRatedMovies().size() != user1.getRatedMovies().size()) {
return user1.getRatedMovies().size() - user2.getRatedMovies().size();
}
return user1.getUsername().compareTo(user2.getUsername());
}
}
<file_sep>/src/action/Recommendation.java
package action;
import compare.CompareVideos;
import fileio.Input;
import fileio.SerialInputData;
import fileio.ShowInput;
import fileio.UserInputData;
import fileio.MovieInputData;
import fileio.ActionInputData;
import convert.Video;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
public final class Recommendation {
private Recommendation() {
}
/**
* Finds the videos from a list of videos that are not seen by the user.
*
* @param input the database which contains the movies and serials where the search occurs
* @param user the user which the search is for
* @return the list of videos not seen by the user
*/
public static List<ShowInput> notSeen(final Input input, final UserInputData user) {
List<ShowInput> result = input.getMovies().stream()
.filter(movie -> !user.getHistory().containsKey(movie.getTitle()))
.collect(Collectors.toList());
List<SerialInputData> serialsNotSeen = input.getSerials().stream()
.filter(movie -> !user.getHistory().containsKey(movie.getTitle()))
.collect(Collectors.toList());
result.addAll(serialsNotSeen);
return result;
}
public static class BasicUser {
/**
* Finds the title of the video from database which is not already seen by the user.
*
* @param input the database which contains the information
* @param user the user which the recommendation is applied for
* @return a message with the corresponding video or if the recommendation cannot be
* applied
*/
public static String standard(final Input input, final UserInputData user) {
for (MovieInputData movie : input.getMovies()) {
if (!user.getHistory().containsKey(movie.getTitle())) {
return "StandardRecommendation result: " + movie.getTitle();
}
}
for (SerialInputData serial : input.getSerials()) {
if (!user.getHistory().containsKey(serial.getTitle())) {
return "StandardRecommendation result: " + serial.getTitle();
}
}
return "StandardRecommendation cannot be applied!";
}
/**
* Finds the title of the video with the biggest grade.
*
* @param input the database which contains the information
* @param user the user which the recommendation is applied for
* @return a message with the corresponding video or if the recommendation cannot be
* applied
*/
public static String bestUnseen(final Input input, final UserInputData user) {
String message;
List<Video> videos = new ArrayList<>();
for (MovieInputData movie : input.getMovies()) {
if (!user.getHistory().containsKey(movie.getTitle())) {
Video video = new Video(movie.getTitle(), -movie.computeGrade(),
input.getMovies().indexOf(movie), "");
videos.add(video);
}
}
for (SerialInputData serial : input.getSerials()) {
if (!user.getHistory().containsKey(serial.getTitle())) {
Video video = new Video(serial.getTitle(), -serial.computeGrade(),
input.getSerials().indexOf(serial), "");
videos.add(video);
}
}
videos.sort(new CompareVideos());
if (videos.size() == 0) {
return "BestRatedUnseenRecommendation cannot be applied!";
}
message = "BestRatedUnseenRecommendation result: " + videos.get(0).getTitle();
return message;
}
}
public static class PremiumUser {
/**
* Finds the title of the video which is the most popular, meaning it is the most viewed.
*
* @param input the database which contains the information
* @param user the user which the recommendation is applied for
* @return a message with the corresponding video or if the recommendation cannot be
* applied
*/
public static String popular(final Input input, final UserInputData user) {
if (!user.getSubscriptionType().equals("PREMIUM")) {
return "PopularRecommendation cannot be applied!";
}
Map<String, Integer> genres;
genres = new HashMap<>();
for (MovieInputData movie : input.getMovies()) {
for (String s : movie.getGenres()) {
if (genres.containsKey(s)) {
genres.put(s, genres.get(s) - 1);
} else {
genres.put(s, -1);
}
}
}
for (SerialInputData serial : input.getSerials()) {
for (String s : serial.getGenres()) {
if (genres.containsKey(s)) {
genres.put(s, genres.get(s) - 1);
} else {
genres.put(s, -1);
}
}
}
Map<String, Integer> sorted = genres.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
for (Map.Entry<String, Integer> entry : sorted.entrySet()) {
for (MovieInputData movie : input.getMovies()) {
if (!user.getHistory().containsKey(movie.getTitle())
&& movie.getGenres().contains(entry.getKey())) {
return "PopularRecommendation result: " + movie.getTitle();
}
}
for (SerialInputData serial : input.getSerials()) {
if (!user.getHistory().containsKey(serial.getTitle())
&& serial.getGenres().contains(entry.getKey())) {
return "PopularRecommendation result: " + serial.getTitle();
}
}
}
return "PopularRecommendation cannot be applied!";
}
/**
* Finds the title of the video which is the most common in the favorite lists of al the
* users. The second criterion is the order of occurrence in database.
*
* @param input the database which contains the information
* @param user the user which the recommendation is applied for
* @return a message with the corresponding video or if the recommendation cannot be
* applied
*/
public static String favorite(final Input input, final UserInputData user) {
if (!user.getSubscriptionType().equals("PREMIUM")) {
return "FavoriteRecommendation cannot be applied!";
}
List<Video> videos = new ArrayList<>();
int favNo;
List<ShowInput> notSeen = notSeen(input, user);
for (ShowInput s : notSeen) {
favNo = 0;
for (UserInputData u : input.getUsers()) {
if (u.getFavoriteMovies().contains(s.getTitle())) {
favNo++;
}
}
Video video;
if (s instanceof MovieInputData) {
MovieInputData movie = (MovieInputData) s;
video = new Video(s.getTitle(), -favNo, input.getMovies().indexOf(movie), "");
} else {
SerialInputData serial = (SerialInputData) s;
video = new Video(s.getTitle(), -favNo, input.getSerials().indexOf(serial),
"");
}
videos.add(video);
}
videos.sort(new CompareVideos());
if (videos.size() == 0) {
return "FavoriteRecommendation cannot be applied!";
}
return "FavoriteRecommendation result: " + videos.get(0).getTitle();
}
/**
* Searches for all the unseen videos of a user of a specific genre.
*
* @param input the database which contains the information
* @param action the parameter which contains the genre
* @param user the user which the recommendation is applied for
* @return a message with the titles of all the corresponding videos or if the
* recommendation cannot be applied
*/
public static String search(final Input input, final ActionInputData action,
final UserInputData user) {
if (!user.getSubscriptionType().equals("PREMIUM")) {
return "SearchRecommendation cannot be applied!";
}
StringBuilder message = new StringBuilder("SearchRecommendation result: [");
List<Video> videos = new ArrayList<>();
ArrayList<ShowInput> notSeen = (ArrayList<ShowInput>) notSeen(input, user);
notSeen = (ArrayList<ShowInput>) notSeen.stream().filter(s -> s.getGenres()
.contains(action.getGenre())).collect(Collectors.toList());
for (ShowInput s : notSeen) {
if (s instanceof MovieInputData) {
Video video = new Video(s.getTitle(), ((MovieInputData) s).computeGrade(), 0,
s.getTitle());
videos.add(video);
}
if (s instanceof SerialInputData) {
Video video = new Video(s.getTitle(), ((SerialInputData) s).computeGrade(), 0,
s.getTitle());
videos.add(video);
}
}
videos.sort(new CompareVideos());
for (Video video : videos) {
message.append(video.getTitle()).append(", ");
}
if (videos.size() == 0) {
return "SearchRecommendation cannot be applied!";
}
message = new StringBuilder(message.substring(0, message.length() - 2));
message.append("]");
return message.toString();
}
}
}
<file_sep>/src/convert/Video.java
package convert;
public class Video {
private final String title;
private final double firstCriterion;
private final int secondCriterion;
private final String thirdCriterion;
public Video(final String title, final double firstCriterion, final int secondCriterion,
final String thirdCriterion) {
this.title = title;
this.firstCriterion = firstCriterion;
this.secondCriterion = secondCriterion;
this.thirdCriterion = thirdCriterion;
}
public final String getTitle() {
return title;
}
public final double getFirstCriterion() {
return firstCriterion;
}
public final int getSecondCriterion() {
return secondCriterion;
}
public final String getThirdCriterion() {
return thirdCriterion;
}
}
<file_sep>/src/action/Command.java
package action;
import fileio.ActionInputData;
import fileio.MovieInputData;
import fileio.SerialInputData;
import fileio.UserInputData;
public class Command {
public static class Movie {
/**
* Adds rating to a season of a movie that is already seen.
*
* @param title the title of the serial that is added
* @param user the user that rates the movie
* @param movie the movie which list the rating is added in
* @param action the parameter which contains the grade (rating)
* @return a message which indicates if the adding takes place
*/
public static String addRating(final String title, final UserInputData user,
final MovieInputData movie,
final ActionInputData action) {
if (user.getHistory().containsKey(title)) {
if (!user.getRatedMovies().contains(title)) {
user.getRatedMovies().add(title);
return movie.addRating(action.getUsername(),
action.getGrade());
}
return "error -> " + movie.getTitle() + " has been already rated";
}
return "error -> " + movie.getTitle() + " is not seen";
}
}
public static class Serial {
/**
* Adds rating to a season of a serial that is already seen.
*
* @param title the title of the serial that is added
* @param seasonNumber the number of the season that is rated
* @param user the user that rates the season of the serial
* @param serial the serial which list the rating is added in
* @param action the parameter which contains the grade (rating)
* @return a message which indicates if the adding takes place
*/
public static String addRating(final String title, final int seasonNumber,
final UserInputData user,
final SerialInputData serial,
final ActionInputData action) {
final String seasonTitle = title + " - season " + seasonNumber;
if (user.getHistory().containsKey(title)) {
if (!user.getRatedMovies().contains(seasonTitle)) {
user.getRatedMovies().add(seasonTitle);
return serial.addRating(action.getUsername(),
action.getSeasonNumber(), action.getGrade());
}
return "error -> " + serial.getTitle() + " has been already rated";
}
return "error -> " + serial.getTitle() + " is not seen";
}
}
}
<file_sep>/src/fileio/MovieInputData.java
package fileio;
import java.util.ArrayList;
import java.util.List;
/**
* Information about a movie, retrieved from parsing the input test files
* <p>
* DO NOT MODIFY
*/
public final class MovieInputData extends ShowInput {
/**
* Duration in minutes of a season
*/
private final int duration;
private List<Double> ratings;
private int favoriteNo;
private int views;
public int getViews() {
return views;
}
public void setViews(final int views) {
this.views = views;
}
public int getFavoriteNo() {
return favoriteNo;
}
public void setFavoriteNo(final int favoriteNo) {
this.favoriteNo = favoriteNo;
}
public List<Double> getRatings() {
return ratings;
}
public void setRatings(final List<Double> ratings) {
this.ratings = ratings;
}
public MovieInputData(final String title, final ArrayList<String> cast,
final ArrayList<String> genres, final int year,
final int duration) {
super(title, year, cast, genres);
this.duration = duration;
this.ratings = new ArrayList<>();
this.favoriteNo = 0;
this.views = 0;
}
public int getDuration() {
return duration;
}
@Override
public String toString() {
return "MovieInputData{" + "title= "
+ super.getTitle() + "year= "
+ super.getYear() + "duration= "
+ duration + "cast {"
+ super.getCast() + " }\n"
+ "genres {" + super.getGenres() + " }\n ";
}
/**
* Adds the rating int the ratings list.
*
* @param username the user that made the rating
* @param grade the grade that is given
* @return a success message with the title of the movie, grade and user of the rating
*/
public String addRating(final String username, final Double grade) {
this.ratings.add(grade);
return "success -> " + this.getTitle() + " was rated with " + grade + " by " + username;
}
/**
* Computes the grade of the MovieInputData object, which is the mean of its seasons.
*
* @return the computed grade
*/
public double computeGrade() {
if (ratings.size() == 0) {
return 0;
}
double sum = 0;
for (Double d : ratings) {
sum += d;
}
return sum / ratings.size();
}
}
<file_sep>/src/compare/CompareActors.java
package compare;
import convert.Actor;
import java.util.Comparator;
public final class CompareActors implements Comparator<Actor> {
@Override
public int compare(final Actor actor1, final Actor actor2) {
if (actor1.getFirstCriterion() > actor2.getFirstCriterion()) {
return 1;
}
if (actor1.getFirstCriterion() < actor2.getFirstCriterion()) {
return -1;
}
return actor1.getName().compareTo(actor2.getName());
}
}
<file_sep>/src/action/Query.java
package action;
import compare.CompareActors;
import compare.CompareRatingsNo;
import compare.CompareVideos;
import contain.ContainsAwards;
import contain.ContainsWords;
import fileio.Input;
import fileio.ActionInputData;
import fileio.ActorInputData;
import fileio.UserInputData;
import fileio.SerialInputData;
import fileio.MovieInputData;
import convert.Actor;
import convert.Video;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Query {
public static class Actors {
/**
* Sorts in ascending/descending order a list of actors.
*
* @param actors the initial actors list that needs to be sorted
* @param action the parameter which contains way the list needs to be sorted
* @return a message containing a list with the sorted actors
*/
public static String sort(final ArrayList<Actor> actors, final ActionInputData action) {
StringBuilder message = new StringBuilder();
actors.sort(new CompareActors());
if (action.getSortType().equals("desc")) {
Collections.reverse(actors);
}
int min = Math.min(actors.size(), action.getNumber());
for (int i = 0; i < min; ++i) {
message.append(actors.get(i).getName());
message.append(", ");
}
if (message.length() > 2) {
message = new StringBuilder(message.substring(0, message.length() - 2));
}
return message.toString();
}
/**
* Lists a number of actors sorted by the mean of the movies and serials they played in.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of actors that need to be listed.
* @return a message which indicates the actors sorted by their mean
*/
public static String sortActorsAverage(final Input input, final ActionInputData action) {
String message = "Query result: [";
List<ActorInputData> actorsList = input.getActors().stream()
.filter(actor -> actor.computeGrade(input) > 0)
.collect(Collectors.toList());
ArrayList<Actor> actors = new ArrayList<>();
for (ActorInputData actor : actorsList) {
Actor a = new Actor(actor.getName(), actor.computeGrade(input));
actors.add(a);
}
message += sort(actors, action);
message += "]";
return message;
}
/**
* Lists all the actors whose description contains all the awards mentioned in query.
*
* @param input the database which contains the information
* @param action the parameter which contains way the actors need to be listed (ascending
* or descending)
* @return a message which indicates the actors with all the awards
*/
public static String sortActorsAwards(final Input input, final ActionInputData action) {
String message = "Query result: [";
List<ActorInputData> actorsFilterApplied = new ArrayList<>();
if (action.getFilters().get(action.getFilters().size() - 1) != null) {
actorsFilterApplied = input.getActors().stream()
.filter(new ContainsAwards(action.getFilters()
.get(action.getFilters().size() - 1)))
.collect(Collectors.toList());
}
ArrayList<Actor> actors = new ArrayList<>();
for (ActorInputData actor : actorsFilterApplied) {
Actor a = new Actor(actor.getName(), actor.getAwardsNo());
actors.add(a);
}
message += sort(actors, action);
message += "]";
return message;
}
/**
* Lists all the actors whose description all the keywords appear.
*
* @param input the database which contains the information
* @param action the parameter which contains way the actors need to be listed (ascending
* or descending)
* @return a message which indicates the actors filtered
*/
public static String sortActorsFilter(final Input input, final ActionInputData action) {
String message = "Query result: [";
for (ActorInputData actor : input.getActors()) {
actor.setCareerDescription(actor.getCareerDescription().toLowerCase());
actor.setCareerDescription(actor.getCareerDescription().replace('-', ' '));
actor.setCareerDescription(actor.getCareerDescription().replace(',', ' '));
actor.setCareerDescription(actor.getCareerDescription().replace('.', ' '));
}
List<ActorInputData> actorsFilterApplied = input.getActors().stream()
.filter(new ContainsWords(action.getFilters().get(2)))
.collect(Collectors.toList());
ArrayList<Actor> actors = new ArrayList<>();
for (ActorInputData actor : actorsFilterApplied) {
Actor a = new Actor(actor.getName(), 0);
actors.add(a);
}
message += sort(actors, action);
message += "]";
return message;
}
}
public static class Videos {
/**
* Sorts in ascending/descending order a list of videos.
*
* @param videos the initial videos list that needs to be sorted
* @param action the parameter which contains way the list needs to be sorted
* @return a message containing a list with the sorted videos
*/
public static String sort(final ArrayList<Video> videos, final ActionInputData action) {
StringBuilder message = new StringBuilder();
videos.sort(new CompareVideos());
if (action.getSortType().equals("desc")) {
Collections.reverse(videos);
}
int min = Math.min(videos.size(), action.getNumber());
for (int i = 0; i < min; ++i) {
message.append(videos.get(i).getTitle());
message.append(", ");
}
if (message.length() > 2) {
message = new StringBuilder(message.substring(0, message.length() - 2));
}
return message.toString();
}
public static class Movies {
/**
* Filters a list of movies.
*
* @param input the database which contains the information
* @param action the parameter which contains the filters
* @return a message containing a list with the filtered movies
*/
public static List<MovieInputData> moviesFiltered(final ActionInputData action,
final Input input) {
List<MovieInputData> moviesFiltered = input.getMovies();
if (action.getFilters().get(0).get(0) != null) {
moviesFiltered = moviesFiltered.stream()
.filter(movie -> Integer.toString(movie.getYear())
.equals(action.getFilters().get(0).get(0)))
.collect(Collectors.toList());
}
if (action.getFilters().get(1).get(0) != null) {
moviesFiltered = moviesFiltered.stream()
.filter(movie -> movie.getGenres()
.contains(action.getFilters().get(1).get(0)))
.collect(Collectors.toList());
}
return moviesFiltered;
}
/**
* Lists a number of movies sorted by their rating.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of movies that need to be
* listed
* @return a message which indicates the movies with the highest/lowest rating
*/
public static String sortRating(final Input input, final ActionInputData action) {
String message = "Query result: [";
List<MovieInputData> moviesFiltered = moviesFiltered(action, input);
ArrayList<Video> videos = new ArrayList<>();
moviesFiltered = moviesFiltered.stream()
.filter(movie -> movie.computeGrade() > 0)
.collect(Collectors.toList());
for (MovieInputData movie : moviesFiltered) {
Video video = new Video(movie.getTitle(), movie.computeGrade(), 0,
movie.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of movies sorted by their numbers of occurrence in users' favorite
* lists.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of movies that need to be
* listed
* @return a message which indicates the movies that appear the most/least in users'
* favorite lists
*/
public static String sortFavorite(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
for (MovieInputData movie : input.getMovies()) {
movie.setFavoriteNo(0);
for (UserInputData user : input.getUsers()) {
if (user.getFavoriteMovies().contains(movie.getTitle())) {
movie.setFavoriteNo(movie.getFavoriteNo() + 1);
}
}
}
List<MovieInputData> moviesFiltered = moviesFiltered(action, input);
moviesFiltered = moviesFiltered.stream()
.filter(serial -> serial.getFavoriteNo() > 0)
.collect(Collectors.toList());
for (MovieInputData movie : moviesFiltered) {
Video video = new Video(movie.getTitle(), 0, movie.getFavoriteNo(),
movie.getTitle());
videos.add(video);
}
message = message + sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of movies sorted by their duration.
*
* @param input the database which contains the information
* @param action the parameter which contains the number movies that need to be
* listed
* @return a message which indicates the longest/shortest serials
*/
public static String sortLongest(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<MovieInputData> moviesFiltered = moviesFiltered(action, input);
for (MovieInputData movie : moviesFiltered) {
Video video = new Video(movie.getTitle(), 0, movie.getDuration(),
movie.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of movies sorted by their views.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of movies that need to be
* listed
* @return a message which indicates the most/least viewed movies
*/
public static String sortMostViewed(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<MovieInputData> moviesFiltered = moviesFiltered(action, input);
for (MovieInputData movie : moviesFiltered) {
movie.setViews(0);
for (UserInputData user : input.getUsers()) {
if (user.getHistory().containsKey(movie.getTitle())) {
movie.setViews(movie.getViews() + user.getHistory()
.get(movie.getTitle()));
}
}
}
moviesFiltered = moviesFiltered.stream()
.filter(movie -> movie.getViews() > 0)
.collect(Collectors.toList());
for (MovieInputData movie : moviesFiltered) {
Video video = new Video(movie.getTitle(), 0, movie.getViews(),
movie.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
}
public static class Serials {
/**
* Filters a list of serials.
*
* @param input the database which contains the information
* @param action the parameter which contains the filters
* @return a message containing a list with the filtered serials
*/
public static List<SerialInputData> serialsFiltered(final ActionInputData action,
final Input input) {
List<SerialInputData> serialsFiltered = input.getSerials();
if (action.getFilters().get(0).get(0) != null) {
serialsFiltered = input.getSerials().stream()
.filter(movie -> Integer.toString(movie.getYear())
.equals(action.getFilters().get(0).get(0)))
.collect(Collectors.toList());
}
if (action.getFilters().get(1).get(0) != null) {
serialsFiltered = serialsFiltered.stream()
.filter(serial -> serial.getGenres()
.contains(action.getFilters().get(1).get(0)))
.collect(Collectors.toList());
}
return serialsFiltered;
}
/**
* Lists a number of serials sorted by their rating.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of serials that need to be
* listed
* @return a message which indicates the serials with the highest/lowest rating
*/
public static String sortRating(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<SerialInputData> serialsFiltered = serialsFiltered(action, input);
serialsFiltered = serialsFiltered.stream()
.filter(serial -> serial.computeGrade() > 0)
.collect(Collectors.toList());
for (SerialInputData serial : serialsFiltered) {
Video video = new Video(serial.getTitle(), serial.computeGrade(), 0,
serial.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of serials sorted by their numbers of occurrence in users' favorite
* lists.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of serials that need to be
* listed
* @return a message which indicates the serials that appear the most/least in users'
* favorite lists
*/
public static String sortFavorite(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<SerialInputData> serialsFiltered = serialsFiltered(action, input);
for (SerialInputData serial : serialsFiltered) {
serial.setFavoriteNo(0);
for (UserInputData user : input.getUsers()) {
if (user.getFavoriteMovies().contains(serial.getTitle())) {
serial.setFavoriteNo(serial.getFavoriteNo() + 1);
}
}
}
serialsFiltered = serialsFiltered.stream()
.filter(serial -> serial.getFavoriteNo() > 0)
.collect(Collectors.toList());
for (SerialInputData serial : serialsFiltered) {
Video video = new Video(serial.getTitle(), 0, serial.getFavoriteNo(),
serial.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of serials sorted by their duration.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of serials that need to be
* listed
* @return a message which indicates the longest/shortest serials
*/
public static String sortLongest(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<SerialInputData> serialsFiltered = serialsFiltered(action, input);
for (SerialInputData serial : serialsFiltered) {
Video video = new Video(serial.getTitle(), 0, serial.getDuration(),
serial.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
/**
* Lists a number of serials sorted by their views.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of serials that need to be
* listed
* @return a message which indicates the most/least viewed serials
*/
public static String sortMostViewed(final Input input, final ActionInputData action) {
String message = "Query result: [";
ArrayList<Video> videos = new ArrayList<>();
List<SerialInputData> serialsFiltered = serialsFiltered(action, input);
for (SerialInputData serial : serialsFiltered) {
serial.setViews(0);
for (UserInputData user : input.getUsers()) {
if (user.getHistory().containsKey(serial.getTitle())) {
serial.setViews(serial.getViews() + user.getHistory()
.get(serial.getTitle()));
}
}
}
serialsFiltered = serialsFiltered.stream()
.filter(serial -> serial.getViews() > 0)
.collect(Collectors.toList());
for (SerialInputData serial : serialsFiltered) {
Video video = new Video(serial.getTitle(), 0, serial.getViews(),
serial.getTitle());
videos.add(video);
}
message += sort(videos, action);
message += "]";
return message;
}
}
}
public static class Users {
/**
* Sorts in ascending or descending order a list.
*
* @param users the list of users that needs to be sorted
* @param action the parameter which contains the number of users that need to be sorted
* @return a message which indicates the most/least active users
*/
public static String sort(final ArrayList<UserInputData> users,
final ActionInputData action) {
users.sort(new CompareRatingsNo());
StringBuilder message = new StringBuilder();
if (action.getSortType().equals("desc")) {
Collections.reverse(users);
}
int min = Math.min(action.getNumber(), users.size());
for (int i = 0; i < min; ++i) {
message.append(users.get(i).getUsername());
message.append(", ");
}
if (message.length() > 2) {
message = new StringBuilder(message.substring(0, message.length() - 2));
}
return message.toString();
}
/**
* Lists a number of users sorted by the number of ratings given.
*
* @param input the database which contains the information
* @param action the parameter which contains the number of users that need to be listed
* @return a message which indicates the most/least active users
*/
public static String sortRatingsNo(final Input input, final ActionInputData action) {
String message = "Query result: [";
List<UserInputData> usersFiltered;
usersFiltered = input.getUsers().stream()
.filter(user -> user.getRatedMovies().size() > 0)
.collect(Collectors.toList());
message += sort((ArrayList<UserInputData>) usersFiltered, action);
message += "]";
return message;
}
}
}
| 6870fe43561ff367d6cc5fa2f47af3db9238952f | [
"Java"
] | 8 | Java | daniela-becheanu/POO--tema1 | 34e0c8c5b5654c98d42c68b9113bc56b579aedc6 | f4464beeb42702104e024488410eef10db3ede9f |
refs/heads/master | <file_sep># KZNPopViewController
===============

Category of UIViewController to make popup UI.
KZNPopViewController is tested on iOS 5.0+ and requires ARC.
## Features
* Simple APIs which are like those in the UIViewController class.
* You're able to customize the popuped UIViewController design by yourself.
* You're able to choose one from some animations.
## Installation
### CocoaPods
If you are using CocoaPods, then just add KZNPopViewController to you Podfile.
```ruby
pod 'KZNPopViewController', :git => 'https://github.com/kenzan8000/KZNPopViewController.git'
```
### Manually
Simply add the files in the KZNPopViewController directory to your project.
## Example
### Default Animation
```objective-c
[self presentKZNPopViewController:viewController
presentAnimation:[KZNPopAnimation presentAnimationFadeInFromCenter]
dismissAnimation:[KZNPopAnimation dismissAnimationFadeOutToCenter]
completion:NULL];
```
### Custom Animation
```objective-c
KZNPopAnimation *presentAnimation = [KZNPopAnimation animationWithAnimationType:KZNPopViewControllerAnimationTypeFadeIn | KZNPopViewControllerAnimationTypeScalingFromOutside
duration:0.3f];
KZNPopAnimation *dismissAnimation = [KZNPopAnimation animationWithAnimationType:KZNPopViewControllerAnimationTypeFadeOut
duration:0.3f];
[self presentKZNPopViewController:viewController
presentAnimation:presentAnimation
dismissAnimation:dismissAnimation
backgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]
completion:NULL];
```
## License
Released under the MIT license.
<file_sep>Pod::Spec.new do |s|
s.name = "KZNPopViewController"
s.version = "0.2"
s.summary = "Category of UIViewController to make popup UI."
s.description = <<-DESC
A longer description of KZNPopViewController in Markdown format.
* Category of UIViewController to make popup UI.
* KZNPopViewController is tested on iOS 5.0+ and requires ARC.
* Simple APIs which are like those in the UIViewController class.
* You're able to customize the popuped UIViewController design by yourself.
* You're able to choose one from some animations.
DESC
s.homepage = "http://kenzan8000.org"
s.license = { :type => 'MIT' }
s.author = { "<NAME>" => "<EMAIL>" }
s.platform = :ios, '5.0'
s.source = { :git => "https://github.com/kenzan8000/KZNPopViewController.git", :tag => "v0.1" }
s.source_files = 'KZNPopViewController/*.{h,m}'
s.requires_arc = true
# s.exclude_files = 'Classes/Exclude'
# s.public_header_files = 'Classes/**/*.h'
end
| 337936ad5d6af795ee6667e1f42840414e6b1394 | [
"Markdown",
"Ruby"
] | 2 | Markdown | kenzan8000/KZNPopViewController | 52ed35cbab3fefc76390bd9214eca32396b6d29f | 0ef941e0aa14682531fd4c457a81deefe00883fc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.